CombinedText
stringlengths
8
3.42M
#include "SignalTest.h" #include <iostream> #include <list> #include <vector> #include <thread> #include <atomic> #include "BSignals/details/BasicTimer.h" #include "SafeQueue.hpp" #include "FunctionTimeRegular.hpp" using BSignals::details::SafeQueue; using BSignals::details::BasicTimer; using std::cout; using std::endl; using ::testing::Values; using std::list; using std::vector; using std::thread; using std::atomic; using std::fixed; using BSignals::Signal; using BSignals::ExecutorScheme; std::atomic<int> globalStaticIntX{0}; struct BigThing { char thing[512]; }; SafeQueue<BigThing> sq; void SignalTest::SetUp() { globalStaticIntX = 0; } void SignalTest::TearDown() { } void pushToQueue(BigThing bt) { sq.enqueue(bt); } void staticSumFunction(int a, int b) { globalStaticIntX += a + b; //cout << a << " + " << b << " = " << globalStaticIntX << endl; } TEST_F(SignalTest, SynchronousSignal) { cout << "Instantiating signal object" << endl; Signal<int, int> testSignal; BasicTimer bt; cout << "Connecting signal" << endl; bt.start(); int id = testSignal.connectSlot(ExecutorScheme::SYNCHRONOUS, staticSumFunction); bt.stop(); cout << "Time to connect: " << bt.getElapsedMilliseconds() << "ms" << endl; cout << "Emitting signal" << endl; bt.start(); testSignal(1, 2); bt.stop(); cout << "Time to emit: " << bt.getElapsedMilliseconds() << "ms" << endl; ASSERT_EQ(globalStaticIntX, 3); ASSERT_EQ(0, id); testSignal.disconnectSlot(0); } TEST_F(SignalTest, DeferredSynchronousSignal) { cout << "Instantiating signal object" << endl; Signal<int, int> testSignal; BasicTimer bt; cout << "Connecting signal" << endl; bt.start(); testSignal.connectSlot(ExecutorScheme::DEFERRED_SYNCHRONOUS, staticSumFunction); bt.stop(); cout << "Time to connect: " << bt.getElapsedMilliseconds() << "ms" << endl; cout << "Emitting signal" << endl; bt.start(); testSignal(1, 2); bt.stop(); cout << "Time to emit: " << bt.getElapsedMilliseconds() << "ms" << endl; ASSERT_NE(globalStaticIntX, 3); testSignal.invokeDeferred(); ASSERT_EQ(globalStaticIntX, 3); testSignal.disconnectSlot(0); } TEST_F(SignalTest, AsynchronousSignal) { cout << "Instantiating signal object" << endl; Signal<int, int> testSignal; BasicTimer bt; BasicTimer bt2; cout << "Connecting signal" << endl; bt.start(); int id = testSignal.connectSlot(ExecutorScheme::ASYNCHRONOUS, staticSumFunction); bt.stop(); cout << "Time to connect: " << bt.getElapsedMilliseconds() << "ms" << endl; cout << "Emitting signal" << endl; bt.start(); bt2.start(); testSignal.emitSignal(1, 2); bt.stop(); while (bt2.getElapsedSeconds() < 0.1) { if (globalStaticIntX == 3) { bt2.stop(); break; } } ASSERT_LT(bt2.getElapsedSeconds(), 0.1); ASSERT_EQ(globalStaticIntX, 3); cout << "Time to emit: " << bt.getElapsedMilliseconds() << "ms" << endl; cout << "Time to emit and process: " << bt2.getElapsedMilliseconds() << "ms" << endl; cout << "Net time to process: " << bt2.getElapsedMilliseconds() - bt.getElapsedMilliseconds() << "ms" << endl; ASSERT_EQ(0, id); testSignal.disconnectSlot(0); } TEST_F(SignalTest, StrandSignal) { cout << "Instantiating signal object" << endl; Signal<int, int> testSignal; BasicTimer bt; BasicTimer bt2; cout << "Connecting signal" << endl; bt.start(); int id = testSignal.connectSlot(ExecutorScheme::STRAND, staticSumFunction); bt.stop(); cout << "Time to connect: " << bt.getElapsedMilliseconds() << "ms" << endl; cout << "Emitting signal" << endl; bt.start(); bt2.start(); testSignal.emitSignal(1, 2); bt.stop(); while (bt2.getElapsedSeconds() < 0.1) { if (globalStaticIntX == 3) { bt2.stop(); break; } } ASSERT_LT(bt2.getElapsedSeconds(), 0.1); ASSERT_EQ(globalStaticIntX, 3); cout << "Time to emit: " << bt.getElapsedMilliseconds() << "ms" << endl; cout << "Time to emit and process: " << bt2.getElapsedMilliseconds() << "ms" << endl; cout << "Net time to process: " << bt2.getElapsedMilliseconds() - bt.getElapsedMilliseconds() << "ms" << endl; ASSERT_EQ(0, id); testSignal.disconnectAllSlots(); } TEST_F(SignalTest, MultipleConnectionTypes) { cout << "Testing multiple connection types for single signal" << endl; Signal<BigThing> testSignal; cout << "Connecting signals" << endl; list<int> ids; ids.push_back(testSignal.connectSlot(ExecutorScheme::SYNCHRONOUS, pushToQueue)); ids.push_back(testSignal.connectSlot(ExecutorScheme::ASYNCHRONOUS, pushToQueue)); ids.push_back(testSignal.connectSlot(ExecutorScheme::STRAND, pushToQueue)); cout << "Emitting signal" << endl; BasicTimer bt; BasicTimer bt2; bt.start(); bt2.start(); BigThing bigthing; for (uint32_t i = 0; i < 10; i++) { testSignal.emitSignal(bigthing); } bt2.stop(); cout << "Dequeueing" << endl; for (int i = 0; i < 30; i++) { sq.dequeue(); } bt.stop(); cout << "Signals emitted" << endl; cout << "Total time for emission: " << bt2.getElapsedMilliseconds() << "ms" << endl; cout << "Total time for emission and processing: " << bt.getElapsedMilliseconds() << "ms" << endl; cout << "Average emission+processing time: " << bt.getElapsedMilliseconds() / 10.0 << "ms" << endl; ASSERT_LT(bt2.getElapsedSeconds(), 0.1); ASSERT_LT(bt.getElapsedSeconds(), 0.2); } class TestClass { public: TestClass() { counter = 0; internalSignal.connectMemberSlot(ExecutorScheme::SYNCHRONOUS, &TestClass::incrementCounter, this); } ~TestClass() { } void dostuff(int a) { cout << "Incrementing by " << a << endl; counter++; cout << "Result: " << counter << endl; } void dostuffconst(int a) const { cout << "Incrementing by " << a << endl; counter++; cout << "Result: " << counter << endl; } void emitIncrement() { cout << "Emitting increment signal from within class" << endl; internalSignal.emitSignal(1); cout << "Result: " << counter << endl; } void incrementCounter(uint32_t amount) { counter += amount; } uint32_t getCounter() { return counter; } uint32_t getCounter() const { return counter; } mutable atomic<uint32_t> counter; Signal<uint32_t> internalSignal; }; TEST_F(SignalTest, MemberFunction) { TestClass tc; Signal<int> testSignal; testSignal.connectMemberSlot(ExecutorScheme::SYNCHRONOUS, &TestClass::dostuff, tc); testSignal.connectMemberSlot(ExecutorScheme::SYNCHRONOUS, &TestClass::dostuffconst, tc); testSignal.emitSignal(1); ASSERT_EQ(tc.getCounter(), 2u); tc.emitIncrement(); ASSERT_EQ(tc.getCounter(), 3u); testSignal.connectMemberSlot(ExecutorScheme::SYNCHRONOUS, &TestClass::dostuff, &tc); testSignal.emitSignal(1); ASSERT_EQ(tc.getCounter(), 6u); const Signal<int> testSignal2; testSignal2.connectMemberSlot(ExecutorScheme::SYNCHRONOUS, &TestClass::dostuffconst, tc); testSignal2.emitSignal(1); ASSERT_EQ(tc.getCounter(), 7u); const TestClass tc2; testSignal2.connectMemberSlot(ExecutorScheme::SYNCHRONOUS, &TestClass::dostuffconst, tc2); testSignal2.connectMemberSlot(ExecutorScheme::SYNCHRONOUS, &TestClass::dostuffconst, &tc2); testSignal2.emitSignal(1); ASSERT_EQ(tc2.getCounter(), 2u); } TEST_F(SignalTest, MultiEmit){ cout << "Instantiating signal object" << endl; Signal<int, int> testSignal; BasicTimer bt; BasicTimer bt2; cout << "Connecting signal" << endl; bt.start(); int id = testSignal.connectSlot(ExecutorScheme::STRAND, staticSumFunction); bt.stop(); cout << "Time to connect: " << bt.getElapsedMilliseconds() << "ms" << endl; cout << "Emitting signal" << endl; bt.start(); list<thread> threads; std::atomic<uint32_t> threadsRemaining{64}; for (uint32_t i=0; i<64; i++){ threads.emplace_back([&, i](){ for (uint32_t i=0; i<100000; ++i){ testSignal.emitSignal(1, 2); } uint32_t tr = threadsRemaining.fetch_sub(1); cout << "Threads remaining: " << tr-1 << endl; cout << "globalStaticInt: " << globalStaticIntX << endl; }); } bt.stop(); bt2.start(); while (bt2.getElapsedSeconds() < 60.0) { if (globalStaticIntX == 100000*3*64) { bt2.stop(); break; } std::this_thread::sleep_for(std::chrono::milliseconds(100)); } //ASSERT_LT(bt2.getElapsedSeconds(), 0.1); cout << "Time to emit: " << bt.getElapsedMilliseconds() << "ms" << endl; cout << "Time to emit and process: " << bt2.getElapsedMilliseconds() << "ms" << endl; cout << "Net time to process: " << bt2.getElapsedMilliseconds() - bt.getElapsedMilliseconds() << "ms" << endl; ASSERT_EQ(0, id); testSignal.disconnectAllSlots(); for (auto &t : threads) t.join(); } TEST_P(SignalTestParametrized, IntenseUsage) { auto tupleParams = GetParam(); SignalTestParameters params = {::testing::get<0>(tupleParams), ::testing::get<1>(tupleParams), ::testing::get<2>(tupleParams), ::testing::get<3>(tupleParams), ::testing::get<4>(tupleParams)}; BasicTimer bt, bt2; cout << "Intense usage test for signal type: "; switch (params.scheme) { case (ExecutorScheme::DEFERRED_SYNCHRONOUS): return; case(ExecutorScheme::ASYNCHRONOUS): cout << "Asynchronous"; break; case(ExecutorScheme::STRAND): cout << "Strand"; break; case(ExecutorScheme::SYNCHRONOUS): cout << "Synchronous"; break; case (ExecutorScheme::THREAD_POOLED): cout << "Thread Pooled"; break; } cout << endl; uint32_t counter = 0; atomic<uint32_t> completedFunctions; completedFunctions = 0; cout << "Emissions: " << params.nEmissions << ", Connections: " << params.nConnections << ", Operations: " << params.nOperations << ", Thread Safe: " << params.threadSafe << endl; typedef uint32_t sigType; auto func = ([&params, &completedFunctions](sigType x) { volatile sigType v = x; for (uint32_t i = 0; i < params.nOperations; i++) { v+=x; } completedFunctions++; }); // // bt.start(); // for (uint32_t i = 0; i < 100; i++) { // func(sigType{i}); // } // bt.stop(); // completedFunctions -= 100; // cout << "Function runtime overhead: " << bt.getElapsedNanoseconds() / 100 << "ns" << endl; Signal<sigType> signal(params.threadSafe); cout << "Connecting " << params.nConnections << " functions" << endl; for (uint32_t i = 0; i < params.nConnections; i++) { signal.connectSlot(params.scheme, func); } FunctionTimeRegular<> printer([this, &counter, &completedFunctions, &bt, &bt2, &params]() { cout << "Total elements emitted: " << counter << " / " << params.nEmissions << fixed << endl; cout << "Emission rate: " << (double) counter / bt.getElapsedMilliseconds() << fixed << "m/ms" << endl; cout << "Total elements processed: " << completedFunctions << " / " << params.nEmissions * params.nConnections << fixed << endl; cout << "Operation rate: " << (double) completedFunctions * params.nOperations / bt2.getElapsedNanoseconds() << "m/ns" << endl; return (bt2.getElapsedSeconds() < 6000); }, std::chrono::milliseconds(500)); FunctionTimeRegular<> checkFinished([this, &params, &completedFunctions]() { return (completedFunctions != params.nEmissions * params.nConnections); }, std::chrono::milliseconds(1)); cout << "Starting emission thread: " << endl; thread emitter([&params, &signal, &bt, &bt2, &counter]() { sigType emitval = 1; bt2.start(); bt.start(); for (uint32_t i=0; i<params.nEmissions; i++) { signal.emitSignal(emitval); counter++; } bt.stop(); }); cout << "Emission thread spawned" << endl; cout.precision(std::numeric_limits<double>::max_digits10); emitter.join(); cout << "Emission completed" << endl; checkFinished.join(); bt2.stop(); printer.stopAndJoin(); cout << "Processing completed" << endl; cout << "Emission rate: " << (double) counter / bt.getElapsedMilliseconds() << fixed << "m/ms" << endl; cout << "Time to emit: " << bt.getElapsedMilliseconds() << "ms" << endl; cout << "Average emit time (overall): " << (double) bt.getElapsedNanoseconds() / (params.nEmissions) << "ns" << endl; cout << "Average emit time (per connection): " << (double) bt.getElapsedNanoseconds() / (params.nEmissions*params.nConnections) << "ns" << endl; cout << "Time to emit+process: " << bt2.getElapsedMilliseconds() << "ms" << endl; cout << "Average emit+process time (overall): " << (double) bt2.getElapsedNanoseconds() / params.nEmissions << "ns" << endl; cout << "Average emit+process time (per connection): " << (double) bt2.getElapsedNanoseconds() / (params.nEmissions*params.nConnections) << "ns" << endl; } TEST_P(SignalTestParametrized, Correctness) { auto tupleParams = GetParam(); SignalTestParameters params = {::testing::get<0>(tupleParams), ::testing::get<1>(tupleParams), ::testing::get<2>(tupleParams), ::testing::get<3>(tupleParams), ::testing::get<4>(tupleParams)}; BasicTimer bt, bt2; cout << "Intense usage test for signal type: "; switch (params.scheme) { case (ExecutorScheme::DEFERRED_SYNCHRONOUS): return; case(ExecutorScheme::ASYNCHRONOUS): cout << "Asynchronous"; break; case(ExecutorScheme::STRAND): cout << "Strand"; break; case(ExecutorScheme::SYNCHRONOUS): cout << "Synchronous"; break; case (ExecutorScheme::THREAD_POOLED): cout << "Thread Pooled"; break; } cout << endl; uint32_t counter = 0; atomic<uint32_t> completedFunctions; completedFunctions = 0; cout << "Emissions: " << params.nEmissions << ", Connections: " << params.nConnections << ", Operations: " << params.nOperations << ", Thread Safe: " << params.threadSafe << endl; typedef uint32_t sigType; std::vector<bool> doneFlags(params.nEmissions, false); auto func = ([&params, &completedFunctions, &doneFlags](sigType x) { volatile sigType v = x; for (uint32_t i = 0; i < params.nOperations; i++) { doneFlags[x] = true; v+=x; } completedFunctions++; }); Signal<sigType> signal(params.threadSafe); cout << "Connecting " << params.nConnections << " functions" << endl; for (uint32_t i = 0; i < params.nConnections; i++) { signal.connectSlot(params.scheme, func); } FunctionTimeRegular<> printer([this, &counter, &completedFunctions, &bt, &bt2, &params]() { cout << "Total elements emitted: " << counter << " / " << params.nEmissions << fixed << endl; cout << "Emission rate: " << (double) counter / bt.getElapsedMilliseconds() << fixed << "m/ms" << endl; cout << "Total elements processed: " << completedFunctions << " / " << params.nEmissions * params.nConnections << fixed << endl; cout << "Operation rate: " << (double) completedFunctions * params.nOperations / bt2.getElapsedNanoseconds() << "m/ns" << endl; return (bt2.getElapsedSeconds() < 6000); }, std::chrono::milliseconds(500)); FunctionTimeRegular<> checkFinished([this, &params, &completedFunctions]() { return (completedFunctions != params.nEmissions * params.nConnections); }, std::chrono::milliseconds(1)); cout << "Starting emission thread: " << endl; std::list<thread> emitters; thread emitter([&params, &signal, &bt, &bt2, &counter]() { bt2.start(); bt.start(); for (counter=0; counter<params.nEmissions; ++counter) { signal.emitSignal(counter); } bt.stop(); }); cout << "Emission thread spawned" << endl; cout.precision(std::numeric_limits<double>::max_digits10); emitter.join(); cout << "Emission completed" << endl; checkFinished.join(); bt2.stop(); printer.stopAndJoin(); cout << "Processing completed" << endl; cout << "Emission rate: " << (double) counter / bt.getElapsedMilliseconds() << fixed << "m/ms" << endl; cout << "Time to emit: " << bt.getElapsedMilliseconds() << "ms" << endl; cout << "Average emit time (overall): " << (double) bt.getElapsedNanoseconds() / (params.nEmissions) << "ns" << endl; cout << "Average emit time (per connection): " << (double) bt.getElapsedNanoseconds() / (params.nEmissions*params.nConnections) << "ns" << endl; cout << "Time to emit+process: " << bt2.getElapsedMilliseconds() << "ms" << endl; cout << "Average emit+process time (overall): " << (double) bt2.getElapsedNanoseconds() / params.nEmissions << "ns" << endl; cout << "Average emit+process time (per connection): " << (double) bt2.getElapsedNanoseconds() / (params.nEmissions*params.nConnections) << "ns" << endl; for (uint32_t i=0; i<params.nEmissions; i++) ASSERT_TRUE(doneFlags[i]); } TEST_P(SignalTestParametrized, LengthyUsage) { auto tupleParams = GetParam(); SignalTestParameters params = {::testing::get<0>(tupleParams), ::testing::get<1>(tupleParams), ::testing::get<2>(tupleParams), ::testing::get<3>(tupleParams)}; BasicTimer bt, bt2; cout << "Lengthy usage test for signal type: "; switch (params.scheme) { case (ExecutorScheme::DEFERRED_SYNCHRONOUS): return; case(ExecutorScheme::ASYNCHRONOUS): cout << "Asynchronous"; break; case(ExecutorScheme::STRAND): cout << "Strand"; break; case(ExecutorScheme::SYNCHRONOUS): cout << "Synchronous"; break; case (ExecutorScheme::THREAD_POOLED): cout << "Thread Pooled"; break; } cout << endl; uint32_t counter = 0; atomic<uint32_t> completedFunctions{0}; cout << "Emissions: " << params.nEmissions << ", Connections: " << params.nConnections << ", Operations: " << params.nOperations << ", Thread Safe: " << params.threadSafe << endl; typedef uint32_t sigType; auto func = ([&params, &completedFunctions](sigType x) { std::this_thread::sleep_for(std::chrono::nanoseconds(params.nOperations)); completedFunctions++; }); bt.start(); for (uint32_t i = 0; i < 100; i++) { func(sigType{i}); } bt.stop(); completedFunctions -= 100; cout << "Function runtime overhead: " << bt.getElapsedNanoseconds() / 100 << "ns" << endl; Signal<sigType> signal(params.threadSafe); cout << "Connecting " << params.nConnections << " functions" << endl; for (uint32_t i = 0; i < params.nConnections; i++) { signal.connectSlot(params.scheme, func); } FunctionTimeRegular<> printer([this, &counter, &completedFunctions, &bt, &bt2, &params]() { cout << "Total elements emitted: " << counter << " / " << params.nEmissions << fixed << endl; cout << "Emission rate: " << (double) counter / bt.getElapsedMilliseconds() << fixed << "m/ms" << endl; cout << "Total elements processed: " << completedFunctions << " / " << params.nEmissions * params.nConnections << fixed << endl; cout << "Operation rate: " << (double) completedFunctions * params.nOperations / bt2.getElapsedNanoseconds() << "m/ns" << endl; return (bt2.getElapsedSeconds() < 6000); }, std::chrono::milliseconds(500)); FunctionTimeRegular<> checkFinished([this, &params, &completedFunctions]() { return (completedFunctions != params.nEmissions * params.nConnections); }, std::chrono::milliseconds(1)); cout << "Starting emission thread: " << endl; thread emitter([&params, &signal, &bt, &bt2, &counter]() { sigType emitval = 1; bt2.start(); bt.start(); for (uint32_t i=0; i<params.nEmissions; i++) { signal.emitSignal(emitval); counter++; } bt.stop(); }); cout << "Emission thread spawned" << endl; cout.precision(std::numeric_limits<double>::max_digits10); emitter.join(); cout << "Emission completed" << endl; checkFinished.join(); bt2.stop(); printer.stopAndJoin(); cout << "Processing completed" << endl; cout << "Emission rate: " << (double) counter / bt.getElapsedMilliseconds() << fixed << "m/ms" << endl; cout << "Time to emit: " << bt.getElapsedMilliseconds() << "ms" << endl; cout << "Average emit time (overall): " << (double) bt.getElapsedNanoseconds() / (params.nEmissions) << "ns" << endl; cout << "Average emit time (per connection): " << (double) bt.getElapsedNanoseconds() / (params.nEmissions*params.nConnections) << "ns" << endl; cout << "Time to emit+process: " << bt2.getElapsedMilliseconds() << "ms" << endl; cout << "Average emit+process time (overall): " << (double) bt2.getElapsedNanoseconds() / params.nEmissions << "ns" << endl; cout << "Average emit+process time (per connection): " << (double) bt2.getElapsedNanoseconds() / (params.nEmissions*params.nConnections) << "ns" << endl; } INSTANTIATE_TEST_CASE_P( SignalTest_Benchmark_Synchronous, SignalTestParametrized, testing::Combine( Values(1, 10, 50), //number of connections Values(10, 1000, 10000), //number of emissions per connection Values(1, 10, 100, 1000, 10000, 50000, 1000000), //number of operations in each function Values(false), Values(ExecutorScheme::SYNCHRONOUS) ) ); INSTANTIATE_TEST_CASE_P( SignalTest_Benchmark_Asynchronous, SignalTestParametrized, testing::Combine( Values(1, 10, 50), //number of connections Values(10, 1000, 10000), //number of emissions per connection Values(1, 10, 100, 1000, 10000, 50000, 1000000), //number of operations in each function Values(false), Values(ExecutorScheme::ASYNCHRONOUS) ) ); INSTANTIATE_TEST_CASE_P( SignalTest_Benchmark_Strand, SignalTestParametrized, testing::Combine( Values(1, 10, 50), //number of connections Values(10, 1000, 10000), //number of emissions per connection Values(1, 10, 100, 1000, 10000, 50000, 1000000), //number of operations in each function Values(false), Values(ExecutorScheme::STRAND) ) ); INSTANTIATE_TEST_CASE_P( SignalTest_Benchmark_ThreadPooled, SignalTestParametrized, testing::Combine( Values(1, 10, 50), //number of connections Values(10, 1000, 10000), //number of emissions per connection Values(1, 10, 100, 1000, 10000, 50000, 1000000), //number of operations in each function Values(false), Values(ExecutorScheme::THREAD_POOLED) ) ); INSTANTIATE_TEST_CASE_P( SignalTest_Benchmark_PureEmission, SignalTestParametrized, testing::Combine( Values(1), //nconnections Values(100000), //number of emissions Values(1), //number of operations Values(true, false), Values(ExecutorScheme::SYNCHRONOUS, ExecutorScheme::ASYNCHRONOUS, ExecutorScheme::STRAND, ExecutorScheme::THREAD_POOLED) ) ); correctness test fix #include "SignalTest.h" #include <iostream> #include <list> #include <vector> #include <thread> #include <atomic> #include "BSignals/details/BasicTimer.h" #include "SafeQueue.hpp" #include "FunctionTimeRegular.hpp" using BSignals::details::SafeQueue; using BSignals::details::BasicTimer; using std::cout; using std::endl; using ::testing::Values; using std::list; using std::vector; using std::thread; using std::atomic; using std::fixed; using BSignals::Signal; using BSignals::ExecutorScheme; std::atomic<int> globalStaticIntX{0}; struct BigThing { char thing[512]; }; SafeQueue<BigThing> sq; void SignalTest::SetUp() { globalStaticIntX = 0; } void SignalTest::TearDown() { } void pushToQueue(BigThing bt) { sq.enqueue(bt); } void staticSumFunction(int a, int b) { globalStaticIntX += a + b; //cout << a << " + " << b << " = " << globalStaticIntX << endl; } TEST_F(SignalTest, SynchronousSignal) { cout << "Instantiating signal object" << endl; Signal<int, int> testSignal; BasicTimer bt; cout << "Connecting signal" << endl; bt.start(); int id = testSignal.connectSlot(ExecutorScheme::SYNCHRONOUS, staticSumFunction); bt.stop(); cout << "Time to connect: " << bt.getElapsedMilliseconds() << "ms" << endl; cout << "Emitting signal" << endl; bt.start(); testSignal(1, 2); bt.stop(); cout << "Time to emit: " << bt.getElapsedMilliseconds() << "ms" << endl; ASSERT_EQ(globalStaticIntX, 3); ASSERT_EQ(0, id); testSignal.disconnectSlot(0); } TEST_F(SignalTest, DeferredSynchronousSignal) { cout << "Instantiating signal object" << endl; Signal<int, int> testSignal; BasicTimer bt; cout << "Connecting signal" << endl; bt.start(); testSignal.connectSlot(ExecutorScheme::DEFERRED_SYNCHRONOUS, staticSumFunction); bt.stop(); cout << "Time to connect: " << bt.getElapsedMilliseconds() << "ms" << endl; cout << "Emitting signal" << endl; bt.start(); testSignal(1, 2); bt.stop(); cout << "Time to emit: " << bt.getElapsedMilliseconds() << "ms" << endl; ASSERT_NE(globalStaticIntX, 3); testSignal.invokeDeferred(); ASSERT_EQ(globalStaticIntX, 3); testSignal.disconnectSlot(0); } TEST_F(SignalTest, AsynchronousSignal) { cout << "Instantiating signal object" << endl; Signal<int, int> testSignal; BasicTimer bt; BasicTimer bt2; cout << "Connecting signal" << endl; bt.start(); int id = testSignal.connectSlot(ExecutorScheme::ASYNCHRONOUS, staticSumFunction); bt.stop(); cout << "Time to connect: " << bt.getElapsedMilliseconds() << "ms" << endl; cout << "Emitting signal" << endl; bt.start(); bt2.start(); testSignal.emitSignal(1, 2); bt.stop(); while (bt2.getElapsedSeconds() < 0.1) { if (globalStaticIntX == 3) { bt2.stop(); break; } } ASSERT_LT(bt2.getElapsedSeconds(), 0.1); ASSERT_EQ(globalStaticIntX, 3); cout << "Time to emit: " << bt.getElapsedMilliseconds() << "ms" << endl; cout << "Time to emit and process: " << bt2.getElapsedMilliseconds() << "ms" << endl; cout << "Net time to process: " << bt2.getElapsedMilliseconds() - bt.getElapsedMilliseconds() << "ms" << endl; ASSERT_EQ(0, id); testSignal.disconnectSlot(0); } TEST_F(SignalTest, StrandSignal) { cout << "Instantiating signal object" << endl; Signal<int, int> testSignal; BasicTimer bt; BasicTimer bt2; cout << "Connecting signal" << endl; bt.start(); int id = testSignal.connectSlot(ExecutorScheme::STRAND, staticSumFunction); bt.stop(); cout << "Time to connect: " << bt.getElapsedMilliseconds() << "ms" << endl; cout << "Emitting signal" << endl; bt.start(); bt2.start(); testSignal.emitSignal(1, 2); bt.stop(); while (bt2.getElapsedSeconds() < 0.1) { if (globalStaticIntX == 3) { bt2.stop(); break; } } ASSERT_LT(bt2.getElapsedSeconds(), 0.1); ASSERT_EQ(globalStaticIntX, 3); cout << "Time to emit: " << bt.getElapsedMilliseconds() << "ms" << endl; cout << "Time to emit and process: " << bt2.getElapsedMilliseconds() << "ms" << endl; cout << "Net time to process: " << bt2.getElapsedMilliseconds() - bt.getElapsedMilliseconds() << "ms" << endl; ASSERT_EQ(0, id); testSignal.disconnectAllSlots(); } TEST_F(SignalTest, MultipleConnectionTypes) { cout << "Testing multiple connection types for single signal" << endl; Signal<BigThing> testSignal; cout << "Connecting signals" << endl; list<int> ids; ids.push_back(testSignal.connectSlot(ExecutorScheme::SYNCHRONOUS, pushToQueue)); ids.push_back(testSignal.connectSlot(ExecutorScheme::ASYNCHRONOUS, pushToQueue)); ids.push_back(testSignal.connectSlot(ExecutorScheme::STRAND, pushToQueue)); cout << "Emitting signal" << endl; BasicTimer bt; BasicTimer bt2; bt.start(); bt2.start(); BigThing bigthing; for (uint32_t i = 0; i < 10; i++) { testSignal.emitSignal(bigthing); } bt2.stop(); cout << "Dequeueing" << endl; for (int i = 0; i < 30; i++) { sq.dequeue(); } bt.stop(); cout << "Signals emitted" << endl; cout << "Total time for emission: " << bt2.getElapsedMilliseconds() << "ms" << endl; cout << "Total time for emission and processing: " << bt.getElapsedMilliseconds() << "ms" << endl; cout << "Average emission+processing time: " << bt.getElapsedMilliseconds() / 10.0 << "ms" << endl; ASSERT_LT(bt2.getElapsedSeconds(), 0.1); ASSERT_LT(bt.getElapsedSeconds(), 0.2); } class TestClass { public: TestClass() { counter = 0; internalSignal.connectMemberSlot(ExecutorScheme::SYNCHRONOUS, &TestClass::incrementCounter, this); } ~TestClass() { } void dostuff(int a) { cout << "Incrementing by " << a << endl; counter++; cout << "Result: " << counter << endl; } void dostuffconst(int a) const { cout << "Incrementing by " << a << endl; counter++; cout << "Result: " << counter << endl; } void emitIncrement() { cout << "Emitting increment signal from within class" << endl; internalSignal.emitSignal(1); cout << "Result: " << counter << endl; } void incrementCounter(uint32_t amount) { counter += amount; } uint32_t getCounter() { return counter; } uint32_t getCounter() const { return counter; } mutable atomic<uint32_t> counter; Signal<uint32_t> internalSignal; }; TEST_F(SignalTest, MemberFunction) { TestClass tc; Signal<int> testSignal; testSignal.connectMemberSlot(ExecutorScheme::SYNCHRONOUS, &TestClass::dostuff, tc); testSignal.connectMemberSlot(ExecutorScheme::SYNCHRONOUS, &TestClass::dostuffconst, tc); testSignal.emitSignal(1); ASSERT_EQ(tc.getCounter(), 2u); tc.emitIncrement(); ASSERT_EQ(tc.getCounter(), 3u); testSignal.connectMemberSlot(ExecutorScheme::SYNCHRONOUS, &TestClass::dostuff, &tc); testSignal.emitSignal(1); ASSERT_EQ(tc.getCounter(), 6u); const Signal<int> testSignal2; testSignal2.connectMemberSlot(ExecutorScheme::SYNCHRONOUS, &TestClass::dostuffconst, tc); testSignal2.emitSignal(1); ASSERT_EQ(tc.getCounter(), 7u); const TestClass tc2; testSignal2.connectMemberSlot(ExecutorScheme::SYNCHRONOUS, &TestClass::dostuffconst, tc2); testSignal2.connectMemberSlot(ExecutorScheme::SYNCHRONOUS, &TestClass::dostuffconst, &tc2); testSignal2.emitSignal(1); ASSERT_EQ(tc2.getCounter(), 2u); } TEST_F(SignalTest, MultiEmit){ cout << "Instantiating signal object" << endl; Signal<int, int> testSignal; BasicTimer bt; BasicTimer bt2; cout << "Connecting signal" << endl; bt.start(); int id = testSignal.connectSlot(ExecutorScheme::STRAND, staticSumFunction); bt.stop(); cout << "Time to connect: " << bt.getElapsedMilliseconds() << "ms" << endl; cout << "Emitting signal" << endl; bt.start(); list<thread> threads; std::atomic<uint32_t> threadsRemaining{64}; for (uint32_t i=0; i<64; i++){ threads.emplace_back([&, i](){ for (uint32_t i=0; i<100000; ++i){ testSignal.emitSignal(1, 2); } uint32_t tr = threadsRemaining.fetch_sub(1); cout << "Threads remaining: " << tr-1 << endl; cout << "globalStaticInt: " << globalStaticIntX << endl; }); } bt.stop(); bt2.start(); while (bt2.getElapsedSeconds() < 60.0) { if (globalStaticIntX == 100000*3*64) { bt2.stop(); break; } std::this_thread::sleep_for(std::chrono::milliseconds(100)); } //ASSERT_LT(bt2.getElapsedSeconds(), 0.1); cout << "Time to emit: " << bt.getElapsedMilliseconds() << "ms" << endl; cout << "Time to emit and process: " << bt2.getElapsedMilliseconds() << "ms" << endl; cout << "Net time to process: " << bt2.getElapsedMilliseconds() - bt.getElapsedMilliseconds() << "ms" << endl; ASSERT_EQ(0, id); testSignal.disconnectAllSlots(); for (auto &t : threads) t.join(); } TEST_P(SignalTestParametrized, IntenseUsage) { auto tupleParams = GetParam(); SignalTestParameters params = {::testing::get<0>(tupleParams), ::testing::get<1>(tupleParams), ::testing::get<2>(tupleParams), ::testing::get<3>(tupleParams), ::testing::get<4>(tupleParams)}; BasicTimer bt, bt2; cout << "Intense usage test for signal type: "; switch (params.scheme) { case (ExecutorScheme::DEFERRED_SYNCHRONOUS): return; case(ExecutorScheme::ASYNCHRONOUS): cout << "Asynchronous"; break; case(ExecutorScheme::STRAND): cout << "Strand"; break; case(ExecutorScheme::SYNCHRONOUS): cout << "Synchronous"; break; case (ExecutorScheme::THREAD_POOLED): cout << "Thread Pooled"; break; } cout << endl; uint32_t counter = 0; atomic<uint32_t> completedFunctions; completedFunctions = 0; cout << "Emissions: " << params.nEmissions << ", Connections: " << params.nConnections << ", Operations: " << params.nOperations << ", Thread Safe: " << params.threadSafe << endl; typedef uint32_t sigType; auto func = ([&params, &completedFunctions](sigType x) { volatile sigType v = x; for (uint32_t i = 0; i < params.nOperations; i++) { v+=x; } completedFunctions++; }); // // bt.start(); // for (uint32_t i = 0; i < 100; i++) { // func(sigType{i}); // } // bt.stop(); // completedFunctions -= 100; // cout << "Function runtime overhead: " << bt.getElapsedNanoseconds() / 100 << "ns" << endl; Signal<sigType> signal(params.threadSafe); cout << "Connecting " << params.nConnections << " functions" << endl; for (uint32_t i = 0; i < params.nConnections; i++) { signal.connectSlot(params.scheme, func); } FunctionTimeRegular<> printer([this, &counter, &completedFunctions, &bt, &bt2, &params]() { cout << "Total elements emitted: " << counter << " / " << params.nEmissions << fixed << endl; cout << "Emission rate: " << (double) counter / bt.getElapsedMilliseconds() << fixed << "m/ms" << endl; cout << "Total elements processed: " << completedFunctions << " / " << params.nEmissions * params.nConnections << fixed << endl; cout << "Operation rate: " << (double) completedFunctions * params.nOperations / bt2.getElapsedNanoseconds() << "m/ns" << endl; return (bt2.getElapsedSeconds() < 6000); }, std::chrono::milliseconds(500)); FunctionTimeRegular<> checkFinished([this, &params, &completedFunctions]() { return (completedFunctions != params.nEmissions * params.nConnections); }, std::chrono::milliseconds(1)); cout << "Starting emission thread: " << endl; thread emitter([&params, &signal, &bt, &bt2, &counter]() { sigType emitval = 1; bt2.start(); bt.start(); for (uint32_t i=0; i<params.nEmissions; i++) { signal.emitSignal(emitval); counter++; } bt.stop(); }); cout << "Emission thread spawned" << endl; cout.precision(std::numeric_limits<double>::max_digits10); emitter.join(); cout << "Emission completed" << endl; checkFinished.join(); bt2.stop(); printer.stopAndJoin(); cout << "Processing completed" << endl; cout << "Emission rate: " << (double) counter / bt.getElapsedMilliseconds() << fixed << "m/ms" << endl; cout << "Time to emit: " << bt.getElapsedMilliseconds() << "ms" << endl; cout << "Average emit time (overall): " << (double) bt.getElapsedNanoseconds() / (params.nEmissions) << "ns" << endl; cout << "Average emit time (per connection): " << (double) bt.getElapsedNanoseconds() / (params.nEmissions*params.nConnections) << "ns" << endl; cout << "Time to emit+process: " << bt2.getElapsedMilliseconds() << "ms" << endl; cout << "Average emit+process time (overall): " << (double) bt2.getElapsedNanoseconds() / params.nEmissions << "ns" << endl; cout << "Average emit+process time (per connection): " << (double) bt2.getElapsedNanoseconds() / (params.nEmissions*params.nConnections) << "ns" << endl; } TEST_P(SignalTestParametrized, Correctness) { auto tupleParams = GetParam(); SignalTestParameters params = {::testing::get<0>(tupleParams), ::testing::get<1>(tupleParams), ::testing::get<2>(tupleParams), ::testing::get<3>(tupleParams), ::testing::get<4>(tupleParams)}; BasicTimer bt, bt2; cout << "Intense usage test for signal type: "; switch (params.scheme) { case (ExecutorScheme::DEFERRED_SYNCHRONOUS): return; case(ExecutorScheme::ASYNCHRONOUS): cout << "Asynchronous"; break; case(ExecutorScheme::STRAND): cout << "Strand"; break; case(ExecutorScheme::SYNCHRONOUS): cout << "Synchronous"; break; case (ExecutorScheme::THREAD_POOLED): cout << "Thread Pooled"; break; } cout << endl; uint32_t counter = 0; atomic<uint32_t> completedFunctions; completedFunctions = 0; cout << "Emissions: " << params.nEmissions << ", Connections: " << params.nConnections << ", Operations: " << params.nOperations << ", Thread Safe: " << params.threadSafe << endl; typedef uint32_t sigType; std::vector<bool> doneFlags(params.nEmissions, false); auto func = ([&params, &completedFunctions, &doneFlags](sigType x) { volatile sigType v = x; for (uint32_t i = 0; i < params.nOperations; i++) { v+=x; } doneFlags[x] = true; completedFunctions++; }); Signal<sigType> signal(params.threadSafe); cout << "Connecting " << params.nConnections << " functions" << endl; for (uint32_t i = 0; i < params.nConnections; i++) { signal.connectSlot(params.scheme, func); } FunctionTimeRegular<> printer([this, &counter, &completedFunctions, &bt, &bt2, &params]() { cout << "Total elements emitted: " << counter << " / " << params.nEmissions << fixed << endl; cout << "Emission rate: " << (double) counter / bt.getElapsedMilliseconds() << fixed << "m/ms" << endl; cout << "Total elements processed: " << completedFunctions << " / " << params.nEmissions * params.nConnections << fixed << endl; cout << "Operation rate: " << (double) completedFunctions * params.nOperations / bt2.getElapsedNanoseconds() << "m/ns" << endl; return (bt2.getElapsedSeconds() < 6000); }, std::chrono::milliseconds(500)); FunctionTimeRegular<> checkFinished([this, &params, &completedFunctions]() { return (completedFunctions != params.nEmissions * params.nConnections); }, std::chrono::milliseconds(1)); cout << "Starting emission thread: " << endl; std::list<thread> emitters; thread emitter([&params, &signal, &bt, &bt2, &counter]() { bt2.start(); bt.start(); for (counter=0; counter<params.nEmissions; ++counter) { signal.emitSignal(counter); } bt.stop(); }); cout << "Emission thread spawned" << endl; cout.precision(std::numeric_limits<double>::max_digits10); emitter.join(); cout << "Emission completed" << endl; checkFinished.join(); bt2.stop(); printer.stopAndJoin(); cout << "Processing completed" << endl; cout << "Emission rate: " << (double) counter / bt.getElapsedMilliseconds() << fixed << "m/ms" << endl; cout << "Time to emit: " << bt.getElapsedMilliseconds() << "ms" << endl; cout << "Average emit time (overall): " << (double) bt.getElapsedNanoseconds() / (params.nEmissions) << "ns" << endl; cout << "Average emit time (per connection): " << (double) bt.getElapsedNanoseconds() / (params.nEmissions*params.nConnections) << "ns" << endl; cout << "Time to emit+process: " << bt2.getElapsedMilliseconds() << "ms" << endl; cout << "Average emit+process time (overall): " << (double) bt2.getElapsedNanoseconds() / params.nEmissions << "ns" << endl; cout << "Average emit+process time (per connection): " << (double) bt2.getElapsedNanoseconds() / (params.nEmissions*params.nConnections) << "ns" << endl; for (uint32_t i=0; i<params.nEmissions; i++) ASSERT_TRUE(doneFlags[i]); } TEST_P(SignalTestParametrized, LengthyUsage) { auto tupleParams = GetParam(); SignalTestParameters params = {::testing::get<0>(tupleParams), ::testing::get<1>(tupleParams), ::testing::get<2>(tupleParams), ::testing::get<3>(tupleParams)}; BasicTimer bt, bt2; cout << "Lengthy usage test for signal type: "; switch (params.scheme) { case (ExecutorScheme::DEFERRED_SYNCHRONOUS): return; case(ExecutorScheme::ASYNCHRONOUS): cout << "Asynchronous"; break; case(ExecutorScheme::STRAND): cout << "Strand"; break; case(ExecutorScheme::SYNCHRONOUS): cout << "Synchronous"; break; case (ExecutorScheme::THREAD_POOLED): cout << "Thread Pooled"; break; } cout << endl; uint32_t counter = 0; atomic<uint32_t> completedFunctions{0}; cout << "Emissions: " << params.nEmissions << ", Connections: " << params.nConnections << ", Operations: " << params.nOperations << ", Thread Safe: " << params.threadSafe << endl; typedef uint32_t sigType; auto func = ([&params, &completedFunctions](sigType x) { std::this_thread::sleep_for(std::chrono::nanoseconds(params.nOperations)); completedFunctions++; }); bt.start(); for (uint32_t i = 0; i < 100; i++) { func(sigType{i}); } bt.stop(); completedFunctions -= 100; cout << "Function runtime overhead: " << bt.getElapsedNanoseconds() / 100 << "ns" << endl; Signal<sigType> signal(params.threadSafe); cout << "Connecting " << params.nConnections << " functions" << endl; for (uint32_t i = 0; i < params.nConnections; i++) { signal.connectSlot(params.scheme, func); } FunctionTimeRegular<> printer([this, &counter, &completedFunctions, &bt, &bt2, &params]() { cout << "Total elements emitted: " << counter << " / " << params.nEmissions << fixed << endl; cout << "Emission rate: " << (double) counter / bt.getElapsedMilliseconds() << fixed << "m/ms" << endl; cout << "Total elements processed: " << completedFunctions << " / " << params.nEmissions * params.nConnections << fixed << endl; cout << "Operation rate: " << (double) completedFunctions * params.nOperations / bt2.getElapsedNanoseconds() << "m/ns" << endl; return (bt2.getElapsedSeconds() < 6000); }, std::chrono::milliseconds(500)); FunctionTimeRegular<> checkFinished([this, &params, &completedFunctions]() { return (completedFunctions != params.nEmissions * params.nConnections); }, std::chrono::milliseconds(1)); cout << "Starting emission thread: " << endl; thread emitter([&params, &signal, &bt, &bt2, &counter]() { sigType emitval = 1; bt2.start(); bt.start(); for (uint32_t i=0; i<params.nEmissions; i++) { signal.emitSignal(emitval); counter++; } bt.stop(); }); cout << "Emission thread spawned" << endl; cout.precision(std::numeric_limits<double>::max_digits10); emitter.join(); cout << "Emission completed" << endl; checkFinished.join(); bt2.stop(); printer.stopAndJoin(); cout << "Processing completed" << endl; cout << "Emission rate: " << (double) counter / bt.getElapsedMilliseconds() << fixed << "m/ms" << endl; cout << "Time to emit: " << bt.getElapsedMilliseconds() << "ms" << endl; cout << "Average emit time (overall): " << (double) bt.getElapsedNanoseconds() / (params.nEmissions) << "ns" << endl; cout << "Average emit time (per connection): " << (double) bt.getElapsedNanoseconds() / (params.nEmissions*params.nConnections) << "ns" << endl; cout << "Time to emit+process: " << bt2.getElapsedMilliseconds() << "ms" << endl; cout << "Average emit+process time (overall): " << (double) bt2.getElapsedNanoseconds() / params.nEmissions << "ns" << endl; cout << "Average emit+process time (per connection): " << (double) bt2.getElapsedNanoseconds() / (params.nEmissions*params.nConnections) << "ns" << endl; } INSTANTIATE_TEST_CASE_P( SignalTest_Benchmark_Synchronous, SignalTestParametrized, testing::Combine( Values(1, 10, 50), //number of connections Values(10, 1000, 10000), //number of emissions per connection Values(1, 10, 100, 1000, 10000, 50000, 1000000), //number of operations in each function Values(false), Values(ExecutorScheme::SYNCHRONOUS) ) ); INSTANTIATE_TEST_CASE_P( SignalTest_Benchmark_Asynchronous, SignalTestParametrized, testing::Combine( Values(1, 10, 50), //number of connections Values(10, 1000, 10000), //number of emissions per connection Values(1, 10, 100, 1000, 10000, 50000, 1000000), //number of operations in each function Values(false), Values(ExecutorScheme::ASYNCHRONOUS) ) ); INSTANTIATE_TEST_CASE_P( SignalTest_Benchmark_Strand, SignalTestParametrized, testing::Combine( Values(1, 10, 50), //number of connections Values(10, 1000, 10000), //number of emissions per connection Values(1, 10, 100, 1000, 10000, 50000, 1000000), //number of operations in each function Values(false), Values(ExecutorScheme::STRAND) ) ); INSTANTIATE_TEST_CASE_P( SignalTest_Benchmark_ThreadPooled, SignalTestParametrized, testing::Combine( Values(1, 10, 50), //number of connections Values(10, 1000, 10000), //number of emissions per connection Values(1, 10, 100, 1000, 10000, 50000, 1000000), //number of operations in each function Values(false), Values(ExecutorScheme::THREAD_POOLED) ) ); INSTANTIATE_TEST_CASE_P( SignalTest_Benchmark_PureEmission, SignalTestParametrized, testing::Combine( Values(1), //nconnections Values(100000), //number of emissions Values(1), //number of operations Values(true, false), Values(ExecutorScheme::SYNCHRONOUS, ExecutorScheme::ASYNCHRONOUS, ExecutorScheme::STRAND, ExecutorScheme::THREAD_POOLED) ) );
#include <boost/version.hpp> #include <boost/detail/lightweight_test.hpp> #include <iostream> #include <mapnik/symbolizer.hpp> #include <vector> #include <algorithm> #include "utils.hpp" using namespace mapnik; int main(int argc, char** argv) { std::vector<std::string> args; for (int i=1;i<argc;++i) { args.push_back(argv[i]); } bool quiet = std::find(args.begin(), args.end(), "-q")!=args.end(); try { marker_multi_policy_enum policy_in = MARKER_WHOLE_MULTI; BOOST_TEST_EQ(policy_in,MARKER_WHOLE_MULTI); markers_symbolizer sym; put(sym, keys::markers_multipolicy, policy_in); BOOST_TEST_EQ(sym.properties.count(keys::markers_multipolicy),1); marker_multi_policy_enum policy_out = get<mapnik::marker_multi_policy_enum>(sym, keys::markers_multipolicy); BOOST_TEST_EQ(policy_out,MARKER_WHOLE_MULTI); } catch (...) { BOOST_TEST(true); } if (!::boost::detail::test_errors()) { if (quiet) std::clog << "\x1b[1;32m.\x1b[0m"; else std::clog << "C++ exceptions: \x1b[1;32m✓ \x1b[0m\n"; #if BOOST_VERSION >= 104600 ::boost::detail::report_errors_remind().called_report_errors_function = true; #endif } else { return ::boost::report_errors(); } } avoid signed comparison warning in symbolizer test #include <boost/version.hpp> #include <boost/detail/lightweight_test.hpp> #include <iostream> #include <mapnik/symbolizer.hpp> #include <vector> #include <algorithm> #include "utils.hpp" using namespace mapnik; int main(int argc, char** argv) { std::vector<std::string> args; for (int i=1;i<argc;++i) { args.push_back(argv[i]); } bool quiet = std::find(args.begin(), args.end(), "-q")!=args.end(); try { marker_multi_policy_enum policy_in = MARKER_WHOLE_MULTI; BOOST_TEST_EQ(policy_in,MARKER_WHOLE_MULTI); markers_symbolizer sym; put(sym, keys::markers_multipolicy, policy_in); BOOST_TEST_EQ(sym.properties.count(keys::markers_multipolicy),static_cast<unsigned long>(1)); marker_multi_policy_enum policy_out = get<mapnik::marker_multi_policy_enum>(sym, keys::markers_multipolicy); BOOST_TEST_EQ(policy_out,MARKER_WHOLE_MULTI); } catch (...) { BOOST_TEST(true); } if (!::boost::detail::test_errors()) { if (quiet) std::clog << "\x1b[1;32m.\x1b[0m"; else std::clog << "C++ exceptions: \x1b[1;32m✓ \x1b[0m\n"; #if BOOST_VERSION >= 104600 ::boost::detail::report_errors_remind().called_report_errors_function = true; #endif } else { return ::boost::report_errors(); } }
/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2016 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * ***************************************************************************** * * Initially developed by Sandro Santilli <strk@keybit.net> for CartoDB * *****************************************************************************/ #include "../postgis/connection_manager.hpp" #include "../postgis/asyncresultset.hpp" #include "pgraster_datasource.hpp" #include "pgraster_featureset.hpp" // mapnik #include <mapnik/debug.hpp> #include <mapnik/global.hpp> // for byte #include <mapnik/boolean.hpp> #include <mapnik/sql_utils.hpp> #include <mapnik/util/conversions.hpp> #include <mapnik/timer.hpp> #include <mapnik/value/types.hpp> #pragma GCC diagnostic push #include <mapnik/warning_ignore.hpp> #include <boost/algorithm/string.hpp> #include <boost/tokenizer.hpp> #pragma GCC diagnostic pop // stl #include <string> #include <algorithm> #include <set> #include <sstream> #include <iomanip> DATASOURCE_PLUGIN(pgraster_datasource) const double pgraster_datasource::FMAX = std::numeric_limits<float>::max(); const std::string pgraster_datasource::RASTER_COLUMNS = "raster_columns"; const std::string pgraster_datasource::RASTER_OVERVIEWS = "raster_overviews"; const std::string pgraster_datasource::SPATIAL_REF_SYS = "spatial_ref_system"; using std::shared_ptr; using mapnik::attribute_descriptor; using mapnik::value_integer; namespace { // TODO: move to sql_utils std::string quote_ident(std::string& s) { return "\"" + s + "\""; // TODO: escape internal quotes } }; pgraster_datasource::pgraster_datasource(parameters const& params) : datasource(params), table_(*params.get<std::string>("table", "")), schema_(""), raster_table_(*params.get<std::string>("raster_table", "")), raster_field_(*params.get<std::string>("raster_field", "")), key_field_(*params.get<std::string>("key_field", "")), cursor_fetch_size_(*params.get<mapnik::value_integer>("cursor_size", 0)), row_limit_(*params.get<value_integer>("row_limit", 0)), type_(datasource::Raster), srid_(*params.get<value_integer>("srid", 0)), band_(*params.get<value_integer>("band", 0)), extent_initialized_(false), prescale_rasters_(*params.get<mapnik::boolean_type>("prescale_rasters", false)), use_overviews_(*params.get<mapnik::boolean_type>("use_overviews", false)), clip_rasters_(*params.get<mapnik::boolean_type>("clip_rasters", false)), desc_(*params.get<std::string>("type"), "utf-8"), creator_(params.get<std::string>("host"), params.get<std::string>("port"), params.get<std::string>("dbname"), params.get<std::string>("user"), params.get<std::string>("password"), params.get<std::string>("connect_timeout", "4")), bbox_token_("!bbox!"), scale_denom_token_("!scale_denominator!"), pixel_width_token_("!pixel_width!"), pixel_height_token_("!pixel_height!"), pool_max_size_(*params_.get<value_integer>("max_size", 10)), persist_connection_(*params.get<mapnik::boolean_type>("persist_connection", true)), extent_from_subquery_(*params.get<mapnik::boolean_type>("extent_from_subquery", false)), estimate_extent_(*params.get<mapnik::boolean_type>("estimate_extent", false)), max_async_connections_(*params_.get<value_integer>("max_async_connection", 1)), asynchronous_request_(false), // params below are for testing purposes only and may be removed at any time intersect_min_scale_(*params.get<value_integer>("intersect_min_scale", 0)), intersect_max_scale_(*params.get<value_integer>("intersect_max_scale", 0)) { #ifdef MAPNIK_STATS mapnik::progress_timer __stats__(std::clog, "pgraster_datasource::init"); #endif if (table_.empty()) { throw mapnik::datasource_exception("Pgraster Plugin: missing <table> parameter"); } boost::optional<std::string> ext = params.get<std::string>("extent"); if (ext && !ext->empty()) { extent_initialized_ = extent_.from_string(*ext); } // NOTE: In multithread environment, pool_max_size_ should be // max_async_connections_ * num_threads if(max_async_connections_ > 1) { if(max_async_connections_ > pool_max_size_) { std::ostringstream err; err << "PostGIS Plugin: Error: 'max_async_connections (" << max_async_connections_ << ") must be <= max_size(" << pool_max_size_ << ")"; throw mapnik::datasource_exception(err.str()); } asynchronous_request_ = true; } boost::optional<value_integer> initial_size = params.get<value_integer>("initial_size", 1); boost::optional<mapnik::boolean_type> autodetect_key_field = params.get<mapnik::boolean_type>("autodetect_key_field", false); ConnectionManager::instance().registerPool(creator_, *initial_size, pool_max_size_); CnxPool_ptr pool = ConnectionManager::instance().getPool(creator_.id()); if (pool) { shared_ptr<Connection> conn = pool->borrowObject(); if (!conn) return; if (conn->isOK()) { desc_.set_encoding(conn->client_encoding()); if (raster_table_.empty()) { raster_table_ = mapnik::sql_utils::table_from_sql(table_); // non-trivial subqueries (having no FROM) make it // impossible to use overviews // TODO: improve "table_from_sql" ? if ( raster_table_[raster_table_.find_first_not_of(" \t\r\n")] == '(' ) { raster_table_.clear(); if ( use_overviews_ ) { std::ostringstream err; err << "Pgraster Plugin: overviews cannot be used " "with non-trivial subqueries"; MAPNIK_LOG_WARN(pgraster) << err.str(); use_overviews_ = false; } if ( ! extent_from_subquery_ ) { std::ostringstream err; err << "Pgraster Plugin: extent can only be computed " "from subquery as we could not found table source"; MAPNIK_LOG_WARN(pgraster) << err.str(); extent_from_subquery_ = true; } } } std::string::size_type idx = raster_table_.find_last_of('.'); if (idx != std::string::npos) { schema_ = raster_table_.substr(0, idx); raster_table_ = raster_table_.substr(idx + 1); } // If we do not know either the geometry_field or the srid or we // want to use overviews but do not know about schema, or // no extent was specified, then attempt to fetch the missing // information from a raster_columns entry. // // This will return no records if we are querying a bogus table returned // from the simplistic table parsing in table_from_sql() or if // the table parameter references a table, view, or subselect not // registered in the geometry columns. // geometryColumn_ = mapnik::sql_utils::unquote_double(raster_field_); if (!raster_table_.empty() && ( geometryColumn_.empty() || srid_ == 0 || (schema_.empty() && use_overviews_) || ! extent_initialized_ )) { #ifdef MAPNIK_STATS mapnik::progress_timer __stats2__(std::clog, "pgraster_datasource::init(get_srid_and_geometry_column)"); #endif std::ostringstream s; try { s << "SELECT r_raster_column col, srid, r_table_schema"; if ( ! extent_initialized_ ) { s << ", st_xmin(extent) xmin, st_ymin(extent) ymin" << ", st_xmax(extent) xmax, st_ymax(extent) ymax"; } s << " FROM " << RASTER_COLUMNS << " WHERE r_table_name='" << mapnik::sql_utils::unquote_double(raster_table_) << "'"; if (! schema_.empty()) { s << " AND r_table_schema='" << mapnik::sql_utils::unquote_double(schema_) << "'"; } if (! raster_field_.empty()) { s << " AND r_raster_column='" << mapnik::sql_utils::unquote_double(raster_field_) << "'"; } MAPNIK_LOG_DEBUG(pgraster) << "pgraster_datasource: running query " << s.str(); shared_ptr<ResultSet> rs = conn->executeQuery(s.str()); if (rs->next()) { geometryColumn_ = rs->getValue("col"); if ( ! extent_initialized_ ) { double lox, loy, hix, hiy; if (mapnik::util::string2double(rs->getValue("xmin"), lox) && mapnik::util::string2double(rs->getValue("ymin"), loy) && mapnik::util::string2double(rs->getValue("xmax"), hix) && mapnik::util::string2double(rs->getValue("ymax"), hiy)) { extent_.init(lox, loy, hix, hiy); extent_initialized_ = true; MAPNIK_LOG_DEBUG(pgraster) << "pgraster_datasource: Layer extent=" << extent_; } else { MAPNIK_LOG_DEBUG(pgraster) << "pgraster_datasource: Could not determine extent from query: " << s.str(); } } if (srid_ == 0) { const char* srid_c = rs->getValue("srid"); if (srid_c != nullptr) { int result = 0; const char * end = srid_c + std::strlen(srid_c); if (mapnik::util::string2int(srid_c, end, result)) { srid_ = result; } } } if ( schema_.empty() ) { schema_ = rs->getValue("r_table_schema"); } } else { MAPNIK_LOG_DEBUG(pgraster) << "pgraster_datasource: no response from metadata query " << s.str(); } rs->close(); } catch (mapnik::datasource_exception const& ex) { // let this pass on query error and use the fallback below MAPNIK_LOG_WARN(pgraster) << "pgraster_datasource: metadata query failed: " << ex.what(); } // If we still do not know the srid then we can try to fetch // it from the 'table_' parameter, which should work even if it is // a subselect as long as we know the geometry_field to query if (! geometryColumn_.empty() && srid_ <= 0) { s.str(""); s << "SELECT ST_SRID(\"" << geometryColumn_ << "\") AS srid FROM " << populate_tokens(table_) << " WHERE \"" << geometryColumn_ << "\" IS NOT NULL LIMIT 1;"; shared_ptr<ResultSet> rs = conn->executeQuery(s.str()); if (rs->next()) { const char* srid_c = rs->getValue("srid"); if (srid_c != nullptr) { int result = 0; const char * end = srid_c + std::strlen(srid_c); if (mapnik::util::string2int(srid_c, end, result)) { srid_ = result; } } } rs->close(); } } // If overviews were requested, take note of the max scale // of each available overview, sorted by scale descending if ( use_overviews_ ) { std::ostringstream err; if ( schema_.empty() ) { err << "Pgraster Plugin: unable to lookup available table" << " overviews due to unknown schema"; throw mapnik::datasource_exception(err.str()); } if ( geometryColumn_.empty() ) { err << "Pgraster Plugin: unable to lookup available table" << " overviews due to unknown column name"; throw mapnik::datasource_exception(err.str()); } std::ostringstream s; s << "select " "r.r_table_schema sch, " "r.r_table_name tab, " "r.r_raster_column col, " "greatest(abs(r.scale_x), abs(r.scale_y)) scl " "from" " raster_overviews o," " raster_columns r " "where" " o.r_table_schema = '" << mapnik::sql_utils::unquote_double(schema_) << "' and o.r_table_name = '" << mapnik::sql_utils::unquote_double(raster_table_) << "' and o.r_raster_column = '" << mapnik::sql_utils::unquote_double(geometryColumn_) << "' and r.r_table_schema = o.o_table_schema" " and r.r_table_name = o.o_table_name" " and r.r_raster_column = o.o_raster_column" " ORDER BY scl ASC"; MAPNIK_LOG_DEBUG(pgraster) << "pgraster_datasource: running query " << s.str(); shared_ptr<ResultSet> rs = conn->executeQuery(s.str()); while (rs->next()) { pgraster_overview ov = pgraster_overview(); ov.schema = rs->getValue("sch"); ov.table = rs->getValue("tab"); ov.column = rs->getValue("col"); ov.scale = atof(rs->getValue("scl")); if(ov.scale == 0.0f) { MAPNIK_LOG_WARN(pgraster) << "pgraster_datasource: found invalid overview " << ov.schema << "." << ov.table << "." << ov.column << " with scale " << ov.scale; continue; } overviews_.push_back(ov); MAPNIK_LOG_DEBUG(pgraster) << "pgraster_datasource: found overview " << ov.schema << "." << ov.table << "." << ov.column << " with scale " << ov.scale; } rs->close(); if ( overviews_.empty() ) { MAPNIK_LOG_DEBUG(pgraster) << "pgraster_datasource: no overview found for " << schema_ << "." << raster_table_ << "." << geometryColumn_; } } // detect primary key if (*autodetect_key_field && key_field_.empty()) { #ifdef MAPNIK_STATS mapnik::progress_timer __stats2__(std::clog, "pgraster_datasource::bind(get_primary_key)"); #endif std::ostringstream s; s << "SELECT a.attname, a.attnum, t.typname, t.typname in ('int2','int4','int8') " "AS is_int FROM pg_class c, pg_attribute a, pg_type t, pg_namespace n, pg_index i " "WHERE a.attnum > 0 AND a.attrelid = c.oid " "AND a.atttypid = t.oid AND c.relnamespace = n.oid " "AND c.oid = i.indrelid AND i.indisprimary = 't' " "AND t.typname !~ '^geom' AND c.relname =" << " '" << mapnik::sql_utils::unquote_double(raster_table_) << "' " //"AND a.attnum = ANY (i.indkey) " // postgres >= 8.1 << "AND (i.indkey[0]=a.attnum OR i.indkey[1]=a.attnum OR i.indkey[2]=a.attnum " "OR i.indkey[3]=a.attnum OR i.indkey[4]=a.attnum OR i.indkey[5]=a.attnum " "OR i.indkey[6]=a.attnum OR i.indkey[7]=a.attnum OR i.indkey[8]=a.attnum " "OR i.indkey[9]=a.attnum) "; if (! schema_.empty()) { s << "AND n.nspname='" << mapnik::sql_utils::unquote_double(schema_) << "' "; } s << "ORDER BY a.attnum"; shared_ptr<ResultSet> rs_key = conn->executeQuery(s.str()); if (rs_key->next()) { unsigned int result_rows = rs_key->size(); if (result_rows == 1) { bool is_int = (std::string(rs_key->getValue(3)) == "t"); if (is_int) { const char* key_field_string = rs_key->getValue(0); if (key_field_string) { key_field_ = std::string(key_field_string); MAPNIK_LOG_DEBUG(pgraster) << "pgraster_datasource: auto-detected key field of '" << key_field_ << "' on table '" << raster_table_ << "'"; } } else { // throw for cases like a numeric primary key, which is invalid // as it should be floating point (int numerics are useless) std::ostringstream err; err << "PostGIS Plugin: Error: '" << rs_key->getValue(0) << "' on table '" << raster_table_ << "' is not a valid integer primary key field\n"; throw mapnik::datasource_exception(err.str()); } } else if (result_rows > 1) { std::ostringstream err; err << "PostGIS Plugin: Error: '" << "multi column primary key detected but is not supported"; throw mapnik::datasource_exception(err.str()); } } rs_key->close(); } // if a globally unique key field/primary key is required // but still not known at this point, then throw if (*autodetect_key_field && key_field_.empty()) { throw mapnik::datasource_exception(std::string("PostGIS Plugin: Error: primary key required") + " but could not be detected for table '" + raster_table_ + "', please supply 'key_field' option to specify field to use for primary key"); } if (srid_ == 0) { srid_ = -1; MAPNIK_LOG_DEBUG(pgraster) << "pgraster_datasource: Table " << table_ << " is using SRID=" << srid_; } // At this point the geometry_field may still not be known // but we'll catch that where more useful... MAPNIK_LOG_DEBUG(pgraster) << "pgraster_datasource: Using SRID=" << srid_; MAPNIK_LOG_DEBUG(pgraster) << "pgraster_datasource: Using geometry_column=" << geometryColumn_; // collect attribute desc #ifdef MAPNIK_STATS mapnik::progress_timer __stats2__(std::clog, "pgraster_datasource::bind(get_column_description)"); #endif std::ostringstream s; s << "SELECT * FROM " << populate_tokens(table_) << " LIMIT 0"; shared_ptr<ResultSet> rs = conn->executeQuery(s.str()); int count = rs->getNumFields(); bool found_key_field = false; for (int i = 0; i < count; ++i) { std::string fld_name = rs->getFieldName(i); int type_oid = rs->getTypeOID(i); // validate type of key_field if (! found_key_field && ! key_field_.empty() && fld_name == key_field_) { if (type_oid == 20 || type_oid == 21 || type_oid == 23) { found_key_field = true; desc_.add_descriptor(attribute_descriptor(fld_name, mapnik::Integer)); } else { std::ostringstream error_s; error_s << "invalid type '"; std::ostringstream type_s; type_s << "SELECT oid, typname FROM pg_type WHERE oid = " << type_oid; shared_ptr<ResultSet> rs_oid = conn->executeQuery(type_s.str()); if (rs_oid->next()) { error_s << rs_oid->getValue("typname") << "' (oid:" << rs_oid->getValue("oid") << ")"; } else { error_s << "oid:" << type_oid << "'"; } rs_oid->close(); error_s << " for key_field '" << fld_name << "' - " << "must be an integer primary key"; rs->close(); throw mapnik::datasource_exception(error_s.str()); } } else { switch (type_oid) { case 16: // bool desc_.add_descriptor(attribute_descriptor(fld_name, mapnik::Boolean)); break; case 20: // int8 case 21: // int2 case 23: // int4 desc_.add_descriptor(attribute_descriptor(fld_name, mapnik::Integer)); break; case 700: // float4 case 701: // float8 case 1700: // numeric desc_.add_descriptor(attribute_descriptor(fld_name, mapnik::Double)); break; case 1042: // bpchar case 1043: // varchar case 25: // text case 705: // literal desc_.add_descriptor(attribute_descriptor(fld_name, mapnik::String)); break; default: // should not get here #ifdef MAPNIK_LOG s.str(""); s << "SELECT oid, typname FROM pg_type WHERE oid = " << type_oid; shared_ptr<ResultSet> rs_oid = conn->executeQuery(s.str()); if (rs_oid->next()) { std::string typname(rs_oid->getValue("typname")); if (typname != "geometry" && typname != "raster") { MAPNIK_LOG_WARN(pgraster) << "pgraster_datasource: Unknown type=" << typname << " (oid:" << rs_oid->getValue("oid") << ")"; } } else { MAPNIK_LOG_WARN(pgraster) << "pgraster_datasource: Unknown type_oid=" << type_oid; } rs_oid->close(); #endif break; } } } rs->close(); } // Close explicitly the connection so we can 'fork()' without sharing open connections conn->close(); } } pgraster_datasource::~pgraster_datasource() { if (! persist_connection_) { CnxPool_ptr pool = ConnectionManager::instance().getPool(creator_.id()); if (pool) { try { shared_ptr<Connection> conn = pool->borrowObject(); if (conn) { conn->close(); } } catch (mapnik::datasource_exception const& ex) { // happens when borrowObject tries to // create a new connection and fails. // In turn, new connection would be needed // when our broke and was thus no good to // be borrowed // See https://github.com/mapnik/mapnik/issues/2191 } } } } const char * pgraster_datasource::name() { return "pgraster"; } mapnik::datasource::datasource_t pgraster_datasource::type() const { return type_; } layer_descriptor pgraster_datasource::get_descriptor() const { return desc_; } std::string pgraster_datasource::sql_bbox(box2d<double> const& env) const { std::ostringstream b; if (srid_ > 0) { b << "ST_SetSRID("; } b << "'BOX("; b << std::setprecision(16); b << env.minx() << " " << env.miny() << ","; b << env.maxx() << " " << env.maxy() << ")'::box2d"; if (srid_ > 0) { b << ", " << srid_ << ")"; } return b.str(); } std::string pgraster_datasource::populate_tokens(std::string const& sql) const { std::string populated_sql = sql; if (boost::algorithm::icontains(sql, bbox_token_)) { box2d<double> max_env(-1.0 * FMAX, -1.0 * FMAX, FMAX, FMAX); const std::string max_box = sql_bbox(max_env); boost::algorithm::replace_all(populated_sql, bbox_token_, max_box); } if (boost::algorithm::icontains(sql, scale_denom_token_)) { std::ostringstream ss; ss << FMAX; boost::algorithm::replace_all(populated_sql, scale_denom_token_, ss.str()); } if (boost::algorithm::icontains(sql, pixel_width_token_)) { std::ostringstream ss; ss << 0; boost::algorithm::replace_all(populated_sql, pixel_width_token_, ss.str()); } if (boost::algorithm::icontains(sql, pixel_height_token_)) { std::ostringstream ss; ss << 0; boost::algorithm::replace_all(populated_sql, pixel_height_token_, ss.str()); } return populated_sql; } std::string pgraster_datasource::populate_tokens(std::string const& sql, double scale_denom, box2d<double> const& env, double pixel_width, double pixel_height) const { std::string populated_sql = sql; std::string box = sql_bbox(env); if (boost::algorithm::icontains(populated_sql, scale_denom_token_)) { std::ostringstream ss; ss << scale_denom; boost::algorithm::replace_all(populated_sql, scale_denom_token_, ss.str()); } if (boost::algorithm::icontains(sql, pixel_width_token_)) { std::ostringstream ss; ss << pixel_width; boost::algorithm::replace_all(populated_sql, pixel_width_token_, ss.str()); } if (boost::algorithm::icontains(sql, pixel_height_token_)) { std::ostringstream ss; ss << pixel_height; boost::algorithm::replace_all(populated_sql, pixel_height_token_, ss.str()); } if (boost::algorithm::icontains(populated_sql, bbox_token_)) { boost::algorithm::replace_all(populated_sql, bbox_token_, box); return populated_sql; } else { std::ostringstream s; if (intersect_min_scale_ > 0 && (scale_denom <= intersect_min_scale_)) { s << " WHERE ST_Intersects(\"" << geometryColumn_ << "\"," << box << ")"; } else if (intersect_max_scale_ > 0 && (scale_denom >= intersect_max_scale_)) { // do no bbox restriction } else { s << " WHERE \"" << geometryColumn_ << "\" && " << box; } return populated_sql + s.str(); } } std::shared_ptr<IResultSet> pgraster_datasource::get_resultset(std::shared_ptr<Connection> &conn, std::string const& sql, CnxPool_ptr const& pool, processor_context_ptr ctx) const { if (!ctx) { // ! asynchronous_request_ if (cursor_fetch_size_ > 0) { // cursor std::ostringstream csql; std::string cursor_name = conn->new_cursor_name(); csql << "DECLARE " << cursor_name << " BINARY INSENSITIVE NO SCROLL CURSOR WITH HOLD FOR " << sql << " FOR READ ONLY"; if (! conn->execute(csql.str())) { // TODO - better error throw mapnik::datasource_exception("Pgraster Plugin: error creating cursor for data select." ); } return std::make_shared<CursorResultSet>(conn, cursor_name, cursor_fetch_size_); } else { // no cursor return conn->executeQuery(sql, 1); } } else { // asynchronous requests std::shared_ptr<postgis_processor_context> pgis_ctxt = std::static_pointer_cast<postgis_processor_context>(ctx); if (conn) { // lauch async req & create asyncresult with conn conn->executeAsyncQuery(sql, 1); return std::make_shared<AsyncResultSet>(pgis_ctxt, pool, conn, sql); } else { // create asyncresult with null connection std::shared_ptr<AsyncResultSet> res = std::make_shared<AsyncResultSet>(pgis_ctxt, pool, conn, sql); pgis_ctxt->add_request(res); return res; } } } processor_context_ptr pgraster_datasource::get_context(feature_style_context_map & ctx) const { if (!asynchronous_request_) { return processor_context_ptr(); } std::string ds_name(name()); feature_style_context_map::const_iterator itr = ctx.find(ds_name); if (itr != ctx.end()) { return itr->second; } else { return ctx.insert(std::make_pair(ds_name,std::make_shared<postgis_processor_context>())).first->second; } } featureset_ptr pgraster_datasource::features(query const& q) const { // if the driver is in asynchronous mode, return the appropriate fetaures if (asynchronous_request_ ) { return features_with_context(q,std::make_shared<postgis_processor_context>()); } else { return features_with_context(q,processor_context_ptr()); } } featureset_ptr pgraster_datasource::features_with_context(query const& q,processor_context_ptr proc_ctx) const { #ifdef MAPNIK_STATS mapnik::progress_timer __stats__(std::clog, "pgraster_datasource::features_with_context"); #endif box2d<double> const& box = q.get_bbox(); double scale_denom = q.scale_denominator(); CnxPool_ptr pool = ConnectionManager::instance().getPool(creator_.id()); if (pool) { shared_ptr<Connection> conn; if ( asynchronous_request_ ) { // limit use to num_async_request_ => if reached don't borrow the last connexion object std::shared_ptr<postgis_processor_context> pgis_ctxt = std::static_pointer_cast<postgis_processor_context>(proc_ctx); if ( pgis_ctxt->num_async_requests_ < max_async_connections_ ) { conn = pool->borrowObject(); pgis_ctxt->num_async_requests_++; } } else { // Always get a connection in synchronous mode conn = pool->borrowObject(); if(!conn ) { throw mapnik::datasource_exception("Pgraster Plugin: Null connection"); } } if (geometryColumn_.empty()) { std::ostringstream s_error; s_error << "PostGIS: geometry name lookup failed for table '"; if (! schema_.empty()) { s_error << schema_ << "."; } s_error << raster_table_ << "'. Please manually provide the 'geometry_field' parameter or add an entry " << "in the geometry_columns for '"; if (! schema_.empty()) { s_error << schema_ << "."; } s_error << raster_table_ << "'."; throw mapnik::datasource_exception(s_error.str()); } const double px_gw = 1.0 / std::get<0>(q.resolution()); const double px_gh = 1.0 / std::get<1>(q.resolution()); MAPNIK_LOG_DEBUG(pgraster) << "pgraster_datasource: px_gw=" << px_gw << " px_gh=" << px_gh; std::string table_with_bbox; std::string col = geometryColumn_; if ( use_overviews_ && !overviews_.empty()) { std::string sch = overviews_[0].schema; std::string tab = overviews_[0].table; col = overviews_[0].column; const double scale = std::min(px_gw, px_gh); std::vector<pgraster_overview>::const_reverse_iterator i; for (i=overviews_.rbegin(); i!=overviews_.rend(); ++i) { const pgraster_overview& o = *i; if ( o.scale < scale ) { sch = o.schema; tab = o.table; col = o.column; MAPNIK_LOG_DEBUG(pgraster) << "pgraster_datasource: using overview " << o.schema << "." << o.table << "." << o.column << " with scale=" << o.scale << " for min out scale=" << scale; break; } else { MAPNIK_LOG_DEBUG(pgraster) << "pgraster_datasource: overview " << o.schema << "." << o.table << "." << o.column << " with scale=" << o.scale << " not good for min out scale " << scale; } } table_with_bbox = table_; // possibly a subquery boost::algorithm::replace_all(table_with_bbox, mapnik::sql_utils::unquote_double(raster_table_), tab); boost::algorithm::replace_all(table_with_bbox, mapnik::sql_utils::unquote_double(schema_), sch); boost::algorithm::replace_all(table_with_bbox, mapnik::sql_utils::unquote_double(geometryColumn_), col); table_with_bbox = populate_tokens(table_with_bbox, scale_denom, box, px_gw, px_gh); } else { table_with_bbox = populate_tokens(table_, scale_denom, box, px_gw, px_gh); } std::ostringstream s; s << "SELECT ST_AsBinary("; if (band_) s << "ST_Band("; if (prescale_rasters_) s << "ST_Resize("; if (clip_rasters_) s << "ST_Clip("; s << "\"" << col << "\""; if (clip_rasters_) { s << ", ST_Expand(" << sql_bbox(box) << ", greatest(abs(ST_ScaleX(\"" << col << "\")), abs(ST_ScaleY(\"" << col << "\")))))"; } if (prescale_rasters_) { const double scale = std::min(px_gw, px_gh); s << ", least(abs(ST_ScaleX(\"" << col << "\"))::float8/" << scale << ", 1.0), least(abs(ST_ScaleY(\"" << col << "\"))::float8/" << scale << ", 1.0))"; // TODO: if band_ is given, we'll interpret as indexed so // the rescaling must NOT ruin it (use algorithm mode!) } if (band_) s << ", " << band_ << ")"; s << ") AS geom"; mapnik::context_ptr ctx = std::make_shared<mapnik::context_type>(); std::set<std::string> const& props = q.property_names(); std::set<std::string>::const_iterator pos = props.begin(); std::set<std::string>::const_iterator end = props.end(); if (! key_field_.empty()) { mapnik::sql_utils::quote_attr(s, key_field_); ctx->push(key_field_); for (; pos != end; ++pos) { if (*pos != key_field_) { mapnik::sql_utils::quote_attr(s, *pos); ctx->push(*pos); } } } else { for (; pos != end; ++pos) { mapnik::sql_utils::quote_attr(s, *pos); ctx->push(*pos); } } s << " FROM " << table_with_bbox; if (row_limit_ > 0) { s << " LIMIT " << row_limit_; } MAPNIK_LOG_DEBUG(pgraster) << "pgraster_datasource: " "features query: " << s.str(); std::shared_ptr<IResultSet> rs = get_resultset(conn, s.str(), pool, proc_ctx); return std::make_shared<pgraster_featureset>(rs, ctx, desc_.get_encoding(), !key_field_.empty(), band_ ? 1 : 0 // whatever band number is given we'd have // extracted with ST_Band above so it becomes // band number 1 ); } return mapnik::make_invalid_featureset(); } featureset_ptr pgraster_datasource::features_at_point(coord2d const& pt, double tol) const { #ifdef MAPNIK_STATS mapnik::progress_timer __stats__(std::clog, "pgraster_datasource::features_at_point"); #endif CnxPool_ptr pool = ConnectionManager::instance().getPool(creator_.id()); if (pool) { shared_ptr<Connection> conn = pool->borrowObject(); if (!conn) return mapnik::make_invalid_featureset(); if (conn->isOK()) { if (geometryColumn_.empty()) { std::ostringstream s_error; s_error << "PostGIS: geometry name lookup failed for table '"; if (! schema_.empty()) { s_error << schema_ << "."; } s_error << raster_table_ << "'. Please manually provide the 'geometry_field' parameter or add an entry " << "in the geometry_columns for '"; if (! schema_.empty()) { s_error << schema_ << "."; } s_error << raster_table_ << "'."; throw mapnik::datasource_exception(s_error.str()); } std::ostringstream s; s << "SELECT ST_AsBinary(\"" << geometryColumn_ << "\") AS geom"; mapnik::context_ptr ctx = std::make_shared<mapnik::context_type>(); auto const& desc = desc_.get_descriptors(); if (!key_field_.empty()) { mapnik::sql_utils::quote_attr(s, key_field_); ctx->push(key_field_); for (auto const& attr_info : desc) { std::string const& name = attr_info.get_name(); if (name != key_field_) { mapnik::sql_utils::quote_attr(s, name); ctx->push(name); } } } else { for (auto const& attr_info : desc) { std::string const& name = attr_info.get_name(); mapnik::sql_utils::quote_attr(s, name); ctx->push(name); } } box2d<double> box(pt.x - tol, pt.y - tol, pt.x + tol, pt.y + tol); std::string table_with_bbox = populate_tokens(table_, FMAX, box, 0, 0); s << " FROM " << table_with_bbox; if (row_limit_ > 0) { s << " LIMIT " << row_limit_; } std::shared_ptr<IResultSet> rs = get_resultset(conn, s.str(), pool); return std::make_shared<pgraster_featureset>(rs, ctx, desc_.get_encoding(), !key_field_.empty()); } } return mapnik::make_invalid_featureset(); } box2d<double> pgraster_datasource::envelope() const { if (extent_initialized_) { return extent_; } CnxPool_ptr pool = ConnectionManager::instance().getPool(creator_.id()); if (pool) { shared_ptr<Connection> conn = pool->borrowObject(); if (!conn) return extent_; if (conn->isOK()) { std::ostringstream s; std::string col = mapnik::sql_utils::unquote_double(geometryColumn_); std::string sch = mapnik::sql_utils::unquote_double(schema_); std::string tab = mapnik::sql_utils::unquote_double(raster_table_); if ( ! overviews_.empty() ) { // query from highest-factor overview instead const pgraster_overview& o = overviews_.back(); sch = o.schema; tab = o.table; col = o.column; } if (col.empty()) { std::ostringstream s_error; s_error << "PostGIS: unable to query the layer extent of table '"; if (! sch.empty()) { s_error << sch << "."; } s_error << raster_table_ << "' because we cannot determine the raster field name." << "\nPlease provide either an 'extent' parameter to skip this query, " << "a 'raster_field' and/or 'raster_table' parameter, or add " << "standard constraints to your raster table."; throw mapnik::datasource_exception("Pgraster Plugin: " + s_error.str()); } if (estimate_extent_) { if (tab.empty()) { std::ostringstream s_error; s_error << "PostGIS: unable to query the layer extent as " << "we couldn't determine the raster table name.\n" << "Please provide either an 'extent' parameter to skip this query, " << "a 'raster_table' parameter, or do not set 'estimate_extent'"; throw mapnik::datasource_exception("Pgraster Plugin: " + s_error.str()); } s << "SELECT ST_XMin(ext),ST_YMin(ext),ST_XMax(ext),ST_YMax(ext)" << " FROM (SELECT ST_Estimated_Extent('"; if (! sch.empty()) { s << mapnik::sql_utils::unquote_double(sch) << "','"; } s << mapnik::sql_utils::unquote_double(tab) << "','" << mapnik::sql_utils::unquote_double(col) << "') as ext) as tmp"; } else { s << "SELECT ST_XMin(ext),ST_YMin(ext),ST_XMax(ext),ST_YMax(ext)" << " FROM (SELECT ST_Extent(" << quote_ident(col) << "::geometry) as ext from "; if (extent_from_subquery_) { // if a subselect limits records then calculating the extent upon the // subquery will be faster and the bounds will be more accurate s << populate_tokens(table_) << ") as tmpx"; } else { if (! sch.empty()) { s << quote_ident(sch) << "."; } // but if the subquery does not limit records then querying the // actual table will be faster as indexes can be used s << quote_ident(tab) << ") as tmp"; } } shared_ptr<ResultSet> rs = conn->executeQuery(s.str()); if (rs->next() && ! rs->isNull(0)) { double lox, loy, hix, hiy; if (mapnik::util::string2double(rs->getValue(0), lox) && mapnik::util::string2double(rs->getValue(1), loy) && mapnik::util::string2double(rs->getValue(2), hix) && mapnik::util::string2double(rs->getValue(3), hiy)) { extent_.init(lox, loy, hix, hiy); extent_initialized_ = true; } else { MAPNIK_LOG_DEBUG(pgraster) << "pgraster_datasource: Could not determine extent from query: " << s.str(); } } rs->close(); } } return extent_; } boost::optional<mapnik::datasource_geometry_t> pgraster_datasource::get_geometry_type() const { return boost::optional<mapnik::datasource_geometry_t>(); } pgraster: indentation /***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2016 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * ***************************************************************************** * * Initially developed by Sandro Santilli <strk@keybit.net> for CartoDB * *****************************************************************************/ #include "../postgis/connection_manager.hpp" #include "../postgis/asyncresultset.hpp" #include "pgraster_datasource.hpp" #include "pgraster_featureset.hpp" // mapnik #include <mapnik/debug.hpp> #include <mapnik/global.hpp> // for byte #include <mapnik/boolean.hpp> #include <mapnik/sql_utils.hpp> #include <mapnik/util/conversions.hpp> #include <mapnik/timer.hpp> #include <mapnik/value/types.hpp> #pragma GCC diagnostic push #include <mapnik/warning_ignore.hpp> #include <boost/algorithm/string.hpp> #include <boost/tokenizer.hpp> #pragma GCC diagnostic pop // stl #include <string> #include <algorithm> #include <set> #include <sstream> #include <iomanip> DATASOURCE_PLUGIN(pgraster_datasource) const double pgraster_datasource::FMAX = std::numeric_limits<float>::max(); const std::string pgraster_datasource::RASTER_COLUMNS = "raster_columns"; const std::string pgraster_datasource::RASTER_OVERVIEWS = "raster_overviews"; const std::string pgraster_datasource::SPATIAL_REF_SYS = "spatial_ref_system"; using std::shared_ptr; using mapnik::attribute_descriptor; using mapnik::value_integer; namespace { // TODO: move to sql_utils std::string quote_ident(std::string& s) { return "\"" + s + "\""; // TODO: escape internal quotes } }; pgraster_datasource::pgraster_datasource(parameters const& params) : datasource(params), table_(*params.get<std::string>("table", "")), schema_(""), raster_table_(*params.get<std::string>("raster_table", "")), raster_field_(*params.get<std::string>("raster_field", "")), key_field_(*params.get<std::string>("key_field", "")), cursor_fetch_size_(*params.get<mapnik::value_integer>("cursor_size", 0)), row_limit_(*params.get<value_integer>("row_limit", 0)), type_(datasource::Raster), srid_(*params.get<value_integer>("srid", 0)), band_(*params.get<value_integer>("band", 0)), extent_initialized_(false), prescale_rasters_(*params.get<mapnik::boolean_type>("prescale_rasters", false)), use_overviews_(*params.get<mapnik::boolean_type>("use_overviews", false)), clip_rasters_(*params.get<mapnik::boolean_type>("clip_rasters", false)), desc_(*params.get<std::string>("type"), "utf-8"), creator_(params.get<std::string>("host"), params.get<std::string>("port"), params.get<std::string>("dbname"), params.get<std::string>("user"), params.get<std::string>("password"), params.get<std::string>("connect_timeout", "4")), bbox_token_("!bbox!"), scale_denom_token_("!scale_denominator!"), pixel_width_token_("!pixel_width!"), pixel_height_token_("!pixel_height!"), pool_max_size_(*params_.get<value_integer>("max_size", 10)), persist_connection_(*params.get<mapnik::boolean_type>("persist_connection", true)), extent_from_subquery_(*params.get<mapnik::boolean_type>("extent_from_subquery", false)), estimate_extent_(*params.get<mapnik::boolean_type>("estimate_extent", false)), max_async_connections_(*params_.get<value_integer>("max_async_connection", 1)), asynchronous_request_(false), // params below are for testing purposes only and may be removed at any time intersect_min_scale_(*params.get<value_integer>("intersect_min_scale", 0)), intersect_max_scale_(*params.get<value_integer>("intersect_max_scale", 0)) { #ifdef MAPNIK_STATS mapnik::progress_timer __stats__(std::clog, "pgraster_datasource::init"); #endif if (table_.empty()) { throw mapnik::datasource_exception("Pgraster Plugin: missing <table> parameter"); } boost::optional<std::string> ext = params.get<std::string>("extent"); if (ext && !ext->empty()) { extent_initialized_ = extent_.from_string(*ext); } // NOTE: In multithread environment, pool_max_size_ should be // max_async_connections_ * num_threads if(max_async_connections_ > 1) { if(max_async_connections_ > pool_max_size_) { std::ostringstream err; err << "PostGIS Plugin: Error: 'max_async_connections (" << max_async_connections_ << ") must be <= max_size(" << pool_max_size_ << ")"; throw mapnik::datasource_exception(err.str()); } asynchronous_request_ = true; } boost::optional<value_integer> initial_size = params.get<value_integer>("initial_size", 1); boost::optional<mapnik::boolean_type> autodetect_key_field = params.get<mapnik::boolean_type>("autodetect_key_field", false); ConnectionManager::instance().registerPool(creator_, *initial_size, pool_max_size_); CnxPool_ptr pool = ConnectionManager::instance().getPool(creator_.id()); if (!pool) return; shared_ptr<Connection> conn = pool->borrowObject(); if (!conn) return; if (conn->isOK()) { desc_.set_encoding(conn->client_encoding()); if (raster_table_.empty()) { raster_table_ = mapnik::sql_utils::table_from_sql(table_); // non-trivial subqueries (having no FROM) make it // impossible to use overviews // TODO: improve "table_from_sql" ? if ( raster_table_[raster_table_.find_first_not_of(" \t\r\n")] == '(' ) { raster_table_.clear(); if ( use_overviews_ ) { std::ostringstream err; err << "Pgraster Plugin: overviews cannot be used " "with non-trivial subqueries"; MAPNIK_LOG_WARN(pgraster) << err.str(); use_overviews_ = false; } if ( ! extent_from_subquery_ ) { std::ostringstream err; err << "Pgraster Plugin: extent can only be computed " "from subquery as we could not found table source"; MAPNIK_LOG_WARN(pgraster) << err.str(); extent_from_subquery_ = true; } } } std::string::size_type idx = raster_table_.find_last_of('.'); if (idx != std::string::npos) { schema_ = raster_table_.substr(0, idx); raster_table_ = raster_table_.substr(idx + 1); } // If we do not know either the geometry_field or the srid or we // want to use overviews but do not know about schema, or // no extent was specified, then attempt to fetch the missing // information from a raster_columns entry. // // This will return no records if we are querying a bogus table returned // from the simplistic table parsing in table_from_sql() or if // the table parameter references a table, view, or subselect not // registered in the geometry columns. // geometryColumn_ = mapnik::sql_utils::unquote_double(raster_field_); if (!raster_table_.empty() && ( geometryColumn_.empty() || srid_ == 0 || (schema_.empty() && use_overviews_) || ! extent_initialized_ )) { #ifdef MAPNIK_STATS mapnik::progress_timer __stats2__(std::clog, "pgraster_datasource::init(get_srid_and_geometry_column)"); #endif std::ostringstream s; try { s << "SELECT r_raster_column col, srid, r_table_schema"; if ( ! extent_initialized_ ) { s << ", st_xmin(extent) xmin, st_ymin(extent) ymin" << ", st_xmax(extent) xmax, st_ymax(extent) ymax"; } s << " FROM " << RASTER_COLUMNS << " WHERE r_table_name='" << mapnik::sql_utils::unquote_double(raster_table_) << "'"; if (! schema_.empty()) { s << " AND r_table_schema='" << mapnik::sql_utils::unquote_double(schema_) << "'"; } if (! raster_field_.empty()) { s << " AND r_raster_column='" << mapnik::sql_utils::unquote_double(raster_field_) << "'"; } MAPNIK_LOG_DEBUG(pgraster) << "pgraster_datasource: running query " << s.str(); shared_ptr<ResultSet> rs = conn->executeQuery(s.str()); if (rs->next()) { geometryColumn_ = rs->getValue("col"); if ( ! extent_initialized_ ) { double lox, loy, hix, hiy; if (mapnik::util::string2double(rs->getValue("xmin"), lox) && mapnik::util::string2double(rs->getValue("ymin"), loy) && mapnik::util::string2double(rs->getValue("xmax"), hix) && mapnik::util::string2double(rs->getValue("ymax"), hiy)) { extent_.init(lox, loy, hix, hiy); extent_initialized_ = true; MAPNIK_LOG_DEBUG(pgraster) << "pgraster_datasource: Layer extent=" << extent_; } else { MAPNIK_LOG_DEBUG(pgraster) << "pgraster_datasource: Could not determine extent from query: " << s.str(); } } if (srid_ == 0) { const char* srid_c = rs->getValue("srid"); if (srid_c != nullptr) { int result = 0; const char * end = srid_c + std::strlen(srid_c); if (mapnik::util::string2int(srid_c, end, result)) { srid_ = result; } } } if ( schema_.empty() ) { schema_ = rs->getValue("r_table_schema"); } } else { MAPNIK_LOG_DEBUG(pgraster) << "pgraster_datasource: no response from metadata query " << s.str(); } rs->close(); } catch (mapnik::datasource_exception const& ex) { // let this pass on query error and use the fallback below MAPNIK_LOG_WARN(pgraster) << "pgraster_datasource: metadata query failed: " << ex.what(); } // If we still do not know the srid then we can try to fetch // it from the 'table_' parameter, which should work even if it is // a subselect as long as we know the geometry_field to query if (! geometryColumn_.empty() && srid_ <= 0) { s.str(""); s << "SELECT ST_SRID(\"" << geometryColumn_ << "\") AS srid FROM " << populate_tokens(table_) << " WHERE \"" << geometryColumn_ << "\" IS NOT NULL LIMIT 1;"; shared_ptr<ResultSet> rs = conn->executeQuery(s.str()); if (rs->next()) { const char* srid_c = rs->getValue("srid"); if (srid_c != nullptr) { int result = 0; const char * end = srid_c + std::strlen(srid_c); if (mapnik::util::string2int(srid_c, end, result)) { srid_ = result; } } } rs->close(); } } // If overviews were requested, take note of the max scale // of each available overview, sorted by scale descending if ( use_overviews_ ) { std::ostringstream err; if ( schema_.empty() ) { err << "Pgraster Plugin: unable to lookup available table" << " overviews due to unknown schema"; throw mapnik::datasource_exception(err.str()); } if ( geometryColumn_.empty() ) { err << "Pgraster Plugin: unable to lookup available table" << " overviews due to unknown column name"; throw mapnik::datasource_exception(err.str()); } std::ostringstream s; s << "select " "r.r_table_schema sch, " "r.r_table_name tab, " "r.r_raster_column col, " "greatest(abs(r.scale_x), abs(r.scale_y)) scl " "from" " raster_overviews o," " raster_columns r " "where" " o.r_table_schema = '" << mapnik::sql_utils::unquote_double(schema_) << "' and o.r_table_name = '" << mapnik::sql_utils::unquote_double(raster_table_) << "' and o.r_raster_column = '" << mapnik::sql_utils::unquote_double(geometryColumn_) << "' and r.r_table_schema = o.o_table_schema" " and r.r_table_name = o.o_table_name" " and r.r_raster_column = o.o_raster_column" " ORDER BY scl ASC"; MAPNIK_LOG_DEBUG(pgraster) << "pgraster_datasource: running query " << s.str(); shared_ptr<ResultSet> rs = conn->executeQuery(s.str()); while (rs->next()) { pgraster_overview ov = pgraster_overview(); ov.schema = rs->getValue("sch"); ov.table = rs->getValue("tab"); ov.column = rs->getValue("col"); ov.scale = atof(rs->getValue("scl")); if(ov.scale == 0.0f) { MAPNIK_LOG_WARN(pgraster) << "pgraster_datasource: found invalid overview " << ov.schema << "." << ov.table << "." << ov.column << " with scale " << ov.scale; continue; } overviews_.push_back(ov); MAPNIK_LOG_DEBUG(pgraster) << "pgraster_datasource: found overview " << ov.schema << "." << ov.table << "." << ov.column << " with scale " << ov.scale; } rs->close(); if ( overviews_.empty() ) { MAPNIK_LOG_DEBUG(pgraster) << "pgraster_datasource: no overview found for " << schema_ << "." << raster_table_ << "." << geometryColumn_; } } // detect primary key if (*autodetect_key_field && key_field_.empty()) { #ifdef MAPNIK_STATS mapnik::progress_timer __stats2__(std::clog, "pgraster_datasource::bind(get_primary_key)"); #endif std::ostringstream s; s << "SELECT a.attname, a.attnum, t.typname, t.typname in ('int2','int4','int8') " "AS is_int FROM pg_class c, pg_attribute a, pg_type t, pg_namespace n, pg_index i " "WHERE a.attnum > 0 AND a.attrelid = c.oid " "AND a.atttypid = t.oid AND c.relnamespace = n.oid " "AND c.oid = i.indrelid AND i.indisprimary = 't' " "AND t.typname !~ '^geom' AND c.relname =" << " '" << mapnik::sql_utils::unquote_double(raster_table_) << "' " //"AND a.attnum = ANY (i.indkey) " // postgres >= 8.1 << "AND (i.indkey[0]=a.attnum OR i.indkey[1]=a.attnum OR i.indkey[2]=a.attnum " "OR i.indkey[3]=a.attnum OR i.indkey[4]=a.attnum OR i.indkey[5]=a.attnum " "OR i.indkey[6]=a.attnum OR i.indkey[7]=a.attnum OR i.indkey[8]=a.attnum " "OR i.indkey[9]=a.attnum) "; if (! schema_.empty()) { s << "AND n.nspname='" << mapnik::sql_utils::unquote_double(schema_) << "' "; } s << "ORDER BY a.attnum"; shared_ptr<ResultSet> rs_key = conn->executeQuery(s.str()); if (rs_key->next()) { unsigned int result_rows = rs_key->size(); if (result_rows == 1) { bool is_int = (std::string(rs_key->getValue(3)) == "t"); if (is_int) { const char* key_field_string = rs_key->getValue(0); if (key_field_string) { key_field_ = std::string(key_field_string); MAPNIK_LOG_DEBUG(pgraster) << "pgraster_datasource: auto-detected key field of '" << key_field_ << "' on table '" << raster_table_ << "'"; } } else { // throw for cases like a numeric primary key, which is invalid // as it should be floating point (int numerics are useless) std::ostringstream err; err << "PostGIS Plugin: Error: '" << rs_key->getValue(0) << "' on table '" << raster_table_ << "' is not a valid integer primary key field\n"; throw mapnik::datasource_exception(err.str()); } } else if (result_rows > 1) { std::ostringstream err; err << "PostGIS Plugin: Error: '" << "multi column primary key detected but is not supported"; throw mapnik::datasource_exception(err.str()); } } rs_key->close(); } // if a globally unique key field/primary key is required // but still not known at this point, then throw if (*autodetect_key_field && key_field_.empty()) { throw mapnik::datasource_exception(std::string("PostGIS Plugin: Error: primary key required") + " but could not be detected for table '" + raster_table_ + "', please supply 'key_field' option to specify field to use for primary key"); } if (srid_ == 0) { srid_ = -1; MAPNIK_LOG_DEBUG(pgraster) << "pgraster_datasource: Table " << table_ << " is using SRID=" << srid_; } // At this point the geometry_field may still not be known // but we'll catch that where more useful... MAPNIK_LOG_DEBUG(pgraster) << "pgraster_datasource: Using SRID=" << srid_; MAPNIK_LOG_DEBUG(pgraster) << "pgraster_datasource: Using geometry_column=" << geometryColumn_; // collect attribute desc #ifdef MAPNIK_STATS mapnik::progress_timer __stats2__(std::clog, "pgraster_datasource::bind(get_column_description)"); #endif std::ostringstream s; s << "SELECT * FROM " << populate_tokens(table_) << " LIMIT 0"; shared_ptr<ResultSet> rs = conn->executeQuery(s.str()); int count = rs->getNumFields(); bool found_key_field = false; for (int i = 0; i < count; ++i) { std::string fld_name = rs->getFieldName(i); int type_oid = rs->getTypeOID(i); // validate type of key_field if (! found_key_field && ! key_field_.empty() && fld_name == key_field_) { if (type_oid == 20 || type_oid == 21 || type_oid == 23) { found_key_field = true; desc_.add_descriptor(attribute_descriptor(fld_name, mapnik::Integer)); } else { std::ostringstream error_s; error_s << "invalid type '"; std::ostringstream type_s; type_s << "SELECT oid, typname FROM pg_type WHERE oid = " << type_oid; shared_ptr<ResultSet> rs_oid = conn->executeQuery(type_s.str()); if (rs_oid->next()) { error_s << rs_oid->getValue("typname") << "' (oid:" << rs_oid->getValue("oid") << ")"; } else { error_s << "oid:" << type_oid << "'"; } rs_oid->close(); error_s << " for key_field '" << fld_name << "' - " << "must be an integer primary key"; rs->close(); throw mapnik::datasource_exception(error_s.str()); } } else { switch (type_oid) { case 16: // bool desc_.add_descriptor(attribute_descriptor(fld_name, mapnik::Boolean)); break; case 20: // int8 case 21: // int2 case 23: // int4 desc_.add_descriptor(attribute_descriptor(fld_name, mapnik::Integer)); break; case 700: // float4 case 701: // float8 case 1700: // numeric desc_.add_descriptor(attribute_descriptor(fld_name, mapnik::Double)); break; case 1042: // bpchar case 1043: // varchar case 25: // text case 705: // literal desc_.add_descriptor(attribute_descriptor(fld_name, mapnik::String)); break; default: // should not get here #ifdef MAPNIK_LOG s.str(""); s << "SELECT oid, typname FROM pg_type WHERE oid = " << type_oid; shared_ptr<ResultSet> rs_oid = conn->executeQuery(s.str()); if (rs_oid->next()) { std::string typname(rs_oid->getValue("typname")); if (typname != "geometry" && typname != "raster") { MAPNIK_LOG_WARN(pgraster) << "pgraster_datasource: Unknown type=" << typname << " (oid:" << rs_oid->getValue("oid") << ")"; } } else { MAPNIK_LOG_WARN(pgraster) << "pgraster_datasource: Unknown type_oid=" << type_oid; } rs_oid->close(); #endif break; } } } rs->close(); } // Close explicitly the connection so we can 'fork()' without sharing open connections conn->close(); } pgraster_datasource::~pgraster_datasource() { if (! persist_connection_) { CnxPool_ptr pool = ConnectionManager::instance().getPool(creator_.id()); if (pool) { try { shared_ptr<Connection> conn = pool->borrowObject(); if (conn) { conn->close(); } } catch (mapnik::datasource_exception const& ex) { // happens when borrowObject tries to // create a new connection and fails. // In turn, new connection would be needed // when our broke and was thus no good to // be borrowed // See https://github.com/mapnik/mapnik/issues/2191 } } } } const char * pgraster_datasource::name() { return "pgraster"; } mapnik::datasource::datasource_t pgraster_datasource::type() const { return type_; } layer_descriptor pgraster_datasource::get_descriptor() const { return desc_; } std::string pgraster_datasource::sql_bbox(box2d<double> const& env) const { std::ostringstream b; if (srid_ > 0) { b << "ST_SetSRID("; } b << "'BOX("; b << std::setprecision(16); b << env.minx() << " " << env.miny() << ","; b << env.maxx() << " " << env.maxy() << ")'::box2d"; if (srid_ > 0) { b << ", " << srid_ << ")"; } return b.str(); } std::string pgraster_datasource::populate_tokens(std::string const& sql) const { std::string populated_sql = sql; if (boost::algorithm::icontains(sql, bbox_token_)) { box2d<double> max_env(-1.0 * FMAX, -1.0 * FMAX, FMAX, FMAX); const std::string max_box = sql_bbox(max_env); boost::algorithm::replace_all(populated_sql, bbox_token_, max_box); } if (boost::algorithm::icontains(sql, scale_denom_token_)) { std::ostringstream ss; ss << FMAX; boost::algorithm::replace_all(populated_sql, scale_denom_token_, ss.str()); } if (boost::algorithm::icontains(sql, pixel_width_token_)) { std::ostringstream ss; ss << 0; boost::algorithm::replace_all(populated_sql, pixel_width_token_, ss.str()); } if (boost::algorithm::icontains(sql, pixel_height_token_)) { std::ostringstream ss; ss << 0; boost::algorithm::replace_all(populated_sql, pixel_height_token_, ss.str()); } return populated_sql; } std::string pgraster_datasource::populate_tokens(std::string const& sql, double scale_denom, box2d<double> const& env, double pixel_width, double pixel_height) const { std::string populated_sql = sql; std::string box = sql_bbox(env); if (boost::algorithm::icontains(populated_sql, scale_denom_token_)) { std::ostringstream ss; ss << scale_denom; boost::algorithm::replace_all(populated_sql, scale_denom_token_, ss.str()); } if (boost::algorithm::icontains(sql, pixel_width_token_)) { std::ostringstream ss; ss << pixel_width; boost::algorithm::replace_all(populated_sql, pixel_width_token_, ss.str()); } if (boost::algorithm::icontains(sql, pixel_height_token_)) { std::ostringstream ss; ss << pixel_height; boost::algorithm::replace_all(populated_sql, pixel_height_token_, ss.str()); } if (boost::algorithm::icontains(populated_sql, bbox_token_)) { boost::algorithm::replace_all(populated_sql, bbox_token_, box); return populated_sql; } else { std::ostringstream s; if (intersect_min_scale_ > 0 && (scale_denom <= intersect_min_scale_)) { s << " WHERE ST_Intersects(\"" << geometryColumn_ << "\"," << box << ")"; } else if (intersect_max_scale_ > 0 && (scale_denom >= intersect_max_scale_)) { // do no bbox restriction } else { s << " WHERE \"" << geometryColumn_ << "\" && " << box; } return populated_sql + s.str(); } } std::shared_ptr<IResultSet> pgraster_datasource::get_resultset(std::shared_ptr<Connection> &conn, std::string const& sql, CnxPool_ptr const& pool, processor_context_ptr ctx) const { if (!ctx) { // ! asynchronous_request_ if (cursor_fetch_size_ > 0) { // cursor std::ostringstream csql; std::string cursor_name = conn->new_cursor_name(); csql << "DECLARE " << cursor_name << " BINARY INSENSITIVE NO SCROLL CURSOR WITH HOLD FOR " << sql << " FOR READ ONLY"; if (! conn->execute(csql.str())) { // TODO - better error throw mapnik::datasource_exception("Pgraster Plugin: error creating cursor for data select." ); } return std::make_shared<CursorResultSet>(conn, cursor_name, cursor_fetch_size_); } else { // no cursor return conn->executeQuery(sql, 1); } } else { // asynchronous requests std::shared_ptr<postgis_processor_context> pgis_ctxt = std::static_pointer_cast<postgis_processor_context>(ctx); if (conn) { // lauch async req & create asyncresult with conn conn->executeAsyncQuery(sql, 1); return std::make_shared<AsyncResultSet>(pgis_ctxt, pool, conn, sql); } else { // create asyncresult with null connection std::shared_ptr<AsyncResultSet> res = std::make_shared<AsyncResultSet>(pgis_ctxt, pool, conn, sql); pgis_ctxt->add_request(res); return res; } } } processor_context_ptr pgraster_datasource::get_context(feature_style_context_map & ctx) const { if (!asynchronous_request_) { return processor_context_ptr(); } std::string ds_name(name()); feature_style_context_map::const_iterator itr = ctx.find(ds_name); if (itr != ctx.end()) { return itr->second; } else { return ctx.insert(std::make_pair(ds_name,std::make_shared<postgis_processor_context>())).first->second; } } featureset_ptr pgraster_datasource::features(query const& q) const { // if the driver is in asynchronous mode, return the appropriate fetaures if (asynchronous_request_ ) { return features_with_context(q,std::make_shared<postgis_processor_context>()); } else { return features_with_context(q,processor_context_ptr()); } } featureset_ptr pgraster_datasource::features_with_context(query const& q,processor_context_ptr proc_ctx) const { #ifdef MAPNIK_STATS mapnik::progress_timer __stats__(std::clog, "pgraster_datasource::features_with_context"); #endif box2d<double> const& box = q.get_bbox(); double scale_denom = q.scale_denominator(); CnxPool_ptr pool = ConnectionManager::instance().getPool(creator_.id()); if (pool) { shared_ptr<Connection> conn; if ( asynchronous_request_ ) { // limit use to num_async_request_ => if reached don't borrow the last connexion object std::shared_ptr<postgis_processor_context> pgis_ctxt = std::static_pointer_cast<postgis_processor_context>(proc_ctx); if ( pgis_ctxt->num_async_requests_ < max_async_connections_ ) { conn = pool->borrowObject(); pgis_ctxt->num_async_requests_++; } } else { // Always get a connection in synchronous mode conn = pool->borrowObject(); if(!conn ) { throw mapnik::datasource_exception("Pgraster Plugin: Null connection"); } } if (geometryColumn_.empty()) { std::ostringstream s_error; s_error << "PostGIS: geometry name lookup failed for table '"; if (! schema_.empty()) { s_error << schema_ << "."; } s_error << raster_table_ << "'. Please manually provide the 'geometry_field' parameter or add an entry " << "in the geometry_columns for '"; if (! schema_.empty()) { s_error << schema_ << "."; } s_error << raster_table_ << "'."; throw mapnik::datasource_exception(s_error.str()); } const double px_gw = 1.0 / std::get<0>(q.resolution()); const double px_gh = 1.0 / std::get<1>(q.resolution()); MAPNIK_LOG_DEBUG(pgraster) << "pgraster_datasource: px_gw=" << px_gw << " px_gh=" << px_gh; std::string table_with_bbox; std::string col = geometryColumn_; if ( use_overviews_ && !overviews_.empty()) { std::string sch = overviews_[0].schema; std::string tab = overviews_[0].table; col = overviews_[0].column; const double scale = std::min(px_gw, px_gh); std::vector<pgraster_overview>::const_reverse_iterator i; for (i=overviews_.rbegin(); i!=overviews_.rend(); ++i) { const pgraster_overview& o = *i; if ( o.scale < scale ) { sch = o.schema; tab = o.table; col = o.column; MAPNIK_LOG_DEBUG(pgraster) << "pgraster_datasource: using overview " << o.schema << "." << o.table << "." << o.column << " with scale=" << o.scale << " for min out scale=" << scale; break; } else { MAPNIK_LOG_DEBUG(pgraster) << "pgraster_datasource: overview " << o.schema << "." << o.table << "." << o.column << " with scale=" << o.scale << " not good for min out scale " << scale; } } table_with_bbox = table_; // possibly a subquery boost::algorithm::replace_all(table_with_bbox, mapnik::sql_utils::unquote_double(raster_table_), tab); boost::algorithm::replace_all(table_with_bbox, mapnik::sql_utils::unquote_double(schema_), sch); boost::algorithm::replace_all(table_with_bbox, mapnik::sql_utils::unquote_double(geometryColumn_), col); table_with_bbox = populate_tokens(table_with_bbox, scale_denom, box, px_gw, px_gh); } else { table_with_bbox = populate_tokens(table_, scale_denom, box, px_gw, px_gh); } std::ostringstream s; s << "SELECT ST_AsBinary("; if (band_) s << "ST_Band("; if (prescale_rasters_) s << "ST_Resize("; if (clip_rasters_) s << "ST_Clip("; s << "\"" << col << "\""; if (clip_rasters_) { s << ", ST_Expand(" << sql_bbox(box) << ", greatest(abs(ST_ScaleX(\"" << col << "\")), abs(ST_ScaleY(\"" << col << "\")))))"; } if (prescale_rasters_) { const double scale = std::min(px_gw, px_gh); s << ", least(abs(ST_ScaleX(\"" << col << "\"))::float8/" << scale << ", 1.0), least(abs(ST_ScaleY(\"" << col << "\"))::float8/" << scale << ", 1.0))"; // TODO: if band_ is given, we'll interpret as indexed so // the rescaling must NOT ruin it (use algorithm mode!) } if (band_) s << ", " << band_ << ")"; s << ") AS geom"; mapnik::context_ptr ctx = std::make_shared<mapnik::context_type>(); std::set<std::string> const& props = q.property_names(); std::set<std::string>::const_iterator pos = props.begin(); std::set<std::string>::const_iterator end = props.end(); if (! key_field_.empty()) { mapnik::sql_utils::quote_attr(s, key_field_); ctx->push(key_field_); for (; pos != end; ++pos) { if (*pos != key_field_) { mapnik::sql_utils::quote_attr(s, *pos); ctx->push(*pos); } } } else { for (; pos != end; ++pos) { mapnik::sql_utils::quote_attr(s, *pos); ctx->push(*pos); } } s << " FROM " << table_with_bbox; if (row_limit_ > 0) { s << " LIMIT " << row_limit_; } MAPNIK_LOG_DEBUG(pgraster) << "pgraster_datasource: " "features query: " << s.str(); std::shared_ptr<IResultSet> rs = get_resultset(conn, s.str(), pool, proc_ctx); return std::make_shared<pgraster_featureset>(rs, ctx, desc_.get_encoding(), !key_field_.empty(), band_ ? 1 : 0 // whatever band number is given we'd have // extracted with ST_Band above so it becomes // band number 1 ); } return mapnik::make_invalid_featureset(); } featureset_ptr pgraster_datasource::features_at_point(coord2d const& pt, double tol) const { #ifdef MAPNIK_STATS mapnik::progress_timer __stats__(std::clog, "pgraster_datasource::features_at_point"); #endif CnxPool_ptr pool = ConnectionManager::instance().getPool(creator_.id()); if (pool) { shared_ptr<Connection> conn = pool->borrowObject(); if (!conn) return mapnik::make_invalid_featureset(); if (conn->isOK()) { if (geometryColumn_.empty()) { std::ostringstream s_error; s_error << "PostGIS: geometry name lookup failed for table '"; if (! schema_.empty()) { s_error << schema_ << "."; } s_error << raster_table_ << "'. Please manually provide the 'geometry_field' parameter or add an entry " << "in the geometry_columns for '"; if (! schema_.empty()) { s_error << schema_ << "."; } s_error << raster_table_ << "'."; throw mapnik::datasource_exception(s_error.str()); } std::ostringstream s; s << "SELECT ST_AsBinary(\"" << geometryColumn_ << "\") AS geom"; mapnik::context_ptr ctx = std::make_shared<mapnik::context_type>(); auto const& desc = desc_.get_descriptors(); if (!key_field_.empty()) { mapnik::sql_utils::quote_attr(s, key_field_); ctx->push(key_field_); for (auto const& attr_info : desc) { std::string const& name = attr_info.get_name(); if (name != key_field_) { mapnik::sql_utils::quote_attr(s, name); ctx->push(name); } } } else { for (auto const& attr_info : desc) { std::string const& name = attr_info.get_name(); mapnik::sql_utils::quote_attr(s, name); ctx->push(name); } } box2d<double> box(pt.x - tol, pt.y - tol, pt.x + tol, pt.y + tol); std::string table_with_bbox = populate_tokens(table_, FMAX, box, 0, 0); s << " FROM " << table_with_bbox; if (row_limit_ > 0) { s << " LIMIT " << row_limit_; } std::shared_ptr<IResultSet> rs = get_resultset(conn, s.str(), pool); return std::make_shared<pgraster_featureset>(rs, ctx, desc_.get_encoding(), !key_field_.empty()); } } return mapnik::make_invalid_featureset(); } box2d<double> pgraster_datasource::envelope() const { if (extent_initialized_) { return extent_; } CnxPool_ptr pool = ConnectionManager::instance().getPool(creator_.id()); if (pool) { shared_ptr<Connection> conn = pool->borrowObject(); if (!conn) return extent_; if (conn->isOK()) { std::ostringstream s; std::string col = mapnik::sql_utils::unquote_double(geometryColumn_); std::string sch = mapnik::sql_utils::unquote_double(schema_); std::string tab = mapnik::sql_utils::unquote_double(raster_table_); if ( ! overviews_.empty() ) { // query from highest-factor overview instead const pgraster_overview& o = overviews_.back(); sch = o.schema; tab = o.table; col = o.column; } if (col.empty()) { std::ostringstream s_error; s_error << "PostGIS: unable to query the layer extent of table '"; if (! sch.empty()) { s_error << sch << "."; } s_error << raster_table_ << "' because we cannot determine the raster field name." << "\nPlease provide either an 'extent' parameter to skip this query, " << "a 'raster_field' and/or 'raster_table' parameter, or add " << "standard constraints to your raster table."; throw mapnik::datasource_exception("Pgraster Plugin: " + s_error.str()); } if (estimate_extent_) { if (tab.empty()) { std::ostringstream s_error; s_error << "PostGIS: unable to query the layer extent as " << "we couldn't determine the raster table name.\n" << "Please provide either an 'extent' parameter to skip this query, " << "a 'raster_table' parameter, or do not set 'estimate_extent'"; throw mapnik::datasource_exception("Pgraster Plugin: " + s_error.str()); } s << "SELECT ST_XMin(ext),ST_YMin(ext),ST_XMax(ext),ST_YMax(ext)" << " FROM (SELECT ST_Estimated_Extent('"; if (! sch.empty()) { s << mapnik::sql_utils::unquote_double(sch) << "','"; } s << mapnik::sql_utils::unquote_double(tab) << "','" << mapnik::sql_utils::unquote_double(col) << "') as ext) as tmp"; } else { s << "SELECT ST_XMin(ext),ST_YMin(ext),ST_XMax(ext),ST_YMax(ext)" << " FROM (SELECT ST_Extent(" << quote_ident(col) << "::geometry) as ext from "; if (extent_from_subquery_) { // if a subselect limits records then calculating the extent upon the // subquery will be faster and the bounds will be more accurate s << populate_tokens(table_) << ") as tmpx"; } else { if (! sch.empty()) { s << quote_ident(sch) << "."; } // but if the subquery does not limit records then querying the // actual table will be faster as indexes can be used s << quote_ident(tab) << ") as tmp"; } } shared_ptr<ResultSet> rs = conn->executeQuery(s.str()); if (rs->next() && ! rs->isNull(0)) { double lox, loy, hix, hiy; if (mapnik::util::string2double(rs->getValue(0), lox) && mapnik::util::string2double(rs->getValue(1), loy) && mapnik::util::string2double(rs->getValue(2), hix) && mapnik::util::string2double(rs->getValue(3), hiy)) { extent_.init(lox, loy, hix, hiy); extent_initialized_ = true; } else { MAPNIK_LOG_DEBUG(pgraster) << "pgraster_datasource: Could not determine extent from query: " << s.str(); } } rs->close(); } } return extent_; } boost::optional<mapnik::datasource_geometry_t> pgraster_datasource::get_geometry_type() const { return boost::optional<mapnik::datasource_geometry_t>(); }
/* Copyright 2021 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/compiler/mlir/tfrt/python_tests/python_test_attrs.h" #include "mlir/IR/Attributes.h" // from @llvm-project #include "mlir/IR/BuiltinTypes.h" // from @llvm-project #include "mlir/IR/MLIRContext.h" // from @llvm-project #include "mlir/IR/Operation.h" // from @llvm-project #include "mlir/Support/LLVM.h" // from @llvm-project #include "mlir/Support/LogicalResult.h" // from @llvm-project // Include the auto-generated dialect defs. #include "tensorflow/compiler/mlir/tfrt/python_tests/python_test_attrs.cc.inc" namespace mlir { namespace tfrt { void PythonTestAttrsDialect::initialize() {} ::mlir::LogicalResult PythonTestAttrsDialect::verifyRegionArgAttribute( ::mlir::Operation* op, unsigned regionIndex, unsigned argIndex, ::mlir::NamedAttribute attribute) { const auto& arg = op->getRegion(regionIndex).getArguments()[argIndex]; // Only verify at the tensor level. We are interested in the correct attribute // values when processing the Tensorflow dialect IR. auto arg_type = arg.getType().dyn_cast<RankedTensorType>(); if (!arg_type) return success(); if (attribute.getName() == GetStaticTypeAttrName()) { auto type_attr = attribute.getValue().dyn_cast<TypeAttr>(); if (!type_attr) { return op->emitError() << GetStaticTypeAttrName() << " argument attribute of other type than TypeAttr"; } auto attr_type = type_attr.getValue().dyn_cast<RankedTensorType>(); if (!attr_type) { return op->emitError() << GetStaticTypeAttrName() << " argument type attribute is not a ranked tensor type"; } if (attr_type.getNumDynamicDims() > 0) { return op->emitError() << GetStaticTypeAttrName() << " argument type attribute is a ranked tensor " "type with dynamic dimensions"; } if (attr_type.getRank() != arg_type.getRank()) { return op->emitError() << GetStaticTypeAttrName() << " argument type attribute is a ranked tensor type with a " "different rank than the rank of the argument tensor"; } if (attr_type.getElementType() != arg_type.getElementType()) { return op->emitError() << GetStaticTypeAttrName() << " argument type attribute is a ranked tensor type with a " "different element type than the element type of the argument " "tensor"; } const auto& attr_shape = attr_type.getShape(); const auto& arg_shape = arg_type.getShape(); for (int64_t i = 0; i < attr_shape.size(); ++i) { if (!arg_type.isDynamicDim(i) && arg_shape[i] != attr_shape[i]) { return op->emitError() << GetStaticTypeAttrName() << " argument type attribute is a ranked tensor type with a " "shape that doesn't match the static dimensions of the " "argument tensor"; } } } else if (attribute.getName() == GetShapeValueAttrName()) { auto dense_attr = attribute.getValue().dyn_cast<DenseIntElementsAttr>(); if (!dense_attr) { return op->emitError() << GetShapeValueAttrName() << " argument attribute is not a dense int elements attribute"; } if (dense_attr.getType() != arg_type) { return op->emitError() << GetShapeValueAttrName() << " argument elements attribute has a different " "type than the argument type"; } // We expect a valid shape value, therefore check that the dimension values // are not negative. for (auto&& dim : dense_attr) { if (dim.isNegative()) { return op->emitError() << GetShapeValueAttrName() << " argument elements attribute has a negative dimension value"; } } } return success(); } } // namespace tfrt } // namespace mlir Consider integer types of width at most 8 bit to be compatible. We legalize I1 type to I8 type, but don't convert the python_test_attrs argument attributes. But I1 and I8 types are compatible in memory, because they take 1 single byte. Also, integer types with the same number of bits are compatible in memory. PiperOrigin-RevId: 430387068 Change-Id: Ia433e0d893fc23100c2ca6a4369945726bfca510 /* Copyright 2021 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/compiler/mlir/tfrt/python_tests/python_test_attrs.h" #include <algorithm> #include "mlir/IR/Attributes.h" // from @llvm-project #include "mlir/IR/BuiltinTypes.h" // from @llvm-project #include "mlir/IR/MLIRContext.h" // from @llvm-project #include "mlir/IR/Operation.h" // from @llvm-project #include "mlir/Support/LLVM.h" // from @llvm-project #include "mlir/Support/LogicalResult.h" // from @llvm-project // Include the auto-generated dialect defs. #include "tensorflow/compiler/mlir/tfrt/python_tests/python_test_attrs.cc.inc" namespace mlir { namespace tfrt { void PythonTestAttrsDialect::initialize() {} ::mlir::LogicalResult PythonTestAttrsDialect::verifyRegionArgAttribute( ::mlir::Operation* op, unsigned regionIndex, unsigned argIndex, ::mlir::NamedAttribute attribute) { const auto& arg = op->getRegion(regionIndex).getArguments()[argIndex]; // Only verify at the tensor level. We are interested in the correct attribute // values when processing the Tensorflow dialect IR. auto arg_type = arg.getType().dyn_cast<RankedTensorType>(); if (!arg_type) return success(); if (attribute.getName() == GetStaticTypeAttrName()) { auto type_attr = attribute.getValue().dyn_cast<TypeAttr>(); if (!type_attr) { return op->emitError() << GetStaticTypeAttrName() << " argument attribute of other type than TypeAttr"; } auto attr_type = type_attr.getValue().dyn_cast<RankedTensorType>(); if (!attr_type) { return op->emitError() << GetStaticTypeAttrName() << " argument type attribute is not a ranked tensor type"; } if (attr_type.getNumDynamicDims() > 0) { return op->emitError() << GetStaticTypeAttrName() << " argument type attribute is a ranked tensor " "type with dynamic dimensions"; } if (attr_type.getRank() != arg_type.getRank()) { return op->emitError() << GetStaticTypeAttrName() << " argument type attribute is a ranked tensor type with a " "different rank than the rank of the argument tensor"; } auto compatible = [&](Type a, Type b) { if (a == b) { return true; } if (!a.isa<IntegerType>() || !b.isa<IntegerType>()) { return false; } auto width_a = a.dyn_cast<IntegerType>().getWidth(); auto width_b = b.dyn_cast<IntegerType>().getWidth(); return width_a == width_b || std::max(width_a, width_b) == 8; }; if (!compatible(attr_type.getElementType(), arg_type.getElementType())) { return op->emitError() << GetStaticTypeAttrName() << " argument type attribute is a ranked tensor type with a " "different element type than the element type of the argument " "tensor"; } const auto& attr_shape = attr_type.getShape(); const auto& arg_shape = arg_type.getShape(); for (int64_t i = 0; i < attr_shape.size(); ++i) { if (!arg_type.isDynamicDim(i) && arg_shape[i] != attr_shape[i]) { return op->emitError() << GetStaticTypeAttrName() << " argument type attribute is a ranked tensor type with a " "shape that doesn't match the static dimensions of the " "argument tensor"; } } } else if (attribute.getName() == GetShapeValueAttrName()) { auto dense_attr = attribute.getValue().dyn_cast<DenseIntElementsAttr>(); if (!dense_attr) { return op->emitError() << GetShapeValueAttrName() << " argument attribute is not a dense int elements attribute"; } if (dense_attr.getType() != arg_type) { return op->emitError() << GetShapeValueAttrName() << " argument elements attribute has a different " "type than the argument type"; } // We expect a valid shape value, therefore check that the dimension values // are not negative. for (auto&& dim : dense_attr) { if (dim.isNegative()) { return op->emitError() << GetShapeValueAttrName() << " argument elements attribute has a negative dimension value"; } } } return success(); } } // namespace tfrt } // namespace mlir
/****************************************************************************** * The MIT License (MIT) * * Copyright (c) 2016-2018 Baldur Karlsson * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. ******************************************************************************/ #include "TextureViewer.h" #include <float.h> #include <math.h> #include <QClipboard> #include <QColorDialog> #include <QFileSystemWatcher> #include <QFontDatabase> #include <QItemDelegate> #include <QJsonDocument> #include <QMenu> #include <QPainter> #include <QPointer> #include <QStyledItemDelegate> #include "3rdparty/flowlayout/FlowLayout.h" #include "3rdparty/toolwindowmanager/ToolWindowManagerArea.h" #include "Code/QRDUtils.h" #include "Code/Resources.h" #include "Dialogs/TextureSaveDialog.h" #include "Widgets/ResourcePreview.h" #include "Widgets/TextureGoto.h" #include "ui_TextureViewer.h" float area(const QSizeF &s) { return s.width() * s.height(); } float aspect(const QSizeF &s) { return s.width() / s.height(); } Q_DECLARE_METATYPE(Following); const Following Following::Default = Following(); Following::Following(FollowType t, ShaderStage s, int i, int a) { Type = t; Stage = s; index = i; arrayEl = a; } Following::Following() { Type = FollowType::OutputColour; Stage = ShaderStage::Pixel; index = 0; arrayEl = 0; } bool Following::operator!=(const Following &o) { return !(*this == o); } bool Following::operator==(const Following &o) { return Type == o.Type && Stage == o.Stage && index == o.index; } void Following::GetDrawContext(ICaptureContext &ctx, bool &copy, bool &clear, bool &compute) { const DrawcallDescription *curDraw = ctx.CurDrawcall(); copy = curDraw != NULL && (curDraw->flags & (DrawFlags::Copy | DrawFlags::Resolve | DrawFlags::Present)); clear = curDraw != NULL && (curDraw->flags & DrawFlags::Clear); compute = curDraw != NULL && (curDraw->flags & DrawFlags::Dispatch) && ctx.CurPipelineState().GetShader(ShaderStage::Compute) != ResourceId(); } int Following::GetHighestMip(ICaptureContext &ctx) { return GetBoundResource(ctx, arrayEl).firstMip; } int Following::GetFirstArraySlice(ICaptureContext &ctx) { return GetBoundResource(ctx, arrayEl).firstSlice; } CompType Following::GetTypeHint(ICaptureContext &ctx) { return GetBoundResource(ctx, arrayEl).typeHint; } ResourceId Following::GetResourceId(ICaptureContext &ctx) { return GetBoundResource(ctx, arrayEl).resourceId; } BoundResource Following::GetBoundResource(ICaptureContext &ctx, int arrayIdx) { BoundResource ret; if(Type == FollowType::OutputColour) { rdcarray<BoundResource> outputs = GetOutputTargets(ctx); if(index < outputs.count()) ret = outputs[index]; } else if(Type == FollowType::OutputDepth) { ret = GetDepthTarget(ctx); } else if(Type == FollowType::ReadWrite) { rdcarray<BoundResourceArray> rw = GetReadWriteResources(ctx); ShaderBindpointMapping mapping = GetMapping(ctx); if(index < mapping.readWriteResources.count()) { Bindpoint &key = mapping.readWriteResources[index]; int residx = rw.indexOf(key); if(residx >= 0) ret = rw[residx].resources[arrayIdx]; } } else if(Type == FollowType::ReadOnly) { rdcarray<BoundResourceArray> ro = GetReadOnlyResources(ctx); ShaderBindpointMapping mapping = GetMapping(ctx); if(index < mapping.readOnlyResources.count()) { Bindpoint &key = mapping.readOnlyResources[index]; int residx = ro.indexOf(key); if(residx >= 0) ret = ro[residx].resources[arrayIdx]; } } return ret; } rdcarray<BoundResource> Following::GetOutputTargets(ICaptureContext &ctx) { const DrawcallDescription *curDraw = ctx.CurDrawcall(); bool copy = false, clear = false, compute = false; GetDrawContext(ctx, copy, clear, compute); if(copy || clear) { return {BoundResource(curDraw->copyDestination)}; } else if(compute) { return {}; } else { rdcarray<BoundResource> ret = ctx.CurPipelineState().GetOutputTargets(); if(ret.isEmpty() && curDraw != NULL && (curDraw->flags & DrawFlags::Present)) { if(curDraw->copyDestination != ResourceId()) return {BoundResource(curDraw->copyDestination)}; for(const TextureDescription &tex : ctx.GetTextures()) { if(tex.creationFlags & TextureCategory::SwapBuffer) return {BoundResource(tex.resourceId)}; } } return ret; } } BoundResource Following::GetDepthTarget(ICaptureContext &ctx) { bool copy = false, clear = false, compute = false; GetDrawContext(ctx, copy, clear, compute); if(copy || clear || compute) return BoundResource(ResourceId()); else return ctx.CurPipelineState().GetDepthTarget(); } rdcarray<BoundResourceArray> Following::GetReadWriteResources(ICaptureContext &ctx, ShaderStage stage) { bool copy = false, clear = false, compute = false; GetDrawContext(ctx, copy, clear, compute); if(copy || clear) { return rdcarray<BoundResourceArray>(); } else if(compute) { // only return compute resources for one stage if(stage == ShaderStage::Pixel || stage == ShaderStage::Compute) return ctx.CurPipelineState().GetReadWriteResources(ShaderStage::Compute); else return rdcarray<BoundResourceArray>(); } else { return ctx.CurPipelineState().GetReadWriteResources(stage); } } rdcarray<BoundResourceArray> Following::GetReadWriteResources(ICaptureContext &ctx) { return GetReadWriteResources(ctx, Stage); } rdcarray<BoundResourceArray> Following::GetReadOnlyResources(ICaptureContext &ctx, ShaderStage stage) { const DrawcallDescription *curDraw = ctx.CurDrawcall(); bool copy = false, clear = false, compute = false; GetDrawContext(ctx, copy, clear, compute); if(copy || clear) { rdcarray<BoundResourceArray> ret; // only return copy source for one stage if(copy && stage == ShaderStage::Pixel) ret.push_back(BoundResourceArray(Bindpoint(0, 0), {BoundResource(curDraw->copySource)})); return ret; } else if(compute) { // only return compute resources for one stage if(stage == ShaderStage::Pixel || stage == ShaderStage::Compute) return ctx.CurPipelineState().GetReadOnlyResources(ShaderStage::Compute); else return rdcarray<BoundResourceArray>(); } else { return ctx.CurPipelineState().GetReadOnlyResources(stage); } } rdcarray<BoundResourceArray> Following::GetReadOnlyResources(ICaptureContext &ctx) { return GetReadOnlyResources(ctx, Stage); } const ShaderReflection *Following::GetReflection(ICaptureContext &ctx, ShaderStage stage) { bool copy = false, clear = false, compute = false; GetDrawContext(ctx, copy, clear, compute); if(copy || clear) return NULL; else if(compute) return ctx.CurPipelineState().GetShaderReflection(ShaderStage::Compute); else return ctx.CurPipelineState().GetShaderReflection(stage); } const ShaderReflection *Following::GetReflection(ICaptureContext &ctx) { return GetReflection(ctx, Stage); } const ShaderBindpointMapping &Following::GetMapping(ICaptureContext &ctx, ShaderStage stage) { bool copy = false, clear = false, compute = false; GetDrawContext(ctx, copy, clear, compute); if(copy || clear) { static ShaderBindpointMapping mapping; // for PS only add a single mapping to get the copy source if(copy && stage == ShaderStage::Pixel) mapping.readOnlyResources = {Bindpoint(0, 0)}; else mapping.readOnlyResources.clear(); return mapping; } else if(compute) { return ctx.CurPipelineState().GetBindpointMapping(ShaderStage::Compute); } else { return ctx.CurPipelineState().GetBindpointMapping(stage); } } const ShaderBindpointMapping &Following::GetMapping(ICaptureContext &ctx) { return GetMapping(ctx, Stage); } class TextureListItemModel : public QAbstractItemModel { public: enum FilterType { Textures, RenderTargets, String }; TextureListItemModel(ICaptureContext &ctx, QWidget *parent) : QAbstractItemModel(parent), m_Ctx(ctx) { goArrow.addPixmap(Pixmaps::action(parent), QIcon::Normal, QIcon::Off); goArrow.addPixmap(Pixmaps::action_hover(parent), QIcon::Normal, QIcon::Off); } void reset(FilterType type, const QString &filter) { const rdcarray<TextureDescription> src = m_Ctx.GetTextures(); texs.clear(); texs.reserve(src.count()); emit beginResetModel(); TextureCategory rtFlags = TextureCategory::ColorTarget | TextureCategory::DepthTarget; for(const TextureDescription &t : src) { if(type == Textures) { if(!(t.creationFlags & rtFlags)) texs.push_back(t); } else if(type == RenderTargets) { if((t.creationFlags & rtFlags)) texs.push_back(t); } else { if(filter.isEmpty()) texs.push_back(t); else if(QString(m_Ctx.GetResourceName(t.resourceId)).contains(filter, Qt::CaseInsensitive)) texs.push_back(t); } } emit endResetModel(); } QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const override { if(row < 0 || row >= rowCount()) return QModelIndex(); return createIndex(row, 0); } QModelIndex parent(const QModelIndex &index) const override { return QModelIndex(); } int rowCount(const QModelIndex &parent = QModelIndex()) const override { return texs.count(); } int columnCount(const QModelIndex &parent = QModelIndex()) const override { return 1; } Qt::ItemFlags flags(const QModelIndex &index) const override { if(!index.isValid()) return 0; return QAbstractItemModel::flags(index); } QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override { if(index.isValid()) { if(role == Qt::DisplayRole) { if(index.row() >= 0 && index.row() < texs.count()) return m_Ctx.GetResourceName(texs[index.row()].resourceId); } if(role == Qt::UserRole) { return QVariant::fromValue(texs[index.row()].resourceId); } if(role == Qt::DecorationRole) { return QVariant(goArrow); } } return QVariant(); } private: ICaptureContext &m_Ctx; QVector<TextureDescription> texs; QIcon goArrow; }; class TextureListItemDelegate : public QItemDelegate { public: TextureListItemDelegate(QObject *parent = 0) : QItemDelegate(parent) {} void paint(QPainter *painter, const QStyleOptionViewItem &opt, const QModelIndex &index) const override { if(index.isValid()) { QStyleOptionViewItem option = opt; option.decorationAlignment = Qt::AlignBaseline | Qt::AlignRight; painter->eraseRect(option.rect); QIcon icon = index.model()->data(index, Qt::DecorationRole).value<QIcon>(); drawBackground(painter, option, index); if(option.state & QStyle::State_MouseOver) drawDecoration(painter, option, option.rect, icon.pixmap(option.decorationSize, QIcon::Active)); else drawDecoration(painter, option, option.rect, icon.pixmap(option.decorationSize, QIcon::Normal)); drawDisplay(painter, option, option.rect, index.model()->data(index, Qt::DisplayRole).toString()); drawFocus(painter, option, option.rect); if(option.state & QStyle::State_MouseOver) { QRect r = option.rect; r.adjust(0, 0, -1, -1); painter->drawRect(r); } } } }; TextureDescription *TextureViewer::GetCurrentTexture() { return m_CachedTexture; } void TextureViewer::UI_UpdateCachedTexture() { if(!m_Ctx.IsCaptureLoaded()) { m_CachedTexture = NULL; return; } ResourceId id = m_LockedId; if(id == ResourceId()) id = m_Following.GetResourceId(m_Ctx); if(id == ResourceId()) id = m_TexDisplay.resourceId; m_CachedTexture = m_Ctx.GetTexture(id); ui->debugPixelContext->setEnabled(m_Ctx.CurPipelineState().IsCaptureD3D11() && m_CachedTexture != NULL); ui->pixelHistory->setEnabled(m_Ctx.CurPipelineState().IsCaptureD3D11() && m_CachedTexture != NULL); } TextureViewer::TextureViewer(ICaptureContext &ctx, QWidget *parent) : QFrame(parent), ui(new Ui::TextureViewer), m_Ctx(ctx) { ui->setupUi(this); ui->textureList->setFont(Formatter::PreferredFont()); ui->textureListFilter->setFont(Formatter::PreferredFont()); ui->rangeBlack->setFont(Formatter::PreferredFont()); ui->rangeWhite->setFont(Formatter::PreferredFont()); ui->hdrMul->setFont(Formatter::PreferredFont()); ui->channels->setFont(Formatter::PreferredFont()); ui->mipLevel->setFont(Formatter::PreferredFont()); ui->sliceFace->setFont(Formatter::PreferredFont()); ui->zoomOption->setFont(Formatter::PreferredFont()); Reset(); on_checkerBack_clicked(); QObject::connect(ui->zoomOption->lineEdit(), &QLineEdit::returnPressed, this, &TextureViewer::zoomOption_returnPressed); QObject::connect(ui->depthDisplay, &QToolButton::toggled, this, &TextureViewer::channelsWidget_toggled); QObject::connect(ui->stencilDisplay, &QToolButton::toggled, this, &TextureViewer::channelsWidget_toggled); QObject::connect(ui->flip_y, &QToolButton::toggled, this, &TextureViewer::channelsWidget_toggled); QObject::connect(ui->gammaDisplay, &QToolButton::toggled, this, &TextureViewer::channelsWidget_toggled); QObject::connect(ui->channels, OverloadedSlot<int>::of(&QComboBox::currentIndexChanged), this, &TextureViewer::channelsWidget_selected); QObject::connect(ui->hdrMul, OverloadedSlot<int>::of(&QComboBox::currentIndexChanged), this, &TextureViewer::channelsWidget_selected); QObject::connect(ui->customShader, OverloadedSlot<int>::of(&QComboBox::currentIndexChanged), this, &TextureViewer::channelsWidget_selected); QObject::connect(ui->customShader, &QComboBox::currentTextChanged, [this] { UI_UpdateChannels(); }); QObject::connect(ui->rangeHistogram, &RangeHistogram::rangeUpdated, this, &TextureViewer::range_rangeUpdated); QObject::connect(ui->rangeBlack, &RDLineEdit::textChanged, this, &TextureViewer::rangePoint_textChanged); QObject::connect(ui->rangeBlack, &RDLineEdit::leave, this, &TextureViewer::rangePoint_leave); QObject::connect(ui->rangeBlack, &RDLineEdit::keyPress, this, &TextureViewer::rangePoint_keyPress); QObject::connect(ui->rangeWhite, &RDLineEdit::textChanged, this, &TextureViewer::rangePoint_textChanged); QObject::connect(ui->rangeWhite, &RDLineEdit::leave, this, &TextureViewer::rangePoint_leave); QObject::connect(ui->rangeWhite, &RDLineEdit::keyPress, this, &TextureViewer::rangePoint_keyPress); for(RDToolButton *butt : {ui->channelRed, ui->channelGreen, ui->channelBlue, ui->channelAlpha}) { QObject::connect(butt, &RDToolButton::toggled, this, &TextureViewer::channelsWidget_toggled); QObject::connect(butt, &RDToolButton::mouseClicked, this, &TextureViewer::channelsWidget_mouseClicked); QObject::connect(butt, &RDToolButton::doubleClicked, this, &TextureViewer::channelsWidget_mouseClicked); } { QMenu *extensionsMenu = new QMenu(this); ui->extensions->setMenu(extensionsMenu); ui->extensions->setPopupMode(QToolButton::InstantPopup); QObject::connect(extensionsMenu, &QMenu::aboutToShow, [this, extensionsMenu]() { extensionsMenu->clear(); m_Ctx.Extensions().MenuDisplaying(PanelMenu::TextureViewer, extensionsMenu, ui->extensions, {}); }); } QWidget *renderContainer = ui->renderContainer; ui->dockarea->addToolWindow(ui->renderContainer, ToolWindowManager::EmptySpace); ui->dockarea->setToolWindowProperties( renderContainer, ToolWindowManager::DisallowUserDocking | ToolWindowManager::HideCloseButton | ToolWindowManager::DisableDraggableTab | ToolWindowManager::AlwaysDisplayFullTabs); ui->dockarea->addToolWindow(ui->inputThumbs, ToolWindowManager::AreaReference( ToolWindowManager::RightOf, ui->dockarea->areaOf(renderContainer), 0.25f)); ui->dockarea->setToolWindowProperties(ui->inputThumbs, ToolWindowManager::HideCloseButton); ui->dockarea->addToolWindow( ui->outputThumbs, ToolWindowManager::AreaReference(ToolWindowManager::AddTo, ui->dockarea->areaOf(ui->inputThumbs))); ui->dockarea->setToolWindowProperties(ui->outputThumbs, ToolWindowManager::HideCloseButton); ui->dockarea->addToolWindow( ui->pixelContextLayout, ToolWindowManager::AreaReference(ToolWindowManager::BottomOf, ui->dockarea->areaOf(ui->outputThumbs), 0.25f)); ui->dockarea->setToolWindowProperties(ui->pixelContextLayout, ToolWindowManager::HideCloseButton); ui->dockarea->addToolWindow(ui->textureListFrame, ToolWindowManager::NoArea); ui->dockarea->setToolWindowProperties(ui->textureListFrame, ToolWindowManager::HideOnClose); ui->dockarea->setAllowFloatingWindow(false); renderContainer->setWindowTitle(tr("Unbound")); ui->pixelContextLayout->setWindowTitle(tr("Pixel Context")); ui->outputThumbs->setWindowTitle(tr("Outputs")); ui->inputThumbs->setWindowTitle(tr("Inputs")); ui->textureListFrame->setWindowTitle(tr("Texture List")); ui->textureList->setHoverCursor(Qt::PointingHandCursor); m_Goto = new TextureGoto(this, [this](QPoint p) { GotoLocation(p.x(), p.y()); }); QVBoxLayout *vertical = new QVBoxLayout(this); vertical->setSpacing(3); vertical->setContentsMargins(3, 3, 3, 3); QWidget *flow1widget = new QWidget(this); QWidget *flow2widget = new QWidget(this); FlowLayout *flow1 = new FlowLayout(flow1widget, 0, 3, 3); FlowLayout *flow2 = new FlowLayout(flow2widget, 0, 3, 3); flow1widget->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Minimum); flow2widget->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Minimum); flow1->addWidget(ui->channelsToolbar); flow1->addWidget(ui->subresourceToolbar); flow1->addWidget(ui->actionToolbar); flow2->addWidget(ui->zoomToolbar); flow2->addWidget(ui->overlayToolbar); flow2->addWidget(ui->rangeToolbar); vertical->addWidget(flow1widget); vertical->addWidget(flow2widget); vertical->addWidget(ui->dockarea); Ui_TextureViewer *u = ui; u->pixelcontextgrid->setAlignment(u->pixelHistory, Qt::AlignCenter); u->pixelcontextgrid->setAlignment(u->debugPixelContext, Qt::AlignCenter); QWidget *statusflowWidget = new QWidget(this); FlowLayout *statusflow = new FlowLayout(statusflowWidget, 0, 3, 0); statusflowWidget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum); ui->statusbar->removeWidget(ui->texStatusDim); ui->statusbar->removeWidget(ui->pickSwatch); ui->statusbar->removeWidget(ui->statusText); statusflow->addWidget(ui->texStatusDim); statusflow->addWidget(ui->pickSwatch); statusflow->addWidget(ui->statusText); ui->texStatusDim->setFont(QFontDatabase::systemFont(QFontDatabase::FixedFont)); ui->statusText->setFont(QFontDatabase::systemFont(QFontDatabase::FixedFont)); ui->statusbar->addWidget(statusflowWidget); ui->channels->addItems({tr("RGBA"), tr("RGBM"), tr("Custom")}); ui->zoomOption->addItems({lit("10%"), lit("25%"), lit("50%"), lit("75%"), lit("100%"), lit("200%"), lit("400%"), lit("800%")}); ui->hdrMul->addItems({lit("2"), lit("4"), lit("8"), lit("16"), lit("32"), lit("128")}); ui->overlay->addItems({tr("None"), tr("Highlight Drawcall"), tr("Wireframe Mesh"), tr("Depth Test"), tr("Stencil Test"), tr("Backface Cull"), tr("Viewport/Scissor Region"), tr("NaN/INF/-ve Display"), tr("Histogram Clipping"), tr("Clear Before Pass"), tr("Clear Before Draw"), tr("Quad Overdraw (Pass)"), tr("Quad Overdraw (Draw)"), tr("Triangle Size (Pass)"), tr("Triangle Size (Draw)")}); ui->textureListFilter->addItems({QString(), tr("Textures"), tr("Render Targets")}); ui->textureList->setModel(new TextureListItemModel(m_Ctx, this)); ui->textureList->setItemDelegate(new TextureListItemDelegate(ui->textureList)); ui->textureList->viewport()->setAttribute(Qt::WA_Hover); ui->zoomOption->setCurrentText(QString()); ui->fitToWindow->toggle(); m_Ctx.AddCaptureViewer(this); SetupTextureTabs(); } TextureViewer::~TextureViewer() { if(m_Output) { m_Ctx.Replay().BlockInvoke([this](IReplayController *r) { m_Output->Shutdown(); }); } m_Ctx.BuiltinWindowClosed(this); m_Ctx.RemoveCaptureViewer(this); delete ui; } void TextureViewer::enterEvent(QEvent *event) { HighlightUsage(); } void TextureViewer::showEvent(QShowEvent *event) { HighlightUsage(); } void TextureViewer::changeEvent(QEvent *event) { if(event->type() == QEvent::PaletteChange || event->type() == QEvent::StyleChange) { updateBackgroundColors(); ui->render->update(); } } void TextureViewer::HighlightUsage() { TextureDescription *texptr = GetCurrentTexture(); if(texptr && m_Ctx.HasTimelineBar()) m_Ctx.GetTimelineBar()->HighlightResourceUsage(texptr->resourceId); } void TextureViewer::RT_FetchCurrentPixel(uint32_t x, uint32_t y, PixelValue &pickValue, PixelValue &realValue) { TextureDescription *texptr = GetCurrentTexture(); if(texptr == NULL) return; if(m_TexDisplay.flipY) y = (texptr->height - 1) - y; pickValue = m_Output->PickPixel(m_TexDisplay.resourceId, true, x, y, m_TexDisplay.sliceFace, m_TexDisplay.mip, m_TexDisplay.sampleIdx); if(m_TexDisplay.customShaderId != ResourceId()) realValue = m_Output->PickPixel(m_TexDisplay.resourceId, false, x, y, m_TexDisplay.sliceFace, m_TexDisplay.mip, m_TexDisplay.sampleIdx); } void TextureViewer::RT_PickPixelsAndUpdate(IReplayController *) { PixelValue pickValue, realValue; if(m_PickedPoint.x() < 0 || m_PickedPoint.y() < 0) return; uint32_t x = (uint32_t)m_PickedPoint.x(); uint32_t y = (uint32_t)m_PickedPoint.y(); RT_FetchCurrentPixel(x, y, pickValue, realValue); m_Output->SetPixelContextLocation(x, y); m_CurHoverValue = pickValue; m_CurPixelValue = pickValue; m_CurRealValue = realValue; GUIInvoke::call(this, [this]() { UI_UpdateStatusText(); }); } void TextureViewer::RT_PickHoverAndUpdate(IReplayController *) { PixelValue pickValue, realValue; uint32_t x = (uint32_t)m_CurHoverPixel.x(); uint32_t y = (uint32_t)m_CurHoverPixel.y(); RT_FetchCurrentPixel(x, y, pickValue, realValue); m_CurHoverValue = pickValue; GUIInvoke::call(this, [this]() { UI_UpdateStatusText(); }); } void TextureViewer::RT_UpdateAndDisplay(IReplayController *) { if(m_Output != NULL) m_Output->SetTextureDisplay(m_TexDisplay); GUIInvoke::call(this, [this]() { ui->render->update(); }); } void TextureViewer::RT_UpdateVisualRange(IReplayController *) { TextureDescription *texptr = GetCurrentTexture(); if(!m_Visualise || texptr == NULL || m_Output == NULL) return; ResourceFormat fmt = texptr->format; if(m_TexDisplay.customShaderId != ResourceId()) fmt.compCount = 4; bool channels[] = { m_TexDisplay.red ? true : false, m_TexDisplay.green && fmt.compCount > 1, m_TexDisplay.blue && fmt.compCount > 2, m_TexDisplay.alpha && fmt.compCount > 3, }; rdcarray<uint32_t> histogram = m_Output->GetHistogram(ui->rangeHistogram->rangeMin(), ui->rangeHistogram->rangeMax(), channels); if(!histogram.empty()) { QVector<uint32_t> histogramVec(histogram.count()); if(!histogram.isEmpty()) memcpy(histogramVec.data(), histogram.data(), histogram.byteSize()); GUIInvoke::call(this, [this, histogramVec]() { ui->rangeHistogram->setHistogramRange(ui->rangeHistogram->rangeMin(), ui->rangeHistogram->rangeMax()); ui->rangeHistogram->setHistogramData(histogramVec); }); } } void TextureViewer::UI_UpdateStatusText() { TextureDescription *texptr = GetCurrentTexture(); if(texptr == NULL) return; TextureDescription &tex = *texptr; bool dsv = (tex.creationFlags & TextureCategory::DepthTarget) || (tex.format.compType == CompType::Depth); bool uintTex = (tex.format.compType == CompType::UInt); bool sintTex = (tex.format.compType == CompType::SInt); if(m_TexDisplay.overlay == DebugOverlay::QuadOverdrawPass || m_TexDisplay.overlay == DebugOverlay::QuadOverdrawDraw || m_TexDisplay.overlay == DebugOverlay::TriangleSizeDraw || m_TexDisplay.overlay == DebugOverlay::TriangleSizeDraw) { dsv = false; uintTex = false; sintTex = false; } QColor swatchColor; if(dsv || uintTex || sintTex) { swatchColor = QColor(0, 0, 0); } else { float r = qBound(0.0f, m_CurHoverValue.floatValue[0], 1.0f); float g = qBound(0.0f, m_CurHoverValue.floatValue[1], 1.0f); float b = qBound(0.0f, m_CurHoverValue.floatValue[2], 1.0f); if(tex.format.srgbCorrected || (tex.creationFlags & TextureCategory::SwapBuffer)) { r = powf(r, 1.0f / 2.2f); g = powf(g, 1.0f / 2.2f); b = powf(b, 1.0f / 2.2f); } swatchColor = QColor(int(255.0f * r), int(255.0f * g), int(255.0f * b)); } { QPalette Pal(palette()); Pal.setColor(QPalette::Background, swatchColor); ui->pickSwatch->setAutoFillBackground(true); ui->pickSwatch->setPalette(Pal); } int y = m_CurHoverPixel.y() >> (int)m_TexDisplay.mip; uint32_t mipWidth = qMax(1U, tex.width >> (int)m_TexDisplay.mip); uint32_t mipHeight = qMax(1U, tex.height >> (int)m_TexDisplay.mip); if(m_Ctx.APIProps().pipelineType == GraphicsAPI::OpenGL) y = (int)(mipHeight - 1) - y; if(m_TexDisplay.flipY) y = (int)(mipHeight - 1) - y; y = qMax(0, y); int x = m_CurHoverPixel.x() >> (int)m_TexDisplay.mip; float invWidth = 1.0f / mipWidth; float invHeight = 1.0f / mipHeight; QString hoverCoords = QFormatStr("%1, %2 (%3, %4)") .arg(x, 4) .arg(y, 4) .arg((x * invWidth), 5, 'f', 4) .arg((y * invHeight), 5, 'f', 4); QString statusText = tr("Hover - ") + hoverCoords; uint32_t hoverX = (uint32_t)m_CurHoverPixel.x(); uint32_t hoverY = (uint32_t)m_CurHoverPixel.y(); if(hoverX > tex.width || hoverY > tex.height) statusText = tr("Hover - [%1]").arg(hoverCoords); if(m_PickedPoint.x() >= 0) { x = m_PickedPoint.x() >> (int)m_TexDisplay.mip; y = m_PickedPoint.y() >> (int)m_TexDisplay.mip; if(m_Ctx.APIProps().pipelineType == GraphicsAPI::OpenGL) y = (int)(mipHeight - 1) - y; if(m_TexDisplay.flipY) y = (int)(mipHeight - 1) - y; y = qMax(0, y); statusText += tr(" - Right click - %1, %2: ").arg(x, 4).arg(y, 4); PixelValue val = m_CurPixelValue; if(m_TexDisplay.customShaderId != ResourceId()) { statusText += QFormatStr("%1, %2, %3, %4") .arg(Formatter::Format(val.floatValue[0])) .arg(Formatter::Format(val.floatValue[1])) .arg(Formatter::Format(val.floatValue[2])) .arg(Formatter::Format(val.floatValue[3])); val = m_CurRealValue; statusText += tr(" (Real: "); } if(dsv) { statusText += tr("Depth "); if(uintTex) { statusText += Formatter::Format(val.uintValue[0]); } else { statusText += Formatter::Format(val.floatValue[0]); } int stencil = (int)(255.0f * val.floatValue[1]); statusText += tr(", Stencil %1 / 0x%2").arg(stencil).arg(Formatter::Format(uint8_t(stencil & 0xff), true)); } else { if(uintTex) { statusText += QFormatStr("%1, %2, %3, %4") .arg(Formatter::Format(val.uintValue[0])) .arg(Formatter::Format(val.uintValue[1])) .arg(Formatter::Format(val.uintValue[2])) .arg(Formatter::Format(val.uintValue[3])); } else if(sintTex) { statusText += QFormatStr("%1, %2, %3, %4") .arg(Formatter::Format(val.intValue[0])) .arg(Formatter::Format(val.intValue[1])) .arg(Formatter::Format(val.intValue[2])) .arg(Formatter::Format(val.intValue[3])); } else { statusText += QFormatStr("%1, %2, %3, %4") .arg(Formatter::Format(val.floatValue[0])) .arg(Formatter::Format(val.floatValue[1])) .arg(Formatter::Format(val.floatValue[2])) .arg(Formatter::Format(val.floatValue[3])); } } if(m_TexDisplay.customShaderId != ResourceId()) statusText += lit(")"); } else { statusText += tr(" - Right click to pick a pixel"); } // try and keep status text consistent by sticking to the high water mark // of length (prevents nasty oscillation when the length of the string is // just popping over/under enough to overflow onto the next line). if(statusText.length() > m_HighWaterStatusLength) m_HighWaterStatusLength = statusText.length(); if(statusText.length() < m_HighWaterStatusLength) statusText += QString(m_HighWaterStatusLength - statusText.length(), QLatin1Char(' ')); ui->statusText->setText(statusText); } void TextureViewer::UI_UpdateTextureDetails() { QString status; TextureDescription *texptr = GetCurrentTexture(); if(texptr == NULL) { ui->texStatusDim->setText(status); ui->renderContainer->setWindowTitle(tr("Unbound")); return; } TextureDescription &current = *texptr; ResourceId followID = m_Following.GetResourceId(m_Ctx); { TextureDescription *followtex = m_Ctx.GetTexture(followID); BufferDescription *followbuf = m_Ctx.GetBuffer(followID); QString title; if(followID == ResourceId()) { title = tr("Unbound"); } else if(followtex || followbuf) { QString name = m_Ctx.GetResourceName(followID); switch(m_Following.Type) { case FollowType::OutputColour: title = QString(tr("Cur Output %1 - %2")).arg(m_Following.index).arg(name); break; case FollowType::OutputDepth: title = QString(tr("Cur Depth Output - %1")).arg(name); break; case FollowType::ReadWrite: title = QString(tr("Cur RW Output %1 - %2")).arg(m_Following.index).arg(name); break; case FollowType::ReadOnly: title = QString(tr("Cur Input %1 - %2")).arg(m_Following.index).arg(name); break; } } else { switch(m_Following.Type) { case FollowType::OutputColour: title = QString(tr("Cur Output %1")).arg(m_Following.index); break; case FollowType::OutputDepth: title = QString(tr("Cur Depth Output")); break; case FollowType::ReadWrite: title = QString(tr("Cur RW Output %1")).arg(m_Following.index); break; case FollowType::ReadOnly: title = QString(tr("Cur Input %1")).arg(m_Following.index); break; } } ui->renderContainer->setWindowTitle(title); } status = m_Ctx.GetResourceName(current.resourceId) + lit(" - "); if(current.dimension >= 1) status += QString::number(current.width); if(current.dimension >= 2) status += lit("x") + QString::number(current.height); if(current.dimension >= 3) status += lit("x") + QString::number(current.depth); if(current.arraysize > 1) status += QFormatStr("[%1]").arg(QString::number(current.arraysize)); if(current.msQual > 0 || current.msSamp > 1) status += QFormatStr(" MS{%1x %2Q}").arg(current.msSamp).arg(current.msQual); status += QFormatStr(" %1 mips").arg(current.mips); status += lit(" - ") + current.format.Name(); if(current.format.compType != m_TexDisplay.typeHint && m_TexDisplay.typeHint != CompType::Typeless) { status += tr(" Viewed as %1").arg(ToQStr(m_TexDisplay.typeHint)); } ui->texStatusDim->setText(status); } void TextureViewer::UI_OnTextureSelectionChanged(bool newdraw) { TextureDescription *texptr = GetCurrentTexture(); // reset high-water mark m_HighWaterStatusLength = 0; if(texptr == NULL) return; TextureDescription &tex = *texptr; bool newtex = (m_TexDisplay.resourceId != tex.resourceId); // save settings for this current texture if(m_Ctx.Config().TextureViewer_PerTexSettings) { m_TextureSettings[m_TexDisplay.resourceId].r = ui->channelRed->isChecked(); m_TextureSettings[m_TexDisplay.resourceId].g = ui->channelGreen->isChecked(); m_TextureSettings[m_TexDisplay.resourceId].b = ui->channelBlue->isChecked(); m_TextureSettings[m_TexDisplay.resourceId].a = ui->channelAlpha->isChecked(); m_TextureSettings[m_TexDisplay.resourceId].displayType = qMax(0, ui->channels->currentIndex()); m_TextureSettings[m_TexDisplay.resourceId].customShader = ui->customShader->currentText(); m_TextureSettings[m_TexDisplay.resourceId].depth = ui->depthDisplay->isChecked(); m_TextureSettings[m_TexDisplay.resourceId].stencil = ui->stencilDisplay->isChecked(); m_TextureSettings[m_TexDisplay.resourceId].mip = qMax(0, ui->mipLevel->currentIndex()); m_TextureSettings[m_TexDisplay.resourceId].slice = qMax(0, ui->sliceFace->currentIndex()); m_TextureSettings[m_TexDisplay.resourceId].minrange = ui->rangeHistogram->blackPoint(); m_TextureSettings[m_TexDisplay.resourceId].maxrange = ui->rangeHistogram->whitePoint(); if(m_TexDisplay.typeHint != CompType::Typeless) m_TextureSettings[m_TexDisplay.resourceId].typeHint = m_TexDisplay.typeHint; } m_TexDisplay.resourceId = tex.resourceId; // interpret the texture according to the currently following type. if(!currentTextureIsLocked()) m_TexDisplay.typeHint = m_Following.GetTypeHint(m_Ctx); else m_TexDisplay.typeHint = CompType::Typeless; // if there is no such type or it isn't being followed, use the last seen interpretation if(m_TexDisplay.typeHint == CompType::Typeless && m_TextureSettings.contains(m_TexDisplay.resourceId)) m_TexDisplay.typeHint = m_TextureSettings[m_TexDisplay.resourceId].typeHint; // try to maintain the pan in the new texture. If the new texture // is approx an integer multiple of the old texture, just changing // the scale will keep everything the same. This is useful for // downsample chains and things where you're flipping back and forth // between overlapping textures, but even in the non-integer case // pan will be kept approximately the same. QSizeF curSize((float)tex.width, (float)tex.height); float curArea = area(curSize); float prevArea = area(m_PrevSize); if(prevArea > 0.0f && m_PrevSize.width() > 0.0f) { float prevX = m_TexDisplay.xOffset; float prevY = m_TexDisplay.yOffset; // allow slight difference in aspect ratio for rounding errors // in downscales (e.g. 1680x1050 -> 840x525 -> 420x262 in the // last downscale the ratios are 1.6 and 1.603053435). if(qAbs(aspect(curSize) - aspect(m_PrevSize)) < 0.01f) { m_TexDisplay.scale *= m_PrevSize.width() / curSize.width(); setCurrentZoomValue(m_TexDisplay.scale); } else { // this scale factor is arbitrary really, only intention is to have // integer scales come out precisely, other 'similar' sizes will be // similar ish float scaleFactor = (float)(sqrt(curArea) / sqrt(prevArea)); m_TexDisplay.xOffset = prevX * scaleFactor; m_TexDisplay.yOffset = prevY * scaleFactor; } } m_PrevSize = curSize; // refresh scroll position setScrollPosition(getScrollPosition()); UI_UpdateStatusText(); // block signals for mipLevel and sliceFace comboboxes while editing them ui->mipLevel->blockSignals(true); ui->sliceFace->blockSignals(true); ui->mipLevel->clear(); m_TexDisplay.mip = 0; m_TexDisplay.sliceFace = 0; bool usemipsettings = true; bool useslicesettings = true; if(tex.msSamp > 1) { for(uint32_t i = 0; i < tex.msSamp; i++) ui->mipLevel->addItem(tr("Sample %1").arg(i)); // add an option to display unweighted average resolved value, // to get an idea of how the samples average if(tex.format.compType != CompType::UInt && tex.format.compType != CompType::SInt && tex.format.compType != CompType::Depth && !(tex.creationFlags & TextureCategory::DepthTarget)) ui->mipLevel->addItem(tr("Average val")); ui->mipLabel->setText(tr("Sample")); ui->mipLevel->setCurrentIndex(0); } else { for(uint32_t i = 0; i < tex.mips; i++) ui->mipLevel->addItem( QFormatStr("%1 - %2x%3").arg(i).arg(qMax(1U, tex.width >> i)).arg(qMax(1U, tex.height >> i))); ui->mipLabel->setText(tr("Mip")); } if(tex.mips == 1 && tex.msSamp <= 1) ui->mipLevel->setEnabled(false); else ui->mipLevel->setEnabled(true); ui->sliceFace->clear(); uint32_t numSlices = 1; if(tex.arraysize == 1 && tex.depth <= 1) { ui->sliceFace->setEnabled(false); } else { ui->sliceFace->setEnabled(true); QString cubeFaces[] = {lit("X+"), lit("X-"), lit("Y+"), lit("Y-"), lit("Z+"), lit("Z-")}; numSlices = tex.arraysize; // for 3D textures, display the number of slices at this mip if(tex.depth > 1) numSlices = qMax(1u, tex.depth >> (int)ui->mipLevel->currentIndex()); for(uint32_t i = 0; i < numSlices; i++) { if(tex.cubemap) { QString name = cubeFaces[i % 6]; if(numSlices > 6) name = QFormatStr("[%1] %2").arg(i / 6).arg( cubeFaces[i % 6]); // Front 1, Back 2, 3, 4 etc for cube arrays ui->sliceFace->addItem(name); } else { ui->sliceFace->addItem(tr("Slice %1").arg(i)); } } } // enable signals for mipLevel and sliceFace ui->mipLevel->blockSignals(false); ui->sliceFace->blockSignals(false); { int highestMip = -1; // only switch to the selected mip for outputs, and when changing drawcall if(!currentTextureIsLocked() && m_Following.Type != FollowType::ReadOnly && newdraw) highestMip = m_Following.GetHighestMip(m_Ctx); // assuming we get a valid mip for the highest mip, only switch to it // if we've selected a new texture, or if it's different than the last mip. // This prevents the case where the user has clicked on another mip and // we don't want to snap their view back when stepping between events with the // same mip used. But it does mean that if they are stepping between // events with different mips used, then we will update in that case. if(highestMip >= 0 && (newtex || highestMip != m_PrevHighestMip)) { usemipsettings = false; ui->mipLevel->setCurrentIndex(qBound(0, highestMip, (int)tex.mips - 1)); } if(ui->mipLevel->currentIndex() == -1) ui->mipLevel->setCurrentIndex(qBound(0, m_PrevHighestMip, (int)tex.mips - 1)); m_PrevHighestMip = highestMip; } { int firstArraySlice = -1; // only switch to the selected mip for outputs, and when changing drawcall if(!currentTextureIsLocked() && m_Following.Type != FollowType::ReadOnly && newdraw) firstArraySlice = m_Following.GetFirstArraySlice(m_Ctx); // see above with highestMip and prevHighestMip for the logic behind this if(firstArraySlice >= 0 && (newtex || firstArraySlice != m_PrevFirstArraySlice)) { useslicesettings = false; ui->sliceFace->setCurrentIndex(qBound(0, firstArraySlice, (int)numSlices - 1)); } if(ui->sliceFace->currentIndex() == -1) ui->sliceFace->setCurrentIndex(qBound(0, m_PrevFirstArraySlice, (int)numSlices - 1)); m_PrevFirstArraySlice = firstArraySlice; } // because slice and mip are specially set above, we restore any per-tex settings to apply // even if we don't switch to a new texture. // Note that if the slice or mip was changed because that slice or mip is the selected one // at the API level, we leave this alone. if(m_Ctx.Config().TextureViewer_PerTexSettings && m_TextureSettings.contains(tex.resourceId)) { if(usemipsettings) ui->mipLevel->setCurrentIndex(m_TextureSettings[tex.resourceId].mip); if(useslicesettings) ui->sliceFace->setCurrentIndex(m_TextureSettings[tex.resourceId].slice); } // handling for if we've switched to a new texture if(newtex) { // if we save certain settings per-texture, restore them (if we have any) if(m_Ctx.Config().TextureViewer_PerTexSettings && m_TextureSettings.contains(tex.resourceId)) { ui->channels->setCurrentIndex(m_TextureSettings[tex.resourceId].displayType); ui->customShader->setCurrentText(m_TextureSettings[tex.resourceId].customShader); ui->channelRed->setChecked(m_TextureSettings[tex.resourceId].r); ui->channelGreen->setChecked(m_TextureSettings[tex.resourceId].g); ui->channelBlue->setChecked(m_TextureSettings[tex.resourceId].b); ui->channelAlpha->setChecked(m_TextureSettings[tex.resourceId].a); ui->depthDisplay->setChecked(m_TextureSettings[tex.resourceId].depth); ui->stencilDisplay->setChecked(m_TextureSettings[tex.resourceId].stencil); m_NoRangePaint = true; ui->rangeHistogram->setRange(m_TextureSettings[m_TexDisplay.resourceId].minrange, m_TextureSettings[m_TexDisplay.resourceId].maxrange); m_NoRangePaint = false; } else if(m_Ctx.Config().TextureViewer_PerTexSettings) { // if we are using per-tex settings, reset back to RGB ui->channels->setCurrentIndex(0); ui->customShader->setCurrentText(QString()); ui->channelRed->setChecked(true); ui->channelGreen->setChecked(true); ui->channelBlue->setChecked(true); ui->channelAlpha->setChecked(false); ui->depthDisplay->setChecked(true); ui->stencilDisplay->setChecked(false); m_NoRangePaint = true; UI_SetHistogramRange(texptr, m_TexDisplay.typeHint); m_NoRangePaint = false; } // reset the range if desired if(m_Ctx.Config().TextureViewer_ResetRange) { UI_SetHistogramRange(texptr, m_TexDisplay.typeHint); } } UI_UpdateFittedScale(); UI_UpdateTextureDetails(); UI_UpdateChannels(); if(ui->autoFit->isChecked()) AutoFitRange(); m_Ctx.Replay().AsyncInvoke([this](IReplayController *r) { RT_UpdateVisualRange(r); RT_UpdateAndDisplay(r); if(m_Output != NULL) RT_PickPixelsAndUpdate(r); }); HighlightUsage(); } void TextureViewer::UI_SetHistogramRange(const TextureDescription *tex, CompType typeHint) { if(tex != NULL && (tex->format.compType == CompType::SNorm || typeHint == CompType::SNorm)) ui->rangeHistogram->setRange(-1.0f, 1.0f); else ui->rangeHistogram->setRange(0.0f, 1.0f); } void TextureViewer::UI_UpdateChannels() { TextureDescription *tex = GetCurrentTexture(); #define SHOW(widget) widget->setVisible(true) #define HIDE(widget) widget->setVisible(false) #define ENABLE(widget) widget->setEnabled(true) #define DISABLE(widget) widget->setEnabled(false) if(tex != NULL && (tex->creationFlags & TextureCategory::SwapBuffer)) { // swapbuffer is always srgb for 8-bit types, linear for 16-bit types DISABLE(ui->gammaDisplay); if(tex->format.compByteWidth == 2 && tex->format.type == ResourceFormatType::Regular) m_TexDisplay.linearDisplayAsGamma = false; else m_TexDisplay.linearDisplayAsGamma = true; } else { if(tex != NULL && !tex->format.srgbCorrected) ENABLE(ui->gammaDisplay); else DISABLE(ui->gammaDisplay); m_TexDisplay.linearDisplayAsGamma = !ui->gammaDisplay->isEnabled() || ui->gammaDisplay->isChecked(); } if(tex != NULL && tex->format.srgbCorrected) m_TexDisplay.linearDisplayAsGamma = false; bool dsv = false; if(tex != NULL) dsv = (tex->creationFlags & TextureCategory::DepthTarget) || (tex->format.compType == CompType::Depth); if(dsv && ui->channels->currentIndex() != 2) { // Depth display (when not using custom) HIDE(ui->channelRed); HIDE(ui->channelGreen); HIDE(ui->channelBlue); HIDE(ui->channelAlpha); HIDE(ui->mulSep); HIDE(ui->mulLabel); HIDE(ui->hdrMul); HIDE(ui->customShader); HIDE(ui->customCreate); HIDE(ui->customEdit); HIDE(ui->customDelete); SHOW(ui->depthDisplay); SHOW(ui->stencilDisplay); m_TexDisplay.red = ui->depthDisplay->isChecked(); m_TexDisplay.green = ui->stencilDisplay->isChecked(); m_TexDisplay.blue = false; m_TexDisplay.alpha = false; if(m_TexDisplay.red == m_TexDisplay.green && !m_TexDisplay.red) { m_TexDisplay.red = true; ui->depthDisplay->setChecked(true); } m_TexDisplay.hdrMultiplier = -1.0f; if(m_TexDisplay.customShaderId != ResourceId()) { memset(m_CurPixelValue.floatValue, 0, sizeof(float) * 4); memset(m_CurRealValue.floatValue, 0, sizeof(float) * 4); UI_UpdateStatusText(); } m_TexDisplay.customShaderId = ResourceId(); } else if(ui->channels->currentIndex() == 0 || !m_Ctx.IsCaptureLoaded()) { // RGBA SHOW(ui->channelRed); SHOW(ui->channelGreen); SHOW(ui->channelBlue); SHOW(ui->channelAlpha); HIDE(ui->mulSep); HIDE(ui->mulLabel); HIDE(ui->hdrMul); HIDE(ui->customShader); HIDE(ui->customCreate); HIDE(ui->customEdit); HIDE(ui->customDelete); HIDE(ui->depthDisplay); HIDE(ui->stencilDisplay); m_TexDisplay.red = ui->channelRed->isChecked(); m_TexDisplay.green = ui->channelGreen->isChecked(); m_TexDisplay.blue = ui->channelBlue->isChecked(); m_TexDisplay.alpha = ui->channelAlpha->isChecked(); m_TexDisplay.hdrMultiplier = -1.0f; if(m_TexDisplay.customShaderId != ResourceId()) { memset(m_CurPixelValue.floatValue, 0, sizeof(float) * 4); memset(m_CurRealValue.floatValue, 0, sizeof(float) * 4); UI_UpdateStatusText(); } m_TexDisplay.customShaderId = ResourceId(); } else if(ui->channels->currentIndex() == 1) { // RGBM SHOW(ui->channelRed); SHOW(ui->channelGreen); SHOW(ui->channelBlue); HIDE(ui->channelAlpha); SHOW(ui->mulSep); SHOW(ui->mulLabel); SHOW(ui->hdrMul); HIDE(ui->customShader); HIDE(ui->customCreate); HIDE(ui->customEdit); HIDE(ui->customDelete); HIDE(ui->depthDisplay); HIDE(ui->stencilDisplay); m_TexDisplay.red = ui->channelRed->isChecked(); m_TexDisplay.green = ui->channelGreen->isChecked(); m_TexDisplay.blue = ui->channelBlue->isChecked(); m_TexDisplay.alpha = false; bool ok = false; float mul = ui->hdrMul->currentText().toFloat(&ok); if(!ok) { mul = 32.0f; ui->hdrMul->setCurrentText(lit("32")); } m_TexDisplay.hdrMultiplier = mul; if(m_TexDisplay.customShaderId != ResourceId()) { memset(m_CurPixelValue.floatValue, 0, sizeof(float) * 4); memset(m_CurRealValue.floatValue, 0, sizeof(float) * 4); UI_UpdateStatusText(); } m_TexDisplay.customShaderId = ResourceId(); } else if(ui->channels->currentIndex() == 2) { // custom shaders SHOW(ui->channelRed); SHOW(ui->channelGreen); SHOW(ui->channelBlue); SHOW(ui->channelAlpha); HIDE(ui->mulSep); HIDE(ui->mulLabel); HIDE(ui->hdrMul); SHOW(ui->customShader); SHOW(ui->customCreate); SHOW(ui->customEdit); SHOW(ui->customDelete); HIDE(ui->depthDisplay); HIDE(ui->stencilDisplay); m_TexDisplay.red = ui->channelRed->isChecked(); m_TexDisplay.green = ui->channelGreen->isChecked(); m_TexDisplay.blue = ui->channelBlue->isChecked(); m_TexDisplay.alpha = ui->channelAlpha->isChecked(); m_TexDisplay.hdrMultiplier = -1.0f; m_TexDisplay.customShaderId = ResourceId(); QString shaderName = ui->customShader->currentText().toUpper(); if(m_CustomShaders.contains(shaderName)) { if(m_TexDisplay.customShaderId == ResourceId()) { memset(m_CurPixelValue.floatValue, 0, sizeof(float) * 4); memset(m_CurRealValue.floatValue, 0, sizeof(float) * 4); UI_UpdateStatusText(); } m_TexDisplay.customShaderId = m_CustomShaders[shaderName]; ui->customDelete->setEnabled(true); ui->customEdit->setEnabled(true); } else { ui->customDelete->setEnabled(false); ui->customEdit->setEnabled(false); } } #undef HIDE #undef SHOW #undef ENABLE #undef DISABLE m_TexDisplay.flipY = ui->flip_y->isChecked(); INVOKE_MEMFN(RT_UpdateAndDisplay); INVOKE_MEMFN(RT_UpdateVisualRange); } void TextureViewer::SetupTextureTabs() { ToolWindowManagerArea *textureTabs = ui->dockarea->areaOf(ui->renderContainer); QIcon tabIcon; tabIcon.addFile(QStringLiteral(":/logo.svg"), QSize(), QIcon::Normal, QIcon::Off); textureTabs->setTabIcon(0, tabIcon); textureTabs->setElideMode(Qt::ElideRight); QObject::connect(textureTabs, &QTabWidget::currentChanged, this, &TextureViewer::textureTab_Changed); QObject::connect(textureTabs, &QTabWidget::tabCloseRequested, this, &TextureViewer::textureTab_Closing); textureTabs->disableUserDrop(); textureTabs->tabBar()->setContextMenuPolicy(Qt::CustomContextMenu); QObject::connect(textureTabs->tabBar(), &QTabBar::customContextMenuRequested, this, &TextureViewer::textureTab_Menu); } void TextureViewer::textureTab_Menu(const QPoint &pos) { ToolWindowManagerArea *textureTabs = ui->dockarea->areaOf(ui->renderContainer); int tabIndex = textureTabs->tabBar()->tabAt(pos); if(tabIndex == -1) return; QAction closeTab(tr("Close tab"), this); QAction closeOtherTabs(tr("Close other tabs"), this); QAction closeRightTabs(tr("Close tabs to the right"), this); if(textureTabs->widget(tabIndex) == ui->renderContainer) closeTab.setEnabled(false); QMenu contextMenu(this); contextMenu.addAction(&closeTab); contextMenu.addAction(&closeOtherTabs); contextMenu.addAction(&closeRightTabs); QObject::connect(&closeTab, &QAction::triggered, [textureTabs, tabIndex]() { // remove the tab at this index textureTabs->removeTab(tabIndex); }); QObject::connect(&closeRightTabs, &QAction::triggered, [textureTabs, tabIndex]() { // remove all tabs with a greater index while(textureTabs->count() > tabIndex + 1) textureTabs->removeTab(tabIndex + 1); }); QObject::connect(&closeOtherTabs, &QAction::triggered, [textureTabs, tabIndex]() { // remove all tabs with a greater index while(textureTabs->count() > tabIndex + 1) textureTabs->removeTab(tabIndex + 1); // remove all tabs at index 1 until there's only two, these are the ones between the locked tab // 0 and the tabIndex while(textureTabs->count() > 2) textureTabs->removeTab(1); }); RDDialog::show(&contextMenu, QCursor::pos()); } void TextureViewer::textureTab_Changed(int index) { ToolWindowManagerArea *textureTabs = ui->dockarea->areaOf(ui->renderContainer); if(!textureTabs) return; QWidget *w = textureTabs->widget(index); if(w) { w->setLayout(ui->renderLayout); if(w == ui->renderContainer) m_LockedId = ResourceId(); else m_LockedId = w->property("id").value<ResourceId>(); UI_UpdateCachedTexture(); } UI_OnTextureSelectionChanged(false); } void TextureViewer::textureTab_Closing(int index) { ToolWindowManagerArea *textureTabs = ui->dockarea->areaOf(ui->renderContainer); if(index > 0) { // this callback happens AFTER the widget has already been removed unfortunately, so // we need to search through the locked tab list to see which one was removed to be // able to delete it properly. QList<ResourceId> ids = m_LockedTabs.keys(); for(int i = 0; i < textureTabs->count(); i++) { QWidget *w = textureTabs->widget(i); ResourceId id = w->property("id").value<ResourceId>(); ids.removeOne(id); } if(ids.count() != 1) qWarning() << "Expected only one removed tab, got " << ids.count(); for(ResourceId id : ids) m_LockedTabs.remove(id); textureTabs->setCurrentIndex(index - 1); textureTabs->widget(index - 1)->show(); return; } // should never get here - tab 0 is the dynamic tab which is uncloseable. qCritical() << "Somehow closing dynamic tab?"; if(textureTabs->count() > 1) { textureTabs->setCurrentIndex(1); textureTabs->widget(1)->show(); } } ResourcePreview *TextureViewer::UI_CreateThumbnail(ThumbnailStrip *strip) { ResourcePreview *prev = new ResourcePreview(m_Ctx, m_Output); QObject::connect(prev, &ResourcePreview::clicked, this, &TextureViewer::thumb_clicked); QObject::connect(prev, &ResourcePreview::doubleClicked, this, &TextureViewer::thumb_doubleClicked); prev->setActive(false); strip->addThumb(prev); return prev; } void TextureViewer::UI_CreateThumbnails() { if(!ui->outputThumbs->thumbs().isEmpty()) return; // these will expand, but we make sure that there is a good set reserved for(int i = 0; i < 9; i++) { ResourcePreview *prev = UI_CreateThumbnail(ui->outputThumbs); if(i == 0) prev->setSelected(true); } for(int i = 0; i < 128; i++) UI_CreateThumbnail(ui->inputThumbs); } void TextureViewer::GotoLocation(int x, int y) { if(!m_Ctx.IsCaptureLoaded()) return; TextureDescription *tex = GetCurrentTexture(); if(tex == NULL) return; m_PickedPoint = QPoint(x, y); uint32_t mipHeight = qMax(1U, tex->height >> (int)m_TexDisplay.mip); if(m_Ctx.APIProps().pipelineType == GraphicsAPI::OpenGL) m_PickedPoint.setY((int)(mipHeight - 1) - m_PickedPoint.y()); if(m_TexDisplay.flipY) m_PickedPoint.setY((int)(mipHeight - 1) - m_PickedPoint.x()); if(m_Output != NULL) INVOKE_MEMFN(RT_PickPixelsAndUpdate); INVOKE_MEMFN(RT_UpdateAndDisplay); UI_UpdateStatusText(); } void TextureViewer::ViewTexture(ResourceId ID, bool focus) { if(QThread::currentThread() != QCoreApplication::instance()->thread()) { GUIInvoke::call(this, [this, ID, focus] { this->ViewTexture(ID, focus); }); return; } if(m_LockedTabs.contains(ID)) { if(focus) ToolWindowManager::raiseToolWindow(this); QWidget *w = m_LockedTabs[ID]; ToolWindowManagerArea *textureTabs = ui->dockarea->areaOf(ui->renderContainer); int idx = textureTabs->indexOf(w); if(idx >= 0) textureTabs->setCurrentIndex(idx); INVOKE_MEMFN(RT_UpdateAndDisplay); return; } TextureDescription *tex = m_Ctx.GetTexture(ID); if(tex) { QWidget *lockedContainer = new QWidget(this); lockedContainer->setWindowTitle(m_Ctx.GetResourceName(ID)); lockedContainer->setProperty("id", QVariant::fromValue(ID)); ToolWindowManagerArea *textureTabs = ui->dockarea->areaOf(ui->renderContainer); ToolWindowManager::AreaReference ref(ToolWindowManager::AddTo, textureTabs); ui->dockarea->addToolWindow(lockedContainer, ref); ui->dockarea->setToolWindowProperties( lockedContainer, ToolWindowManager::DisallowUserDocking | ToolWindowManager::AlwaysDisplayFullTabs); lockedContainer->setLayout(ui->renderLayout); int idx = textureTabs->indexOf(lockedContainer); if(idx >= 0) textureTabs->setTabIcon(idx, Icons::page_go()); else qCritical() << "Couldn't get tab index of new tab to set icon"; // newPanel.DockHandler.TabPageContextMenuStrip = tabContextMenu; if(focus) ToolWindowManager::raiseToolWindow(this); m_LockedTabs[ID] = lockedContainer; INVOKE_MEMFN(RT_UpdateAndDisplay); return; } BufferDescription *buf = m_Ctx.GetBuffer(ID); if(buf) { IBufferViewer *viewer = m_Ctx.ViewBuffer(0, 0, ID); m_Ctx.AddDockWindow(viewer->Widget(), DockReference::AddTo, this); } } void TextureViewer::texContextItem_triggered() { QAction *act = qobject_cast<QAction *>(QObject::sender()); QVariant eid = act->property("eid"); if(eid.isValid()) { m_Ctx.SetEventID({}, eid.toUInt(), eid.toUInt()); return; } QVariant id = act->property("id"); if(id.isValid()) { ViewTexture(id.value<ResourceId>(), false); return; } } void TextureViewer::showDisabled_triggered() { m_ShowDisabled = !m_ShowDisabled; if(m_Ctx.IsCaptureLoaded()) m_Ctx.RefreshStatus(); } void TextureViewer::showEmpty_triggered() { m_ShowEmpty = !m_ShowEmpty; if(m_Ctx.IsCaptureLoaded()) m_Ctx.RefreshStatus(); } void TextureViewer::AddResourceUsageEntry(QMenu &menu, uint32_t start, uint32_t end, ResourceUsage usage) { QAction *item = NULL; if(start == end) item = new QAction( QFormatStr("EID %1: %2").arg(start).arg(ToQStr(usage, m_Ctx.APIProps().pipelineType)), this); else item = new QAction( QFormatStr("EID %1-%2: %3").arg(start).arg(end).arg(ToQStr(usage, m_Ctx.APIProps().pipelineType)), this); QObject::connect(item, &QAction::triggered, this, &TextureViewer::texContextItem_triggered); item->setProperty("eid", QVariant(end)); menu.addAction(item); } void TextureViewer::OpenResourceContextMenu(ResourceId id, bool input, const rdcarray<EventUsage> &usage) { QMenu contextMenu(this); QAction showDisabled(tr("Show Disabled"), this); QAction showEmpty(tr("Show Empty"), this); QAction openLockedTab(tr("Open new Locked Tab"), this); QAction openResourceInspector(tr("Open in Resource Inspector"), this); QAction usageTitle(tr("Used:"), this); QAction imageLayout(this); openLockedTab.setIcon(Icons::action_hover()); openResourceInspector.setIcon(Icons::link()); showDisabled.setChecked(m_ShowDisabled); showDisabled.setChecked(m_ShowEmpty); contextMenu.addAction(&showDisabled); contextMenu.addAction(&showEmpty); QObject::connect(&showDisabled, &QAction::triggered, this, &TextureViewer::showDisabled_triggered); QObject::connect(&showEmpty, &QAction::triggered, this, &TextureViewer::showEmpty_triggered); if(m_Ctx.CurPipelineState().SupportsBarriers()) { contextMenu.addSeparator(); imageLayout.setText(tr("Image is in layout ") + m_Ctx.CurPipelineState().GetResourceLayout(id)); contextMenu.addAction(&imageLayout); } if(id != ResourceId()) { contextMenu.addSeparator(); contextMenu.addAction(&openLockedTab); contextMenu.addAction(&openResourceInspector); contextMenu.addSeparator(); m_Ctx.Extensions().MenuDisplaying(input ? ContextMenu::TextureViewer_InputThumbnail : ContextMenu::TextureViewer_OutputThumbnail, &contextMenu, {{"resourceId", id}}); contextMenu.addSeparator(); contextMenu.addAction(&usageTitle); openLockedTab.setProperty("id", QVariant::fromValue(id)); QObject::connect(&openLockedTab, &QAction::triggered, this, &TextureViewer::texContextItem_triggered); QObject::connect(&openResourceInspector, &QAction::triggered, [this, id]() { m_Ctx.ShowResourceInspector(); m_Ctx.GetResourceInspector()->Inspect(id); }); CombineUsageEvents(m_Ctx, usage, [this, &contextMenu](uint32_t start, uint32_t end, ResourceUsage use) { AddResourceUsageEntry(contextMenu, start, end, use); }); RDDialog::show(&contextMenu, QCursor::pos()); } else { contextMenu.addSeparator(); m_Ctx.Extensions().MenuDisplaying(input ? ContextMenu::TextureViewer_InputThumbnail : ContextMenu::TextureViewer_OutputThumbnail, &contextMenu, {}); RDDialog::show(&contextMenu, QCursor::pos()); } } void TextureViewer::InitResourcePreview(ResourcePreview *prev, ResourceId id, CompType typeHint, bool force, Following &follow, const QString &bindName, const QString &slotName) { if(id != ResourceId() || force) { QString fullname = bindName; if(!m_Ctx.IsAutogeneratedName(id)) { if(!fullname.isEmpty()) fullname += lit(" = "); fullname += m_Ctx.GetResourceName(id); } if(fullname.isEmpty()) fullname = m_Ctx.GetResourceName(id); prev->setResourceName(fullname); WindowingData winData = m_Ctx.CreateWindowingData(prev->thumbWidget()); if(m_Ctx.GetTexture(id)) { m_Ctx.Replay().AsyncInvoke([this, winData, id, typeHint](IReplayController *) { m_Output->AddThumbnail(winData, id, typeHint); }); } else { m_Ctx.Replay().AsyncInvoke([this, winData](IReplayController *) { m_Output->AddThumbnail(winData, ResourceId(), CompType::Typeless); }); } prev->setProperty("f", QVariant::fromValue(follow)); prev->setSlotName(slotName); prev->setActive(true); prev->setSelected(m_Following == follow); } else if(m_Following == follow) { prev->setResourceName(tr("Unused")); prev->setActive(true); prev->setSelected(true); WindowingData winData = m_Ctx.CreateWindowingData(prev->thumbWidget()); m_Ctx.Replay().AsyncInvoke([this, winData](IReplayController *) { m_Output->AddThumbnail(winData, ResourceId(), CompType::Typeless); }); } else { prev->setResourceName(QString()); prev->setActive(false); prev->setSelected(false); } } void TextureViewer::InitStageResourcePreviews(ShaderStage stage, const rdcarray<ShaderResource> &resourceDetails, const rdcarray<Bindpoint> &mapping, rdcarray<BoundResourceArray> &ResList, ThumbnailStrip *prevs, int &prevIndex, bool copy, bool rw) { for(int idx = 0; idx < mapping.count(); idx++) { const Bindpoint &key = mapping[idx]; const rdcarray<BoundResource> *resArray = NULL; int residx = ResList.indexOf(key); if(residx >= 0) resArray = &ResList[residx].resources; int arrayLen = resArray != NULL ? resArray->count() : 1; // it's too expensive in bindless-type cases to create a thumbnail for every array element, so // for now we create one just for the first element and add an array size indicator to the slot // name // for(int arrayIdx = 0; arrayIdx < arrayLen; arrayIdx++) int arrayIdx = 0; { ResourceId id = resArray != NULL ? resArray->at(arrayIdx).resourceId : ResourceId(); CompType typeHint = resArray != NULL ? resArray->at(arrayIdx).typeHint : CompType::Typeless; bool used = key.used; QString bindName; for(const ShaderResource &bind : resourceDetails) { if(bind.bindPoint == idx) { bindName = bind.name; break; } } if(copy) { used = true; bindName = tr("Source"); } Following follow(rw ? FollowType::ReadWrite : FollowType::ReadOnly, stage, idx, arrayIdx); QString slotName = QFormatStr("%1 %2%3") .arg(m_Ctx.CurPipelineState().Abbrev(stage)) .arg(rw ? lit("RW ") : lit("")) .arg(idx); if(arrayLen > 1) slotName += QFormatStr(" Arr[%1]").arg(arrayLen); if(copy) slotName = tr("SRC"); // show if it's referenced by the shader - regardless of empty or not bool show = used; // it's bound, but not referenced, and we have "show disabled" show = show || (m_ShowDisabled && !used && id != ResourceId()); // it's empty, and we have "show empty" show = show || (m_ShowEmpty && id == ResourceId()); // it's the one we're following show = show || (follow == m_Following); ResourcePreview *prev = NULL; if(prevIndex < prevs->thumbs().size()) { prev = prevs->thumbs()[prevIndex]; // don't use it if we're not actually going to show it if(!show && !prev->isActive()) continue; } else { // don't create it if we're not actually going to show it if(!show) continue; prev = UI_CreateThumbnail(prevs); } prevIndex++; InitResourcePreview(prev, show ? id : ResourceId(), typeHint, show, follow, bindName, slotName); } } } void TextureViewer::thumb_doubleClicked(QMouseEvent *e) { if(e->buttons() & Qt::LeftButton) { ResourceId id = m_Following.GetResourceId(m_Ctx); if(id != ResourceId()) ViewTexture(id, false); } } void TextureViewer::thumb_clicked(QMouseEvent *e) { if(e->buttons() & Qt::LeftButton) { ResourcePreview *prev = qobject_cast<ResourcePreview *>(QObject::sender()); Following follow = prev->property("f").value<Following>(); for(ResourcePreview *p : ui->outputThumbs->thumbs()) p->setSelected(false); for(ResourcePreview *p : ui->inputThumbs->thumbs()) p->setSelected(false); m_Following = follow; prev->setSelected(true); UI_UpdateCachedTexture(); ResourceId id = m_Following.GetResourceId(m_Ctx); if(id != ResourceId()) { UI_OnTextureSelectionChanged(false); ui->renderContainer->show(); } } if(e->buttons() & Qt::RightButton) { ResourcePreview *prev = qobject_cast<ResourcePreview *>(QObject::sender()); Following follow = prev->property("f").value<Following>(); ResourceId id = follow.GetResourceId(m_Ctx); if(id == ResourceId() && follow == m_Following) id = m_TexDisplay.resourceId; rdcarray<EventUsage> empty; bool input = follow.Type == FollowType::ReadOnly; if(id == ResourceId()) { OpenResourceContextMenu(id, input, empty); } else { m_Ctx.Replay().AsyncInvoke([this, id, input](IReplayController *r) { rdcarray<EventUsage> usage = r->GetUsage(id); GUIInvoke::call(this, [this, id, input, usage]() { OpenResourceContextMenu(id, input, usage); }); }); } } } void TextureViewer::render_mouseWheel(QWheelEvent *e) { QPoint cursorPos = e->pos(); setFitToWindow(false); // scroll in logarithmic scale double logScale = logf(m_TexDisplay.scale); logScale += e->delta() / 2500.0; UI_SetScale((float)expf(logScale), cursorPos.x(), cursorPos.y()); e->accept(); } void TextureViewer::render_mouseMove(QMouseEvent *e) { if(m_Output == NULL) return; m_CurHoverPixel.setX(int((float(e->x() * ui->render->devicePixelRatio()) - m_TexDisplay.xOffset) / m_TexDisplay.scale)); m_CurHoverPixel.setY(int((float(e->y() * ui->render->devicePixelRatio()) - m_TexDisplay.yOffset) / m_TexDisplay.scale)); if(m_TexDisplay.resourceId != ResourceId()) { TextureDescription *texptr = GetCurrentTexture(); if(texptr != NULL) { if(e->buttons() & Qt::RightButton) { ui->render->setCursor(QCursor(Qt::CrossCursor)); m_PickedPoint = m_CurHoverPixel; m_PickedPoint.setX(qBound(0, m_PickedPoint.x(), (int)texptr->width - 1)); m_PickedPoint.setY(qBound(0, m_PickedPoint.y(), (int)texptr->height - 1)); m_Ctx.Replay().AsyncInvoke(lit("PickPixelClick"), [this](IReplayController *r) { RT_PickPixelsAndUpdate(r); }); } else if(e->buttons() == Qt::NoButton) { m_Ctx.Replay().AsyncInvoke(lit("PickPixelHover"), [this](IReplayController *r) { RT_PickHoverAndUpdate(r); }); } } } QPoint curpos = QCursor::pos(); if(e->buttons() & Qt::LeftButton) { if(qAbs(m_DragStartPos.x() - curpos.x()) > ui->renderHScroll->singleStep() || qAbs(m_DragStartPos.y() - curpos.y()) > ui->renderVScroll->singleStep()) { setScrollPosition(QPoint(m_DragStartScroll.x() + (curpos.x() - m_DragStartPos.x()), m_DragStartScroll.y() + (curpos.y() - m_DragStartPos.y()))); } ui->render->setCursor(QCursor(Qt::SizeAllCursor)); } if(e->buttons() == Qt::NoButton) { ui->render->unsetCursor(); } UI_UpdateStatusText(); } void TextureViewer::render_mouseClick(QMouseEvent *e) { ui->render->setFocus(); if(e->buttons() & Qt::RightButton) render_mouseMove(e); if(e->buttons() & Qt::LeftButton) { m_DragStartPos = QCursor::pos(); m_DragStartScroll = getScrollPosition(); ui->render->setCursor(QCursor(Qt::SizeAllCursor)); } } void TextureViewer::render_resize(QResizeEvent *e) { UI_UpdateFittedScale(); UI_CalcScrollbars(); INVOKE_MEMFN(RT_UpdateAndDisplay); } void TextureViewer::render_keyPress(QKeyEvent *e) { TextureDescription *texptr = GetCurrentTexture(); if(texptr == NULL) return; if(e->matches(QKeySequence::Copy)) { QClipboard *clipboard = QApplication::clipboard(); clipboard->setText(ui->texStatusDim->text() + lit(" | ") + ui->statusText->text()); } if(!m_Ctx.IsCaptureLoaded()) return; if((e->modifiers() & Qt::ControlModifier) && e->key() == Qt::Key_G) { ShowGotoPopup(); } bool nudged = false; int increment = 1 << (int)m_TexDisplay.mip; if(e->key() == Qt::Key_Up && m_PickedPoint.y() > 0) { m_PickedPoint -= QPoint(0, increment); nudged = true; } else if(e->key() == Qt::Key_Down && m_PickedPoint.y() < (int)texptr->height - 1) { m_PickedPoint += QPoint(0, increment); nudged = true; } else if(e->key() == Qt::Key_Left && m_PickedPoint.x() > 0) { m_PickedPoint -= QPoint(increment, 0); nudged = true; } else if(e->key() == Qt::Key_Right && m_PickedPoint.x() < (int)texptr->height - 1) { m_PickedPoint += QPoint(increment, 0); nudged = true; } if(nudged) { m_PickedPoint = QPoint(qBound(0, m_PickedPoint.x(), (int)texptr->width - 1), qBound(0, m_PickedPoint.y(), (int)texptr->height - 1)); e->accept(); m_Ctx.Replay().AsyncInvoke([this](IReplayController *r) { RT_PickPixelsAndUpdate(r); RT_UpdateAndDisplay(r); }); UI_UpdateStatusText(); } } float TextureViewer::CurMaxScrollX() { TextureDescription *texptr = GetCurrentTexture(); QSizeF size(1.0f, 1.0f); if(texptr != NULL) size = QSizeF(texptr->width, texptr->height); return realRenderWidth() - size.width() * m_TexDisplay.scale; } float TextureViewer::CurMaxScrollY() { TextureDescription *texptr = GetCurrentTexture(); QSizeF size(1.0f, 1.0f); if(texptr != NULL) size = QSizeF(texptr->width, texptr->height); return realRenderHeight() - size.height() * m_TexDisplay.scale; } QPoint TextureViewer::getScrollPosition() { return QPoint((int)m_TexDisplay.xOffset, m_TexDisplay.yOffset); } void TextureViewer::setScrollPosition(const QPoint &pos) { m_TexDisplay.xOffset = qMax(CurMaxScrollX(), (float)pos.x()); m_TexDisplay.yOffset = qMax(CurMaxScrollY(), (float)pos.y()); m_TexDisplay.xOffset = qMin(0.0f, m_TexDisplay.xOffset); m_TexDisplay.yOffset = qMin(0.0f, m_TexDisplay.yOffset); if(ScrollUpdateScrollbars) { ScrollUpdateScrollbars = false; if(ui->renderHScroll->isEnabled()) ui->renderHScroll->setValue(qBound(0, -int(m_TexDisplay.xOffset), ui->renderHScroll->maximum())); if(ui->renderVScroll->isEnabled()) ui->renderVScroll->setValue(qBound(0, -int(m_TexDisplay.yOffset), ui->renderVScroll->maximum())); ScrollUpdateScrollbars = true; } INVOKE_MEMFN(RT_UpdateAndDisplay); } void TextureViewer::UI_CalcScrollbars() { TextureDescription *texptr = GetCurrentTexture(); QSizeF size(1.0f, 1.0f); if(texptr != NULL) { size = QSizeF(texptr->width, texptr->height); } if((int)floor(size.width() * m_TexDisplay.scale) <= realRenderWidth()) { ui->renderHScroll->setEnabled(false); } else { ui->renderHScroll->setEnabled(true); ui->renderHScroll->setMaximum((int)ceil(size.width() * m_TexDisplay.scale - realRenderWidth())); ui->renderHScroll->setPageStep(qMax(1, ui->renderHScroll->maximum() / 6)); ui->renderHScroll->setSingleStep(int(m_TexDisplay.scale)); } if((int)floor(size.height() * m_TexDisplay.scale) <= realRenderHeight()) { ui->renderVScroll->setEnabled(false); } else { ui->renderVScroll->setEnabled(true); ui->renderVScroll->setMaximum((int)ceil(size.height() * m_TexDisplay.scale - realRenderHeight())); ui->renderVScroll->setPageStep(qMax(1, ui->renderVScroll->maximum() / 6)); ui->renderVScroll->setSingleStep(int(m_TexDisplay.scale)); } } void TextureViewer::on_renderHScroll_valueChanged(int position) { if(!ScrollUpdateScrollbars) return; ScrollUpdateScrollbars = false; { float delta = (float)position / (float)ui->renderHScroll->maximum(); setScrollPosition(QPoint((int)(CurMaxScrollX() * delta), getScrollPosition().y())); } ScrollUpdateScrollbars = true; } void TextureViewer::on_renderVScroll_valueChanged(int position) { if(!ScrollUpdateScrollbars) return; ScrollUpdateScrollbars = false; { float delta = (float)position / (float)ui->renderVScroll->maximum(); setScrollPosition(QPoint(getScrollPosition().x(), (int)(CurMaxScrollY() * delta))); } ScrollUpdateScrollbars = true; } void TextureViewer::UI_RecreatePanels() { ICaptureContext *ctx = &m_Ctx; // while a capture is loaded, pass NULL into the widget if(!m_Ctx.IsCaptureLoaded()) ctx = NULL; { CustomPaintWidget *render = new CustomPaintWidget(ctx, ui->renderContainer); render->setObjectName(ui->render->objectName()); render->setSizePolicy(ui->render->sizePolicy()); delete ui->render; ui->render = render; ui->gridLayout->addWidget(render, 1, 0, 1, 1); } { CustomPaintWidget *pixelContext = new CustomPaintWidget(ctx, ui->pixelContextLayout); pixelContext->setObjectName(ui->pixelContext->objectName()); pixelContext->setSizePolicy(ui->pixelContext->sizePolicy()); delete ui->pixelContext; ui->pixelContext = pixelContext; ui->pixelcontextgrid->addWidget(pixelContext, 0, 0, 1, 2); } updateBackgroundColors(); QObject::connect(ui->render, &CustomPaintWidget::clicked, this, &TextureViewer::render_mouseClick); QObject::connect(ui->render, &CustomPaintWidget::mouseMove, this, &TextureViewer::render_mouseMove); QObject::connect(ui->render, &CustomPaintWidget::mouseWheel, this, &TextureViewer::render_mouseWheel); QObject::connect(ui->render, &CustomPaintWidget::resize, this, &TextureViewer::render_resize); QObject::connect(ui->render, &CustomPaintWidget::keyPress, this, &TextureViewer::render_keyPress); QObject::connect(ui->pixelContext, &CustomPaintWidget::keyPress, this, &TextureViewer::render_keyPress); } void TextureViewer::updateBackgroundColors() { if(backCol.isValid()) { ui->render->setColours(backCol, backCol); ui->pixelContext->setColours(backCol, backCol); } else { ui->render->setColours(Formatter::DarkCheckerColor(), Formatter::LightCheckerColor()); ui->pixelContext->setColours(Formatter::DarkCheckerColor(), Formatter::LightCheckerColor()); } } void TextureViewer::OnCaptureLoaded() { Reset(); WindowingData renderData = m_Ctx.CreateWindowingData(ui->render); WindowingData contextData = m_Ctx.CreateWindowingData(ui->pixelContext); ui->saveTex->setEnabled(true); ui->locationGoto->setEnabled(true); ui->viewTexBuffer->setEnabled(true); if(m_Ctx.CurPipelineState().IsCaptureD3D11()) { ui->pixelHistory->setEnabled(true); ui->pixelHistory->setToolTip(QString()); } else { ui->pixelHistory->setEnabled(false); ui->pixelHistory->setToolTip(tr("Pixel History not implemented on this API")); } if(m_Ctx.CurPipelineState().IsCaptureD3D11()) { ui->debugPixelContext->setEnabled(true); ui->debugPixelContext->setToolTip(QString()); } else { ui->debugPixelContext->setEnabled(false); ui->debugPixelContext->setToolTip(tr("Shader Debugging not implemented on this API")); } TextureListItemModel *model = (TextureListItemModel *)ui->textureList->model(); model->reset(TextureListItemModel::String, QString()); m_TexDisplay.backgroundColor = backCol.isValid() ? FloatVector(backCol.redF(), backCol.greenF(), backCol.blueF(), 1.0f) : FloatVector(); m_Ctx.Replay().BlockInvoke([renderData, contextData, this](IReplayController *r) { m_Output = r->CreateOutput(renderData, ReplayOutputType::Texture); m_Output->SetPixelContext(contextData); ui->render->setOutput(m_Output); ui->pixelContext->setOutput(m_Output); RT_UpdateAndDisplay(r); GUIInvoke::call(this, [this]() { OnEventChanged(m_Ctx.CurEvent()); }); }); m_Watcher = new QFileSystemWatcher({configFilePath(QString())}, this); QObject::connect(m_Watcher, &QFileSystemWatcher::fileChanged, this, &TextureViewer::customShaderModified); QObject::connect(m_Watcher, &QFileSystemWatcher::directoryChanged, this, &TextureViewer::customShaderModified); reloadCustomShaders(QString()); } void TextureViewer::Reset() { m_CachedTexture = NULL; m_PickedPoint.setX(-1); m_PickedPoint.setY(-1); memset(&m_TexDisplay, 0, sizeof(m_TexDisplay)); m_TexDisplay.backgroundColor = backCol.isValid() ? FloatVector(backCol.redF(), backCol.greenF(), backCol.blueF(), 1.0f) : FloatVector(); m_Output = NULL; m_TextureSettings.clear(); m_PrevSize = QSizeF(); m_HighWaterStatusLength = 0; ui->rangeHistogram->setRange(0.0f, 1.0f); ui->textureListFilter->setCurrentIndex(0); ui->renderHScroll->setEnabled(false); ui->renderVScroll->setEnabled(false); ui->pixelHistory->setEnabled(false); ui->pixelHistory->setToolTip(QString()); ui->debugPixelContext->setEnabled(false); ui->debugPixelContext->setToolTip(QString()); ui->statusText->setText(QString()); ui->renderContainer->setWindowTitle(tr("Current")); ui->mipLevel->clear(); ui->sliceFace->clear(); UI_SetScale(1.0f); ui->channels->setCurrentIndex(0); ui->overlay->setCurrentIndex(0); { QPalette Pal(palette()); Pal.setColor(QPalette::Background, Qt::black); ui->pickSwatch->setAutoFillBackground(true); ui->pickSwatch->setPalette(Pal); } ui->customShader->clear(); UI_RecreatePanels(); ui->inputThumbs->clearThumbs(); ui->outputThumbs->clearThumbs(); UI_UpdateTextureDetails(); UI_UpdateChannels(); } void TextureViewer::OnCaptureClosed() { Reset(); refreshTextureList(); delete m_Watcher; m_Watcher = NULL; ToolWindowManagerArea *textureTabs = ui->dockarea->areaOf(ui->renderContainer); while(textureTabs->count() > 1) textureTabs->removeTab(1); m_LockedTabs.clear(); ui->customShader->clear(); m_CustomShaders.clear(); ui->saveTex->setEnabled(false); ui->locationGoto->setEnabled(false); ui->viewTexBuffer->setEnabled(false); } void TextureViewer::OnEventChanged(uint32_t eventId) { UI_UpdateCachedTexture(); TextureDescription *CurrentTexture = GetCurrentTexture(); if(!currentTextureIsLocked() || (CurrentTexture != NULL && m_TexDisplay.resourceId != CurrentTexture->resourceId)) UI_OnTextureSelectionChanged(true); if(m_Output == NULL) return; UI_CreateThumbnails(); UI_UpdateTextureDetails(); refreshTextureList(); // iterate over locked tabs, and update the name if it's changed for(QWidget *w : m_LockedTabs.values()) { ResourceId id = w->property("id").value<ResourceId>(); w->setWindowTitle(m_Ctx.GetResourceName(id)); } rdcarray<BoundResource> RTs = Following::GetOutputTargets(m_Ctx); BoundResource Depth = Following::GetDepthTarget(m_Ctx); int outIndex = 0; int inIndex = 0; bool copy = false, clear = false, compute = false; Following::GetDrawContext(m_Ctx, copy, clear, compute); for(int rt = 0; rt < RTs.count(); rt++) { ResourcePreview *prev; if(outIndex < ui->outputThumbs->thumbs().size()) prev = ui->outputThumbs->thumbs()[outIndex]; else prev = UI_CreateThumbnail(ui->outputThumbs); outIndex++; Following follow(FollowType::OutputColour, ShaderStage::Pixel, rt, 0); QString bindName = (copy || clear) ? tr("Destination") : QString(); QString slotName = (copy || clear) ? tr("DST") : (m_Ctx.CurPipelineState().OutputAbbrev() + QString::number(rt)); InitResourcePreview(prev, RTs[rt].resourceId, RTs[rt].typeHint, false, follow, bindName, slotName); } // depth { ResourcePreview *prev; if(outIndex < ui->outputThumbs->thumbs().size()) prev = ui->outputThumbs->thumbs()[outIndex]; else prev = UI_CreateThumbnail(ui->outputThumbs); outIndex++; Following follow(FollowType::OutputDepth, ShaderStage::Pixel, 0, 0); InitResourcePreview(prev, Depth.resourceId, Depth.typeHint, false, follow, QString(), tr("DS")); } ShaderStage stages[] = {ShaderStage::Vertex, ShaderStage::Hull, ShaderStage::Domain, ShaderStage::Geometry, ShaderStage::Pixel}; int count = 5; if(compute) { stages[0] = ShaderStage::Compute; count = 1; } const rdcarray<ShaderResource> empty; // display resources used for all stages for(int i = 0; i < count; i++) { ShaderStage stage = stages[i]; rdcarray<BoundResourceArray> RWs = Following::GetReadWriteResources(m_Ctx, stage); rdcarray<BoundResourceArray> ROs = Following::GetReadOnlyResources(m_Ctx, stage); const ShaderReflection *details = Following::GetReflection(m_Ctx, stage); const ShaderBindpointMapping &mapping = Following::GetMapping(m_Ctx, stage); InitStageResourcePreviews(stage, details != NULL ? details->readWriteResources : empty, mapping.readWriteResources, RWs, ui->outputThumbs, outIndex, copy, true); InitStageResourcePreviews(stage, details != NULL ? details->readOnlyResources : empty, mapping.readOnlyResources, ROs, ui->inputThumbs, inIndex, copy, false); } // hide others const QVector<ResourcePreview *> &outThumbs = ui->outputThumbs->thumbs(); for(; outIndex < outThumbs.size(); outIndex++) { ResourcePreview *prev = outThumbs[outIndex]; prev->setResourceName(QString()); prev->setActive(false); prev->setSelected(false); } ui->outputThumbs->refreshLayout(); const QVector<ResourcePreview *> &inThumbs = ui->inputThumbs->thumbs(); for(; inIndex < inThumbs.size(); inIndex++) { ResourcePreview *prev = inThumbs[inIndex]; prev->setResourceName(QString()); prev->setActive(false); prev->setSelected(false); } ui->inputThumbs->refreshLayout(); INVOKE_MEMFN(RT_UpdateAndDisplay); if(ui->autoFit->isChecked()) AutoFitRange(); } QVariant TextureViewer::persistData() { QVariantMap state = ui->dockarea->saveState(); state[lit("backCol")] = backCol; state[lit("checker")] = !backCol.isValid(); return state; } void TextureViewer::setPersistData(const QVariant &persistData) { QVariantMap state = persistData.toMap(); backCol = state[lit("backCol")].value<QColor>(); bool checker = state[lit("checker")].value<bool>(); if(checker) backCol = QColor(); ui->backcolorPick->setChecked(!checker); ui->checkerBack->setChecked(checker); m_TexDisplay.backgroundColor = checker ? FloatVector() : FloatVector(backCol.redF(), backCol.greenF(), backCol.blueF(), 1.0f); ToolWindowManagerArea *textureTabs = ui->dockarea->areaOf(ui->renderContainer); while(textureTabs->count() > 1) textureTabs->removeTab(1); m_LockedTabs.clear(); updateBackgroundColors(); ui->dockarea->restoreState(state); SetupTextureTabs(); } float TextureViewer::GetFitScale() { TextureDescription *texptr = GetCurrentTexture(); if(texptr == NULL) return 1.0f; float xscale = (float)realRenderWidth() / (float)texptr->width; float yscale = (float)realRenderHeight() / (float)texptr->height; return qMin(xscale, yscale); } int TextureViewer::realRenderWidth() const { return ui->render->width() * ui->render->devicePixelRatio(); } int TextureViewer::realRenderHeight() const { return ui->render->height() * ui->render->devicePixelRatio(); } void TextureViewer::UI_UpdateFittedScale() { if(ui->fitToWindow->isChecked()) UI_SetScale(1.0f); } void TextureViewer::UI_SetScale(float s) { UI_SetScale(s, ui->render->width() / 2, ui->render->height() / 2); } void TextureViewer::UI_SetScale(float s, int x, int y) { if(ui->fitToWindow->isChecked()) s = GetFitScale(); float prevScale = m_TexDisplay.scale; m_TexDisplay.scale = qBound(0.1f, s, 256.0f); INVOKE_MEMFN(RT_UpdateAndDisplay); float scaleDelta = (m_TexDisplay.scale / prevScale); QPoint newPos = getScrollPosition(); newPos -= QPoint(x, y); newPos = QPoint((int)(newPos.x() * scaleDelta), (int)(newPos.y() * scaleDelta)); newPos += QPoint(x, y); setScrollPosition(newPos); setCurrentZoomValue(m_TexDisplay.scale); UI_CalcScrollbars(); } void TextureViewer::setCurrentZoomValue(float zoom) { ui->zoomOption->setCurrentText(QString::number(ceil(zoom * 100)) + lit("%")); } float TextureViewer::getCurrentZoomValue() { if(ui->fitToWindow->isChecked()) return m_TexDisplay.scale; QString zoomText = ui->zoomOption->currentText().replace(QLatin1Char('%'), QLatin1Char(' ')); bool ok = false; int zoom = zoomText.toInt(&ok); if(!ok) zoom = 100; return (float)(zoom) / 100.0f; } void TextureViewer::setFitToWindow(bool checked) { if(checked) { UI_UpdateFittedScale(); ui->fitToWindow->setChecked(true); } else if(!checked) { ui->fitToWindow->setChecked(false); float curScale = m_TexDisplay.scale; ui->zoomOption->setCurrentText(QString()); setCurrentZoomValue(curScale); } } void TextureViewer::on_fitToWindow_toggled(bool checked) { UI_UpdateFittedScale(); } void TextureViewer::on_zoomExactSize_clicked() { ui->fitToWindow->setChecked(false); UI_SetScale(1.0f); } void TextureViewer::on_zoomOption_currentIndexChanged(int index) { if(index >= 0) { setFitToWindow(false); ui->zoomOption->setCurrentText(ui->zoomOption->itemText(index)); UI_SetScale(getCurrentZoomValue()); } } void TextureViewer::zoomOption_returnPressed() { UI_SetScale(getCurrentZoomValue()); } void TextureViewer::on_overlay_currentIndexChanged(int index) { m_TexDisplay.overlay = DebugOverlay::NoOverlay; if(ui->overlay->currentIndex() > 0) m_TexDisplay.overlay = (DebugOverlay)ui->overlay->currentIndex(); #define ANALYTICS_OVERLAY(name) \ case DebugOverlay::name: ANALYTIC_SET(TextureOverlays.name, true); break; switch(m_TexDisplay.overlay) { ANALYTICS_OVERLAY(Drawcall); ANALYTICS_OVERLAY(Wireframe); ANALYTICS_OVERLAY(Depth); ANALYTICS_OVERLAY(Stencil); ANALYTICS_OVERLAY(BackfaceCull); ANALYTICS_OVERLAY(ViewportScissor); ANALYTICS_OVERLAY(NaN); ANALYTICS_OVERLAY(Clipping); ANALYTICS_OVERLAY(ClearBeforePass); ANALYTICS_OVERLAY(ClearBeforeDraw); ANALYTICS_OVERLAY(QuadOverdrawPass); ANALYTICS_OVERLAY(QuadOverdrawDraw); ANALYTICS_OVERLAY(TriangleSizePass); ANALYTICS_OVERLAY(TriangleSizeDraw); default: break; } #undef ANALYTICS_OVERLAY INVOKE_MEMFN(RT_UpdateAndDisplay); if(m_Output != NULL && m_PickedPoint.x() >= 0 && m_PickedPoint.y() >= 0) { INVOKE_MEMFN(RT_PickPixelsAndUpdate); } } void TextureViewer::channelsWidget_mouseClicked(QMouseEvent *event) { RDToolButton *s = qobject_cast<RDToolButton *>(QObject::sender()); if(event->button() == Qt::RightButton && s) { bool checkd = false; RDToolButton *butts[] = {ui->channelRed, ui->channelGreen, ui->channelBlue, ui->channelAlpha}; for(RDToolButton *b : butts) { if(b->isChecked() && b != s) checkd = true; if(!b->isChecked() && b == s) checkd = true; } ui->channelRed->setChecked(!checkd); ui->channelGreen->setChecked(!checkd); ui->channelBlue->setChecked(!checkd); ui->channelAlpha->setChecked(!checkd); s->setChecked(checkd); } } void TextureViewer::range_rangeUpdated() { m_TexDisplay.rangeMin = ui->rangeHistogram->blackPoint(); m_TexDisplay.rangeMax = ui->rangeHistogram->whitePoint(); ui->rangeBlack->setText(Formatter::Format(m_TexDisplay.rangeMin)); ui->rangeWhite->setText(Formatter::Format(m_TexDisplay.rangeMax)); if(m_NoRangePaint) return; INVOKE_MEMFN(RT_UpdateAndDisplay); if(m_Output == NULL) { ui->render->update(); ui->pixelContext->update(); } } void TextureViewer::rangePoint_textChanged(QString text) { m_RangePoint_Dirty = true; } void TextureViewer::rangePoint_Update() { float black = ui->rangeHistogram->blackPoint(); float white = ui->rangeHistogram->whitePoint(); bool ok = false; double d = ui->rangeBlack->text().toDouble(&ok); if(ok) black = d; d = ui->rangeWhite->text().toDouble(&ok); if(ok) white = d; ui->rangeHistogram->setRange(black, white); INVOKE_MEMFN(RT_UpdateVisualRange); } void TextureViewer::rangePoint_leave() { if(!m_RangePoint_Dirty) return; rangePoint_Update(); m_RangePoint_Dirty = false; } void TextureViewer::rangePoint_keyPress(QKeyEvent *e) { // escape key if(e->key() == Qt::Key_Escape) { m_RangePoint_Dirty = false; ui->rangeHistogram->setRange(ui->rangeHistogram->blackPoint(), ui->rangeHistogram->whitePoint()); } if(e->key() == Qt::Key_Return || e->key() == Qt::Key_Enter) { rangePoint_Update(); } } void TextureViewer::on_zoomRange_clicked() { float black = ui->rangeHistogram->blackPoint(); float white = ui->rangeHistogram->whitePoint(); ui->autoFit->setChecked(false); ui->rangeHistogram->setRange(black, white); INVOKE_MEMFN(RT_UpdateVisualRange); } void TextureViewer::on_autoFit_clicked() { AutoFitRange(); ui->autoFit->setChecked(false); } void TextureViewer::on_autoFit_mouseClicked(QMouseEvent *e) { if(e->buttons() & Qt::RightButton) ui->autoFit->setChecked(!ui->autoFit->isChecked()); } void TextureViewer::on_reset01_clicked() { UI_SetHistogramRange(GetCurrentTexture(), m_TexDisplay.typeHint); ui->autoFit->setChecked(false); INVOKE_MEMFN(RT_UpdateVisualRange); } void TextureViewer::on_visualiseRange_clicked() { if(ui->visualiseRange->isChecked()) { ui->rangeHistogram->setMinimumSize(QSize(300, 90)); m_Visualise = true; INVOKE_MEMFN(RT_UpdateVisualRange); } else { m_Visualise = false; ui->rangeHistogram->setMinimumSize(QSize(200, 0)); ui->rangeHistogram->setHistogramData({}); } } void TextureViewer::AutoFitRange() { // no capture loaded or buffer/empty texture currently being viewed - don't autofit if(!m_Ctx.IsCaptureLoaded() || GetCurrentTexture() == NULL || m_Output == NULL) return; m_Ctx.Replay().AsyncInvoke([this](IReplayController *r) { PixelValue min, max; std::tie(min, max) = m_Output->GetMinMax(); { float minval = FLT_MAX; float maxval = -FLT_MAX; bool changeRange = false; ResourceFormat fmt = GetCurrentTexture()->format; if(m_TexDisplay.customShaderId != ResourceId()) { fmt.compType = CompType::Float; } for(int i = 0; i < 4; i++) { if(fmt.compType == CompType::UInt) { min.floatValue[i] = min.uintValue[i]; max.floatValue[i] = max.uintValue[i]; } else if(fmt.compType == CompType::SInt) { min.floatValue[i] = min.intValue[i]; max.floatValue[i] = max.intValue[i]; } } if(m_TexDisplay.red) { minval = qMin(minval, min.floatValue[0]); maxval = qMax(maxval, max.floatValue[0]); changeRange = true; } if(m_TexDisplay.green && fmt.compCount > 1) { minval = qMin(minval, min.floatValue[1]); maxval = qMax(maxval, max.floatValue[1]); changeRange = true; } if(m_TexDisplay.blue && fmt.compCount > 2) { minval = qMin(minval, min.floatValue[2]); maxval = qMax(maxval, max.floatValue[2]); changeRange = true; } if(m_TexDisplay.alpha && fmt.compCount > 3) { minval = qMin(minval, min.floatValue[3]); maxval = qMax(maxval, max.floatValue[3]); changeRange = true; } if(changeRange) { GUIInvoke::call(this, [this, minval, maxval]() { ui->rangeHistogram->setRange(minval, maxval); INVOKE_MEMFN(RT_UpdateVisualRange); }); } } }); } void TextureViewer::on_backcolorPick_clicked() { QColor col = QColorDialog::getColor(Qt::black, this, tr("Choose background colour")); if(!col.isValid()) return; col = col.toRgb(); m_TexDisplay.backgroundColor = FloatVector(col.redF(), col.greenF(), col.blueF(), 1.0f); backCol = col; updateBackgroundColors(); ui->backcolorPick->setChecked(true); ui->checkerBack->setChecked(false); INVOKE_MEMFN(RT_UpdateAndDisplay); if(m_Output == NULL) { ui->render->update(); ui->pixelContext->update(); } } void TextureViewer::on_checkerBack_clicked() { ui->checkerBack->setChecked(true); ui->backcolorPick->setChecked(false); backCol = QColor(); m_TexDisplay.backgroundColor = FloatVector(); updateBackgroundColors(); INVOKE_MEMFN(RT_UpdateAndDisplay); if(m_Output == NULL) { ui->render->update(); ui->pixelContext->update(); } } void TextureViewer::on_mipLevel_currentIndexChanged(int index) { TextureDescription *texptr = GetCurrentTexture(); if(texptr == NULL) return; TextureDescription &tex = *texptr; uint32_t prevSlice = m_TexDisplay.sliceFace; if(tex.mips > 1) { m_TexDisplay.mip = (uint32_t)qMax(0, index); m_TexDisplay.sampleIdx = 0; } else { m_TexDisplay.mip = 0; m_TexDisplay.sampleIdx = (uint32_t)qMax(0, index); if(m_TexDisplay.sampleIdx == tex.msSamp) m_TexDisplay.sampleIdx = ~0U; } // For 3D textures, update the slice list for this mip if(tex.depth > 1) { uint32_t newSlice = prevSlice >> (int)m_TexDisplay.mip; uint32_t numSlices = qMax(1U, tex.depth >> (int)m_TexDisplay.mip); ui->sliceFace->clear(); for(uint32_t i = 0; i < numSlices; i++) ui->sliceFace->addItem(tr("Slice %1").arg(i)); // changing sliceFace index will handle updating range & re-picking ui->sliceFace->setCurrentIndex((int)qBound(0U, newSlice, numSlices - 1)); return; } INVOKE_MEMFN(RT_UpdateVisualRange); if(m_Output != NULL && m_PickedPoint.x() >= 0 && m_PickedPoint.y() >= 0) { INVOKE_MEMFN(RT_PickPixelsAndUpdate); } INVOKE_MEMFN(RT_UpdateAndDisplay); } void TextureViewer::on_sliceFace_currentIndexChanged(int index) { TextureDescription *texptr = GetCurrentTexture(); if(texptr == NULL) return; TextureDescription &tex = *texptr; m_TexDisplay.sliceFace = (uint32_t)qMax(0, index); if(tex.depth > 1) m_TexDisplay.sliceFace = (uint32_t)(qMax(0, index) << (int)m_TexDisplay.mip); INVOKE_MEMFN(RT_UpdateVisualRange); if(m_Output != NULL && m_PickedPoint.x() >= 0 && m_PickedPoint.y() >= 0) { INVOKE_MEMFN(RT_PickPixelsAndUpdate); } INVOKE_MEMFN(RT_UpdateAndDisplay); } void TextureViewer::on_locationGoto_clicked() { ShowGotoPopup(); } void TextureViewer::ShowGotoPopup() { TextureDescription *texptr = GetCurrentTexture(); if(texptr) { QPoint p = m_PickedPoint; uint32_t mipHeight = qMax(1U, texptr->height >> (int)m_TexDisplay.mip); if(m_Ctx.APIProps().pipelineType == GraphicsAPI::OpenGL) p.setY((int)(mipHeight - 1) - p.y()); if(m_TexDisplay.flipY) p.setY((int)(mipHeight - 1) - p.y()); m_Goto->show(ui->render, p); } } void TextureViewer::on_viewTexBuffer_clicked() { TextureDescription *texptr = GetCurrentTexture(); if(texptr) { IBufferViewer *viewer = m_Ctx.ViewTextureAsBuffer(m_TexDisplay.sliceFace, m_TexDisplay.mip, texptr->resourceId, FormatElement::GenerateTextureBufferFormat(*texptr)); m_Ctx.AddDockWindow(viewer->Widget(), DockReference::AddTo, this); } } void TextureViewer::on_resourceDetails_clicked() { TextureDescription *texptr = GetCurrentTexture(); if(texptr) { if(!m_Ctx.HasResourceInspector()) m_Ctx.ShowResourceInspector(); m_Ctx.GetResourceInspector()->Inspect(texptr->resourceId); ToolWindowManager::raiseToolWindow(m_Ctx.GetResourceInspector()->Widget()); } } void TextureViewer::on_saveTex_clicked() { TextureDescription *texptr = GetCurrentTexture(); if(!texptr || !m_Output) return; // overwrite save params with current texture display settings m_SaveConfig.resourceId = m_TexDisplay.resourceId; m_SaveConfig.typeHint = m_TexDisplay.typeHint; m_SaveConfig.slice.sliceIndex = (int)m_TexDisplay.sliceFace; m_SaveConfig.mip = (int)m_TexDisplay.mip; if(texptr->depth > 1) m_SaveConfig.slice.sliceIndex = (int)m_TexDisplay.sliceFace >> (int)m_TexDisplay.mip; m_SaveConfig.channelExtract = -1; if(m_TexDisplay.red && !m_TexDisplay.green && !m_TexDisplay.blue && !m_TexDisplay.alpha) m_SaveConfig.channelExtract = 0; if(!m_TexDisplay.red && m_TexDisplay.green && !m_TexDisplay.blue && !m_TexDisplay.alpha) m_SaveConfig.channelExtract = 1; if(!m_TexDisplay.red && !m_TexDisplay.green && m_TexDisplay.blue && !m_TexDisplay.alpha) m_SaveConfig.channelExtract = 2; if(!m_TexDisplay.red && !m_TexDisplay.green && !m_TexDisplay.blue && m_TexDisplay.alpha) m_SaveConfig.channelExtract = 3; m_SaveConfig.comp.blackPoint = m_TexDisplay.rangeMin; m_SaveConfig.comp.whitePoint = m_TexDisplay.rangeMax; m_SaveConfig.alphaCol = m_TexDisplay.backgroundColor; if(m_TexDisplay.customShaderId != ResourceId()) { ResourceId id; m_Ctx.Replay().BlockInvoke( [this, &id](IReplayController *r) { id = m_Output->GetCustomShaderTexID(); }); if(id != ResourceId()) m_SaveConfig.resourceId = id; } const ResourceId overlayTexID = m_Output->GetDebugOverlayTexID(); const bool hasSelectedOverlay = (m_TexDisplay.overlay != DebugOverlay::NoOverlay); const bool hasOverlay = (hasSelectedOverlay && overlayTexID != ResourceId()); TextureSaveDialog saveDialog(*texptr, hasOverlay, m_SaveConfig, this); int res = RDDialog::show(&saveDialog); m_SaveConfig = saveDialog.config(); if(saveDialog.saveOverlayInstead()) { m_SaveConfig.resourceId = overlayTexID; if(m_TexDisplay.overlay == DebugOverlay::QuadOverdrawDraw || m_TexDisplay.overlay == DebugOverlay::QuadOverdrawPass || m_TexDisplay.overlay == DebugOverlay::TriangleSizeDraw || m_TexDisplay.overlay == DebugOverlay::TriangleSizePass) { m_SaveConfig.comp.blackPoint = 0.0f; m_SaveConfig.comp.whitePoint = 255.0f; } } if(res) { ANALYTIC_SET(Export.Texture, true); bool ret = false; QString fn = saveDialog.filename(); m_Ctx.Replay().BlockInvoke([this, &ret, fn](IReplayController *r) { ret = r->SaveTexture(m_SaveConfig, fn.toUtf8().data()); }); if(!ret) { RDDialog::critical( NULL, tr("Error saving texture"), tr("Error saving texture %1.\n\nCheck diagnostic log in Help menu for more details.").arg(fn)); } } } void TextureViewer::on_debugPixelContext_clicked() { if(m_PickedPoint.x() < 0 || m_PickedPoint.y() < 0) return; int x = m_PickedPoint.x() >> (int)m_TexDisplay.mip; int y = m_PickedPoint.y() >> (int)m_TexDisplay.mip; TextureDescription *texptr = GetCurrentTexture(); uint32_t mipHeight = qMax(1U, texptr->height >> (int)m_TexDisplay.mip); if(m_TexDisplay.flipY) y = (int)(mipHeight - 1) - y; bool done = false; ShaderDebugTrace *trace = NULL; m_Ctx.Replay().AsyncInvoke([this, &trace, &done, x, y](IReplayController *r) { trace = r->DebugPixel((uint32_t)x, (uint32_t)y, m_TexDisplay.sampleIdx, ~0U); if(trace->states.isEmpty()) { r->FreeTrace(trace); trace = NULL; } done = true; }); QString debugContext = tr("Pixel %1,%2").arg(x).arg(y); // wait a short while before displaying the progress dialog (which won't show if we're already // done by the time we reach it) for(int i = 0; !done && i < 100; i++) QThread::msleep(5); ShowProgressDialog(this, tr("Debugging %1").arg(debugContext), [&done]() { return done; }); // if we couldn't debug the pixel on this event, open up a pixel history if(!trace) { on_pixelHistory_clicked(); return; } const ShaderReflection *shaderDetails = m_Ctx.CurPipelineState().GetShaderReflection(ShaderStage::Pixel); const ShaderBindpointMapping &bindMapping = m_Ctx.CurPipelineState().GetBindpointMapping(ShaderStage::Pixel); ResourceId pipeline = m_Ctx.CurPipelineState().GetGraphicsPipelineObject(); // viewer takes ownership of the trace IShaderViewer *s = m_Ctx.DebugShader(&bindMapping, shaderDetails, pipeline, trace, debugContext); m_Ctx.AddDockWindow(s->Widget(), DockReference::AddTo, this); } void TextureViewer::on_pixelHistory_clicked() { TextureDescription *texptr = GetCurrentTexture(); if(!texptr || !m_Output) return; ANALYTIC_SET(UIFeatures.PixelHistory, true); int x = m_PickedPoint.x() >> (int)m_TexDisplay.mip; int y = m_PickedPoint.y() >> (int)m_TexDisplay.mip; uint32_t mipHeight = qMax(1U, texptr->height >> (int)m_TexDisplay.mip); if(m_TexDisplay.flipY) y = (int)(mipHeight - 1) - y; IPixelHistoryView *hist = m_Ctx.ViewPixelHistory(texptr->resourceId, x, y, m_TexDisplay); m_Ctx.AddDockWindow(hist->Widget(), DockReference::TransientPopupArea, this, 0.3f); // we use this pointer to ensure that the history viewer is still visible (and hasn't been closed) // by the time we want to set the results. QPointer<QWidget> histWidget = hist->Widget(); // add a short delay so that controls repainting after a new panel appears can get at the // render thread before we insert the long blocking pixel history task LambdaThread *thread = new LambdaThread([this, texptr, x, y, hist, histWidget]() { QThread::msleep(150); m_Ctx.Replay().AsyncInvoke([this, texptr, x, y, hist, histWidget](IReplayController *r) { rdcarray<PixelModification> history = r->PixelHistory(texptr->resourceId, (uint32_t)x, (int32_t)y, m_TexDisplay.sliceFace, m_TexDisplay.mip, m_TexDisplay.sampleIdx, m_TexDisplay.typeHint); GUIInvoke::call(this, [hist, histWidget, history] { if(histWidget) hist->SetHistory(history); }); }); }); thread->selfDelete(true); thread->start(); } void TextureViewer::on_texListShow_clicked() { if(ui->textureListFrame->isVisible()) { ui->dockarea->moveToolWindow(ui->textureListFrame, ToolWindowManager::NoArea); } else { ui->textureListFilter->setCurrentText(QString()); ui->dockarea->moveToolWindow( ui->textureListFrame, ToolWindowManager::AreaReference(ToolWindowManager::LeftOf, ui->dockarea->areaOf(ui->renderContainer), 0.2f)); ui->dockarea->setToolWindowProperties(ui->textureListFrame, ToolWindowManager::HideOnClose); } } void TextureViewer::on_cancelTextureListFilter_clicked() { ui->textureListFilter->setCurrentText(QString()); } void TextureViewer::on_textureListFilter_editTextChanged(const QString &text) { TextureListItemModel *model = (TextureListItemModel *)ui->textureList->model(); if(model == NULL) return; model->reset(TextureListItemModel::String, text); } void TextureViewer::on_textureListFilter_currentIndexChanged(int index) { refreshTextureList(); } void TextureViewer::refreshTextureList() { TextureListItemModel *model = (TextureListItemModel *)ui->textureList->model(); if(model == NULL) return; if(ui->textureListFilter->currentIndex() == 1) model->reset(TextureListItemModel::Textures, QString()); else if(ui->textureListFilter->currentIndex() == 2) model->reset(TextureListItemModel::RenderTargets, QString()); else model->reset(TextureListItemModel::String, ui->textureListFilter->currentText()); } void TextureViewer::on_textureList_clicked(const QModelIndex &index) { ResourceId id = index.model()->data(index, Qt::UserRole).value<ResourceId>(); ViewTexture(id, false); } void TextureViewer::reloadCustomShaders(const QString &filter) { if(!m_Ctx.IsCaptureLoaded()) return; if(filter.isEmpty()) { QString prevtext = ui->customShader->currentText(); QList<ResourceId> shaders = m_CustomShaders.values(); m_Ctx.Replay().AsyncInvoke([shaders](IReplayController *r) { for(ResourceId s : shaders) r->FreeCustomShader(s); }); ui->customShader->clear(); m_CustomShaders.clear(); ui->customShader->setCurrentText(prevtext); } else { QString fn = QFileInfo(filter).baseName(); QString key = fn.toUpper(); if(m_CustomShaders.contains(key)) { if(m_CustomShadersBusy.contains(key)) return; ResourceId freed = m_CustomShaders[key]; m_Ctx.Replay().AsyncInvoke([freed](IReplayController *r) { r->FreeCustomShader(freed); }); m_CustomShaders.remove(key); QString text = ui->customShader->currentText(); for(int i = 0; i < ui->customShader->count(); i++) { if(ui->customShader->itemText(i).compare(fn, Qt::CaseInsensitive) == 0) { ui->customShader->removeItem(i); break; } } ui->customShader->setCurrentText(text); } } QStringList files = QDir(configFilePath(QString())) .entryList({QFormatStr("*.%1").arg(m_Ctx.CurPipelineState().GetShaderExtension())}, QDir::Files | QDir::NoDotAndDotDot, QDir::Name | QDir::IgnoreCase); QStringList watchedFiles = m_Watcher->files(); if(!watchedFiles.isEmpty()) m_Watcher->removePaths(watchedFiles); for(const QString &f : files) { QString fn = QFileInfo(f).baseName(); QString key = fn.toUpper(); m_Watcher->addPath(configFilePath(f)); if(!m_CustomShaders.contains(key) && !m_CustomShadersBusy.contains(key)) { QFile fileHandle(configFilePath(f)); if(fileHandle.open(QFile::ReadOnly | QFile::Text)) { QTextStream stream(&fileHandle); QString source = stream.readAll(); ANALYTIC_SET(UIFeatures.CustomTextureVisualise, true); fileHandle.close(); m_CustomShaders[key] = ResourceId(); m_CustomShadersBusy.push_back(key); m_Ctx.Replay().AsyncInvoke([this, fn, key, source](IReplayController *r) { rdcstr errors; ResourceId id; std::tie(id, errors) = r->BuildCustomShader("main", source.toUtf8().data(), ShaderCompileFlags(), ShaderStage::Pixel); if(m_CustomShaderEditor.contains(key)) { IShaderViewer *editor = m_CustomShaderEditor[key]; GUIInvoke::call(editor->Widget(), [editor, errors]() { editor->ShowErrors(errors); }); } GUIInvoke::call(this, [this, fn, key, id]() { QString prevtext = ui->customShader->currentText(); ui->customShader->addItem(fn); ui->customShader->setCurrentText(prevtext); m_CustomShaders[key] = id; m_CustomShadersBusy.removeOne(key); UI_UpdateChannels(); }); }); } } } } void TextureViewer::on_customCreate_clicked() { QString filename = ui->customShader->currentText(); if(filename.isEmpty()) { RDDialog::critical(this, tr("Error Creating Shader"), tr("No shader name specified.\nEnter a new name in the textbox")); return; } if(m_CustomShaders.contains(filename.toUpper())) { RDDialog::critical(this, tr("Error Creating Shader"), tr("Selected shader already exists.\nEnter a new name in the textbox.")); ui->customShader->setCurrentText(QString()); UI_UpdateChannels(); return; } QString path = configFilePath(filename + lit(".") + m_Ctx.CurPipelineState().GetShaderExtension()); QString src; if(IsD3D(m_Ctx.APIProps().pipelineType)) { src = lit("float4 main(float4 pos : SV_Position, float4 uv : TEXCOORD0) : SV_Target0\n" "{\n" " return float4(0,0,0,1);\n" "}\n"); } else { src = lit("#version 420 core\n\n" "layout (location = 0) in vec2 uv;\n\n" "layout (location = 0) out vec4 color_out;\n\n" "void main()\n" "{\n" " color_out = vec4(0,0,0,1);\n" "}\n"); } QFile fileHandle(path); if(fileHandle.open(QFile::WriteOnly | QIODevice::Truncate | QIODevice::Text)) { fileHandle.write(src.toUtf8()); fileHandle.close(); } else { RDDialog::critical( this, tr("Cannot create shader"), tr("Couldn't create file for shader %1\n%2").arg(filename).arg(fileHandle.errorString())); } // auto-open edit window on_customEdit_clicked(); reloadCustomShaders(filename); } void TextureViewer::on_customEdit_clicked() { QString filename = ui->customShader->currentText(); QString key = filename.toUpper(); if(filename.isEmpty()) { RDDialog::critical(this, tr("Error Editing Shader"), tr("No shader selected.\nSelect a custom shader from the drop-down")); return; } QString path = configFilePath(filename + lit(".") + m_Ctx.CurPipelineState().GetShaderExtension()); QString src; QFile fileHandle(path); if(fileHandle.open(QFile::ReadOnly | QFile::Text)) { QTextStream stream(&fileHandle); src = stream.readAll(); fileHandle.close(); } else { RDDialog::critical( this, tr("Cannot open shader"), tr("Couldn't open file for shader %1\n%2").arg(filename).arg(fileHandle.errorString())); return; } rdcstrpairs files; files.push_back(make_rdcpair<rdcstr, rdcstr>(filename, src)); QPointer<TextureViewer> thisPointer(this); IShaderViewer *s = m_Ctx.EditShader( true, ShaderStage::Fragment, lit("main"), files, IsD3D(m_Ctx.APIProps().localRenderer) ? ShaderEncoding::HLSL : ShaderEncoding::GLSL, ShaderCompileFlags(), // Save Callback [thisPointer, key, filename, path](ICaptureContext *ctx, IShaderViewer *viewer, ShaderEncoding encoding, ShaderCompileFlags flags, rdcstr entryFunc, bytebuf bytes) { { QFile fileHandle(path); if(fileHandle.open(QFile::WriteOnly | QIODevice::Truncate | QIODevice::Text)) { fileHandle.write(QByteArray(bytes)); fileHandle.close(); // watcher doesn't trigger on internal modifications if(thisPointer) thisPointer->reloadCustomShaders(filename); } else { if(thisPointer) { RDDialog::critical( thisPointer, tr("Cannot save shader"), tr("Couldn't save file for shader %1\n%2").arg(filename).arg(fileHandle.errorString())); } } } }, [thisPointer, key](ICaptureContext *ctx) { if(thisPointer) thisPointer->m_CustomShaderEditor.remove(key); }); m_CustomShaderEditor[key] = s; m_Ctx.AddDockWindow(s->Widget(), DockReference::AddTo, this); } void TextureViewer::on_customDelete_clicked() { QString shaderName = ui->customShader->currentText(); if(shaderName.isEmpty()) { RDDialog::critical(this, tr("Error Deleting Shader"), tr("No shader selected.\nSelect a custom shader from the drop-down")); return; } if(!m_CustomShaders.contains(shaderName.toUpper())) { RDDialog::critical( this, tr("Error Deleting Shader"), tr("Selected shader doesn't exist.\nSelect a custom shader from the drop-down")); return; } QMessageBox::StandardButton res = RDDialog::question(this, tr("Deleting Custom Shader"), tr("Really delete %1?").arg(shaderName), RDDialog::YesNoCancel); if(res == QMessageBox::Yes) { QString path = configFilePath(shaderName + lit(".") + m_Ctx.CurPipelineState().GetShaderExtension()); if(!QFileInfo::exists(path)) { RDDialog::critical( this, tr("Error Deleting Shader"), tr("Shader file %1 can't be found.\nSelect a custom shader from the drop-down") .arg(shaderName)); return; } if(!QFile::remove(path)) { RDDialog::critical(this, tr("Error Deleting Shader"), tr("Error deleting shader %1 from disk").arg(shaderName)); return; } ui->customShader->setCurrentText(QString()); UI_UpdateChannels(); } } void TextureViewer::customShaderModified(const QString &path) { // allow time for modifications to finish QThread::msleep(15); reloadCustomShaders(QString()); } TextureViewer: fix wheel zooming on HiDPI screens Without adjusting for pixel ratio it zoomed in into a wrong place. /****************************************************************************** * The MIT License (MIT) * * Copyright (c) 2016-2018 Baldur Karlsson * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. ******************************************************************************/ #include "TextureViewer.h" #include <float.h> #include <math.h> #include <QClipboard> #include <QColorDialog> #include <QFileSystemWatcher> #include <QFontDatabase> #include <QItemDelegate> #include <QJsonDocument> #include <QMenu> #include <QPainter> #include <QPointer> #include <QStyledItemDelegate> #include "3rdparty/flowlayout/FlowLayout.h" #include "3rdparty/toolwindowmanager/ToolWindowManagerArea.h" #include "Code/QRDUtils.h" #include "Code/Resources.h" #include "Dialogs/TextureSaveDialog.h" #include "Widgets/ResourcePreview.h" #include "Widgets/TextureGoto.h" #include "ui_TextureViewer.h" float area(const QSizeF &s) { return s.width() * s.height(); } float aspect(const QSizeF &s) { return s.width() / s.height(); } Q_DECLARE_METATYPE(Following); const Following Following::Default = Following(); Following::Following(FollowType t, ShaderStage s, int i, int a) { Type = t; Stage = s; index = i; arrayEl = a; } Following::Following() { Type = FollowType::OutputColour; Stage = ShaderStage::Pixel; index = 0; arrayEl = 0; } bool Following::operator!=(const Following &o) { return !(*this == o); } bool Following::operator==(const Following &o) { return Type == o.Type && Stage == o.Stage && index == o.index; } void Following::GetDrawContext(ICaptureContext &ctx, bool &copy, bool &clear, bool &compute) { const DrawcallDescription *curDraw = ctx.CurDrawcall(); copy = curDraw != NULL && (curDraw->flags & (DrawFlags::Copy | DrawFlags::Resolve | DrawFlags::Present)); clear = curDraw != NULL && (curDraw->flags & DrawFlags::Clear); compute = curDraw != NULL && (curDraw->flags & DrawFlags::Dispatch) && ctx.CurPipelineState().GetShader(ShaderStage::Compute) != ResourceId(); } int Following::GetHighestMip(ICaptureContext &ctx) { return GetBoundResource(ctx, arrayEl).firstMip; } int Following::GetFirstArraySlice(ICaptureContext &ctx) { return GetBoundResource(ctx, arrayEl).firstSlice; } CompType Following::GetTypeHint(ICaptureContext &ctx) { return GetBoundResource(ctx, arrayEl).typeHint; } ResourceId Following::GetResourceId(ICaptureContext &ctx) { return GetBoundResource(ctx, arrayEl).resourceId; } BoundResource Following::GetBoundResource(ICaptureContext &ctx, int arrayIdx) { BoundResource ret; if(Type == FollowType::OutputColour) { rdcarray<BoundResource> outputs = GetOutputTargets(ctx); if(index < outputs.count()) ret = outputs[index]; } else if(Type == FollowType::OutputDepth) { ret = GetDepthTarget(ctx); } else if(Type == FollowType::ReadWrite) { rdcarray<BoundResourceArray> rw = GetReadWriteResources(ctx); ShaderBindpointMapping mapping = GetMapping(ctx); if(index < mapping.readWriteResources.count()) { Bindpoint &key = mapping.readWriteResources[index]; int residx = rw.indexOf(key); if(residx >= 0) ret = rw[residx].resources[arrayIdx]; } } else if(Type == FollowType::ReadOnly) { rdcarray<BoundResourceArray> ro = GetReadOnlyResources(ctx); ShaderBindpointMapping mapping = GetMapping(ctx); if(index < mapping.readOnlyResources.count()) { Bindpoint &key = mapping.readOnlyResources[index]; int residx = ro.indexOf(key); if(residx >= 0) ret = ro[residx].resources[arrayIdx]; } } return ret; } rdcarray<BoundResource> Following::GetOutputTargets(ICaptureContext &ctx) { const DrawcallDescription *curDraw = ctx.CurDrawcall(); bool copy = false, clear = false, compute = false; GetDrawContext(ctx, copy, clear, compute); if(copy || clear) { return {BoundResource(curDraw->copyDestination)}; } else if(compute) { return {}; } else { rdcarray<BoundResource> ret = ctx.CurPipelineState().GetOutputTargets(); if(ret.isEmpty() && curDraw != NULL && (curDraw->flags & DrawFlags::Present)) { if(curDraw->copyDestination != ResourceId()) return {BoundResource(curDraw->copyDestination)}; for(const TextureDescription &tex : ctx.GetTextures()) { if(tex.creationFlags & TextureCategory::SwapBuffer) return {BoundResource(tex.resourceId)}; } } return ret; } } BoundResource Following::GetDepthTarget(ICaptureContext &ctx) { bool copy = false, clear = false, compute = false; GetDrawContext(ctx, copy, clear, compute); if(copy || clear || compute) return BoundResource(ResourceId()); else return ctx.CurPipelineState().GetDepthTarget(); } rdcarray<BoundResourceArray> Following::GetReadWriteResources(ICaptureContext &ctx, ShaderStage stage) { bool copy = false, clear = false, compute = false; GetDrawContext(ctx, copy, clear, compute); if(copy || clear) { return rdcarray<BoundResourceArray>(); } else if(compute) { // only return compute resources for one stage if(stage == ShaderStage::Pixel || stage == ShaderStage::Compute) return ctx.CurPipelineState().GetReadWriteResources(ShaderStage::Compute); else return rdcarray<BoundResourceArray>(); } else { return ctx.CurPipelineState().GetReadWriteResources(stage); } } rdcarray<BoundResourceArray> Following::GetReadWriteResources(ICaptureContext &ctx) { return GetReadWriteResources(ctx, Stage); } rdcarray<BoundResourceArray> Following::GetReadOnlyResources(ICaptureContext &ctx, ShaderStage stage) { const DrawcallDescription *curDraw = ctx.CurDrawcall(); bool copy = false, clear = false, compute = false; GetDrawContext(ctx, copy, clear, compute); if(copy || clear) { rdcarray<BoundResourceArray> ret; // only return copy source for one stage if(copy && stage == ShaderStage::Pixel) ret.push_back(BoundResourceArray(Bindpoint(0, 0), {BoundResource(curDraw->copySource)})); return ret; } else if(compute) { // only return compute resources for one stage if(stage == ShaderStage::Pixel || stage == ShaderStage::Compute) return ctx.CurPipelineState().GetReadOnlyResources(ShaderStage::Compute); else return rdcarray<BoundResourceArray>(); } else { return ctx.CurPipelineState().GetReadOnlyResources(stage); } } rdcarray<BoundResourceArray> Following::GetReadOnlyResources(ICaptureContext &ctx) { return GetReadOnlyResources(ctx, Stage); } const ShaderReflection *Following::GetReflection(ICaptureContext &ctx, ShaderStage stage) { bool copy = false, clear = false, compute = false; GetDrawContext(ctx, copy, clear, compute); if(copy || clear) return NULL; else if(compute) return ctx.CurPipelineState().GetShaderReflection(ShaderStage::Compute); else return ctx.CurPipelineState().GetShaderReflection(stage); } const ShaderReflection *Following::GetReflection(ICaptureContext &ctx) { return GetReflection(ctx, Stage); } const ShaderBindpointMapping &Following::GetMapping(ICaptureContext &ctx, ShaderStage stage) { bool copy = false, clear = false, compute = false; GetDrawContext(ctx, copy, clear, compute); if(copy || clear) { static ShaderBindpointMapping mapping; // for PS only add a single mapping to get the copy source if(copy && stage == ShaderStage::Pixel) mapping.readOnlyResources = {Bindpoint(0, 0)}; else mapping.readOnlyResources.clear(); return mapping; } else if(compute) { return ctx.CurPipelineState().GetBindpointMapping(ShaderStage::Compute); } else { return ctx.CurPipelineState().GetBindpointMapping(stage); } } const ShaderBindpointMapping &Following::GetMapping(ICaptureContext &ctx) { return GetMapping(ctx, Stage); } class TextureListItemModel : public QAbstractItemModel { public: enum FilterType { Textures, RenderTargets, String }; TextureListItemModel(ICaptureContext &ctx, QWidget *parent) : QAbstractItemModel(parent), m_Ctx(ctx) { goArrow.addPixmap(Pixmaps::action(parent), QIcon::Normal, QIcon::Off); goArrow.addPixmap(Pixmaps::action_hover(parent), QIcon::Normal, QIcon::Off); } void reset(FilterType type, const QString &filter) { const rdcarray<TextureDescription> src = m_Ctx.GetTextures(); texs.clear(); texs.reserve(src.count()); emit beginResetModel(); TextureCategory rtFlags = TextureCategory::ColorTarget | TextureCategory::DepthTarget; for(const TextureDescription &t : src) { if(type == Textures) { if(!(t.creationFlags & rtFlags)) texs.push_back(t); } else if(type == RenderTargets) { if((t.creationFlags & rtFlags)) texs.push_back(t); } else { if(filter.isEmpty()) texs.push_back(t); else if(QString(m_Ctx.GetResourceName(t.resourceId)).contains(filter, Qt::CaseInsensitive)) texs.push_back(t); } } emit endResetModel(); } QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const override { if(row < 0 || row >= rowCount()) return QModelIndex(); return createIndex(row, 0); } QModelIndex parent(const QModelIndex &index) const override { return QModelIndex(); } int rowCount(const QModelIndex &parent = QModelIndex()) const override { return texs.count(); } int columnCount(const QModelIndex &parent = QModelIndex()) const override { return 1; } Qt::ItemFlags flags(const QModelIndex &index) const override { if(!index.isValid()) return 0; return QAbstractItemModel::flags(index); } QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override { if(index.isValid()) { if(role == Qt::DisplayRole) { if(index.row() >= 0 && index.row() < texs.count()) return m_Ctx.GetResourceName(texs[index.row()].resourceId); } if(role == Qt::UserRole) { return QVariant::fromValue(texs[index.row()].resourceId); } if(role == Qt::DecorationRole) { return QVariant(goArrow); } } return QVariant(); } private: ICaptureContext &m_Ctx; QVector<TextureDescription> texs; QIcon goArrow; }; class TextureListItemDelegate : public QItemDelegate { public: TextureListItemDelegate(QObject *parent = 0) : QItemDelegate(parent) {} void paint(QPainter *painter, const QStyleOptionViewItem &opt, const QModelIndex &index) const override { if(index.isValid()) { QStyleOptionViewItem option = opt; option.decorationAlignment = Qt::AlignBaseline | Qt::AlignRight; painter->eraseRect(option.rect); QIcon icon = index.model()->data(index, Qt::DecorationRole).value<QIcon>(); drawBackground(painter, option, index); if(option.state & QStyle::State_MouseOver) drawDecoration(painter, option, option.rect, icon.pixmap(option.decorationSize, QIcon::Active)); else drawDecoration(painter, option, option.rect, icon.pixmap(option.decorationSize, QIcon::Normal)); drawDisplay(painter, option, option.rect, index.model()->data(index, Qt::DisplayRole).toString()); drawFocus(painter, option, option.rect); if(option.state & QStyle::State_MouseOver) { QRect r = option.rect; r.adjust(0, 0, -1, -1); painter->drawRect(r); } } } }; TextureDescription *TextureViewer::GetCurrentTexture() { return m_CachedTexture; } void TextureViewer::UI_UpdateCachedTexture() { if(!m_Ctx.IsCaptureLoaded()) { m_CachedTexture = NULL; return; } ResourceId id = m_LockedId; if(id == ResourceId()) id = m_Following.GetResourceId(m_Ctx); if(id == ResourceId()) id = m_TexDisplay.resourceId; m_CachedTexture = m_Ctx.GetTexture(id); ui->debugPixelContext->setEnabled(m_Ctx.CurPipelineState().IsCaptureD3D11() && m_CachedTexture != NULL); ui->pixelHistory->setEnabled(m_Ctx.CurPipelineState().IsCaptureD3D11() && m_CachedTexture != NULL); } TextureViewer::TextureViewer(ICaptureContext &ctx, QWidget *parent) : QFrame(parent), ui(new Ui::TextureViewer), m_Ctx(ctx) { ui->setupUi(this); ui->textureList->setFont(Formatter::PreferredFont()); ui->textureListFilter->setFont(Formatter::PreferredFont()); ui->rangeBlack->setFont(Formatter::PreferredFont()); ui->rangeWhite->setFont(Formatter::PreferredFont()); ui->hdrMul->setFont(Formatter::PreferredFont()); ui->channels->setFont(Formatter::PreferredFont()); ui->mipLevel->setFont(Formatter::PreferredFont()); ui->sliceFace->setFont(Formatter::PreferredFont()); ui->zoomOption->setFont(Formatter::PreferredFont()); Reset(); on_checkerBack_clicked(); QObject::connect(ui->zoomOption->lineEdit(), &QLineEdit::returnPressed, this, &TextureViewer::zoomOption_returnPressed); QObject::connect(ui->depthDisplay, &QToolButton::toggled, this, &TextureViewer::channelsWidget_toggled); QObject::connect(ui->stencilDisplay, &QToolButton::toggled, this, &TextureViewer::channelsWidget_toggled); QObject::connect(ui->flip_y, &QToolButton::toggled, this, &TextureViewer::channelsWidget_toggled); QObject::connect(ui->gammaDisplay, &QToolButton::toggled, this, &TextureViewer::channelsWidget_toggled); QObject::connect(ui->channels, OverloadedSlot<int>::of(&QComboBox::currentIndexChanged), this, &TextureViewer::channelsWidget_selected); QObject::connect(ui->hdrMul, OverloadedSlot<int>::of(&QComboBox::currentIndexChanged), this, &TextureViewer::channelsWidget_selected); QObject::connect(ui->customShader, OverloadedSlot<int>::of(&QComboBox::currentIndexChanged), this, &TextureViewer::channelsWidget_selected); QObject::connect(ui->customShader, &QComboBox::currentTextChanged, [this] { UI_UpdateChannels(); }); QObject::connect(ui->rangeHistogram, &RangeHistogram::rangeUpdated, this, &TextureViewer::range_rangeUpdated); QObject::connect(ui->rangeBlack, &RDLineEdit::textChanged, this, &TextureViewer::rangePoint_textChanged); QObject::connect(ui->rangeBlack, &RDLineEdit::leave, this, &TextureViewer::rangePoint_leave); QObject::connect(ui->rangeBlack, &RDLineEdit::keyPress, this, &TextureViewer::rangePoint_keyPress); QObject::connect(ui->rangeWhite, &RDLineEdit::textChanged, this, &TextureViewer::rangePoint_textChanged); QObject::connect(ui->rangeWhite, &RDLineEdit::leave, this, &TextureViewer::rangePoint_leave); QObject::connect(ui->rangeWhite, &RDLineEdit::keyPress, this, &TextureViewer::rangePoint_keyPress); for(RDToolButton *butt : {ui->channelRed, ui->channelGreen, ui->channelBlue, ui->channelAlpha}) { QObject::connect(butt, &RDToolButton::toggled, this, &TextureViewer::channelsWidget_toggled); QObject::connect(butt, &RDToolButton::mouseClicked, this, &TextureViewer::channelsWidget_mouseClicked); QObject::connect(butt, &RDToolButton::doubleClicked, this, &TextureViewer::channelsWidget_mouseClicked); } { QMenu *extensionsMenu = new QMenu(this); ui->extensions->setMenu(extensionsMenu); ui->extensions->setPopupMode(QToolButton::InstantPopup); QObject::connect(extensionsMenu, &QMenu::aboutToShow, [this, extensionsMenu]() { extensionsMenu->clear(); m_Ctx.Extensions().MenuDisplaying(PanelMenu::TextureViewer, extensionsMenu, ui->extensions, {}); }); } QWidget *renderContainer = ui->renderContainer; ui->dockarea->addToolWindow(ui->renderContainer, ToolWindowManager::EmptySpace); ui->dockarea->setToolWindowProperties( renderContainer, ToolWindowManager::DisallowUserDocking | ToolWindowManager::HideCloseButton | ToolWindowManager::DisableDraggableTab | ToolWindowManager::AlwaysDisplayFullTabs); ui->dockarea->addToolWindow(ui->inputThumbs, ToolWindowManager::AreaReference( ToolWindowManager::RightOf, ui->dockarea->areaOf(renderContainer), 0.25f)); ui->dockarea->setToolWindowProperties(ui->inputThumbs, ToolWindowManager::HideCloseButton); ui->dockarea->addToolWindow( ui->outputThumbs, ToolWindowManager::AreaReference(ToolWindowManager::AddTo, ui->dockarea->areaOf(ui->inputThumbs))); ui->dockarea->setToolWindowProperties(ui->outputThumbs, ToolWindowManager::HideCloseButton); ui->dockarea->addToolWindow( ui->pixelContextLayout, ToolWindowManager::AreaReference(ToolWindowManager::BottomOf, ui->dockarea->areaOf(ui->outputThumbs), 0.25f)); ui->dockarea->setToolWindowProperties(ui->pixelContextLayout, ToolWindowManager::HideCloseButton); ui->dockarea->addToolWindow(ui->textureListFrame, ToolWindowManager::NoArea); ui->dockarea->setToolWindowProperties(ui->textureListFrame, ToolWindowManager::HideOnClose); ui->dockarea->setAllowFloatingWindow(false); renderContainer->setWindowTitle(tr("Unbound")); ui->pixelContextLayout->setWindowTitle(tr("Pixel Context")); ui->outputThumbs->setWindowTitle(tr("Outputs")); ui->inputThumbs->setWindowTitle(tr("Inputs")); ui->textureListFrame->setWindowTitle(tr("Texture List")); ui->textureList->setHoverCursor(Qt::PointingHandCursor); m_Goto = new TextureGoto(this, [this](QPoint p) { GotoLocation(p.x(), p.y()); }); QVBoxLayout *vertical = new QVBoxLayout(this); vertical->setSpacing(3); vertical->setContentsMargins(3, 3, 3, 3); QWidget *flow1widget = new QWidget(this); QWidget *flow2widget = new QWidget(this); FlowLayout *flow1 = new FlowLayout(flow1widget, 0, 3, 3); FlowLayout *flow2 = new FlowLayout(flow2widget, 0, 3, 3); flow1widget->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Minimum); flow2widget->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Minimum); flow1->addWidget(ui->channelsToolbar); flow1->addWidget(ui->subresourceToolbar); flow1->addWidget(ui->actionToolbar); flow2->addWidget(ui->zoomToolbar); flow2->addWidget(ui->overlayToolbar); flow2->addWidget(ui->rangeToolbar); vertical->addWidget(flow1widget); vertical->addWidget(flow2widget); vertical->addWidget(ui->dockarea); Ui_TextureViewer *u = ui; u->pixelcontextgrid->setAlignment(u->pixelHistory, Qt::AlignCenter); u->pixelcontextgrid->setAlignment(u->debugPixelContext, Qt::AlignCenter); QWidget *statusflowWidget = new QWidget(this); FlowLayout *statusflow = new FlowLayout(statusflowWidget, 0, 3, 0); statusflowWidget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum); ui->statusbar->removeWidget(ui->texStatusDim); ui->statusbar->removeWidget(ui->pickSwatch); ui->statusbar->removeWidget(ui->statusText); statusflow->addWidget(ui->texStatusDim); statusflow->addWidget(ui->pickSwatch); statusflow->addWidget(ui->statusText); ui->texStatusDim->setFont(QFontDatabase::systemFont(QFontDatabase::FixedFont)); ui->statusText->setFont(QFontDatabase::systemFont(QFontDatabase::FixedFont)); ui->statusbar->addWidget(statusflowWidget); ui->channels->addItems({tr("RGBA"), tr("RGBM"), tr("Custom")}); ui->zoomOption->addItems({lit("10%"), lit("25%"), lit("50%"), lit("75%"), lit("100%"), lit("200%"), lit("400%"), lit("800%")}); ui->hdrMul->addItems({lit("2"), lit("4"), lit("8"), lit("16"), lit("32"), lit("128")}); ui->overlay->addItems({tr("None"), tr("Highlight Drawcall"), tr("Wireframe Mesh"), tr("Depth Test"), tr("Stencil Test"), tr("Backface Cull"), tr("Viewport/Scissor Region"), tr("NaN/INF/-ve Display"), tr("Histogram Clipping"), tr("Clear Before Pass"), tr("Clear Before Draw"), tr("Quad Overdraw (Pass)"), tr("Quad Overdraw (Draw)"), tr("Triangle Size (Pass)"), tr("Triangle Size (Draw)")}); ui->textureListFilter->addItems({QString(), tr("Textures"), tr("Render Targets")}); ui->textureList->setModel(new TextureListItemModel(m_Ctx, this)); ui->textureList->setItemDelegate(new TextureListItemDelegate(ui->textureList)); ui->textureList->viewport()->setAttribute(Qt::WA_Hover); ui->zoomOption->setCurrentText(QString()); ui->fitToWindow->toggle(); m_Ctx.AddCaptureViewer(this); SetupTextureTabs(); } TextureViewer::~TextureViewer() { if(m_Output) { m_Ctx.Replay().BlockInvoke([this](IReplayController *r) { m_Output->Shutdown(); }); } m_Ctx.BuiltinWindowClosed(this); m_Ctx.RemoveCaptureViewer(this); delete ui; } void TextureViewer::enterEvent(QEvent *event) { HighlightUsage(); } void TextureViewer::showEvent(QShowEvent *event) { HighlightUsage(); } void TextureViewer::changeEvent(QEvent *event) { if(event->type() == QEvent::PaletteChange || event->type() == QEvent::StyleChange) { updateBackgroundColors(); ui->render->update(); } } void TextureViewer::HighlightUsage() { TextureDescription *texptr = GetCurrentTexture(); if(texptr && m_Ctx.HasTimelineBar()) m_Ctx.GetTimelineBar()->HighlightResourceUsage(texptr->resourceId); } void TextureViewer::RT_FetchCurrentPixel(uint32_t x, uint32_t y, PixelValue &pickValue, PixelValue &realValue) { TextureDescription *texptr = GetCurrentTexture(); if(texptr == NULL) return; if(m_TexDisplay.flipY) y = (texptr->height - 1) - y; pickValue = m_Output->PickPixel(m_TexDisplay.resourceId, true, x, y, m_TexDisplay.sliceFace, m_TexDisplay.mip, m_TexDisplay.sampleIdx); if(m_TexDisplay.customShaderId != ResourceId()) realValue = m_Output->PickPixel(m_TexDisplay.resourceId, false, x, y, m_TexDisplay.sliceFace, m_TexDisplay.mip, m_TexDisplay.sampleIdx); } void TextureViewer::RT_PickPixelsAndUpdate(IReplayController *) { PixelValue pickValue, realValue; if(m_PickedPoint.x() < 0 || m_PickedPoint.y() < 0) return; uint32_t x = (uint32_t)m_PickedPoint.x(); uint32_t y = (uint32_t)m_PickedPoint.y(); RT_FetchCurrentPixel(x, y, pickValue, realValue); m_Output->SetPixelContextLocation(x, y); m_CurHoverValue = pickValue; m_CurPixelValue = pickValue; m_CurRealValue = realValue; GUIInvoke::call(this, [this]() { UI_UpdateStatusText(); }); } void TextureViewer::RT_PickHoverAndUpdate(IReplayController *) { PixelValue pickValue, realValue; uint32_t x = (uint32_t)m_CurHoverPixel.x(); uint32_t y = (uint32_t)m_CurHoverPixel.y(); RT_FetchCurrentPixel(x, y, pickValue, realValue); m_CurHoverValue = pickValue; GUIInvoke::call(this, [this]() { UI_UpdateStatusText(); }); } void TextureViewer::RT_UpdateAndDisplay(IReplayController *) { if(m_Output != NULL) m_Output->SetTextureDisplay(m_TexDisplay); GUIInvoke::call(this, [this]() { ui->render->update(); }); } void TextureViewer::RT_UpdateVisualRange(IReplayController *) { TextureDescription *texptr = GetCurrentTexture(); if(!m_Visualise || texptr == NULL || m_Output == NULL) return; ResourceFormat fmt = texptr->format; if(m_TexDisplay.customShaderId != ResourceId()) fmt.compCount = 4; bool channels[] = { m_TexDisplay.red ? true : false, m_TexDisplay.green && fmt.compCount > 1, m_TexDisplay.blue && fmt.compCount > 2, m_TexDisplay.alpha && fmt.compCount > 3, }; rdcarray<uint32_t> histogram = m_Output->GetHistogram(ui->rangeHistogram->rangeMin(), ui->rangeHistogram->rangeMax(), channels); if(!histogram.empty()) { QVector<uint32_t> histogramVec(histogram.count()); if(!histogram.isEmpty()) memcpy(histogramVec.data(), histogram.data(), histogram.byteSize()); GUIInvoke::call(this, [this, histogramVec]() { ui->rangeHistogram->setHistogramRange(ui->rangeHistogram->rangeMin(), ui->rangeHistogram->rangeMax()); ui->rangeHistogram->setHistogramData(histogramVec); }); } } void TextureViewer::UI_UpdateStatusText() { TextureDescription *texptr = GetCurrentTexture(); if(texptr == NULL) return; TextureDescription &tex = *texptr; bool dsv = (tex.creationFlags & TextureCategory::DepthTarget) || (tex.format.compType == CompType::Depth); bool uintTex = (tex.format.compType == CompType::UInt); bool sintTex = (tex.format.compType == CompType::SInt); if(m_TexDisplay.overlay == DebugOverlay::QuadOverdrawPass || m_TexDisplay.overlay == DebugOverlay::QuadOverdrawDraw || m_TexDisplay.overlay == DebugOverlay::TriangleSizeDraw || m_TexDisplay.overlay == DebugOverlay::TriangleSizeDraw) { dsv = false; uintTex = false; sintTex = false; } QColor swatchColor; if(dsv || uintTex || sintTex) { swatchColor = QColor(0, 0, 0); } else { float r = qBound(0.0f, m_CurHoverValue.floatValue[0], 1.0f); float g = qBound(0.0f, m_CurHoverValue.floatValue[1], 1.0f); float b = qBound(0.0f, m_CurHoverValue.floatValue[2], 1.0f); if(tex.format.srgbCorrected || (tex.creationFlags & TextureCategory::SwapBuffer)) { r = powf(r, 1.0f / 2.2f); g = powf(g, 1.0f / 2.2f); b = powf(b, 1.0f / 2.2f); } swatchColor = QColor(int(255.0f * r), int(255.0f * g), int(255.0f * b)); } { QPalette Pal(palette()); Pal.setColor(QPalette::Background, swatchColor); ui->pickSwatch->setAutoFillBackground(true); ui->pickSwatch->setPalette(Pal); } int y = m_CurHoverPixel.y() >> (int)m_TexDisplay.mip; uint32_t mipWidth = qMax(1U, tex.width >> (int)m_TexDisplay.mip); uint32_t mipHeight = qMax(1U, tex.height >> (int)m_TexDisplay.mip); if(m_Ctx.APIProps().pipelineType == GraphicsAPI::OpenGL) y = (int)(mipHeight - 1) - y; if(m_TexDisplay.flipY) y = (int)(mipHeight - 1) - y; y = qMax(0, y); int x = m_CurHoverPixel.x() >> (int)m_TexDisplay.mip; float invWidth = 1.0f / mipWidth; float invHeight = 1.0f / mipHeight; QString hoverCoords = QFormatStr("%1, %2 (%3, %4)") .arg(x, 4) .arg(y, 4) .arg((x * invWidth), 5, 'f', 4) .arg((y * invHeight), 5, 'f', 4); QString statusText = tr("Hover - ") + hoverCoords; uint32_t hoverX = (uint32_t)m_CurHoverPixel.x(); uint32_t hoverY = (uint32_t)m_CurHoverPixel.y(); if(hoverX > tex.width || hoverY > tex.height) statusText = tr("Hover - [%1]").arg(hoverCoords); if(m_PickedPoint.x() >= 0) { x = m_PickedPoint.x() >> (int)m_TexDisplay.mip; y = m_PickedPoint.y() >> (int)m_TexDisplay.mip; if(m_Ctx.APIProps().pipelineType == GraphicsAPI::OpenGL) y = (int)(mipHeight - 1) - y; if(m_TexDisplay.flipY) y = (int)(mipHeight - 1) - y; y = qMax(0, y); statusText += tr(" - Right click - %1, %2: ").arg(x, 4).arg(y, 4); PixelValue val = m_CurPixelValue; if(m_TexDisplay.customShaderId != ResourceId()) { statusText += QFormatStr("%1, %2, %3, %4") .arg(Formatter::Format(val.floatValue[0])) .arg(Formatter::Format(val.floatValue[1])) .arg(Formatter::Format(val.floatValue[2])) .arg(Formatter::Format(val.floatValue[3])); val = m_CurRealValue; statusText += tr(" (Real: "); } if(dsv) { statusText += tr("Depth "); if(uintTex) { statusText += Formatter::Format(val.uintValue[0]); } else { statusText += Formatter::Format(val.floatValue[0]); } int stencil = (int)(255.0f * val.floatValue[1]); statusText += tr(", Stencil %1 / 0x%2").arg(stencil).arg(Formatter::Format(uint8_t(stencil & 0xff), true)); } else { if(uintTex) { statusText += QFormatStr("%1, %2, %3, %4") .arg(Formatter::Format(val.uintValue[0])) .arg(Formatter::Format(val.uintValue[1])) .arg(Formatter::Format(val.uintValue[2])) .arg(Formatter::Format(val.uintValue[3])); } else if(sintTex) { statusText += QFormatStr("%1, %2, %3, %4") .arg(Formatter::Format(val.intValue[0])) .arg(Formatter::Format(val.intValue[1])) .arg(Formatter::Format(val.intValue[2])) .arg(Formatter::Format(val.intValue[3])); } else { statusText += QFormatStr("%1, %2, %3, %4") .arg(Formatter::Format(val.floatValue[0])) .arg(Formatter::Format(val.floatValue[1])) .arg(Formatter::Format(val.floatValue[2])) .arg(Formatter::Format(val.floatValue[3])); } } if(m_TexDisplay.customShaderId != ResourceId()) statusText += lit(")"); } else { statusText += tr(" - Right click to pick a pixel"); } // try and keep status text consistent by sticking to the high water mark // of length (prevents nasty oscillation when the length of the string is // just popping over/under enough to overflow onto the next line). if(statusText.length() > m_HighWaterStatusLength) m_HighWaterStatusLength = statusText.length(); if(statusText.length() < m_HighWaterStatusLength) statusText += QString(m_HighWaterStatusLength - statusText.length(), QLatin1Char(' ')); ui->statusText->setText(statusText); } void TextureViewer::UI_UpdateTextureDetails() { QString status; TextureDescription *texptr = GetCurrentTexture(); if(texptr == NULL) { ui->texStatusDim->setText(status); ui->renderContainer->setWindowTitle(tr("Unbound")); return; } TextureDescription &current = *texptr; ResourceId followID = m_Following.GetResourceId(m_Ctx); { TextureDescription *followtex = m_Ctx.GetTexture(followID); BufferDescription *followbuf = m_Ctx.GetBuffer(followID); QString title; if(followID == ResourceId()) { title = tr("Unbound"); } else if(followtex || followbuf) { QString name = m_Ctx.GetResourceName(followID); switch(m_Following.Type) { case FollowType::OutputColour: title = QString(tr("Cur Output %1 - %2")).arg(m_Following.index).arg(name); break; case FollowType::OutputDepth: title = QString(tr("Cur Depth Output - %1")).arg(name); break; case FollowType::ReadWrite: title = QString(tr("Cur RW Output %1 - %2")).arg(m_Following.index).arg(name); break; case FollowType::ReadOnly: title = QString(tr("Cur Input %1 - %2")).arg(m_Following.index).arg(name); break; } } else { switch(m_Following.Type) { case FollowType::OutputColour: title = QString(tr("Cur Output %1")).arg(m_Following.index); break; case FollowType::OutputDepth: title = QString(tr("Cur Depth Output")); break; case FollowType::ReadWrite: title = QString(tr("Cur RW Output %1")).arg(m_Following.index); break; case FollowType::ReadOnly: title = QString(tr("Cur Input %1")).arg(m_Following.index); break; } } ui->renderContainer->setWindowTitle(title); } status = m_Ctx.GetResourceName(current.resourceId) + lit(" - "); if(current.dimension >= 1) status += QString::number(current.width); if(current.dimension >= 2) status += lit("x") + QString::number(current.height); if(current.dimension >= 3) status += lit("x") + QString::number(current.depth); if(current.arraysize > 1) status += QFormatStr("[%1]").arg(QString::number(current.arraysize)); if(current.msQual > 0 || current.msSamp > 1) status += QFormatStr(" MS{%1x %2Q}").arg(current.msSamp).arg(current.msQual); status += QFormatStr(" %1 mips").arg(current.mips); status += lit(" - ") + current.format.Name(); if(current.format.compType != m_TexDisplay.typeHint && m_TexDisplay.typeHint != CompType::Typeless) { status += tr(" Viewed as %1").arg(ToQStr(m_TexDisplay.typeHint)); } ui->texStatusDim->setText(status); } void TextureViewer::UI_OnTextureSelectionChanged(bool newdraw) { TextureDescription *texptr = GetCurrentTexture(); // reset high-water mark m_HighWaterStatusLength = 0; if(texptr == NULL) return; TextureDescription &tex = *texptr; bool newtex = (m_TexDisplay.resourceId != tex.resourceId); // save settings for this current texture if(m_Ctx.Config().TextureViewer_PerTexSettings) { m_TextureSettings[m_TexDisplay.resourceId].r = ui->channelRed->isChecked(); m_TextureSettings[m_TexDisplay.resourceId].g = ui->channelGreen->isChecked(); m_TextureSettings[m_TexDisplay.resourceId].b = ui->channelBlue->isChecked(); m_TextureSettings[m_TexDisplay.resourceId].a = ui->channelAlpha->isChecked(); m_TextureSettings[m_TexDisplay.resourceId].displayType = qMax(0, ui->channels->currentIndex()); m_TextureSettings[m_TexDisplay.resourceId].customShader = ui->customShader->currentText(); m_TextureSettings[m_TexDisplay.resourceId].depth = ui->depthDisplay->isChecked(); m_TextureSettings[m_TexDisplay.resourceId].stencil = ui->stencilDisplay->isChecked(); m_TextureSettings[m_TexDisplay.resourceId].mip = qMax(0, ui->mipLevel->currentIndex()); m_TextureSettings[m_TexDisplay.resourceId].slice = qMax(0, ui->sliceFace->currentIndex()); m_TextureSettings[m_TexDisplay.resourceId].minrange = ui->rangeHistogram->blackPoint(); m_TextureSettings[m_TexDisplay.resourceId].maxrange = ui->rangeHistogram->whitePoint(); if(m_TexDisplay.typeHint != CompType::Typeless) m_TextureSettings[m_TexDisplay.resourceId].typeHint = m_TexDisplay.typeHint; } m_TexDisplay.resourceId = tex.resourceId; // interpret the texture according to the currently following type. if(!currentTextureIsLocked()) m_TexDisplay.typeHint = m_Following.GetTypeHint(m_Ctx); else m_TexDisplay.typeHint = CompType::Typeless; // if there is no such type or it isn't being followed, use the last seen interpretation if(m_TexDisplay.typeHint == CompType::Typeless && m_TextureSettings.contains(m_TexDisplay.resourceId)) m_TexDisplay.typeHint = m_TextureSettings[m_TexDisplay.resourceId].typeHint; // try to maintain the pan in the new texture. If the new texture // is approx an integer multiple of the old texture, just changing // the scale will keep everything the same. This is useful for // downsample chains and things where you're flipping back and forth // between overlapping textures, but even in the non-integer case // pan will be kept approximately the same. QSizeF curSize((float)tex.width, (float)tex.height); float curArea = area(curSize); float prevArea = area(m_PrevSize); if(prevArea > 0.0f && m_PrevSize.width() > 0.0f) { float prevX = m_TexDisplay.xOffset; float prevY = m_TexDisplay.yOffset; // allow slight difference in aspect ratio for rounding errors // in downscales (e.g. 1680x1050 -> 840x525 -> 420x262 in the // last downscale the ratios are 1.6 and 1.603053435). if(qAbs(aspect(curSize) - aspect(m_PrevSize)) < 0.01f) { m_TexDisplay.scale *= m_PrevSize.width() / curSize.width(); setCurrentZoomValue(m_TexDisplay.scale); } else { // this scale factor is arbitrary really, only intention is to have // integer scales come out precisely, other 'similar' sizes will be // similar ish float scaleFactor = (float)(sqrt(curArea) / sqrt(prevArea)); m_TexDisplay.xOffset = prevX * scaleFactor; m_TexDisplay.yOffset = prevY * scaleFactor; } } m_PrevSize = curSize; // refresh scroll position setScrollPosition(getScrollPosition()); UI_UpdateStatusText(); // block signals for mipLevel and sliceFace comboboxes while editing them ui->mipLevel->blockSignals(true); ui->sliceFace->blockSignals(true); ui->mipLevel->clear(); m_TexDisplay.mip = 0; m_TexDisplay.sliceFace = 0; bool usemipsettings = true; bool useslicesettings = true; if(tex.msSamp > 1) { for(uint32_t i = 0; i < tex.msSamp; i++) ui->mipLevel->addItem(tr("Sample %1").arg(i)); // add an option to display unweighted average resolved value, // to get an idea of how the samples average if(tex.format.compType != CompType::UInt && tex.format.compType != CompType::SInt && tex.format.compType != CompType::Depth && !(tex.creationFlags & TextureCategory::DepthTarget)) ui->mipLevel->addItem(tr("Average val")); ui->mipLabel->setText(tr("Sample")); ui->mipLevel->setCurrentIndex(0); } else { for(uint32_t i = 0; i < tex.mips; i++) ui->mipLevel->addItem( QFormatStr("%1 - %2x%3").arg(i).arg(qMax(1U, tex.width >> i)).arg(qMax(1U, tex.height >> i))); ui->mipLabel->setText(tr("Mip")); } if(tex.mips == 1 && tex.msSamp <= 1) ui->mipLevel->setEnabled(false); else ui->mipLevel->setEnabled(true); ui->sliceFace->clear(); uint32_t numSlices = 1; if(tex.arraysize == 1 && tex.depth <= 1) { ui->sliceFace->setEnabled(false); } else { ui->sliceFace->setEnabled(true); QString cubeFaces[] = {lit("X+"), lit("X-"), lit("Y+"), lit("Y-"), lit("Z+"), lit("Z-")}; numSlices = tex.arraysize; // for 3D textures, display the number of slices at this mip if(tex.depth > 1) numSlices = qMax(1u, tex.depth >> (int)ui->mipLevel->currentIndex()); for(uint32_t i = 0; i < numSlices; i++) { if(tex.cubemap) { QString name = cubeFaces[i % 6]; if(numSlices > 6) name = QFormatStr("[%1] %2").arg(i / 6).arg( cubeFaces[i % 6]); // Front 1, Back 2, 3, 4 etc for cube arrays ui->sliceFace->addItem(name); } else { ui->sliceFace->addItem(tr("Slice %1").arg(i)); } } } // enable signals for mipLevel and sliceFace ui->mipLevel->blockSignals(false); ui->sliceFace->blockSignals(false); { int highestMip = -1; // only switch to the selected mip for outputs, and when changing drawcall if(!currentTextureIsLocked() && m_Following.Type != FollowType::ReadOnly && newdraw) highestMip = m_Following.GetHighestMip(m_Ctx); // assuming we get a valid mip for the highest mip, only switch to it // if we've selected a new texture, or if it's different than the last mip. // This prevents the case where the user has clicked on another mip and // we don't want to snap their view back when stepping between events with the // same mip used. But it does mean that if they are stepping between // events with different mips used, then we will update in that case. if(highestMip >= 0 && (newtex || highestMip != m_PrevHighestMip)) { usemipsettings = false; ui->mipLevel->setCurrentIndex(qBound(0, highestMip, (int)tex.mips - 1)); } if(ui->mipLevel->currentIndex() == -1) ui->mipLevel->setCurrentIndex(qBound(0, m_PrevHighestMip, (int)tex.mips - 1)); m_PrevHighestMip = highestMip; } { int firstArraySlice = -1; // only switch to the selected mip for outputs, and when changing drawcall if(!currentTextureIsLocked() && m_Following.Type != FollowType::ReadOnly && newdraw) firstArraySlice = m_Following.GetFirstArraySlice(m_Ctx); // see above with highestMip and prevHighestMip for the logic behind this if(firstArraySlice >= 0 && (newtex || firstArraySlice != m_PrevFirstArraySlice)) { useslicesettings = false; ui->sliceFace->setCurrentIndex(qBound(0, firstArraySlice, (int)numSlices - 1)); } if(ui->sliceFace->currentIndex() == -1) ui->sliceFace->setCurrentIndex(qBound(0, m_PrevFirstArraySlice, (int)numSlices - 1)); m_PrevFirstArraySlice = firstArraySlice; } // because slice and mip are specially set above, we restore any per-tex settings to apply // even if we don't switch to a new texture. // Note that if the slice or mip was changed because that slice or mip is the selected one // at the API level, we leave this alone. if(m_Ctx.Config().TextureViewer_PerTexSettings && m_TextureSettings.contains(tex.resourceId)) { if(usemipsettings) ui->mipLevel->setCurrentIndex(m_TextureSettings[tex.resourceId].mip); if(useslicesettings) ui->sliceFace->setCurrentIndex(m_TextureSettings[tex.resourceId].slice); } // handling for if we've switched to a new texture if(newtex) { // if we save certain settings per-texture, restore them (if we have any) if(m_Ctx.Config().TextureViewer_PerTexSettings && m_TextureSettings.contains(tex.resourceId)) { ui->channels->setCurrentIndex(m_TextureSettings[tex.resourceId].displayType); ui->customShader->setCurrentText(m_TextureSettings[tex.resourceId].customShader); ui->channelRed->setChecked(m_TextureSettings[tex.resourceId].r); ui->channelGreen->setChecked(m_TextureSettings[tex.resourceId].g); ui->channelBlue->setChecked(m_TextureSettings[tex.resourceId].b); ui->channelAlpha->setChecked(m_TextureSettings[tex.resourceId].a); ui->depthDisplay->setChecked(m_TextureSettings[tex.resourceId].depth); ui->stencilDisplay->setChecked(m_TextureSettings[tex.resourceId].stencil); m_NoRangePaint = true; ui->rangeHistogram->setRange(m_TextureSettings[m_TexDisplay.resourceId].minrange, m_TextureSettings[m_TexDisplay.resourceId].maxrange); m_NoRangePaint = false; } else if(m_Ctx.Config().TextureViewer_PerTexSettings) { // if we are using per-tex settings, reset back to RGB ui->channels->setCurrentIndex(0); ui->customShader->setCurrentText(QString()); ui->channelRed->setChecked(true); ui->channelGreen->setChecked(true); ui->channelBlue->setChecked(true); ui->channelAlpha->setChecked(false); ui->depthDisplay->setChecked(true); ui->stencilDisplay->setChecked(false); m_NoRangePaint = true; UI_SetHistogramRange(texptr, m_TexDisplay.typeHint); m_NoRangePaint = false; } // reset the range if desired if(m_Ctx.Config().TextureViewer_ResetRange) { UI_SetHistogramRange(texptr, m_TexDisplay.typeHint); } } UI_UpdateFittedScale(); UI_UpdateTextureDetails(); UI_UpdateChannels(); if(ui->autoFit->isChecked()) AutoFitRange(); m_Ctx.Replay().AsyncInvoke([this](IReplayController *r) { RT_UpdateVisualRange(r); RT_UpdateAndDisplay(r); if(m_Output != NULL) RT_PickPixelsAndUpdate(r); }); HighlightUsage(); } void TextureViewer::UI_SetHistogramRange(const TextureDescription *tex, CompType typeHint) { if(tex != NULL && (tex->format.compType == CompType::SNorm || typeHint == CompType::SNorm)) ui->rangeHistogram->setRange(-1.0f, 1.0f); else ui->rangeHistogram->setRange(0.0f, 1.0f); } void TextureViewer::UI_UpdateChannels() { TextureDescription *tex = GetCurrentTexture(); #define SHOW(widget) widget->setVisible(true) #define HIDE(widget) widget->setVisible(false) #define ENABLE(widget) widget->setEnabled(true) #define DISABLE(widget) widget->setEnabled(false) if(tex != NULL && (tex->creationFlags & TextureCategory::SwapBuffer)) { // swapbuffer is always srgb for 8-bit types, linear for 16-bit types DISABLE(ui->gammaDisplay); if(tex->format.compByteWidth == 2 && tex->format.type == ResourceFormatType::Regular) m_TexDisplay.linearDisplayAsGamma = false; else m_TexDisplay.linearDisplayAsGamma = true; } else { if(tex != NULL && !tex->format.srgbCorrected) ENABLE(ui->gammaDisplay); else DISABLE(ui->gammaDisplay); m_TexDisplay.linearDisplayAsGamma = !ui->gammaDisplay->isEnabled() || ui->gammaDisplay->isChecked(); } if(tex != NULL && tex->format.srgbCorrected) m_TexDisplay.linearDisplayAsGamma = false; bool dsv = false; if(tex != NULL) dsv = (tex->creationFlags & TextureCategory::DepthTarget) || (tex->format.compType == CompType::Depth); if(dsv && ui->channels->currentIndex() != 2) { // Depth display (when not using custom) HIDE(ui->channelRed); HIDE(ui->channelGreen); HIDE(ui->channelBlue); HIDE(ui->channelAlpha); HIDE(ui->mulSep); HIDE(ui->mulLabel); HIDE(ui->hdrMul); HIDE(ui->customShader); HIDE(ui->customCreate); HIDE(ui->customEdit); HIDE(ui->customDelete); SHOW(ui->depthDisplay); SHOW(ui->stencilDisplay); m_TexDisplay.red = ui->depthDisplay->isChecked(); m_TexDisplay.green = ui->stencilDisplay->isChecked(); m_TexDisplay.blue = false; m_TexDisplay.alpha = false; if(m_TexDisplay.red == m_TexDisplay.green && !m_TexDisplay.red) { m_TexDisplay.red = true; ui->depthDisplay->setChecked(true); } m_TexDisplay.hdrMultiplier = -1.0f; if(m_TexDisplay.customShaderId != ResourceId()) { memset(m_CurPixelValue.floatValue, 0, sizeof(float) * 4); memset(m_CurRealValue.floatValue, 0, sizeof(float) * 4); UI_UpdateStatusText(); } m_TexDisplay.customShaderId = ResourceId(); } else if(ui->channels->currentIndex() == 0 || !m_Ctx.IsCaptureLoaded()) { // RGBA SHOW(ui->channelRed); SHOW(ui->channelGreen); SHOW(ui->channelBlue); SHOW(ui->channelAlpha); HIDE(ui->mulSep); HIDE(ui->mulLabel); HIDE(ui->hdrMul); HIDE(ui->customShader); HIDE(ui->customCreate); HIDE(ui->customEdit); HIDE(ui->customDelete); HIDE(ui->depthDisplay); HIDE(ui->stencilDisplay); m_TexDisplay.red = ui->channelRed->isChecked(); m_TexDisplay.green = ui->channelGreen->isChecked(); m_TexDisplay.blue = ui->channelBlue->isChecked(); m_TexDisplay.alpha = ui->channelAlpha->isChecked(); m_TexDisplay.hdrMultiplier = -1.0f; if(m_TexDisplay.customShaderId != ResourceId()) { memset(m_CurPixelValue.floatValue, 0, sizeof(float) * 4); memset(m_CurRealValue.floatValue, 0, sizeof(float) * 4); UI_UpdateStatusText(); } m_TexDisplay.customShaderId = ResourceId(); } else if(ui->channels->currentIndex() == 1) { // RGBM SHOW(ui->channelRed); SHOW(ui->channelGreen); SHOW(ui->channelBlue); HIDE(ui->channelAlpha); SHOW(ui->mulSep); SHOW(ui->mulLabel); SHOW(ui->hdrMul); HIDE(ui->customShader); HIDE(ui->customCreate); HIDE(ui->customEdit); HIDE(ui->customDelete); HIDE(ui->depthDisplay); HIDE(ui->stencilDisplay); m_TexDisplay.red = ui->channelRed->isChecked(); m_TexDisplay.green = ui->channelGreen->isChecked(); m_TexDisplay.blue = ui->channelBlue->isChecked(); m_TexDisplay.alpha = false; bool ok = false; float mul = ui->hdrMul->currentText().toFloat(&ok); if(!ok) { mul = 32.0f; ui->hdrMul->setCurrentText(lit("32")); } m_TexDisplay.hdrMultiplier = mul; if(m_TexDisplay.customShaderId != ResourceId()) { memset(m_CurPixelValue.floatValue, 0, sizeof(float) * 4); memset(m_CurRealValue.floatValue, 0, sizeof(float) * 4); UI_UpdateStatusText(); } m_TexDisplay.customShaderId = ResourceId(); } else if(ui->channels->currentIndex() == 2) { // custom shaders SHOW(ui->channelRed); SHOW(ui->channelGreen); SHOW(ui->channelBlue); SHOW(ui->channelAlpha); HIDE(ui->mulSep); HIDE(ui->mulLabel); HIDE(ui->hdrMul); SHOW(ui->customShader); SHOW(ui->customCreate); SHOW(ui->customEdit); SHOW(ui->customDelete); HIDE(ui->depthDisplay); HIDE(ui->stencilDisplay); m_TexDisplay.red = ui->channelRed->isChecked(); m_TexDisplay.green = ui->channelGreen->isChecked(); m_TexDisplay.blue = ui->channelBlue->isChecked(); m_TexDisplay.alpha = ui->channelAlpha->isChecked(); m_TexDisplay.hdrMultiplier = -1.0f; m_TexDisplay.customShaderId = ResourceId(); QString shaderName = ui->customShader->currentText().toUpper(); if(m_CustomShaders.contains(shaderName)) { if(m_TexDisplay.customShaderId == ResourceId()) { memset(m_CurPixelValue.floatValue, 0, sizeof(float) * 4); memset(m_CurRealValue.floatValue, 0, sizeof(float) * 4); UI_UpdateStatusText(); } m_TexDisplay.customShaderId = m_CustomShaders[shaderName]; ui->customDelete->setEnabled(true); ui->customEdit->setEnabled(true); } else { ui->customDelete->setEnabled(false); ui->customEdit->setEnabled(false); } } #undef HIDE #undef SHOW #undef ENABLE #undef DISABLE m_TexDisplay.flipY = ui->flip_y->isChecked(); INVOKE_MEMFN(RT_UpdateAndDisplay); INVOKE_MEMFN(RT_UpdateVisualRange); } void TextureViewer::SetupTextureTabs() { ToolWindowManagerArea *textureTabs = ui->dockarea->areaOf(ui->renderContainer); QIcon tabIcon; tabIcon.addFile(QStringLiteral(":/logo.svg"), QSize(), QIcon::Normal, QIcon::Off); textureTabs->setTabIcon(0, tabIcon); textureTabs->setElideMode(Qt::ElideRight); QObject::connect(textureTabs, &QTabWidget::currentChanged, this, &TextureViewer::textureTab_Changed); QObject::connect(textureTabs, &QTabWidget::tabCloseRequested, this, &TextureViewer::textureTab_Closing); textureTabs->disableUserDrop(); textureTabs->tabBar()->setContextMenuPolicy(Qt::CustomContextMenu); QObject::connect(textureTabs->tabBar(), &QTabBar::customContextMenuRequested, this, &TextureViewer::textureTab_Menu); } void TextureViewer::textureTab_Menu(const QPoint &pos) { ToolWindowManagerArea *textureTabs = ui->dockarea->areaOf(ui->renderContainer); int tabIndex = textureTabs->tabBar()->tabAt(pos); if(tabIndex == -1) return; QAction closeTab(tr("Close tab"), this); QAction closeOtherTabs(tr("Close other tabs"), this); QAction closeRightTabs(tr("Close tabs to the right"), this); if(textureTabs->widget(tabIndex) == ui->renderContainer) closeTab.setEnabled(false); QMenu contextMenu(this); contextMenu.addAction(&closeTab); contextMenu.addAction(&closeOtherTabs); contextMenu.addAction(&closeRightTabs); QObject::connect(&closeTab, &QAction::triggered, [textureTabs, tabIndex]() { // remove the tab at this index textureTabs->removeTab(tabIndex); }); QObject::connect(&closeRightTabs, &QAction::triggered, [textureTabs, tabIndex]() { // remove all tabs with a greater index while(textureTabs->count() > tabIndex + 1) textureTabs->removeTab(tabIndex + 1); }); QObject::connect(&closeOtherTabs, &QAction::triggered, [textureTabs, tabIndex]() { // remove all tabs with a greater index while(textureTabs->count() > tabIndex + 1) textureTabs->removeTab(tabIndex + 1); // remove all tabs at index 1 until there's only two, these are the ones between the locked tab // 0 and the tabIndex while(textureTabs->count() > 2) textureTabs->removeTab(1); }); RDDialog::show(&contextMenu, QCursor::pos()); } void TextureViewer::textureTab_Changed(int index) { ToolWindowManagerArea *textureTabs = ui->dockarea->areaOf(ui->renderContainer); if(!textureTabs) return; QWidget *w = textureTabs->widget(index); if(w) { w->setLayout(ui->renderLayout); if(w == ui->renderContainer) m_LockedId = ResourceId(); else m_LockedId = w->property("id").value<ResourceId>(); UI_UpdateCachedTexture(); } UI_OnTextureSelectionChanged(false); } void TextureViewer::textureTab_Closing(int index) { ToolWindowManagerArea *textureTabs = ui->dockarea->areaOf(ui->renderContainer); if(index > 0) { // this callback happens AFTER the widget has already been removed unfortunately, so // we need to search through the locked tab list to see which one was removed to be // able to delete it properly. QList<ResourceId> ids = m_LockedTabs.keys(); for(int i = 0; i < textureTabs->count(); i++) { QWidget *w = textureTabs->widget(i); ResourceId id = w->property("id").value<ResourceId>(); ids.removeOne(id); } if(ids.count() != 1) qWarning() << "Expected only one removed tab, got " << ids.count(); for(ResourceId id : ids) m_LockedTabs.remove(id); textureTabs->setCurrentIndex(index - 1); textureTabs->widget(index - 1)->show(); return; } // should never get here - tab 0 is the dynamic tab which is uncloseable. qCritical() << "Somehow closing dynamic tab?"; if(textureTabs->count() > 1) { textureTabs->setCurrentIndex(1); textureTabs->widget(1)->show(); } } ResourcePreview *TextureViewer::UI_CreateThumbnail(ThumbnailStrip *strip) { ResourcePreview *prev = new ResourcePreview(m_Ctx, m_Output); QObject::connect(prev, &ResourcePreview::clicked, this, &TextureViewer::thumb_clicked); QObject::connect(prev, &ResourcePreview::doubleClicked, this, &TextureViewer::thumb_doubleClicked); prev->setActive(false); strip->addThumb(prev); return prev; } void TextureViewer::UI_CreateThumbnails() { if(!ui->outputThumbs->thumbs().isEmpty()) return; // these will expand, but we make sure that there is a good set reserved for(int i = 0; i < 9; i++) { ResourcePreview *prev = UI_CreateThumbnail(ui->outputThumbs); if(i == 0) prev->setSelected(true); } for(int i = 0; i < 128; i++) UI_CreateThumbnail(ui->inputThumbs); } void TextureViewer::GotoLocation(int x, int y) { if(!m_Ctx.IsCaptureLoaded()) return; TextureDescription *tex = GetCurrentTexture(); if(tex == NULL) return; m_PickedPoint = QPoint(x, y); uint32_t mipHeight = qMax(1U, tex->height >> (int)m_TexDisplay.mip); if(m_Ctx.APIProps().pipelineType == GraphicsAPI::OpenGL) m_PickedPoint.setY((int)(mipHeight - 1) - m_PickedPoint.y()); if(m_TexDisplay.flipY) m_PickedPoint.setY((int)(mipHeight - 1) - m_PickedPoint.x()); if(m_Output != NULL) INVOKE_MEMFN(RT_PickPixelsAndUpdate); INVOKE_MEMFN(RT_UpdateAndDisplay); UI_UpdateStatusText(); } void TextureViewer::ViewTexture(ResourceId ID, bool focus) { if(QThread::currentThread() != QCoreApplication::instance()->thread()) { GUIInvoke::call(this, [this, ID, focus] { this->ViewTexture(ID, focus); }); return; } if(m_LockedTabs.contains(ID)) { if(focus) ToolWindowManager::raiseToolWindow(this); QWidget *w = m_LockedTabs[ID]; ToolWindowManagerArea *textureTabs = ui->dockarea->areaOf(ui->renderContainer); int idx = textureTabs->indexOf(w); if(idx >= 0) textureTabs->setCurrentIndex(idx); INVOKE_MEMFN(RT_UpdateAndDisplay); return; } TextureDescription *tex = m_Ctx.GetTexture(ID); if(tex) { QWidget *lockedContainer = new QWidget(this); lockedContainer->setWindowTitle(m_Ctx.GetResourceName(ID)); lockedContainer->setProperty("id", QVariant::fromValue(ID)); ToolWindowManagerArea *textureTabs = ui->dockarea->areaOf(ui->renderContainer); ToolWindowManager::AreaReference ref(ToolWindowManager::AddTo, textureTabs); ui->dockarea->addToolWindow(lockedContainer, ref); ui->dockarea->setToolWindowProperties( lockedContainer, ToolWindowManager::DisallowUserDocking | ToolWindowManager::AlwaysDisplayFullTabs); lockedContainer->setLayout(ui->renderLayout); int idx = textureTabs->indexOf(lockedContainer); if(idx >= 0) textureTabs->setTabIcon(idx, Icons::page_go()); else qCritical() << "Couldn't get tab index of new tab to set icon"; // newPanel.DockHandler.TabPageContextMenuStrip = tabContextMenu; if(focus) ToolWindowManager::raiseToolWindow(this); m_LockedTabs[ID] = lockedContainer; INVOKE_MEMFN(RT_UpdateAndDisplay); return; } BufferDescription *buf = m_Ctx.GetBuffer(ID); if(buf) { IBufferViewer *viewer = m_Ctx.ViewBuffer(0, 0, ID); m_Ctx.AddDockWindow(viewer->Widget(), DockReference::AddTo, this); } } void TextureViewer::texContextItem_triggered() { QAction *act = qobject_cast<QAction *>(QObject::sender()); QVariant eid = act->property("eid"); if(eid.isValid()) { m_Ctx.SetEventID({}, eid.toUInt(), eid.toUInt()); return; } QVariant id = act->property("id"); if(id.isValid()) { ViewTexture(id.value<ResourceId>(), false); return; } } void TextureViewer::showDisabled_triggered() { m_ShowDisabled = !m_ShowDisabled; if(m_Ctx.IsCaptureLoaded()) m_Ctx.RefreshStatus(); } void TextureViewer::showEmpty_triggered() { m_ShowEmpty = !m_ShowEmpty; if(m_Ctx.IsCaptureLoaded()) m_Ctx.RefreshStatus(); } void TextureViewer::AddResourceUsageEntry(QMenu &menu, uint32_t start, uint32_t end, ResourceUsage usage) { QAction *item = NULL; if(start == end) item = new QAction( QFormatStr("EID %1: %2").arg(start).arg(ToQStr(usage, m_Ctx.APIProps().pipelineType)), this); else item = new QAction( QFormatStr("EID %1-%2: %3").arg(start).arg(end).arg(ToQStr(usage, m_Ctx.APIProps().pipelineType)), this); QObject::connect(item, &QAction::triggered, this, &TextureViewer::texContextItem_triggered); item->setProperty("eid", QVariant(end)); menu.addAction(item); } void TextureViewer::OpenResourceContextMenu(ResourceId id, bool input, const rdcarray<EventUsage> &usage) { QMenu contextMenu(this); QAction showDisabled(tr("Show Disabled"), this); QAction showEmpty(tr("Show Empty"), this); QAction openLockedTab(tr("Open new Locked Tab"), this); QAction openResourceInspector(tr("Open in Resource Inspector"), this); QAction usageTitle(tr("Used:"), this); QAction imageLayout(this); openLockedTab.setIcon(Icons::action_hover()); openResourceInspector.setIcon(Icons::link()); showDisabled.setChecked(m_ShowDisabled); showDisabled.setChecked(m_ShowEmpty); contextMenu.addAction(&showDisabled); contextMenu.addAction(&showEmpty); QObject::connect(&showDisabled, &QAction::triggered, this, &TextureViewer::showDisabled_triggered); QObject::connect(&showEmpty, &QAction::triggered, this, &TextureViewer::showEmpty_triggered); if(m_Ctx.CurPipelineState().SupportsBarriers()) { contextMenu.addSeparator(); imageLayout.setText(tr("Image is in layout ") + m_Ctx.CurPipelineState().GetResourceLayout(id)); contextMenu.addAction(&imageLayout); } if(id != ResourceId()) { contextMenu.addSeparator(); contextMenu.addAction(&openLockedTab); contextMenu.addAction(&openResourceInspector); contextMenu.addSeparator(); m_Ctx.Extensions().MenuDisplaying(input ? ContextMenu::TextureViewer_InputThumbnail : ContextMenu::TextureViewer_OutputThumbnail, &contextMenu, {{"resourceId", id}}); contextMenu.addSeparator(); contextMenu.addAction(&usageTitle); openLockedTab.setProperty("id", QVariant::fromValue(id)); QObject::connect(&openLockedTab, &QAction::triggered, this, &TextureViewer::texContextItem_triggered); QObject::connect(&openResourceInspector, &QAction::triggered, [this, id]() { m_Ctx.ShowResourceInspector(); m_Ctx.GetResourceInspector()->Inspect(id); }); CombineUsageEvents(m_Ctx, usage, [this, &contextMenu](uint32_t start, uint32_t end, ResourceUsage use) { AddResourceUsageEntry(contextMenu, start, end, use); }); RDDialog::show(&contextMenu, QCursor::pos()); } else { contextMenu.addSeparator(); m_Ctx.Extensions().MenuDisplaying(input ? ContextMenu::TextureViewer_InputThumbnail : ContextMenu::TextureViewer_OutputThumbnail, &contextMenu, {}); RDDialog::show(&contextMenu, QCursor::pos()); } } void TextureViewer::InitResourcePreview(ResourcePreview *prev, ResourceId id, CompType typeHint, bool force, Following &follow, const QString &bindName, const QString &slotName) { if(id != ResourceId() || force) { QString fullname = bindName; if(!m_Ctx.IsAutogeneratedName(id)) { if(!fullname.isEmpty()) fullname += lit(" = "); fullname += m_Ctx.GetResourceName(id); } if(fullname.isEmpty()) fullname = m_Ctx.GetResourceName(id); prev->setResourceName(fullname); WindowingData winData = m_Ctx.CreateWindowingData(prev->thumbWidget()); if(m_Ctx.GetTexture(id)) { m_Ctx.Replay().AsyncInvoke([this, winData, id, typeHint](IReplayController *) { m_Output->AddThumbnail(winData, id, typeHint); }); } else { m_Ctx.Replay().AsyncInvoke([this, winData](IReplayController *) { m_Output->AddThumbnail(winData, ResourceId(), CompType::Typeless); }); } prev->setProperty("f", QVariant::fromValue(follow)); prev->setSlotName(slotName); prev->setActive(true); prev->setSelected(m_Following == follow); } else if(m_Following == follow) { prev->setResourceName(tr("Unused")); prev->setActive(true); prev->setSelected(true); WindowingData winData = m_Ctx.CreateWindowingData(prev->thumbWidget()); m_Ctx.Replay().AsyncInvoke([this, winData](IReplayController *) { m_Output->AddThumbnail(winData, ResourceId(), CompType::Typeless); }); } else { prev->setResourceName(QString()); prev->setActive(false); prev->setSelected(false); } } void TextureViewer::InitStageResourcePreviews(ShaderStage stage, const rdcarray<ShaderResource> &resourceDetails, const rdcarray<Bindpoint> &mapping, rdcarray<BoundResourceArray> &ResList, ThumbnailStrip *prevs, int &prevIndex, bool copy, bool rw) { for(int idx = 0; idx < mapping.count(); idx++) { const Bindpoint &key = mapping[idx]; const rdcarray<BoundResource> *resArray = NULL; int residx = ResList.indexOf(key); if(residx >= 0) resArray = &ResList[residx].resources; int arrayLen = resArray != NULL ? resArray->count() : 1; // it's too expensive in bindless-type cases to create a thumbnail for every array element, so // for now we create one just for the first element and add an array size indicator to the slot // name // for(int arrayIdx = 0; arrayIdx < arrayLen; arrayIdx++) int arrayIdx = 0; { ResourceId id = resArray != NULL ? resArray->at(arrayIdx).resourceId : ResourceId(); CompType typeHint = resArray != NULL ? resArray->at(arrayIdx).typeHint : CompType::Typeless; bool used = key.used; QString bindName; for(const ShaderResource &bind : resourceDetails) { if(bind.bindPoint == idx) { bindName = bind.name; break; } } if(copy) { used = true; bindName = tr("Source"); } Following follow(rw ? FollowType::ReadWrite : FollowType::ReadOnly, stage, idx, arrayIdx); QString slotName = QFormatStr("%1 %2%3") .arg(m_Ctx.CurPipelineState().Abbrev(stage)) .arg(rw ? lit("RW ") : lit("")) .arg(idx); if(arrayLen > 1) slotName += QFormatStr(" Arr[%1]").arg(arrayLen); if(copy) slotName = tr("SRC"); // show if it's referenced by the shader - regardless of empty or not bool show = used; // it's bound, but not referenced, and we have "show disabled" show = show || (m_ShowDisabled && !used && id != ResourceId()); // it's empty, and we have "show empty" show = show || (m_ShowEmpty && id == ResourceId()); // it's the one we're following show = show || (follow == m_Following); ResourcePreview *prev = NULL; if(prevIndex < prevs->thumbs().size()) { prev = prevs->thumbs()[prevIndex]; // don't use it if we're not actually going to show it if(!show && !prev->isActive()) continue; } else { // don't create it if we're not actually going to show it if(!show) continue; prev = UI_CreateThumbnail(prevs); } prevIndex++; InitResourcePreview(prev, show ? id : ResourceId(), typeHint, show, follow, bindName, slotName); } } } void TextureViewer::thumb_doubleClicked(QMouseEvent *e) { if(e->buttons() & Qt::LeftButton) { ResourceId id = m_Following.GetResourceId(m_Ctx); if(id != ResourceId()) ViewTexture(id, false); } } void TextureViewer::thumb_clicked(QMouseEvent *e) { if(e->buttons() & Qt::LeftButton) { ResourcePreview *prev = qobject_cast<ResourcePreview *>(QObject::sender()); Following follow = prev->property("f").value<Following>(); for(ResourcePreview *p : ui->outputThumbs->thumbs()) p->setSelected(false); for(ResourcePreview *p : ui->inputThumbs->thumbs()) p->setSelected(false); m_Following = follow; prev->setSelected(true); UI_UpdateCachedTexture(); ResourceId id = m_Following.GetResourceId(m_Ctx); if(id != ResourceId()) { UI_OnTextureSelectionChanged(false); ui->renderContainer->show(); } } if(e->buttons() & Qt::RightButton) { ResourcePreview *prev = qobject_cast<ResourcePreview *>(QObject::sender()); Following follow = prev->property("f").value<Following>(); ResourceId id = follow.GetResourceId(m_Ctx); if(id == ResourceId() && follow == m_Following) id = m_TexDisplay.resourceId; rdcarray<EventUsage> empty; bool input = follow.Type == FollowType::ReadOnly; if(id == ResourceId()) { OpenResourceContextMenu(id, input, empty); } else { m_Ctx.Replay().AsyncInvoke([this, id, input](IReplayController *r) { rdcarray<EventUsage> usage = r->GetUsage(id); GUIInvoke::call(this, [this, id, input, usage]() { OpenResourceContextMenu(id, input, usage); }); }); } } } void TextureViewer::render_mouseWheel(QWheelEvent *e) { QPoint cursorPos = e->pos(); setFitToWindow(false); // scroll in logarithmic scale double logScale = logf(m_TexDisplay.scale); logScale += e->delta() / 2500.0; UI_SetScale((float)expf(logScale), cursorPos.x() * ui->render->devicePixelRatio(), cursorPos.y() * ui->render->devicePixelRatio()); e->accept(); } void TextureViewer::render_mouseMove(QMouseEvent *e) { if(m_Output == NULL) return; m_CurHoverPixel.setX(int((float(e->x() * ui->render->devicePixelRatio()) - m_TexDisplay.xOffset) / m_TexDisplay.scale)); m_CurHoverPixel.setY(int((float(e->y() * ui->render->devicePixelRatio()) - m_TexDisplay.yOffset) / m_TexDisplay.scale)); if(m_TexDisplay.resourceId != ResourceId()) { TextureDescription *texptr = GetCurrentTexture(); if(texptr != NULL) { if(e->buttons() & Qt::RightButton) { ui->render->setCursor(QCursor(Qt::CrossCursor)); m_PickedPoint = m_CurHoverPixel; m_PickedPoint.setX(qBound(0, m_PickedPoint.x(), (int)texptr->width - 1)); m_PickedPoint.setY(qBound(0, m_PickedPoint.y(), (int)texptr->height - 1)); m_Ctx.Replay().AsyncInvoke(lit("PickPixelClick"), [this](IReplayController *r) { RT_PickPixelsAndUpdate(r); }); } else if(e->buttons() == Qt::NoButton) { m_Ctx.Replay().AsyncInvoke(lit("PickPixelHover"), [this](IReplayController *r) { RT_PickHoverAndUpdate(r); }); } } } QPoint curpos = QCursor::pos(); if(e->buttons() & Qt::LeftButton) { if(qAbs(m_DragStartPos.x() - curpos.x()) > ui->renderHScroll->singleStep() || qAbs(m_DragStartPos.y() - curpos.y()) > ui->renderVScroll->singleStep()) { setScrollPosition(QPoint(m_DragStartScroll.x() + (curpos.x() - m_DragStartPos.x()), m_DragStartScroll.y() + (curpos.y() - m_DragStartPos.y()))); } ui->render->setCursor(QCursor(Qt::SizeAllCursor)); } if(e->buttons() == Qt::NoButton) { ui->render->unsetCursor(); } UI_UpdateStatusText(); } void TextureViewer::render_mouseClick(QMouseEvent *e) { ui->render->setFocus(); if(e->buttons() & Qt::RightButton) render_mouseMove(e); if(e->buttons() & Qt::LeftButton) { m_DragStartPos = QCursor::pos(); m_DragStartScroll = getScrollPosition(); ui->render->setCursor(QCursor(Qt::SizeAllCursor)); } } void TextureViewer::render_resize(QResizeEvent *e) { UI_UpdateFittedScale(); UI_CalcScrollbars(); INVOKE_MEMFN(RT_UpdateAndDisplay); } void TextureViewer::render_keyPress(QKeyEvent *e) { TextureDescription *texptr = GetCurrentTexture(); if(texptr == NULL) return; if(e->matches(QKeySequence::Copy)) { QClipboard *clipboard = QApplication::clipboard(); clipboard->setText(ui->texStatusDim->text() + lit(" | ") + ui->statusText->text()); } if(!m_Ctx.IsCaptureLoaded()) return; if((e->modifiers() & Qt::ControlModifier) && e->key() == Qt::Key_G) { ShowGotoPopup(); } bool nudged = false; int increment = 1 << (int)m_TexDisplay.mip; if(e->key() == Qt::Key_Up && m_PickedPoint.y() > 0) { m_PickedPoint -= QPoint(0, increment); nudged = true; } else if(e->key() == Qt::Key_Down && m_PickedPoint.y() < (int)texptr->height - 1) { m_PickedPoint += QPoint(0, increment); nudged = true; } else if(e->key() == Qt::Key_Left && m_PickedPoint.x() > 0) { m_PickedPoint -= QPoint(increment, 0); nudged = true; } else if(e->key() == Qt::Key_Right && m_PickedPoint.x() < (int)texptr->height - 1) { m_PickedPoint += QPoint(increment, 0); nudged = true; } if(nudged) { m_PickedPoint = QPoint(qBound(0, m_PickedPoint.x(), (int)texptr->width - 1), qBound(0, m_PickedPoint.y(), (int)texptr->height - 1)); e->accept(); m_Ctx.Replay().AsyncInvoke([this](IReplayController *r) { RT_PickPixelsAndUpdate(r); RT_UpdateAndDisplay(r); }); UI_UpdateStatusText(); } } float TextureViewer::CurMaxScrollX() { TextureDescription *texptr = GetCurrentTexture(); QSizeF size(1.0f, 1.0f); if(texptr != NULL) size = QSizeF(texptr->width, texptr->height); return realRenderWidth() - size.width() * m_TexDisplay.scale; } float TextureViewer::CurMaxScrollY() { TextureDescription *texptr = GetCurrentTexture(); QSizeF size(1.0f, 1.0f); if(texptr != NULL) size = QSizeF(texptr->width, texptr->height); return realRenderHeight() - size.height() * m_TexDisplay.scale; } QPoint TextureViewer::getScrollPosition() { return QPoint((int)m_TexDisplay.xOffset, m_TexDisplay.yOffset); } void TextureViewer::setScrollPosition(const QPoint &pos) { m_TexDisplay.xOffset = qMax(CurMaxScrollX(), (float)pos.x()); m_TexDisplay.yOffset = qMax(CurMaxScrollY(), (float)pos.y()); m_TexDisplay.xOffset = qMin(0.0f, m_TexDisplay.xOffset); m_TexDisplay.yOffset = qMin(0.0f, m_TexDisplay.yOffset); if(ScrollUpdateScrollbars) { ScrollUpdateScrollbars = false; if(ui->renderHScroll->isEnabled()) ui->renderHScroll->setValue(qBound(0, -int(m_TexDisplay.xOffset), ui->renderHScroll->maximum())); if(ui->renderVScroll->isEnabled()) ui->renderVScroll->setValue(qBound(0, -int(m_TexDisplay.yOffset), ui->renderVScroll->maximum())); ScrollUpdateScrollbars = true; } INVOKE_MEMFN(RT_UpdateAndDisplay); } void TextureViewer::UI_CalcScrollbars() { TextureDescription *texptr = GetCurrentTexture(); QSizeF size(1.0f, 1.0f); if(texptr != NULL) { size = QSizeF(texptr->width, texptr->height); } if((int)floor(size.width() * m_TexDisplay.scale) <= realRenderWidth()) { ui->renderHScroll->setEnabled(false); } else { ui->renderHScroll->setEnabled(true); ui->renderHScroll->setMaximum((int)ceil(size.width() * m_TexDisplay.scale - realRenderWidth())); ui->renderHScroll->setPageStep(qMax(1, ui->renderHScroll->maximum() / 6)); ui->renderHScroll->setSingleStep(int(m_TexDisplay.scale)); } if((int)floor(size.height() * m_TexDisplay.scale) <= realRenderHeight()) { ui->renderVScroll->setEnabled(false); } else { ui->renderVScroll->setEnabled(true); ui->renderVScroll->setMaximum((int)ceil(size.height() * m_TexDisplay.scale - realRenderHeight())); ui->renderVScroll->setPageStep(qMax(1, ui->renderVScroll->maximum() / 6)); ui->renderVScroll->setSingleStep(int(m_TexDisplay.scale)); } } void TextureViewer::on_renderHScroll_valueChanged(int position) { if(!ScrollUpdateScrollbars) return; ScrollUpdateScrollbars = false; { float delta = (float)position / (float)ui->renderHScroll->maximum(); setScrollPosition(QPoint((int)(CurMaxScrollX() * delta), getScrollPosition().y())); } ScrollUpdateScrollbars = true; } void TextureViewer::on_renderVScroll_valueChanged(int position) { if(!ScrollUpdateScrollbars) return; ScrollUpdateScrollbars = false; { float delta = (float)position / (float)ui->renderVScroll->maximum(); setScrollPosition(QPoint(getScrollPosition().x(), (int)(CurMaxScrollY() * delta))); } ScrollUpdateScrollbars = true; } void TextureViewer::UI_RecreatePanels() { ICaptureContext *ctx = &m_Ctx; // while a capture is loaded, pass NULL into the widget if(!m_Ctx.IsCaptureLoaded()) ctx = NULL; { CustomPaintWidget *render = new CustomPaintWidget(ctx, ui->renderContainer); render->setObjectName(ui->render->objectName()); render->setSizePolicy(ui->render->sizePolicy()); delete ui->render; ui->render = render; ui->gridLayout->addWidget(render, 1, 0, 1, 1); } { CustomPaintWidget *pixelContext = new CustomPaintWidget(ctx, ui->pixelContextLayout); pixelContext->setObjectName(ui->pixelContext->objectName()); pixelContext->setSizePolicy(ui->pixelContext->sizePolicy()); delete ui->pixelContext; ui->pixelContext = pixelContext; ui->pixelcontextgrid->addWidget(pixelContext, 0, 0, 1, 2); } updateBackgroundColors(); QObject::connect(ui->render, &CustomPaintWidget::clicked, this, &TextureViewer::render_mouseClick); QObject::connect(ui->render, &CustomPaintWidget::mouseMove, this, &TextureViewer::render_mouseMove); QObject::connect(ui->render, &CustomPaintWidget::mouseWheel, this, &TextureViewer::render_mouseWheel); QObject::connect(ui->render, &CustomPaintWidget::resize, this, &TextureViewer::render_resize); QObject::connect(ui->render, &CustomPaintWidget::keyPress, this, &TextureViewer::render_keyPress); QObject::connect(ui->pixelContext, &CustomPaintWidget::keyPress, this, &TextureViewer::render_keyPress); } void TextureViewer::updateBackgroundColors() { if(backCol.isValid()) { ui->render->setColours(backCol, backCol); ui->pixelContext->setColours(backCol, backCol); } else { ui->render->setColours(Formatter::DarkCheckerColor(), Formatter::LightCheckerColor()); ui->pixelContext->setColours(Formatter::DarkCheckerColor(), Formatter::LightCheckerColor()); } } void TextureViewer::OnCaptureLoaded() { Reset(); WindowingData renderData = m_Ctx.CreateWindowingData(ui->render); WindowingData contextData = m_Ctx.CreateWindowingData(ui->pixelContext); ui->saveTex->setEnabled(true); ui->locationGoto->setEnabled(true); ui->viewTexBuffer->setEnabled(true); if(m_Ctx.CurPipelineState().IsCaptureD3D11()) { ui->pixelHistory->setEnabled(true); ui->pixelHistory->setToolTip(QString()); } else { ui->pixelHistory->setEnabled(false); ui->pixelHistory->setToolTip(tr("Pixel History not implemented on this API")); } if(m_Ctx.CurPipelineState().IsCaptureD3D11()) { ui->debugPixelContext->setEnabled(true); ui->debugPixelContext->setToolTip(QString()); } else { ui->debugPixelContext->setEnabled(false); ui->debugPixelContext->setToolTip(tr("Shader Debugging not implemented on this API")); } TextureListItemModel *model = (TextureListItemModel *)ui->textureList->model(); model->reset(TextureListItemModel::String, QString()); m_TexDisplay.backgroundColor = backCol.isValid() ? FloatVector(backCol.redF(), backCol.greenF(), backCol.blueF(), 1.0f) : FloatVector(); m_Ctx.Replay().BlockInvoke([renderData, contextData, this](IReplayController *r) { m_Output = r->CreateOutput(renderData, ReplayOutputType::Texture); m_Output->SetPixelContext(contextData); ui->render->setOutput(m_Output); ui->pixelContext->setOutput(m_Output); RT_UpdateAndDisplay(r); GUIInvoke::call(this, [this]() { OnEventChanged(m_Ctx.CurEvent()); }); }); m_Watcher = new QFileSystemWatcher({configFilePath(QString())}, this); QObject::connect(m_Watcher, &QFileSystemWatcher::fileChanged, this, &TextureViewer::customShaderModified); QObject::connect(m_Watcher, &QFileSystemWatcher::directoryChanged, this, &TextureViewer::customShaderModified); reloadCustomShaders(QString()); } void TextureViewer::Reset() { m_CachedTexture = NULL; m_PickedPoint.setX(-1); m_PickedPoint.setY(-1); memset(&m_TexDisplay, 0, sizeof(m_TexDisplay)); m_TexDisplay.backgroundColor = backCol.isValid() ? FloatVector(backCol.redF(), backCol.greenF(), backCol.blueF(), 1.0f) : FloatVector(); m_Output = NULL; m_TextureSettings.clear(); m_PrevSize = QSizeF(); m_HighWaterStatusLength = 0; ui->rangeHistogram->setRange(0.0f, 1.0f); ui->textureListFilter->setCurrentIndex(0); ui->renderHScroll->setEnabled(false); ui->renderVScroll->setEnabled(false); ui->pixelHistory->setEnabled(false); ui->pixelHistory->setToolTip(QString()); ui->debugPixelContext->setEnabled(false); ui->debugPixelContext->setToolTip(QString()); ui->statusText->setText(QString()); ui->renderContainer->setWindowTitle(tr("Current")); ui->mipLevel->clear(); ui->sliceFace->clear(); UI_SetScale(1.0f); ui->channels->setCurrentIndex(0); ui->overlay->setCurrentIndex(0); { QPalette Pal(palette()); Pal.setColor(QPalette::Background, Qt::black); ui->pickSwatch->setAutoFillBackground(true); ui->pickSwatch->setPalette(Pal); } ui->customShader->clear(); UI_RecreatePanels(); ui->inputThumbs->clearThumbs(); ui->outputThumbs->clearThumbs(); UI_UpdateTextureDetails(); UI_UpdateChannels(); } void TextureViewer::OnCaptureClosed() { Reset(); refreshTextureList(); delete m_Watcher; m_Watcher = NULL; ToolWindowManagerArea *textureTabs = ui->dockarea->areaOf(ui->renderContainer); while(textureTabs->count() > 1) textureTabs->removeTab(1); m_LockedTabs.clear(); ui->customShader->clear(); m_CustomShaders.clear(); ui->saveTex->setEnabled(false); ui->locationGoto->setEnabled(false); ui->viewTexBuffer->setEnabled(false); } void TextureViewer::OnEventChanged(uint32_t eventId) { UI_UpdateCachedTexture(); TextureDescription *CurrentTexture = GetCurrentTexture(); if(!currentTextureIsLocked() || (CurrentTexture != NULL && m_TexDisplay.resourceId != CurrentTexture->resourceId)) UI_OnTextureSelectionChanged(true); if(m_Output == NULL) return; UI_CreateThumbnails(); UI_UpdateTextureDetails(); refreshTextureList(); // iterate over locked tabs, and update the name if it's changed for(QWidget *w : m_LockedTabs.values()) { ResourceId id = w->property("id").value<ResourceId>(); w->setWindowTitle(m_Ctx.GetResourceName(id)); } rdcarray<BoundResource> RTs = Following::GetOutputTargets(m_Ctx); BoundResource Depth = Following::GetDepthTarget(m_Ctx); int outIndex = 0; int inIndex = 0; bool copy = false, clear = false, compute = false; Following::GetDrawContext(m_Ctx, copy, clear, compute); for(int rt = 0; rt < RTs.count(); rt++) { ResourcePreview *prev; if(outIndex < ui->outputThumbs->thumbs().size()) prev = ui->outputThumbs->thumbs()[outIndex]; else prev = UI_CreateThumbnail(ui->outputThumbs); outIndex++; Following follow(FollowType::OutputColour, ShaderStage::Pixel, rt, 0); QString bindName = (copy || clear) ? tr("Destination") : QString(); QString slotName = (copy || clear) ? tr("DST") : (m_Ctx.CurPipelineState().OutputAbbrev() + QString::number(rt)); InitResourcePreview(prev, RTs[rt].resourceId, RTs[rt].typeHint, false, follow, bindName, slotName); } // depth { ResourcePreview *prev; if(outIndex < ui->outputThumbs->thumbs().size()) prev = ui->outputThumbs->thumbs()[outIndex]; else prev = UI_CreateThumbnail(ui->outputThumbs); outIndex++; Following follow(FollowType::OutputDepth, ShaderStage::Pixel, 0, 0); InitResourcePreview(prev, Depth.resourceId, Depth.typeHint, false, follow, QString(), tr("DS")); } ShaderStage stages[] = {ShaderStage::Vertex, ShaderStage::Hull, ShaderStage::Domain, ShaderStage::Geometry, ShaderStage::Pixel}; int count = 5; if(compute) { stages[0] = ShaderStage::Compute; count = 1; } const rdcarray<ShaderResource> empty; // display resources used for all stages for(int i = 0; i < count; i++) { ShaderStage stage = stages[i]; rdcarray<BoundResourceArray> RWs = Following::GetReadWriteResources(m_Ctx, stage); rdcarray<BoundResourceArray> ROs = Following::GetReadOnlyResources(m_Ctx, stage); const ShaderReflection *details = Following::GetReflection(m_Ctx, stage); const ShaderBindpointMapping &mapping = Following::GetMapping(m_Ctx, stage); InitStageResourcePreviews(stage, details != NULL ? details->readWriteResources : empty, mapping.readWriteResources, RWs, ui->outputThumbs, outIndex, copy, true); InitStageResourcePreviews(stage, details != NULL ? details->readOnlyResources : empty, mapping.readOnlyResources, ROs, ui->inputThumbs, inIndex, copy, false); } // hide others const QVector<ResourcePreview *> &outThumbs = ui->outputThumbs->thumbs(); for(; outIndex < outThumbs.size(); outIndex++) { ResourcePreview *prev = outThumbs[outIndex]; prev->setResourceName(QString()); prev->setActive(false); prev->setSelected(false); } ui->outputThumbs->refreshLayout(); const QVector<ResourcePreview *> &inThumbs = ui->inputThumbs->thumbs(); for(; inIndex < inThumbs.size(); inIndex++) { ResourcePreview *prev = inThumbs[inIndex]; prev->setResourceName(QString()); prev->setActive(false); prev->setSelected(false); } ui->inputThumbs->refreshLayout(); INVOKE_MEMFN(RT_UpdateAndDisplay); if(ui->autoFit->isChecked()) AutoFitRange(); } QVariant TextureViewer::persistData() { QVariantMap state = ui->dockarea->saveState(); state[lit("backCol")] = backCol; state[lit("checker")] = !backCol.isValid(); return state; } void TextureViewer::setPersistData(const QVariant &persistData) { QVariantMap state = persistData.toMap(); backCol = state[lit("backCol")].value<QColor>(); bool checker = state[lit("checker")].value<bool>(); if(checker) backCol = QColor(); ui->backcolorPick->setChecked(!checker); ui->checkerBack->setChecked(checker); m_TexDisplay.backgroundColor = checker ? FloatVector() : FloatVector(backCol.redF(), backCol.greenF(), backCol.blueF(), 1.0f); ToolWindowManagerArea *textureTabs = ui->dockarea->areaOf(ui->renderContainer); while(textureTabs->count() > 1) textureTabs->removeTab(1); m_LockedTabs.clear(); updateBackgroundColors(); ui->dockarea->restoreState(state); SetupTextureTabs(); } float TextureViewer::GetFitScale() { TextureDescription *texptr = GetCurrentTexture(); if(texptr == NULL) return 1.0f; float xscale = (float)realRenderWidth() / (float)texptr->width; float yscale = (float)realRenderHeight() / (float)texptr->height; return qMin(xscale, yscale); } int TextureViewer::realRenderWidth() const { return ui->render->width() * ui->render->devicePixelRatio(); } int TextureViewer::realRenderHeight() const { return ui->render->height() * ui->render->devicePixelRatio(); } void TextureViewer::UI_UpdateFittedScale() { if(ui->fitToWindow->isChecked()) UI_SetScale(1.0f); } void TextureViewer::UI_SetScale(float s) { UI_SetScale(s, ui->render->width() / 2, ui->render->height() / 2); } void TextureViewer::UI_SetScale(float s, int x, int y) { if(ui->fitToWindow->isChecked()) s = GetFitScale(); float prevScale = m_TexDisplay.scale; m_TexDisplay.scale = qBound(0.1f, s, 256.0f); INVOKE_MEMFN(RT_UpdateAndDisplay); float scaleDelta = (m_TexDisplay.scale / prevScale); QPoint newPos = getScrollPosition(); newPos -= QPoint(x, y); newPos = QPoint((int)(newPos.x() * scaleDelta), (int)(newPos.y() * scaleDelta)); newPos += QPoint(x, y); setScrollPosition(newPos); setCurrentZoomValue(m_TexDisplay.scale); UI_CalcScrollbars(); } void TextureViewer::setCurrentZoomValue(float zoom) { ui->zoomOption->setCurrentText(QString::number(ceil(zoom * 100)) + lit("%")); } float TextureViewer::getCurrentZoomValue() { if(ui->fitToWindow->isChecked()) return m_TexDisplay.scale; QString zoomText = ui->zoomOption->currentText().replace(QLatin1Char('%'), QLatin1Char(' ')); bool ok = false; int zoom = zoomText.toInt(&ok); if(!ok) zoom = 100; return (float)(zoom) / 100.0f; } void TextureViewer::setFitToWindow(bool checked) { if(checked) { UI_UpdateFittedScale(); ui->fitToWindow->setChecked(true); } else if(!checked) { ui->fitToWindow->setChecked(false); float curScale = m_TexDisplay.scale; ui->zoomOption->setCurrentText(QString()); setCurrentZoomValue(curScale); } } void TextureViewer::on_fitToWindow_toggled(bool checked) { UI_UpdateFittedScale(); } void TextureViewer::on_zoomExactSize_clicked() { ui->fitToWindow->setChecked(false); UI_SetScale(1.0f); } void TextureViewer::on_zoomOption_currentIndexChanged(int index) { if(index >= 0) { setFitToWindow(false); ui->zoomOption->setCurrentText(ui->zoomOption->itemText(index)); UI_SetScale(getCurrentZoomValue()); } } void TextureViewer::zoomOption_returnPressed() { UI_SetScale(getCurrentZoomValue()); } void TextureViewer::on_overlay_currentIndexChanged(int index) { m_TexDisplay.overlay = DebugOverlay::NoOverlay; if(ui->overlay->currentIndex() > 0) m_TexDisplay.overlay = (DebugOverlay)ui->overlay->currentIndex(); #define ANALYTICS_OVERLAY(name) \ case DebugOverlay::name: ANALYTIC_SET(TextureOverlays.name, true); break; switch(m_TexDisplay.overlay) { ANALYTICS_OVERLAY(Drawcall); ANALYTICS_OVERLAY(Wireframe); ANALYTICS_OVERLAY(Depth); ANALYTICS_OVERLAY(Stencil); ANALYTICS_OVERLAY(BackfaceCull); ANALYTICS_OVERLAY(ViewportScissor); ANALYTICS_OVERLAY(NaN); ANALYTICS_OVERLAY(Clipping); ANALYTICS_OVERLAY(ClearBeforePass); ANALYTICS_OVERLAY(ClearBeforeDraw); ANALYTICS_OVERLAY(QuadOverdrawPass); ANALYTICS_OVERLAY(QuadOverdrawDraw); ANALYTICS_OVERLAY(TriangleSizePass); ANALYTICS_OVERLAY(TriangleSizeDraw); default: break; } #undef ANALYTICS_OVERLAY INVOKE_MEMFN(RT_UpdateAndDisplay); if(m_Output != NULL && m_PickedPoint.x() >= 0 && m_PickedPoint.y() >= 0) { INVOKE_MEMFN(RT_PickPixelsAndUpdate); } } void TextureViewer::channelsWidget_mouseClicked(QMouseEvent *event) { RDToolButton *s = qobject_cast<RDToolButton *>(QObject::sender()); if(event->button() == Qt::RightButton && s) { bool checkd = false; RDToolButton *butts[] = {ui->channelRed, ui->channelGreen, ui->channelBlue, ui->channelAlpha}; for(RDToolButton *b : butts) { if(b->isChecked() && b != s) checkd = true; if(!b->isChecked() && b == s) checkd = true; } ui->channelRed->setChecked(!checkd); ui->channelGreen->setChecked(!checkd); ui->channelBlue->setChecked(!checkd); ui->channelAlpha->setChecked(!checkd); s->setChecked(checkd); } } void TextureViewer::range_rangeUpdated() { m_TexDisplay.rangeMin = ui->rangeHistogram->blackPoint(); m_TexDisplay.rangeMax = ui->rangeHistogram->whitePoint(); ui->rangeBlack->setText(Formatter::Format(m_TexDisplay.rangeMin)); ui->rangeWhite->setText(Formatter::Format(m_TexDisplay.rangeMax)); if(m_NoRangePaint) return; INVOKE_MEMFN(RT_UpdateAndDisplay); if(m_Output == NULL) { ui->render->update(); ui->pixelContext->update(); } } void TextureViewer::rangePoint_textChanged(QString text) { m_RangePoint_Dirty = true; } void TextureViewer::rangePoint_Update() { float black = ui->rangeHistogram->blackPoint(); float white = ui->rangeHistogram->whitePoint(); bool ok = false; double d = ui->rangeBlack->text().toDouble(&ok); if(ok) black = d; d = ui->rangeWhite->text().toDouble(&ok); if(ok) white = d; ui->rangeHistogram->setRange(black, white); INVOKE_MEMFN(RT_UpdateVisualRange); } void TextureViewer::rangePoint_leave() { if(!m_RangePoint_Dirty) return; rangePoint_Update(); m_RangePoint_Dirty = false; } void TextureViewer::rangePoint_keyPress(QKeyEvent *e) { // escape key if(e->key() == Qt::Key_Escape) { m_RangePoint_Dirty = false; ui->rangeHistogram->setRange(ui->rangeHistogram->blackPoint(), ui->rangeHistogram->whitePoint()); } if(e->key() == Qt::Key_Return || e->key() == Qt::Key_Enter) { rangePoint_Update(); } } void TextureViewer::on_zoomRange_clicked() { float black = ui->rangeHistogram->blackPoint(); float white = ui->rangeHistogram->whitePoint(); ui->autoFit->setChecked(false); ui->rangeHistogram->setRange(black, white); INVOKE_MEMFN(RT_UpdateVisualRange); } void TextureViewer::on_autoFit_clicked() { AutoFitRange(); ui->autoFit->setChecked(false); } void TextureViewer::on_autoFit_mouseClicked(QMouseEvent *e) { if(e->buttons() & Qt::RightButton) ui->autoFit->setChecked(!ui->autoFit->isChecked()); } void TextureViewer::on_reset01_clicked() { UI_SetHistogramRange(GetCurrentTexture(), m_TexDisplay.typeHint); ui->autoFit->setChecked(false); INVOKE_MEMFN(RT_UpdateVisualRange); } void TextureViewer::on_visualiseRange_clicked() { if(ui->visualiseRange->isChecked()) { ui->rangeHistogram->setMinimumSize(QSize(300, 90)); m_Visualise = true; INVOKE_MEMFN(RT_UpdateVisualRange); } else { m_Visualise = false; ui->rangeHistogram->setMinimumSize(QSize(200, 0)); ui->rangeHistogram->setHistogramData({}); } } void TextureViewer::AutoFitRange() { // no capture loaded or buffer/empty texture currently being viewed - don't autofit if(!m_Ctx.IsCaptureLoaded() || GetCurrentTexture() == NULL || m_Output == NULL) return; m_Ctx.Replay().AsyncInvoke([this](IReplayController *r) { PixelValue min, max; std::tie(min, max) = m_Output->GetMinMax(); { float minval = FLT_MAX; float maxval = -FLT_MAX; bool changeRange = false; ResourceFormat fmt = GetCurrentTexture()->format; if(m_TexDisplay.customShaderId != ResourceId()) { fmt.compType = CompType::Float; } for(int i = 0; i < 4; i++) { if(fmt.compType == CompType::UInt) { min.floatValue[i] = min.uintValue[i]; max.floatValue[i] = max.uintValue[i]; } else if(fmt.compType == CompType::SInt) { min.floatValue[i] = min.intValue[i]; max.floatValue[i] = max.intValue[i]; } } if(m_TexDisplay.red) { minval = qMin(minval, min.floatValue[0]); maxval = qMax(maxval, max.floatValue[0]); changeRange = true; } if(m_TexDisplay.green && fmt.compCount > 1) { minval = qMin(minval, min.floatValue[1]); maxval = qMax(maxval, max.floatValue[1]); changeRange = true; } if(m_TexDisplay.blue && fmt.compCount > 2) { minval = qMin(minval, min.floatValue[2]); maxval = qMax(maxval, max.floatValue[2]); changeRange = true; } if(m_TexDisplay.alpha && fmt.compCount > 3) { minval = qMin(minval, min.floatValue[3]); maxval = qMax(maxval, max.floatValue[3]); changeRange = true; } if(changeRange) { GUIInvoke::call(this, [this, minval, maxval]() { ui->rangeHistogram->setRange(minval, maxval); INVOKE_MEMFN(RT_UpdateVisualRange); }); } } }); } void TextureViewer::on_backcolorPick_clicked() { QColor col = QColorDialog::getColor(Qt::black, this, tr("Choose background colour")); if(!col.isValid()) return; col = col.toRgb(); m_TexDisplay.backgroundColor = FloatVector(col.redF(), col.greenF(), col.blueF(), 1.0f); backCol = col; updateBackgroundColors(); ui->backcolorPick->setChecked(true); ui->checkerBack->setChecked(false); INVOKE_MEMFN(RT_UpdateAndDisplay); if(m_Output == NULL) { ui->render->update(); ui->pixelContext->update(); } } void TextureViewer::on_checkerBack_clicked() { ui->checkerBack->setChecked(true); ui->backcolorPick->setChecked(false); backCol = QColor(); m_TexDisplay.backgroundColor = FloatVector(); updateBackgroundColors(); INVOKE_MEMFN(RT_UpdateAndDisplay); if(m_Output == NULL) { ui->render->update(); ui->pixelContext->update(); } } void TextureViewer::on_mipLevel_currentIndexChanged(int index) { TextureDescription *texptr = GetCurrentTexture(); if(texptr == NULL) return; TextureDescription &tex = *texptr; uint32_t prevSlice = m_TexDisplay.sliceFace; if(tex.mips > 1) { m_TexDisplay.mip = (uint32_t)qMax(0, index); m_TexDisplay.sampleIdx = 0; } else { m_TexDisplay.mip = 0; m_TexDisplay.sampleIdx = (uint32_t)qMax(0, index); if(m_TexDisplay.sampleIdx == tex.msSamp) m_TexDisplay.sampleIdx = ~0U; } // For 3D textures, update the slice list for this mip if(tex.depth > 1) { uint32_t newSlice = prevSlice >> (int)m_TexDisplay.mip; uint32_t numSlices = qMax(1U, tex.depth >> (int)m_TexDisplay.mip); ui->sliceFace->clear(); for(uint32_t i = 0; i < numSlices; i++) ui->sliceFace->addItem(tr("Slice %1").arg(i)); // changing sliceFace index will handle updating range & re-picking ui->sliceFace->setCurrentIndex((int)qBound(0U, newSlice, numSlices - 1)); return; } INVOKE_MEMFN(RT_UpdateVisualRange); if(m_Output != NULL && m_PickedPoint.x() >= 0 && m_PickedPoint.y() >= 0) { INVOKE_MEMFN(RT_PickPixelsAndUpdate); } INVOKE_MEMFN(RT_UpdateAndDisplay); } void TextureViewer::on_sliceFace_currentIndexChanged(int index) { TextureDescription *texptr = GetCurrentTexture(); if(texptr == NULL) return; TextureDescription &tex = *texptr; m_TexDisplay.sliceFace = (uint32_t)qMax(0, index); if(tex.depth > 1) m_TexDisplay.sliceFace = (uint32_t)(qMax(0, index) << (int)m_TexDisplay.mip); INVOKE_MEMFN(RT_UpdateVisualRange); if(m_Output != NULL && m_PickedPoint.x() >= 0 && m_PickedPoint.y() >= 0) { INVOKE_MEMFN(RT_PickPixelsAndUpdate); } INVOKE_MEMFN(RT_UpdateAndDisplay); } void TextureViewer::on_locationGoto_clicked() { ShowGotoPopup(); } void TextureViewer::ShowGotoPopup() { TextureDescription *texptr = GetCurrentTexture(); if(texptr) { QPoint p = m_PickedPoint; uint32_t mipHeight = qMax(1U, texptr->height >> (int)m_TexDisplay.mip); if(m_Ctx.APIProps().pipelineType == GraphicsAPI::OpenGL) p.setY((int)(mipHeight - 1) - p.y()); if(m_TexDisplay.flipY) p.setY((int)(mipHeight - 1) - p.y()); m_Goto->show(ui->render, p); } } void TextureViewer::on_viewTexBuffer_clicked() { TextureDescription *texptr = GetCurrentTexture(); if(texptr) { IBufferViewer *viewer = m_Ctx.ViewTextureAsBuffer(m_TexDisplay.sliceFace, m_TexDisplay.mip, texptr->resourceId, FormatElement::GenerateTextureBufferFormat(*texptr)); m_Ctx.AddDockWindow(viewer->Widget(), DockReference::AddTo, this); } } void TextureViewer::on_resourceDetails_clicked() { TextureDescription *texptr = GetCurrentTexture(); if(texptr) { if(!m_Ctx.HasResourceInspector()) m_Ctx.ShowResourceInspector(); m_Ctx.GetResourceInspector()->Inspect(texptr->resourceId); ToolWindowManager::raiseToolWindow(m_Ctx.GetResourceInspector()->Widget()); } } void TextureViewer::on_saveTex_clicked() { TextureDescription *texptr = GetCurrentTexture(); if(!texptr || !m_Output) return; // overwrite save params with current texture display settings m_SaveConfig.resourceId = m_TexDisplay.resourceId; m_SaveConfig.typeHint = m_TexDisplay.typeHint; m_SaveConfig.slice.sliceIndex = (int)m_TexDisplay.sliceFace; m_SaveConfig.mip = (int)m_TexDisplay.mip; if(texptr->depth > 1) m_SaveConfig.slice.sliceIndex = (int)m_TexDisplay.sliceFace >> (int)m_TexDisplay.mip; m_SaveConfig.channelExtract = -1; if(m_TexDisplay.red && !m_TexDisplay.green && !m_TexDisplay.blue && !m_TexDisplay.alpha) m_SaveConfig.channelExtract = 0; if(!m_TexDisplay.red && m_TexDisplay.green && !m_TexDisplay.blue && !m_TexDisplay.alpha) m_SaveConfig.channelExtract = 1; if(!m_TexDisplay.red && !m_TexDisplay.green && m_TexDisplay.blue && !m_TexDisplay.alpha) m_SaveConfig.channelExtract = 2; if(!m_TexDisplay.red && !m_TexDisplay.green && !m_TexDisplay.blue && m_TexDisplay.alpha) m_SaveConfig.channelExtract = 3; m_SaveConfig.comp.blackPoint = m_TexDisplay.rangeMin; m_SaveConfig.comp.whitePoint = m_TexDisplay.rangeMax; m_SaveConfig.alphaCol = m_TexDisplay.backgroundColor; if(m_TexDisplay.customShaderId != ResourceId()) { ResourceId id; m_Ctx.Replay().BlockInvoke( [this, &id](IReplayController *r) { id = m_Output->GetCustomShaderTexID(); }); if(id != ResourceId()) m_SaveConfig.resourceId = id; } const ResourceId overlayTexID = m_Output->GetDebugOverlayTexID(); const bool hasSelectedOverlay = (m_TexDisplay.overlay != DebugOverlay::NoOverlay); const bool hasOverlay = (hasSelectedOverlay && overlayTexID != ResourceId()); TextureSaveDialog saveDialog(*texptr, hasOverlay, m_SaveConfig, this); int res = RDDialog::show(&saveDialog); m_SaveConfig = saveDialog.config(); if(saveDialog.saveOverlayInstead()) { m_SaveConfig.resourceId = overlayTexID; if(m_TexDisplay.overlay == DebugOverlay::QuadOverdrawDraw || m_TexDisplay.overlay == DebugOverlay::QuadOverdrawPass || m_TexDisplay.overlay == DebugOverlay::TriangleSizeDraw || m_TexDisplay.overlay == DebugOverlay::TriangleSizePass) { m_SaveConfig.comp.blackPoint = 0.0f; m_SaveConfig.comp.whitePoint = 255.0f; } } if(res) { ANALYTIC_SET(Export.Texture, true); bool ret = false; QString fn = saveDialog.filename(); m_Ctx.Replay().BlockInvoke([this, &ret, fn](IReplayController *r) { ret = r->SaveTexture(m_SaveConfig, fn.toUtf8().data()); }); if(!ret) { RDDialog::critical( NULL, tr("Error saving texture"), tr("Error saving texture %1.\n\nCheck diagnostic log in Help menu for more details.").arg(fn)); } } } void TextureViewer::on_debugPixelContext_clicked() { if(m_PickedPoint.x() < 0 || m_PickedPoint.y() < 0) return; int x = m_PickedPoint.x() >> (int)m_TexDisplay.mip; int y = m_PickedPoint.y() >> (int)m_TexDisplay.mip; TextureDescription *texptr = GetCurrentTexture(); uint32_t mipHeight = qMax(1U, texptr->height >> (int)m_TexDisplay.mip); if(m_TexDisplay.flipY) y = (int)(mipHeight - 1) - y; bool done = false; ShaderDebugTrace *trace = NULL; m_Ctx.Replay().AsyncInvoke([this, &trace, &done, x, y](IReplayController *r) { trace = r->DebugPixel((uint32_t)x, (uint32_t)y, m_TexDisplay.sampleIdx, ~0U); if(trace->states.isEmpty()) { r->FreeTrace(trace); trace = NULL; } done = true; }); QString debugContext = tr("Pixel %1,%2").arg(x).arg(y); // wait a short while before displaying the progress dialog (which won't show if we're already // done by the time we reach it) for(int i = 0; !done && i < 100; i++) QThread::msleep(5); ShowProgressDialog(this, tr("Debugging %1").arg(debugContext), [&done]() { return done; }); // if we couldn't debug the pixel on this event, open up a pixel history if(!trace) { on_pixelHistory_clicked(); return; } const ShaderReflection *shaderDetails = m_Ctx.CurPipelineState().GetShaderReflection(ShaderStage::Pixel); const ShaderBindpointMapping &bindMapping = m_Ctx.CurPipelineState().GetBindpointMapping(ShaderStage::Pixel); ResourceId pipeline = m_Ctx.CurPipelineState().GetGraphicsPipelineObject(); // viewer takes ownership of the trace IShaderViewer *s = m_Ctx.DebugShader(&bindMapping, shaderDetails, pipeline, trace, debugContext); m_Ctx.AddDockWindow(s->Widget(), DockReference::AddTo, this); } void TextureViewer::on_pixelHistory_clicked() { TextureDescription *texptr = GetCurrentTexture(); if(!texptr || !m_Output) return; ANALYTIC_SET(UIFeatures.PixelHistory, true); int x = m_PickedPoint.x() >> (int)m_TexDisplay.mip; int y = m_PickedPoint.y() >> (int)m_TexDisplay.mip; uint32_t mipHeight = qMax(1U, texptr->height >> (int)m_TexDisplay.mip); if(m_TexDisplay.flipY) y = (int)(mipHeight - 1) - y; IPixelHistoryView *hist = m_Ctx.ViewPixelHistory(texptr->resourceId, x, y, m_TexDisplay); m_Ctx.AddDockWindow(hist->Widget(), DockReference::TransientPopupArea, this, 0.3f); // we use this pointer to ensure that the history viewer is still visible (and hasn't been closed) // by the time we want to set the results. QPointer<QWidget> histWidget = hist->Widget(); // add a short delay so that controls repainting after a new panel appears can get at the // render thread before we insert the long blocking pixel history task LambdaThread *thread = new LambdaThread([this, texptr, x, y, hist, histWidget]() { QThread::msleep(150); m_Ctx.Replay().AsyncInvoke([this, texptr, x, y, hist, histWidget](IReplayController *r) { rdcarray<PixelModification> history = r->PixelHistory(texptr->resourceId, (uint32_t)x, (int32_t)y, m_TexDisplay.sliceFace, m_TexDisplay.mip, m_TexDisplay.sampleIdx, m_TexDisplay.typeHint); GUIInvoke::call(this, [hist, histWidget, history] { if(histWidget) hist->SetHistory(history); }); }); }); thread->selfDelete(true); thread->start(); } void TextureViewer::on_texListShow_clicked() { if(ui->textureListFrame->isVisible()) { ui->dockarea->moveToolWindow(ui->textureListFrame, ToolWindowManager::NoArea); } else { ui->textureListFilter->setCurrentText(QString()); ui->dockarea->moveToolWindow( ui->textureListFrame, ToolWindowManager::AreaReference(ToolWindowManager::LeftOf, ui->dockarea->areaOf(ui->renderContainer), 0.2f)); ui->dockarea->setToolWindowProperties(ui->textureListFrame, ToolWindowManager::HideOnClose); } } void TextureViewer::on_cancelTextureListFilter_clicked() { ui->textureListFilter->setCurrentText(QString()); } void TextureViewer::on_textureListFilter_editTextChanged(const QString &text) { TextureListItemModel *model = (TextureListItemModel *)ui->textureList->model(); if(model == NULL) return; model->reset(TextureListItemModel::String, text); } void TextureViewer::on_textureListFilter_currentIndexChanged(int index) { refreshTextureList(); } void TextureViewer::refreshTextureList() { TextureListItemModel *model = (TextureListItemModel *)ui->textureList->model(); if(model == NULL) return; if(ui->textureListFilter->currentIndex() == 1) model->reset(TextureListItemModel::Textures, QString()); else if(ui->textureListFilter->currentIndex() == 2) model->reset(TextureListItemModel::RenderTargets, QString()); else model->reset(TextureListItemModel::String, ui->textureListFilter->currentText()); } void TextureViewer::on_textureList_clicked(const QModelIndex &index) { ResourceId id = index.model()->data(index, Qt::UserRole).value<ResourceId>(); ViewTexture(id, false); } void TextureViewer::reloadCustomShaders(const QString &filter) { if(!m_Ctx.IsCaptureLoaded()) return; if(filter.isEmpty()) { QString prevtext = ui->customShader->currentText(); QList<ResourceId> shaders = m_CustomShaders.values(); m_Ctx.Replay().AsyncInvoke([shaders](IReplayController *r) { for(ResourceId s : shaders) r->FreeCustomShader(s); }); ui->customShader->clear(); m_CustomShaders.clear(); ui->customShader->setCurrentText(prevtext); } else { QString fn = QFileInfo(filter).baseName(); QString key = fn.toUpper(); if(m_CustomShaders.contains(key)) { if(m_CustomShadersBusy.contains(key)) return; ResourceId freed = m_CustomShaders[key]; m_Ctx.Replay().AsyncInvoke([freed](IReplayController *r) { r->FreeCustomShader(freed); }); m_CustomShaders.remove(key); QString text = ui->customShader->currentText(); for(int i = 0; i < ui->customShader->count(); i++) { if(ui->customShader->itemText(i).compare(fn, Qt::CaseInsensitive) == 0) { ui->customShader->removeItem(i); break; } } ui->customShader->setCurrentText(text); } } QStringList files = QDir(configFilePath(QString())) .entryList({QFormatStr("*.%1").arg(m_Ctx.CurPipelineState().GetShaderExtension())}, QDir::Files | QDir::NoDotAndDotDot, QDir::Name | QDir::IgnoreCase); QStringList watchedFiles = m_Watcher->files(); if(!watchedFiles.isEmpty()) m_Watcher->removePaths(watchedFiles); for(const QString &f : files) { QString fn = QFileInfo(f).baseName(); QString key = fn.toUpper(); m_Watcher->addPath(configFilePath(f)); if(!m_CustomShaders.contains(key) && !m_CustomShadersBusy.contains(key)) { QFile fileHandle(configFilePath(f)); if(fileHandle.open(QFile::ReadOnly | QFile::Text)) { QTextStream stream(&fileHandle); QString source = stream.readAll(); ANALYTIC_SET(UIFeatures.CustomTextureVisualise, true); fileHandle.close(); m_CustomShaders[key] = ResourceId(); m_CustomShadersBusy.push_back(key); m_Ctx.Replay().AsyncInvoke([this, fn, key, source](IReplayController *r) { rdcstr errors; ResourceId id; std::tie(id, errors) = r->BuildCustomShader("main", source.toUtf8().data(), ShaderCompileFlags(), ShaderStage::Pixel); if(m_CustomShaderEditor.contains(key)) { IShaderViewer *editor = m_CustomShaderEditor[key]; GUIInvoke::call(editor->Widget(), [editor, errors]() { editor->ShowErrors(errors); }); } GUIInvoke::call(this, [this, fn, key, id]() { QString prevtext = ui->customShader->currentText(); ui->customShader->addItem(fn); ui->customShader->setCurrentText(prevtext); m_CustomShaders[key] = id; m_CustomShadersBusy.removeOne(key); UI_UpdateChannels(); }); }); } } } } void TextureViewer::on_customCreate_clicked() { QString filename = ui->customShader->currentText(); if(filename.isEmpty()) { RDDialog::critical(this, tr("Error Creating Shader"), tr("No shader name specified.\nEnter a new name in the textbox")); return; } if(m_CustomShaders.contains(filename.toUpper())) { RDDialog::critical(this, tr("Error Creating Shader"), tr("Selected shader already exists.\nEnter a new name in the textbox.")); ui->customShader->setCurrentText(QString()); UI_UpdateChannels(); return; } QString path = configFilePath(filename + lit(".") + m_Ctx.CurPipelineState().GetShaderExtension()); QString src; if(IsD3D(m_Ctx.APIProps().pipelineType)) { src = lit("float4 main(float4 pos : SV_Position, float4 uv : TEXCOORD0) : SV_Target0\n" "{\n" " return float4(0,0,0,1);\n" "}\n"); } else { src = lit("#version 420 core\n\n" "layout (location = 0) in vec2 uv;\n\n" "layout (location = 0) out vec4 color_out;\n\n" "void main()\n" "{\n" " color_out = vec4(0,0,0,1);\n" "}\n"); } QFile fileHandle(path); if(fileHandle.open(QFile::WriteOnly | QIODevice::Truncate | QIODevice::Text)) { fileHandle.write(src.toUtf8()); fileHandle.close(); } else { RDDialog::critical( this, tr("Cannot create shader"), tr("Couldn't create file for shader %1\n%2").arg(filename).arg(fileHandle.errorString())); } // auto-open edit window on_customEdit_clicked(); reloadCustomShaders(filename); } void TextureViewer::on_customEdit_clicked() { QString filename = ui->customShader->currentText(); QString key = filename.toUpper(); if(filename.isEmpty()) { RDDialog::critical(this, tr("Error Editing Shader"), tr("No shader selected.\nSelect a custom shader from the drop-down")); return; } QString path = configFilePath(filename + lit(".") + m_Ctx.CurPipelineState().GetShaderExtension()); QString src; QFile fileHandle(path); if(fileHandle.open(QFile::ReadOnly | QFile::Text)) { QTextStream stream(&fileHandle); src = stream.readAll(); fileHandle.close(); } else { RDDialog::critical( this, tr("Cannot open shader"), tr("Couldn't open file for shader %1\n%2").arg(filename).arg(fileHandle.errorString())); return; } rdcstrpairs files; files.push_back(make_rdcpair<rdcstr, rdcstr>(filename, src)); QPointer<TextureViewer> thisPointer(this); IShaderViewer *s = m_Ctx.EditShader( true, ShaderStage::Fragment, lit("main"), files, IsD3D(m_Ctx.APIProps().localRenderer) ? ShaderEncoding::HLSL : ShaderEncoding::GLSL, ShaderCompileFlags(), // Save Callback [thisPointer, key, filename, path](ICaptureContext *ctx, IShaderViewer *viewer, ShaderEncoding encoding, ShaderCompileFlags flags, rdcstr entryFunc, bytebuf bytes) { { QFile fileHandle(path); if(fileHandle.open(QFile::WriteOnly | QIODevice::Truncate | QIODevice::Text)) { fileHandle.write(QByteArray(bytes)); fileHandle.close(); // watcher doesn't trigger on internal modifications if(thisPointer) thisPointer->reloadCustomShaders(filename); } else { if(thisPointer) { RDDialog::critical( thisPointer, tr("Cannot save shader"), tr("Couldn't save file for shader %1\n%2").arg(filename).arg(fileHandle.errorString())); } } } }, [thisPointer, key](ICaptureContext *ctx) { if(thisPointer) thisPointer->m_CustomShaderEditor.remove(key); }); m_CustomShaderEditor[key] = s; m_Ctx.AddDockWindow(s->Widget(), DockReference::AddTo, this); } void TextureViewer::on_customDelete_clicked() { QString shaderName = ui->customShader->currentText(); if(shaderName.isEmpty()) { RDDialog::critical(this, tr("Error Deleting Shader"), tr("No shader selected.\nSelect a custom shader from the drop-down")); return; } if(!m_CustomShaders.contains(shaderName.toUpper())) { RDDialog::critical( this, tr("Error Deleting Shader"), tr("Selected shader doesn't exist.\nSelect a custom shader from the drop-down")); return; } QMessageBox::StandardButton res = RDDialog::question(this, tr("Deleting Custom Shader"), tr("Really delete %1?").arg(shaderName), RDDialog::YesNoCancel); if(res == QMessageBox::Yes) { QString path = configFilePath(shaderName + lit(".") + m_Ctx.CurPipelineState().GetShaderExtension()); if(!QFileInfo::exists(path)) { RDDialog::critical( this, tr("Error Deleting Shader"), tr("Shader file %1 can't be found.\nSelect a custom shader from the drop-down") .arg(shaderName)); return; } if(!QFile::remove(path)) { RDDialog::critical(this, tr("Error Deleting Shader"), tr("Error deleting shader %1 from disk").arg(shaderName)); return; } ui->customShader->setCurrentText(QString()); UI_UpdateChannels(); } } void TextureViewer::customShaderModified(const QString &path) { // allow time for modifications to finish QThread::msleep(15); reloadCustomShaders(QString()); }
#include <gbBase/Assert.hpp> #include <gbBase/Exception.hpp> #include <catch.hpp> namespace { // catch's exception checking does not seem to work // with abstract exception types; let's roll our own! template<typename T> void checkExceptionType(void (*fun)()) { bool was_caught = false; try { fun(); } catch(T&) { was_caught = true; } catch(...) { CHECK(("Incorrect exception type.", false)); } CHECK(was_caught); } } TEST_CASE("Assert") { using namespace GHULBUS_BASE_NAMESPACE; SECTION("Default handler is failAbort") { CHECK(Assert::getAssertionHandler() == &Assert::failAbort); } SECTION("Getting and setting handler") { auto handler = [](Assert::HandlerParameters const& param) {}; Assert::setAssertionHandler(handler); REQUIRE(Assert::getAssertionHandler() == handler); Assert::setAssertionHandler(&Assert::failAbort); } SECTION("Default user param is NULL") { CHECK(Assert::getHandlerParam() == nullptr); } SECTION("Getting and setting user param") { int token; Assert::setHandlerParam(&token); REQUIRE(Assert::getHandlerParam() == &token); Assert::setHandlerParam(nullptr); } SECTION("assertionFailed should invoke currently active handler") { auto handler = [](Assert::HandlerParameters const& param) { CHECK(param.file == std::string("file")); CHECK(param.line == 42); CHECK(param.function == std::string("func")); CHECK(param.condition == std::string("cond")); CHECK(param.message == std::string("msg")); *static_cast<bool*>(param.user_param) = true; }; Assert::setAssertionHandler(handler); bool handlerWasCalled = false; Assert::assertionFailed(Assert::HandlerParameters{ "file", 42, "func", "cond", "msg", &handlerWasCalled }); CHECK(handlerWasCalled); Assert::setAssertionHandler(&Assert::failAbort); } SECTION("Macro invokes assertion handler with user param") { auto handler = [](Assert::HandlerParameters const& param) { CHECK(param.message == std::string("hello from the test!")); *static_cast<bool*>(param.user_param) = true; }; Assert::setAssertionHandler(handler); bool handlerWasCalled = false; Assert::setHandlerParam(&handlerWasCalled); GHULBUS_ASSERT_PRD_MESSAGE(false, "hello from the test!"); CHECK(handlerWasCalled); Assert::setAssertionHandler(&Assert::failAbort); } SECTION("Throw Handler throws AssertFailed exception") { // the big gotcha of this test is that we throw across dll boundaries here. // on some platforms, this can mess up the rtti if the exception was not declared correctly. // technically, this is probably more a test of Exceptions::AssertFailed than GHULBUS_ASSERT... Assert::setAssertionHandler(&Assert::failThrow); auto doAssert = []() { GHULBUS_ASSERT_PRD(false); }; checkExceptionType<Exceptions::AssertFailed>(doAssert); checkExceptionType<Exception>(doAssert); checkExceptionType<std::exception>(doAssert); Assert::setAssertionHandler(&Assert::failAbort); } SECTION("Assert with message should forward message to exception") { Assert::setAssertionHandler(&Assert::failThrow); bool was_caught = false; char const* test_msg = "Just an example error message for testing purposes"; try { GHULBUS_ASSERT_PRD_MESSAGE(false, test_msg); } catch(Exceptions::AssertFailed& e) { auto const err_msg = boost::get_error_info<Exception_Info::description>(e); REQUIRE(err_msg); CHECK(*err_msg == std::string("false - ") + test_msg); was_caught = true; } CHECK(was_caught); Assert::setAssertionHandler(&Assert::failAbort); } SECTION("Precondition macro should behave the same as assert") { Assert::setAssertionHandler(&Assert::failThrow); auto doAssert = []() { GHULBUS_PRECONDITION_PRD(false); }; checkExceptionType<Exceptions::AssertFailed>(doAssert); Assert::setAssertionHandler(&Assert::failAbort); } SECTION("Unreachable macro should trigger failing assertion") { Assert::setAssertionHandler(&Assert::failThrow); auto doAssert = []() { GHULBUS_UNREACHABLE(); }; checkExceptionType<Exceptions::AssertFailed>(doAssert); Assert::setAssertionHandler(&Assert::failAbort); } } fixed clang warning #include <gbBase/Assert.hpp> #include <gbBase/Exception.hpp> #include <catch.hpp> namespace { // catch's exception checking does not seem to work // with abstract exception types; let's roll our own! template<typename T> void checkExceptionType(void (*fun)()) { bool was_caught = false; try { fun(); } catch(T&) { was_caught = true; } catch(...) { CHECK_FALSE("Incorrect exception type"); } CHECK(was_caught); } } TEST_CASE("Assert") { using namespace GHULBUS_BASE_NAMESPACE; SECTION("Default handler is failAbort") { CHECK(Assert::getAssertionHandler() == &Assert::failAbort); } SECTION("Getting and setting handler") { auto handler = [](Assert::HandlerParameters const& param) {}; Assert::setAssertionHandler(handler); REQUIRE(Assert::getAssertionHandler() == handler); Assert::setAssertionHandler(&Assert::failAbort); } SECTION("Default user param is NULL") { CHECK(Assert::getHandlerParam() == nullptr); } SECTION("Getting and setting user param") { int token; Assert::setHandlerParam(&token); REQUIRE(Assert::getHandlerParam() == &token); Assert::setHandlerParam(nullptr); } SECTION("assertionFailed should invoke currently active handler") { auto handler = [](Assert::HandlerParameters const& param) { CHECK(param.file == std::string("file")); CHECK(param.line == 42); CHECK(param.function == std::string("func")); CHECK(param.condition == std::string("cond")); CHECK(param.message == std::string("msg")); *static_cast<bool*>(param.user_param) = true; }; Assert::setAssertionHandler(handler); bool handlerWasCalled = false; Assert::assertionFailed(Assert::HandlerParameters{ "file", 42, "func", "cond", "msg", &handlerWasCalled }); CHECK(handlerWasCalled); Assert::setAssertionHandler(&Assert::failAbort); } SECTION("Macro invokes assertion handler with user param") { auto handler = [](Assert::HandlerParameters const& param) { CHECK(param.message == std::string("hello from the test!")); *static_cast<bool*>(param.user_param) = true; }; Assert::setAssertionHandler(handler); bool handlerWasCalled = false; Assert::setHandlerParam(&handlerWasCalled); GHULBUS_ASSERT_PRD_MESSAGE(false, "hello from the test!"); CHECK(handlerWasCalled); Assert::setAssertionHandler(&Assert::failAbort); } SECTION("Throw Handler throws AssertFailed exception") { // the big gotcha of this test is that we throw across dll boundaries here. // on some platforms, this can mess up the rtti if the exception was not declared correctly. // technically, this is probably more a test of Exceptions::AssertFailed than GHULBUS_ASSERT... Assert::setAssertionHandler(&Assert::failThrow); auto doAssert = []() { GHULBUS_ASSERT_PRD(false); }; checkExceptionType<Exceptions::AssertFailed>(doAssert); checkExceptionType<Exception>(doAssert); checkExceptionType<std::exception>(doAssert); Assert::setAssertionHandler(&Assert::failAbort); } SECTION("Assert with message should forward message to exception") { Assert::setAssertionHandler(&Assert::failThrow); bool was_caught = false; char const* test_msg = "Just an example error message for testing purposes"; try { GHULBUS_ASSERT_PRD_MESSAGE(false, test_msg); } catch(Exceptions::AssertFailed& e) { auto const err_msg = boost::get_error_info<Exception_Info::description>(e); REQUIRE(err_msg); CHECK(*err_msg == std::string("false - ") + test_msg); was_caught = true; } CHECK(was_caught); Assert::setAssertionHandler(&Assert::failAbort); } SECTION("Precondition macro should behave the same as assert") { Assert::setAssertionHandler(&Assert::failThrow); auto doAssert = []() { GHULBUS_PRECONDITION_PRD(false); }; checkExceptionType<Exceptions::AssertFailed>(doAssert); Assert::setAssertionHandler(&Assert::failAbort); } SECTION("Unreachable macro should trigger failing assertion") { Assert::setAssertionHandler(&Assert::failThrow); auto doAssert = []() { GHULBUS_UNREACHABLE(); }; checkExceptionType<Exceptions::AssertFailed>(doAssert); Assert::setAssertionHandler(&Assert::failAbort); } }
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "quic/masque/masque_server_backend.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" namespace quic { namespace { std::string GetRequestHandlerKey( const QuicSimpleServerBackend::RequestHandler* request_handler) { return absl::StrCat(request_handler->connection_id().ToString(), "_", request_handler->stream_id(), "_", request_handler->peer_host()); } } // namespace MasqueServerBackend::MasqueServerBackend(MasqueMode masque_mode, const std::string& server_authority, const std::string& cache_directory) : masque_mode_(masque_mode), server_authority_(server_authority) { if (!cache_directory.empty()) { QuicMemoryCacheBackend::InitializeBackend(cache_directory); } } bool MasqueServerBackend::MaybeHandleMasqueRequest( const spdy::Http2HeaderBlock& request_headers, const std::string& request_body, QuicSimpleServerBackend::RequestHandler* request_handler) { auto path_pair = request_headers.find(":path"); auto method_pair = request_headers.find(":method"); auto scheme_pair = request_headers.find(":scheme"); if (path_pair == request_headers.end() || method_pair == request_headers.end() || scheme_pair == request_headers.end()) { // This request is missing required headers. return false; } absl::string_view path = path_pair->second; absl::string_view scheme = scheme_pair->second; absl::string_view method = method_pair->second; std::string masque_path = ""; if (masque_mode_ == MasqueMode::kLegacy) { if (scheme != "https" || method != "POST" || request_body.empty()) { // MASQUE requests MUST be a non-empty https POST. return false; } if (path.rfind("/.well-known/masque/", 0) != 0) { // This request is not a MASQUE path. return false; } masque_path = path.substr(sizeof("/.well-known/masque/") - 1); } else { if (method != "CONNECT-UDP") { // Unexpected method. return false; } } if (!server_authority_.empty()) { auto authority_pair = request_headers.find(":authority"); if (authority_pair == request_headers.end()) { // Cannot enforce missing authority. return false; } absl::string_view authority = authority_pair->second; if (server_authority_ != authority) { // This request does not match server_authority. return false; } } auto backend_client_pair = backend_clients_.find(request_handler->connection_id()); if (backend_client_pair == backend_clients_.end()) { QUIC_LOG(ERROR) << "Could not find backend client for " << GetRequestHandlerKey(request_handler) << " " << masque_path << request_headers.DebugString(); return false; } BackendClient* backend_client = backend_client_pair->second; std::unique_ptr<QuicBackendResponse> response = backend_client->HandleMasqueRequest(masque_path, request_headers, request_body, request_handler); if (response == nullptr) { QUIC_LOG(ERROR) << "Backend client did not process request for " << GetRequestHandlerKey(request_handler) << " " << masque_path << request_headers.DebugString(); return false; } QUIC_DLOG(INFO) << "Sending MASQUE response for " << GetRequestHandlerKey(request_handler) << " " << masque_path << request_headers.DebugString(); request_handler->OnResponseBackendComplete(response.get(), {}); active_response_map_[GetRequestHandlerKey(request_handler)] = std::move(response); return true; } void MasqueServerBackend::FetchResponseFromBackend( const spdy::Http2HeaderBlock& request_headers, const std::string& request_body, QuicSimpleServerBackend::RequestHandler* request_handler) { if (MaybeHandleMasqueRequest(request_headers, request_body, request_handler)) { // Request was handled as a MASQUE request. return; } QUIC_DLOG(INFO) << "Fetching non-MASQUE response for " << GetRequestHandlerKey(request_handler) << request_headers.DebugString(); QuicMemoryCacheBackend::FetchResponseFromBackend( request_headers, request_body, request_handler); } void MasqueServerBackend::CloseBackendResponseStream( QuicSimpleServerBackend::RequestHandler* request_handler) { QUIC_DLOG(INFO) << "Closing response stream for " << GetRequestHandlerKey(request_handler); active_response_map_.erase(GetRequestHandlerKey(request_handler)); QuicMemoryCacheBackend::CloseBackendResponseStream(request_handler); } void MasqueServerBackend::RegisterBackendClient(QuicConnectionId connection_id, BackendClient* backend_client) { QUIC_BUG_IF(backend_clients_.find(connection_id) != backend_clients_.end()) << connection_id << " already in backend clients map"; backend_clients_[connection_id] = backend_client; QUIC_DLOG(INFO) << "Registering backend client for " << connection_id; } void MasqueServerBackend::RemoveBackendClient(QuicConnectionId connection_id) { backend_clients_.erase(connection_id); QUIC_DLOG(INFO) << "Removing backend client for " << connection_id; } } // namespace quic Make absl::string_view to std::string conversion explicit in Masque. This is to unblock merge, because current code does not compile on Chromium. It makes sense for this conversion not to happen implicitly, given that it involves copying data and potentially an allocation, which can be expensive. Not sure why it compiles in Google3. Note that there has recently been a similar, merge-blocking string_view-related issue: https://quiche.googlesource.com/quiche/+/9f5ac0fb08fe7e7bd4689c682667b2434bb8960a PiperOrigin-RevId: 359856329 Change-Id: Ib5593d7e8d26cdf2501b86e90e359c7ba3775ba2 // Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "quic/masque/masque_server_backend.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" namespace quic { namespace { std::string GetRequestHandlerKey( const QuicSimpleServerBackend::RequestHandler* request_handler) { return absl::StrCat(request_handler->connection_id().ToString(), "_", request_handler->stream_id(), "_", request_handler->peer_host()); } } // namespace MasqueServerBackend::MasqueServerBackend(MasqueMode masque_mode, const std::string& server_authority, const std::string& cache_directory) : masque_mode_(masque_mode), server_authority_(server_authority) { if (!cache_directory.empty()) { QuicMemoryCacheBackend::InitializeBackend(cache_directory); } } bool MasqueServerBackend::MaybeHandleMasqueRequest( const spdy::Http2HeaderBlock& request_headers, const std::string& request_body, QuicSimpleServerBackend::RequestHandler* request_handler) { auto path_pair = request_headers.find(":path"); auto method_pair = request_headers.find(":method"); auto scheme_pair = request_headers.find(":scheme"); if (path_pair == request_headers.end() || method_pair == request_headers.end() || scheme_pair == request_headers.end()) { // This request is missing required headers. return false; } absl::string_view path = path_pair->second; absl::string_view scheme = scheme_pair->second; absl::string_view method = method_pair->second; std::string masque_path = ""; if (masque_mode_ == MasqueMode::kLegacy) { if (scheme != "https" || method != "POST" || request_body.empty()) { // MASQUE requests MUST be a non-empty https POST. return false; } if (path.rfind("/.well-known/masque/", 0) != 0) { // This request is not a MASQUE path. return false; } masque_path = std::string(path.substr(sizeof("/.well-known/masque/") - 1)); } else { if (method != "CONNECT-UDP") { // Unexpected method. return false; } } if (!server_authority_.empty()) { auto authority_pair = request_headers.find(":authority"); if (authority_pair == request_headers.end()) { // Cannot enforce missing authority. return false; } absl::string_view authority = authority_pair->second; if (server_authority_ != authority) { // This request does not match server_authority. return false; } } auto backend_client_pair = backend_clients_.find(request_handler->connection_id()); if (backend_client_pair == backend_clients_.end()) { QUIC_LOG(ERROR) << "Could not find backend client for " << GetRequestHandlerKey(request_handler) << " " << masque_path << request_headers.DebugString(); return false; } BackendClient* backend_client = backend_client_pair->second; std::unique_ptr<QuicBackendResponse> response = backend_client->HandleMasqueRequest(masque_path, request_headers, request_body, request_handler); if (response == nullptr) { QUIC_LOG(ERROR) << "Backend client did not process request for " << GetRequestHandlerKey(request_handler) << " " << masque_path << request_headers.DebugString(); return false; } QUIC_DLOG(INFO) << "Sending MASQUE response for " << GetRequestHandlerKey(request_handler) << " " << masque_path << request_headers.DebugString(); request_handler->OnResponseBackendComplete(response.get(), {}); active_response_map_[GetRequestHandlerKey(request_handler)] = std::move(response); return true; } void MasqueServerBackend::FetchResponseFromBackend( const spdy::Http2HeaderBlock& request_headers, const std::string& request_body, QuicSimpleServerBackend::RequestHandler* request_handler) { if (MaybeHandleMasqueRequest(request_headers, request_body, request_handler)) { // Request was handled as a MASQUE request. return; } QUIC_DLOG(INFO) << "Fetching non-MASQUE response for " << GetRequestHandlerKey(request_handler) << request_headers.DebugString(); QuicMemoryCacheBackend::FetchResponseFromBackend( request_headers, request_body, request_handler); } void MasqueServerBackend::CloseBackendResponseStream( QuicSimpleServerBackend::RequestHandler* request_handler) { QUIC_DLOG(INFO) << "Closing response stream for " << GetRequestHandlerKey(request_handler); active_response_map_.erase(GetRequestHandlerKey(request_handler)); QuicMemoryCacheBackend::CloseBackendResponseStream(request_handler); } void MasqueServerBackend::RegisterBackendClient(QuicConnectionId connection_id, BackendClient* backend_client) { QUIC_BUG_IF(backend_clients_.find(connection_id) != backend_clients_.end()) << connection_id << " already in backend clients map"; backend_clients_[connection_id] = backend_client; QUIC_DLOG(INFO) << "Registering backend client for " << connection_id; } void MasqueServerBackend::RemoveBackendClient(QuicConnectionId connection_id) { backend_clients_.erase(connection_id); QUIC_DLOG(INFO) << "Removing backend client for " << connection_id; } } // namespace quic
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "quiche/quic/tools/quic_toy_server.h" #include <utility> #include <vector> #include "quiche/quic/core/quic_versions.h" #include "quiche/quic/platform/api/quic_default_proof_providers.h" #include "quiche/quic/platform/api/quic_socket_address.h" #include "quiche/quic/tools/quic_memory_cache_backend.h" #include "quiche/common/platform/api/quiche_command_line_flags.h" DEFINE_QUICHE_COMMAND_LINE_FLAG(int32_t, port, 6121, "The port the quic server will listen on."); DEFINE_QUICHE_COMMAND_LINE_FLAG( std::string, quic_response_cache_dir, "", "Specifies the directory used during QuicHttpResponseCache " "construction to seed the cache. Cache directory can be " "generated using `wget -p --save-headers <url>`"); DEFINE_QUICHE_COMMAND_LINE_FLAG( bool, generate_dynamic_responses, false, "If true, then URLs which have a numeric path will send a dynamically " "generated response of that many bytes."); DEFINE_QUICHE_COMMAND_LINE_FLAG(bool, quic_ietf_draft, false, "Only enable IETF draft versions. This also " "enables required internal QUIC flags."); DEFINE_QUICHE_COMMAND_LINE_FLAG( std::string, quic_versions, "", "QUIC versions to enable, e.g. \"h3-25,h3-27\". If not set, then all " "available versions are enabled."); DEFINE_QUICHE_COMMAND_LINE_FLAG(bool, enable_webtransport, false, "If true, WebTransport support is enabled."); namespace quic { std::unique_ptr<quic::QuicSimpleServerBackend> QuicToyServer::MemoryCacheBackendFactory::CreateBackend() { auto memory_cache_backend = std::make_unique<QuicMemoryCacheBackend>(); if (quiche::GetQuicheCommandLineFlag(FLAGS_generate_dynamic_responses)) { memory_cache_backend->GenerateDynamicResponses(); } if (!quiche::GetQuicheCommandLineFlag(FLAGS_quic_response_cache_dir) .empty()) { memory_cache_backend->InitializeBackend( quiche::GetQuicheCommandLineFlag(FLAGS_quic_response_cache_dir)); } if (quiche::GetQuicheCommandLineFlag(FLAGS_enable_webtransport)) { memory_cache_backend->EnableWebTransport(); } return memory_cache_backend; } QuicToyServer::QuicToyServer(BackendFactory* backend_factory, ServerFactory* server_factory) : backend_factory_(backend_factory), server_factory_(server_factory) {} int QuicToyServer::Start() { ParsedQuicVersionVector supported_versions; if (quiche::GetQuicheCommandLineFlag(FLAGS_quic_ietf_draft)) { QuicVersionInitializeSupportForIetfDraft(); for (const ParsedQuicVersion& version : AllSupportedVersions()) { // Add all versions that supports IETF QUIC. if (version.HasIetfQuicFrames() && version.handshake_protocol == quic::PROTOCOL_TLS1_3) { supported_versions.push_back(version); } } } else { supported_versions = AllSupportedVersions(); } std::string versions_string = quiche::GetQuicheCommandLineFlag(FLAGS_quic_versions); if (!versions_string.empty()) { supported_versions = ParseQuicVersionVectorString(versions_string); } if (supported_versions.empty()) { return 1; } for (const auto& version : supported_versions) { QuicEnableVersion(version); } auto proof_source = quic::CreateDefaultProofSource(); auto backend = backend_factory_->CreateBackend(); auto server = server_factory_->CreateServer( backend.get(), std::move(proof_source), supported_versions); if (!server->CreateUDPSocketAndListen(quic::QuicSocketAddress( quic::QuicIpAddress::Any6(), quiche::GetQuicheCommandLineFlag(FLAGS_port)))) { return 1; } server->HandleEventsForever(); return 0; } } // namespace quic Re-implement QUIC toy server CONNECT flags Was previously rolled back in cl/468306591 due to issues with ConnectServerBackend adding dependencies on POSIX-only code via the LookupAddress() calls for host resolution, and those added dependencies interacting poorly with Chrome's partial dependency on QuicToyServer. Those issues should be fixed by cl/468763588 and cl/480145712. PiperOrigin-RevId: 481204878 // Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "quiche/quic/tools/quic_toy_server.h" #include <utility> #include <vector> #include "absl/container/flat_hash_set.h" #include "absl/strings/str_split.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/quic_server_id.h" #include "quiche/quic/core/quic_versions.h" #include "quiche/quic/platform/api/quic_default_proof_providers.h" #include "quiche/quic/platform/api/quic_socket_address.h" #include "quiche/quic/tools/connect_server_backend.h" #include "quiche/quic/tools/quic_memory_cache_backend.h" #include "quiche/common/platform/api/quiche_command_line_flags.h" #include "quiche/common/platform/api/quiche_logging.h" DEFINE_QUICHE_COMMAND_LINE_FLAG(int32_t, port, 6121, "The port the quic server will listen on."); DEFINE_QUICHE_COMMAND_LINE_FLAG( std::string, quic_response_cache_dir, "", "Specifies the directory used during QuicHttpResponseCache " "construction to seed the cache. Cache directory can be " "generated using `wget -p --save-headers <url>`"); DEFINE_QUICHE_COMMAND_LINE_FLAG( bool, generate_dynamic_responses, false, "If true, then URLs which have a numeric path will send a dynamically " "generated response of that many bytes."); DEFINE_QUICHE_COMMAND_LINE_FLAG(bool, quic_ietf_draft, false, "Only enable IETF draft versions. This also " "enables required internal QUIC flags."); DEFINE_QUICHE_COMMAND_LINE_FLAG( std::string, quic_versions, "", "QUIC versions to enable, e.g. \"h3-25,h3-27\". If not set, then all " "available versions are enabled."); DEFINE_QUICHE_COMMAND_LINE_FLAG(bool, enable_webtransport, false, "If true, WebTransport support is enabled."); DEFINE_QUICHE_COMMAND_LINE_FLAG( std::string, connect_proxy_destinations, "", "Specifies a comma-separated list of destinations (\"hostname:port\") to " "which the quic server will allow tunneling via CONNECT."); namespace quic { std::unique_ptr<quic::QuicSimpleServerBackend> QuicToyServer::MemoryCacheBackendFactory::CreateBackend() { auto memory_cache_backend = std::make_unique<QuicMemoryCacheBackend>(); if (quiche::GetQuicheCommandLineFlag(FLAGS_generate_dynamic_responses)) { memory_cache_backend->GenerateDynamicResponses(); } if (!quiche::GetQuicheCommandLineFlag(FLAGS_quic_response_cache_dir) .empty()) { memory_cache_backend->InitializeBackend( quiche::GetQuicheCommandLineFlag(FLAGS_quic_response_cache_dir)); } if (quiche::GetQuicheCommandLineFlag(FLAGS_enable_webtransport)) { memory_cache_backend->EnableWebTransport(); } if (!quiche::GetQuicheCommandLineFlag(FLAGS_connect_proxy_destinations) .empty()) { absl::flat_hash_set<QuicServerId> connect_proxy_destinations; for (absl::string_view destination : absl::StrSplit( quiche::GetQuicheCommandLineFlag(FLAGS_connect_proxy_destinations), ',', absl::SkipEmpty())) { absl::optional<QuicServerId> destination_server_id = QuicServerId::ParseFromHostPortString(destination); QUICHE_CHECK(destination_server_id.has_value()); connect_proxy_destinations.insert( std::move(destination_server_id).value()); } QUICHE_CHECK(!connect_proxy_destinations.empty()); return std::make_unique<ConnectServerBackend>( std::move(memory_cache_backend), std::move(connect_proxy_destinations)); } return memory_cache_backend; } QuicToyServer::QuicToyServer(BackendFactory* backend_factory, ServerFactory* server_factory) : backend_factory_(backend_factory), server_factory_(server_factory) {} int QuicToyServer::Start() { ParsedQuicVersionVector supported_versions; if (quiche::GetQuicheCommandLineFlag(FLAGS_quic_ietf_draft)) { QuicVersionInitializeSupportForIetfDraft(); for (const ParsedQuicVersion& version : AllSupportedVersions()) { // Add all versions that supports IETF QUIC. if (version.HasIetfQuicFrames() && version.handshake_protocol == quic::PROTOCOL_TLS1_3) { supported_versions.push_back(version); } } } else { supported_versions = AllSupportedVersions(); } std::string versions_string = quiche::GetQuicheCommandLineFlag(FLAGS_quic_versions); if (!versions_string.empty()) { supported_versions = ParseQuicVersionVectorString(versions_string); } if (supported_versions.empty()) { return 1; } for (const auto& version : supported_versions) { QuicEnableVersion(version); } auto proof_source = quic::CreateDefaultProofSource(); auto backend = backend_factory_->CreateBackend(); auto server = server_factory_->CreateServer( backend.get(), std::move(proof_source), supported_versions); if (!server->CreateUDPSocketAndListen(quic::QuicSocketAddress( quic::QuicIpAddress::Any6(), quiche::GetQuicheCommandLineFlag(FLAGS_port)))) { return 1; } server->HandleEventsForever(); return 0; } } // namespace quic
/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2010, Rice University * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the Rice University nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *********************************************************************/ /* Author: Ioan Sucan */ #include "ompl/base/manifolds/RealVectorStateManifold.h" #include "ompl/base/manifolds/RealVectorStateProjections.h" #include "ompl/util/Exception.h" #include <algorithm> #include <cstring> #include <limits> #include <cmath> void ompl::base::RealVectorStateSampler::sampleUniform(State *state) { const unsigned int dim = manifold_->getDimension(); const RealVectorBounds &bounds = static_cast<const RealVectorStateManifold*>(manifold_)->getBounds(); RealVectorStateManifold::StateType *rstate = static_cast<RealVectorStateManifold::StateType*>(state); for (unsigned int i = 0 ; i < dim ; ++i) rstate->values[i] = rng_.uniformReal(bounds.low[i], bounds.high[i]); } void ompl::base::RealVectorStateSampler::sampleUniformNear(State *state, const State *near, const double distance) { const unsigned int dim = manifold_->getDimension(); const RealVectorBounds &bounds = static_cast<const RealVectorStateManifold*>(manifold_)->getBounds(); RealVectorStateManifold::StateType *rstate = static_cast<RealVectorStateManifold::StateType*>(state); const RealVectorStateManifold::StateType *rnear = static_cast<const RealVectorStateManifold::StateType*>(near); for (unsigned int i = 0 ; i < dim ; ++i) rstate->values[i] = rng_.uniformReal(std::max(bounds.low[i], rnear->values[i] - distance), std::min(bounds.high[i], rnear->values[i] + distance)); } void ompl::base::RealVectorStateSampler::sampleGaussian(State *state, const State *mean, const double stdDev) { const unsigned int dim = manifold_->getDimension(); const RealVectorBounds &bounds = static_cast<const RealVectorStateManifold*>(manifold_)->getBounds(); RealVectorStateManifold::StateType *rstate = static_cast<RealVectorStateManifold::StateType*>(state); const RealVectorStateManifold::StateType *rmean = static_cast<const RealVectorStateManifold::StateType*>(mean); for (unsigned int i = 0 ; i < dim ; ++i) { double v = rng_.gaussian(rmean->values[i], stdDev); if (v < bounds.low[i]) v = bounds.low[i]; else if (v > bounds.high[i]) v = bounds.high[i]; rstate->values[i] = v; } } void ompl::base::RealVectorStateManifold::registerProjections(void) { // compute a default random projection if (dimension_ > 0) { if (dimension_ > 2) { int p = std::max(2, (int)ceil(log((double)dimension_))); registerDefaultProjection(ProjectionEvaluatorPtr(new RealVectorRandomLinearProjectionEvaluator(this, p))); } else registerDefaultProjection(ProjectionEvaluatorPtr(new RealVectorIdentityProjectionEvaluator(this))); } } void ompl::base::RealVectorStateManifold::setup(void) { bounds_.check(); StateManifold::setup(); } void ompl::base::RealVectorStateManifold::addDimension(const std::string &name, double minBound, double maxBound) { addDimension(minBound, maxBound); setDimensionName(dimension_ - 1, name); } void ompl::base::RealVectorStateManifold::addDimension(double minBound, double maxBound) { dimension_++; stateBytes_ = dimension_ * sizeof(double); bounds_.low.push_back(minBound); bounds_.high.push_back(maxBound); dimensionNames_.resize(dimension_, ""); } void ompl::base::RealVectorStateManifold::setBounds(const RealVectorBounds &bounds) { bounds.check(); if (bounds.low.size() != dimension_) throw Exception("Bounds do not match dimension of manifold"); bounds_ = bounds; } void ompl::base::RealVectorStateManifold::setBounds(double low, double high) { RealVectorBounds bounds(dimension_); bounds.setLow(low); bounds.setHigh(high); setBounds(bounds); } unsigned int ompl::base::RealVectorStateManifold::getDimension(void) const { return dimension_; } const std::string& ompl::base::RealVectorStateManifold::getDimensionName(unsigned int index) const { if (index < dimensionNames_.size()) return dimensionNames_[index]; throw Exception("Index out of bounds"); } int ompl::base::RealVectorStateManifold::getDimensionIndex(const std::string &name) const { std::map<std::string, unsigned int>::const_iterator it = dimensionIndex_.find(name); return it != dimensionIndex_.end() ? it->second : -1; } void ompl::base::RealVectorStateManifold::setDimensionName(unsigned int index, const std::string &name) { if (index < dimensionNames_.size()) { dimensionNames_[index] = name; dimensionIndex_[name] = index; } else throw Exception("Cannot set dimension name. Index out of bounds"); } double ompl::base::RealVectorStateManifold::getMaximumExtent(void) const { double e = 0.0; for (unsigned int i = 0 ; i < dimension_ ; ++i) { double d = bounds_.high[i] - bounds_.low[i]; e += d*d; } return sqrt(e); } void ompl::base::RealVectorStateManifold::enforceBounds(State *state) const { StateType *rstate = static_cast<StateType*>(state); for (unsigned int i = 0 ; i < dimension_ ; ++i) { if (rstate->values[i] > bounds_.high[i]) rstate->values[i] = bounds_.high[i]; else if (rstate->values[i] < bounds_.low[i]) rstate->values[i] = bounds_.low[i]; } } bool ompl::base::RealVectorStateManifold::satisfiesBounds(const State *state) const { const StateType *rstate = static_cast<const StateType*>(state); for (unsigned int i = 0 ; i < dimension_ ; ++i) if (rstate->values[i] - std::numeric_limits<double>::epsilon() > bounds_.high[i] || rstate->values[i] + std::numeric_limits<double>::epsilon() < bounds_.low[i]) return false; return true; } void ompl::base::RealVectorStateManifold::copyState(State *destination, const State *source) const { memcpy(static_cast<StateType*>(destination)->values, static_cast<const StateType*>(source)->values, stateBytes_); } double ompl::base::RealVectorStateManifold::distance(const State *state1, const State *state2) const { double dist = 0.0; const double *s1 = static_cast<const StateType*>(state1)->values; const double *s2 = static_cast<const StateType*>(state2)->values; for (unsigned int i = 0 ; i < dimension_ ; ++i) { double diff = (*s1++) - (*s2++); dist += diff * diff; } return sqrt(dist); } bool ompl::base::RealVectorStateManifold::equalStates(const State *state1, const State *state2) const { const double *s1 = static_cast<const StateType*>(state1)->values; const double *s2 = static_cast<const StateType*>(state2)->values; for (unsigned int i = 0 ; i < dimension_ ; ++i) { double diff = (*s1++) - (*s2++); if (fabs(diff) > std::numeric_limits<double>::epsilon() * 2.0) return false; } return true; } void ompl::base::RealVectorStateManifold::interpolate(const State *from, const State *to, const double t, State *state) const { const StateType *rfrom = static_cast<const StateType*>(from); const StateType *rto = static_cast<const StateType*>(to); const StateType *rstate = static_cast<StateType*>(state); for (unsigned int i = 0 ; i < dimension_ ; ++i) rstate->values[i] = rfrom->values[i] + (rto->values[i] - rfrom->values[i]) * t; } ompl::base::ManifoldStateSamplerPtr ompl::base::RealVectorStateManifold::allocStateSampler(void) const { return ManifoldStateSamplerPtr(new RealVectorStateSampler(this)); } ompl::base::State* ompl::base::RealVectorStateManifold::allocState(void) const { StateType *rstate = new StateType(); rstate->values = new double[dimension_]; return rstate; } void ompl::base::RealVectorStateManifold::freeState(State *state) const { StateType *rstate = static_cast<StateType*>(state); delete[] rstate->values; delete rstate; } void ompl::base::RealVectorStateManifold::copyToReals(const State *state, std::vector<double> &reals) const { reals.reserve(reals.size() + dimension_); const StateType *rstate = static_cast<const StateType*>(state); for (unsigned int i = 0 ; i < dimension_ ; ++i) reals.push_back(rstate->values[i]); } unsigned int ompl::base::RealVectorStateManifold::copyFromReals(State *state, const std::vector<double> &reals) const { StateType *rstate = static_cast<StateType*>(state); for (unsigned int i = 0 ; i < dimension_ ; ++i) rstate->values[i] = reals[i]; return dimension_; } void ompl::base::RealVectorStateManifold::printState(const State *state, std::ostream &out) const { out << "RealVectorState ["; if (state) { const StateType *rstate = static_cast<const StateType*>(state); for (unsigned int i = 0 ; i < dimension_ ; ++i) { out << rstate->values[i]; if (i + 1 < dimension_) out << ' '; } } else out << "NULL" << std::endl; out << ']' << std::endl; } void ompl::base::RealVectorStateManifold::printSettings(std::ostream &out) const { out << "Real vector state manifold '" << name_ << "' of dimension " << dimension_ << " with bounds: " << std::endl; out << " - min: "; for (unsigned int i = 0 ; i < dimension_ ; ++i) out << bounds_.low[i] << " "; out << std::endl; out << " - max: "; for (unsigned int i = 0 ; i < dimension_ ; ++i) out << bounds_.high[i] << " "; out << std::endl; } print dimension names for real vector manifolds --HG-- extra : convert_revision : 1f5d71f9a5c99e0f5ca1635590730e16619ebdb2 /********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2010, Rice University * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the Rice University nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *********************************************************************/ /* Author: Ioan Sucan */ #include "ompl/base/manifolds/RealVectorStateManifold.h" #include "ompl/base/manifolds/RealVectorStateProjections.h" #include "ompl/util/Exception.h" #include <algorithm> #include <cstring> #include <limits> #include <cmath> void ompl::base::RealVectorStateSampler::sampleUniform(State *state) { const unsigned int dim = manifold_->getDimension(); const RealVectorBounds &bounds = static_cast<const RealVectorStateManifold*>(manifold_)->getBounds(); RealVectorStateManifold::StateType *rstate = static_cast<RealVectorStateManifold::StateType*>(state); for (unsigned int i = 0 ; i < dim ; ++i) rstate->values[i] = rng_.uniformReal(bounds.low[i], bounds.high[i]); } void ompl::base::RealVectorStateSampler::sampleUniformNear(State *state, const State *near, const double distance) { const unsigned int dim = manifold_->getDimension(); const RealVectorBounds &bounds = static_cast<const RealVectorStateManifold*>(manifold_)->getBounds(); RealVectorStateManifold::StateType *rstate = static_cast<RealVectorStateManifold::StateType*>(state); const RealVectorStateManifold::StateType *rnear = static_cast<const RealVectorStateManifold::StateType*>(near); for (unsigned int i = 0 ; i < dim ; ++i) rstate->values[i] = rng_.uniformReal(std::max(bounds.low[i], rnear->values[i] - distance), std::min(bounds.high[i], rnear->values[i] + distance)); } void ompl::base::RealVectorStateSampler::sampleGaussian(State *state, const State *mean, const double stdDev) { const unsigned int dim = manifold_->getDimension(); const RealVectorBounds &bounds = static_cast<const RealVectorStateManifold*>(manifold_)->getBounds(); RealVectorStateManifold::StateType *rstate = static_cast<RealVectorStateManifold::StateType*>(state); const RealVectorStateManifold::StateType *rmean = static_cast<const RealVectorStateManifold::StateType*>(mean); for (unsigned int i = 0 ; i < dim ; ++i) { double v = rng_.gaussian(rmean->values[i], stdDev); if (v < bounds.low[i]) v = bounds.low[i]; else if (v > bounds.high[i]) v = bounds.high[i]; rstate->values[i] = v; } } void ompl::base::RealVectorStateManifold::registerProjections(void) { // compute a default random projection if (dimension_ > 0) { if (dimension_ > 2) { int p = std::max(2, (int)ceil(log((double)dimension_))); registerDefaultProjection(ProjectionEvaluatorPtr(new RealVectorRandomLinearProjectionEvaluator(this, p))); } else registerDefaultProjection(ProjectionEvaluatorPtr(new RealVectorIdentityProjectionEvaluator(this))); } } void ompl::base::RealVectorStateManifold::setup(void) { bounds_.check(); StateManifold::setup(); } void ompl::base::RealVectorStateManifold::addDimension(const std::string &name, double minBound, double maxBound) { addDimension(minBound, maxBound); setDimensionName(dimension_ - 1, name); } void ompl::base::RealVectorStateManifold::addDimension(double minBound, double maxBound) { dimension_++; stateBytes_ = dimension_ * sizeof(double); bounds_.low.push_back(minBound); bounds_.high.push_back(maxBound); dimensionNames_.resize(dimension_, ""); } void ompl::base::RealVectorStateManifold::setBounds(const RealVectorBounds &bounds) { bounds.check(); if (bounds.low.size() != dimension_) throw Exception("Bounds do not match dimension of manifold"); bounds_ = bounds; } void ompl::base::RealVectorStateManifold::setBounds(double low, double high) { RealVectorBounds bounds(dimension_); bounds.setLow(low); bounds.setHigh(high); setBounds(bounds); } unsigned int ompl::base::RealVectorStateManifold::getDimension(void) const { return dimension_; } const std::string& ompl::base::RealVectorStateManifold::getDimensionName(unsigned int index) const { if (index < dimensionNames_.size()) return dimensionNames_[index]; throw Exception("Index out of bounds"); } int ompl::base::RealVectorStateManifold::getDimensionIndex(const std::string &name) const { std::map<std::string, unsigned int>::const_iterator it = dimensionIndex_.find(name); return it != dimensionIndex_.end() ? it->second : -1; } void ompl::base::RealVectorStateManifold::setDimensionName(unsigned int index, const std::string &name) { if (index < dimensionNames_.size()) { dimensionNames_[index] = name; dimensionIndex_[name] = index; } else throw Exception("Cannot set dimension name. Index out of bounds"); } double ompl::base::RealVectorStateManifold::getMaximumExtent(void) const { double e = 0.0; for (unsigned int i = 0 ; i < dimension_ ; ++i) { double d = bounds_.high[i] - bounds_.low[i]; e += d*d; } return sqrt(e); } void ompl::base::RealVectorStateManifold::enforceBounds(State *state) const { StateType *rstate = static_cast<StateType*>(state); for (unsigned int i = 0 ; i < dimension_ ; ++i) { if (rstate->values[i] > bounds_.high[i]) rstate->values[i] = bounds_.high[i]; else if (rstate->values[i] < bounds_.low[i]) rstate->values[i] = bounds_.low[i]; } } bool ompl::base::RealVectorStateManifold::satisfiesBounds(const State *state) const { const StateType *rstate = static_cast<const StateType*>(state); for (unsigned int i = 0 ; i < dimension_ ; ++i) if (rstate->values[i] - std::numeric_limits<double>::epsilon() > bounds_.high[i] || rstate->values[i] + std::numeric_limits<double>::epsilon() < bounds_.low[i]) return false; return true; } void ompl::base::RealVectorStateManifold::copyState(State *destination, const State *source) const { memcpy(static_cast<StateType*>(destination)->values, static_cast<const StateType*>(source)->values, stateBytes_); } double ompl::base::RealVectorStateManifold::distance(const State *state1, const State *state2) const { double dist = 0.0; const double *s1 = static_cast<const StateType*>(state1)->values; const double *s2 = static_cast<const StateType*>(state2)->values; for (unsigned int i = 0 ; i < dimension_ ; ++i) { double diff = (*s1++) - (*s2++); dist += diff * diff; } return sqrt(dist); } bool ompl::base::RealVectorStateManifold::equalStates(const State *state1, const State *state2) const { const double *s1 = static_cast<const StateType*>(state1)->values; const double *s2 = static_cast<const StateType*>(state2)->values; for (unsigned int i = 0 ; i < dimension_ ; ++i) { double diff = (*s1++) - (*s2++); if (fabs(diff) > std::numeric_limits<double>::epsilon() * 2.0) return false; } return true; } void ompl::base::RealVectorStateManifold::interpolate(const State *from, const State *to, const double t, State *state) const { const StateType *rfrom = static_cast<const StateType*>(from); const StateType *rto = static_cast<const StateType*>(to); const StateType *rstate = static_cast<StateType*>(state); for (unsigned int i = 0 ; i < dimension_ ; ++i) rstate->values[i] = rfrom->values[i] + (rto->values[i] - rfrom->values[i]) * t; } ompl::base::ManifoldStateSamplerPtr ompl::base::RealVectorStateManifold::allocStateSampler(void) const { return ManifoldStateSamplerPtr(new RealVectorStateSampler(this)); } ompl::base::State* ompl::base::RealVectorStateManifold::allocState(void) const { StateType *rstate = new StateType(); rstate->values = new double[dimension_]; return rstate; } void ompl::base::RealVectorStateManifold::freeState(State *state) const { StateType *rstate = static_cast<StateType*>(state); delete[] rstate->values; delete rstate; } void ompl::base::RealVectorStateManifold::copyToReals(const State *state, std::vector<double> &reals) const { reals.reserve(reals.size() + dimension_); const StateType *rstate = static_cast<const StateType*>(state); for (unsigned int i = 0 ; i < dimension_ ; ++i) reals.push_back(rstate->values[i]); } unsigned int ompl::base::RealVectorStateManifold::copyFromReals(State *state, const std::vector<double> &reals) const { StateType *rstate = static_cast<StateType*>(state); for (unsigned int i = 0 ; i < dimension_ ; ++i) rstate->values[i] = reals[i]; return dimension_; } void ompl::base::RealVectorStateManifold::printState(const State *state, std::ostream &out) const { out << "RealVectorState ["; if (state) { const StateType *rstate = static_cast<const StateType*>(state); for (unsigned int i = 0 ; i < dimension_ ; ++i) { out << rstate->values[i]; if (i + 1 < dimension_) out << ' '; } } else out << "NULL" << std::endl; out << ']' << std::endl; } void ompl::base::RealVectorStateManifold::printSettings(std::ostream &out) const { out << "Real vector state manifold '" << name_ << "' of dimension " << dimension_ << " with bounds: " << std::endl; out << " - min: "; for (unsigned int i = 0 ; i < dimension_ ; ++i) out << bounds_.low[i] << " "; out << std::endl; out << " - max: "; for (unsigned int i = 0 ; i < dimension_ ; ++i) out << bounds_.high[i] << " "; out << std::endl; bool printNames = false; for (unsigned int i = 0 ; i < dimension_ ; ++i) if (!dimensionNames_[i].empty()) printNames = true; if (printNames) { out << " and dimension names: "; for (unsigned int i = 0 ; i < dimension_ ; ++i) out << "'" << dimensionNames_[i] << "' "; out << std::endl; } }
#include "coverage_generator.hpp" #include "tile_renderer.hpp" #include "tile_set.hpp" #include "../platform/settings.hpp" #include "../platform/platform.hpp" #include "../graphics/opengl/gl_render_context.hpp" #include "../graphics/display_list.hpp" #include "../base/logging.hpp" #include "../std/bind.hpp" CoverageGenerator::CoverageGenerator(TileRenderer * tileRenderer, shared_ptr<WindowHandle> const & windowHandle, shared_ptr<graphics::RenderContext> const & primaryRC, shared_ptr<graphics::ResourceManager> const & rm, graphics::PacketsQueue * glQueue) : m_coverageInfo(tileRenderer) , m_queue(1) , m_windowHandle(windowHandle) { shared_ptr<graphics::RenderContext> renderContext; if (!glQueue) renderContext.reset(primaryRC->createShared()); m_queue.AddInitCommand(bind(&CoverageGenerator::InitializeThreadGL, this, renderContext, rm, glQueue)); m_queue.AddFinCommand(bind(&CoverageGenerator::FinalizeThreadGL, this, renderContext, rm)); m_queue.Start(); Settings::Get("IsBenchmarking", m_benchmarkInfo.m_isBenchmarking); m_currentCoverage = new CachedCoverageInfo(); m_backCoverage = new CachedCoverageInfo(); } CoverageGenerator::~CoverageGenerator() { LOG(LINFO, ("cancelling coverage thread")); ClearCoverage(); } void CoverageGenerator::Shutdown() { LOG(LINFO, ("shutdown resources")); m_stateInfo.SetSequenceID(numeric_limits<int>::max()); m_queue.CancelCommands(); m_queue.Cancel(); } void CoverageGenerator::InitializeThreadGL(shared_ptr<graphics::RenderContext> context, shared_ptr<graphics::ResourceManager> resourceManager, graphics::PacketsQueue * glQueue) { threads::MutexGuard g(m_stateInfo.m_mutex); LOG(LINFO, ("initializing CoverageGenerator on it's own thread.")); if (context) { context->makeCurrent(); context->startThreadDrawing(resourceManager->cacheThreadSlot()); } graphics::Screen::Params params; params.m_resourceManager = resourceManager; params.m_renderQueue = glQueue; params.m_threadSlot = resourceManager->cacheThreadSlot(); params.m_renderContext = context; params.m_storageType = graphics::EMediumStorage; params.m_textureType = graphics::EMediumTexture; m_cacheScreen.reset(new graphics::Screen(params)); } void CoverageGenerator::FinalizeThreadGL(shared_ptr<graphics::RenderContext> context, shared_ptr<graphics::ResourceManager> resourceManager) { if (context) context->endThreadDrawing(resourceManager->cacheThreadSlot()); } void CoverageGenerator::Pause() { m_stateInfo.Pause(); m_queue.CancelCommands(); } void CoverageGenerator::Resume() { m_stateInfo.Resume(); } void CoverageGenerator::InvalidateTiles(m2::AnyRectD const & r, int startScale) { if (m_stateInfo.m_sequenceID == numeric_limits<int>::max()) return; /// this automatically will skip the previous CoverScreen commands /// and MergeTiles commands from previously generated ScreenCoverages ++m_stateInfo.m_sequenceID; m_queue.AddCommand(bind(&CoverageGenerator::InvalidateTilesImpl, this, r, startScale)); } void CoverageGenerator::CoverScreen(ScreenBase const & screen, bool doForce) { if (screen == m_stateInfo.m_currentScreen && !doForce) return; if (m_stateInfo.m_sequenceID == numeric_limits<int>::max()) return; m_stateInfo.m_currentScreen = screen; ++m_stateInfo.m_sequenceID; m_queue.AddCommand(bind(&CoverageGenerator::CoverScreenImpl, this, _1, screen, m_stateInfo.m_sequenceID)); } void CoverageGenerator::MergeTile(Tiler::RectInfo const & rectInfo, int sequenceID) { m_queue.AddCommand(bind(&CoverageGenerator::MergeTileImpl, this, _1, rectInfo, sequenceID)); } void CoverageGenerator::FinishSequenceIfNeeded() { m_queue.AddCommand(bind(&CoverageGenerator::BenchmarkInfo::TryFinishSequence, &m_benchmarkInfo)); } void CoverageGenerator::Lock() { m_stateInfo.m_mutex.Lock(); } void CoverageGenerator::Unlock() { m_stateInfo.m_mutex.Unlock(); } void CoverageGenerator::Draw(graphics::Screen * s, ScreenBase const & screen) { math::Matrix<double, 3, 3> m = m_currentCoverage->m_screen.PtoGMatrix() * screen.GtoPMatrix(); ASSERT(m_currentCoverage, ()); if (m_currentCoverage->m_mainElements) s->drawDisplayList(m_currentCoverage->m_mainElements, m); if (m_currentCoverage->m_sharpElements) s->drawDisplayList(m_currentCoverage->m_sharpElements, m); if (m_benchmarkInfo.m_isBenchmarking) FinishSequenceIfNeeded(); } graphics::Overlay * CoverageGenerator::GetOverlay() const { return m_coverageInfo.m_overlay; } bool CoverageGenerator::IsEmptyDrawing() const { return (m_currentCoverage->m_renderLeafTilesCount <= 0) && m_currentCoverage->m_isEmptyDrawing; } bool CoverageGenerator::IsBackEmptyDrawing() const { return (m_backCoverage->m_renderLeafTilesCount <= 0) && m_backCoverage->m_isEmptyDrawing; } bool CoverageGenerator::DoForceUpdate() const { return m_stateInfo.m_needForceUpdate; } //////////////////////////////////////////////////// /// Benchmark support //////////////////////////////////////////////////// int CoverageGenerator::InsertBenchmarkFence() { return m_benchmarkInfo.InsertBenchmarkFence(); } void CoverageGenerator::JoinBenchmarkFence(int fenceID) { m_benchmarkInfo.JoinBenchmarkFence(fenceID); } //////////////////////////////////////////////////// /// On Coverage generator thread methods //////////////////////////////////////////////////// void CoverageGenerator::CoverScreenImpl(core::CommandsQueue::Environment const & env, ScreenBase const & screen, int sequenceID) { if (sequenceID < m_stateInfo.m_sequenceID) return; m_stateInfo.m_currentScreen = screen; m_backCoverage->m_screen = screen; m_coverageInfo.m_tiler.seed(screen, screen.GlobalRect().GlobalCenter(), m_coverageInfo.m_tileRenderer->TileSize()); ComputeCoverTasks(); bool const shouldSwap = !m_stateInfo.m_isPause && CacheCoverage(env); if (shouldSwap) { threads::MutexGuard g(m_stateInfo.m_mutex); swap(m_currentCoverage, m_backCoverage); } else { // we should skip all the following MergeTile commands ++m_stateInfo.m_sequenceID; } m_stateInfo.SetForceUpdate(!shouldSwap); m_windowHandle->invalidate(); } void CoverageGenerator::MergeTileImpl(core::CommandsQueue::Environment const & env, Tiler::RectInfo const & rectInfo, int sequenceID) { if (sequenceID < m_stateInfo.m_sequenceID) { m_coverageInfo.m_tileRenderer->RemoveActiveTile(rectInfo, sequenceID); return; } m_backCoverage->m_screen = m_stateInfo.m_currentScreen; m_backCoverage->m_isEmptyDrawing = m_currentCoverage->m_isEmptyDrawing; m_backCoverage->m_renderLeafTilesCount = m_currentCoverage->m_renderLeafTilesCount; MergeSingleTile(rectInfo); bool const shouldSwap = !m_stateInfo.m_isPause && CacheCoverage(env); if (shouldSwap) { threads::MutexGuard g(m_stateInfo.m_mutex); swap(m_currentCoverage, m_backCoverage); } m_benchmarkInfo.DecrementTileCount(sequenceID); m_stateInfo.SetForceUpdate(!shouldSwap); m_windowHandle->invalidate(); } void CoverageGenerator::InvalidateTilesImpl(m2::AnyRectD const & r, int startScale) { TileCache & tileCache = m_coverageInfo.m_tileRenderer->GetTileCache(); tileCache.Lock(); { threads::MutexGuard g(m_stateInfo.m_mutex); typedef buffer_vector<Tile const *, 8> vector8_t; vector8_t toRemove; for (CoverageInfo::TTileSet::const_iterator it = m_coverageInfo.m_tiles.begin(); it != m_coverageInfo.m_tiles.end(); ++it) { Tiler::RectInfo const & ri = (*it)->m_rectInfo; if (r.IsIntersect(m2::AnyRectD(ri.m_rect)) && (ri.m_tileScale >= startScale)) { toRemove.push_back(*it); tileCache.UnlockTile(ri); } } for (vector8_t::const_iterator it = toRemove.begin(); it != toRemove.end(); ++it) { m_coverageInfo.m_tiles.erase(*it); } } /// here we should copy elements as we've delete some of them later set<Tiler::RectInfo> k = tileCache.Keys(); for (set<Tiler::RectInfo>::const_iterator it = k.begin(); it != k.end(); ++it) { Tiler::RectInfo const & ri = *it; if ((ri.m_tileScale >= startScale) && r.IsIntersect(m2::AnyRectD(ri.m_rect))) { ASSERT(tileCache.LockCount(ri) == 0, ()); tileCache.Remove(ri); } } tileCache.Unlock(); MergeOverlay(); } //////////////////////////////////////////////////////////// /// Support methods //////////////////////////////////////////////////////////// void CoverageGenerator::ComputeCoverTasks() { m_backCoverage->m_isEmptyDrawing = false; m_backCoverage->m_renderLeafTilesCount = 0; vector<Tiler::RectInfo> allRects; allRects.reserve(16); buffer_vector<Tiler::RectInfo, 8> newRects; m_coverageInfo.m_tiler.tiles(allRects, GetPlatform().PreCachingDepth()); TileCache & tileCache = m_coverageInfo.m_tileRenderer->GetTileCache(); tileCache.Lock(); int const step = GetPlatform().PreCachingDepth() - 1; bool isEmptyDrawingBuf = true; CoverageInfo::TTileSet tiles; for (size_t i = 0; i < allRects.size(); ++i) { Tiler::RectInfo const & ri = allRects[i]; if (!((ri.m_tileScale == m_coverageInfo.m_tiler.tileScale() - step) || (ri.m_tileScale == m_coverageInfo.m_tiler.tileScale() ))) { continue; } if (tileCache.HasTile(ri)) { tileCache.TouchTile(ri); Tile const * tile = &tileCache.GetTile(ri); ASSERT(tiles.find(tile) == tiles.end(), ()); if (m_coverageInfo.m_tiler.isLeaf(ri)) isEmptyDrawingBuf &= tile->m_isEmptyDrawing; tiles.insert(tile); } else { if (m_coverageInfo.m_tiler.isLeaf(ri)) { newRects.push_back(ri); ++m_backCoverage->m_renderLeafTilesCount; } } } m_backCoverage->m_isEmptyDrawing = isEmptyDrawingBuf; /// computing difference between current and previous coverage /// tiles, that aren't in current coverage are unlocked to allow their deletion from TileCache /// tiles, that are new to the current coverage are added into m_tiles and locked in TileCache size_t firstTileForAdd = 0; buffer_vector<const Tile *, 64> diff_tiles; diff_tiles.reserve(m_coverageInfo.m_tiles.size() + tiles.size()); set_difference(m_coverageInfo.m_tiles.begin(), m_coverageInfo.m_tiles.end(), tiles.begin(), tiles.end(), back_inserter(diff_tiles), CoverageInfo::TTileSet::key_compare()); firstTileForAdd = diff_tiles.size(); set_difference(tiles.begin(), tiles.end(), m_coverageInfo.m_tiles.begin(), m_coverageInfo.m_tiles.end(), back_inserter(diff_tiles), CoverageInfo::TTileSet::key_compare()); for (size_t i = 0; i < firstTileForAdd; ++i) tileCache.UnlockTile(diff_tiles[i]->m_rectInfo); for (size_t i = firstTileForAdd; i < diff_tiles.size(); ++i) tileCache.LockTile(diff_tiles[i]->m_rectInfo); tileCache.Unlock(); m_coverageInfo.m_tiles = tiles; MergeOverlay(); /// clearing all old commands m_coverageInfo.m_tileRenderer->ClearCommands(); /// setting new sequenceID m_coverageInfo.m_tileRenderer->SetSequenceID(m_stateInfo.m_sequenceID); /// @todo After ClearCommands i think we have no commands to cancel. m_coverageInfo.m_tileRenderer->CancelCommands(); m_benchmarkInfo.m_tilesCount = newRects.size(); m_benchmarkInfo.m_benchmarkSequenceID = m_stateInfo.m_sequenceID; for (size_t i = 0; i < newRects.size(); ++i) { Tiler::RectInfo const & ri = newRects[i]; core::CommandsQueue::Chain chain; chain.addCommand(bind(&CoverageGenerator::MergeTile, this, ri, m_stateInfo.m_sequenceID)); m_coverageInfo.m_tileRenderer->AddCommand(ri, m_stateInfo.m_sequenceID, chain); } } void CoverageGenerator::MergeOverlay() { m_coverageInfo.m_overlay->lock(); m_coverageInfo.m_overlay->clear(); for (CoverageInfo::TTileSet::const_iterator it = m_coverageInfo.m_tiles.begin(); it != m_coverageInfo.m_tiles.end(); ++it) { Tiler::RectInfo const & ri = (*it)->m_rectInfo; if (m_coverageInfo.m_tiler.isLeaf(ri)) m_coverageInfo.m_overlay->merge(*(*it)->m_overlay, (*it)->m_tileScreen.PtoGMatrix() * m_stateInfo.m_currentScreen.GtoPMatrix()); } m_coverageInfo.m_overlay->unlock(); } void CoverageGenerator::MergeSingleTile(Tiler::RectInfo const & rectInfo) { m_coverageInfo.m_tileRenderer->CacheActiveTile(rectInfo); TileCache & tileCache = m_coverageInfo.m_tileRenderer->GetTileCache(); tileCache.Lock(); Tile const * tile = NULL; if (tileCache.HasTile(rectInfo)) { tileCache.LockTile(rectInfo); tile = &tileCache.GetTile(rectInfo); } if (tile != NULL) { m_coverageInfo.m_tiles.insert(tile); if (m_coverageInfo.m_tiler.isLeaf(rectInfo)) { m_backCoverage->m_isEmptyDrawing &= tile->m_isEmptyDrawing; m_backCoverage->m_renderLeafTilesCount--; } } tileCache.Unlock(); if (tile != NULL && m_coverageInfo.m_tiler.isLeaf(rectInfo)) { m_coverageInfo.m_overlay->lock(); m_coverageInfo.m_overlay->merge(*tile->m_overlay, tile->m_tileScreen.PtoGMatrix() * m_stateInfo.m_currentScreen.GtoPMatrix()); m_coverageInfo.m_overlay->unlock(); } } namespace { bool SharpnessComparator(shared_ptr<graphics::OverlayElement> const & e1, shared_ptr<graphics::OverlayElement> const & e2) { return e1->hasSharpGeometry() && (!e2->hasSharpGeometry()); } } bool CoverageGenerator::CacheCoverage(core::CommandsQueue::Environment const & env) { delete m_backCoverage->m_mainElements; delete m_backCoverage->m_sharpElements; m_backCoverage->m_mainElements = m_cacheScreen->createDisplayList(); m_backCoverage->m_sharpElements = m_cacheScreen->createDisplayList(); m_cacheScreen->setEnvironment(&env); m_cacheScreen->beginFrame(); m_cacheScreen->setDisplayList(m_backCoverage->m_mainElements); vector<graphics::BlitInfo> infos; for (CoverageInfo::TTileSet::const_iterator it = m_coverageInfo.m_tiles.begin(); it != m_coverageInfo.m_tiles.end(); ++it) { Tile const * tile = *it; size_t tileWidth = tile->m_renderTarget->width(); size_t tileHeight = tile->m_renderTarget->height(); graphics::BlitInfo bi; bi.m_matrix = tile->m_tileScreen.PtoGMatrix() * m_stateInfo.m_currentScreen.GtoPMatrix(); bi.m_srcRect = m2::RectI(0, 0, tileWidth - 2, tileHeight - 2); bi.m_texRect = m2::RectU(1, 1, tileWidth - 1, tileHeight - 1); bi.m_srcSurface = tile->m_renderTarget; infos.push_back(bi); } if (!infos.empty()) m_cacheScreen->blit(&infos[0], infos.size(), true, graphics::minDepth); math::Matrix<double, 3, 3> idM = math::Identity<double, 3>(); m_coverageInfo.m_overlay->lock(); vector<shared_ptr<graphics::OverlayElement> > overlayElements; overlayElements.reserve(m_coverageInfo.m_overlay->getElementsCount()); m_coverageInfo.m_overlay->forEach(MakeBackInsertFunctor(overlayElements)); sort(overlayElements.begin(), overlayElements.end(), SharpnessComparator); unsigned currentElement = 0; for (; currentElement < overlayElements.size(); ++currentElement) { shared_ptr<graphics::OverlayElement> const & elem = overlayElements[currentElement]; if (elem->hasSharpGeometry()) break; elem->draw(m_cacheScreen.get(), idM); } m_cacheScreen->applySharpStates(); m_cacheScreen->setDisplayList(m_backCoverage->m_sharpElements); for (; currentElement < overlayElements.size(); ++currentElement) overlayElements[currentElement]->draw(m_cacheScreen.get(), idM); m_coverageInfo.m_overlay->unlock(); m_cacheScreen->setDisplayList(0); m_cacheScreen->applyStates(); m_cacheScreen->endFrame(); /// completing commands that was immediately executed /// while recording of displayList(for example UnlockStorage) m_cacheScreen->completeCommands(); bool isCancelled = m_cacheScreen->isCancelled(); m_cacheScreen->setEnvironment(0); return !isCancelled; } void CoverageGenerator::ClearCoverage() { { m_coverageInfo.m_overlay->lock(); m_coverageInfo.m_overlay->clear(); m_coverageInfo.m_overlay->unlock(); } TileCache & tileCache = m_coverageInfo.m_tileRenderer->GetTileCache(); tileCache.Lock(); for (CoverageInfo::TTileSet::const_iterator it = m_coverageInfo.m_tiles.begin(); it != m_coverageInfo.m_tiles.end(); ++it) { Tiler::RectInfo const & ri = (*it)->m_rectInfo; tileCache.UnlockTile(ri); } tileCache.Unlock(); m_coverageInfo.m_tiles.clear(); delete m_currentCoverage; m_currentCoverage = 0; delete m_backCoverage; m_backCoverage = 0; } //////////////////////////////////////////////////////////// /// BenchmarkInfo //////////////////////////////////////////////////////////// CoverageGenerator::BenchmarkInfo::BenchmarkInfo() : m_benchmarkSequenceID(numeric_limits<int>::max()) , m_tilesCount(-1) , m_fenceManager(2) , m_currentFenceID(-1) , m_isBenchmarking(false) { } void CoverageGenerator::BenchmarkInfo::DecrementTileCount(int sequenceID) { if (!m_isBenchmarking) return; if (sequenceID < m_benchmarkSequenceID) { m_tilesCount = -1; return; } m_tilesCount -= 1; } int CoverageGenerator::BenchmarkInfo::InsertBenchmarkFence() { ASSERT(m_isBenchmarking, ("Only for benchmark mode")); m_currentFenceID = m_fenceManager.insertFence(); return m_currentFenceID; } void CoverageGenerator::BenchmarkInfo::JoinBenchmarkFence(int fenceID) { ASSERT(m_isBenchmarking, ("Only for benchmark mode")); CHECK(fenceID == m_currentFenceID, ("InsertBenchmarkFence without corresponding SignalBenchmarkFence detected")); m_fenceManager.joinFence(fenceID); } void CoverageGenerator::BenchmarkInfo::SignalBenchmarkFence() { ASSERT(m_isBenchmarking, ("Only for benchmark mode")); if (m_currentFenceID != -1) m_fenceManager.signalFence(m_currentFenceID); } void CoverageGenerator::BenchmarkInfo::TryFinishSequence() { if (m_tilesCount == 0) { m_tilesCount = -1; SignalBenchmarkFence(); } } //////////////////////////////////////////////////////////// /// StateInfo //////////////////////////////////////////////////////////// CoverageGenerator::StateInfo::StateInfo() : m_isPause(false) , m_needForceUpdate(false) , m_sequenceID(0) { } void CoverageGenerator::StateInfo::SetSequenceID(int sequenceID) { m_sequenceID = sequenceID; } void CoverageGenerator::StateInfo::SetForceUpdate(bool needForceUpdate) { m_needForceUpdate = needForceUpdate; } void CoverageGenerator::StateInfo::Pause() { m_isPause = true; } void CoverageGenerator::StateInfo::Resume() { m_isPause = false; m_needForceUpdate = true; } //////////////////////////////////////////////////////////// /// CoverageGenerator //////////////////////////////////////////////////////////// CoverageGenerator::CoverageInfo::CoverageInfo(TileRenderer *tileRenderer) : m_tileRenderer(tileRenderer) , m_overlay(new graphics::Overlay()) { m_overlay->setCouldOverlap(false); } CoverageGenerator::CoverageInfo::~CoverageInfo() { delete m_overlay; } CoverageGenerator::CachedCoverageInfo::CachedCoverageInfo() : m_mainElements(NULL) , m_sharpElements(NULL) , m_renderLeafTilesCount(0) , m_isEmptyDrawing(false) { } CoverageGenerator::CachedCoverageInfo::~CachedCoverageInfo() { delete m_mainElements; delete m_sharpElements; } return tile precaching from n-2 zoom level #include "coverage_generator.hpp" #include "tile_renderer.hpp" #include "tile_set.hpp" #include "../platform/settings.hpp" #include "../platform/platform.hpp" #include "../graphics/opengl/gl_render_context.hpp" #include "../graphics/display_list.hpp" #include "../base/logging.hpp" #include "../std/bind.hpp" CoverageGenerator::CoverageGenerator(TileRenderer * tileRenderer, shared_ptr<WindowHandle> const & windowHandle, shared_ptr<graphics::RenderContext> const & primaryRC, shared_ptr<graphics::ResourceManager> const & rm, graphics::PacketsQueue * glQueue) : m_coverageInfo(tileRenderer) , m_queue(1) , m_windowHandle(windowHandle) { shared_ptr<graphics::RenderContext> renderContext; if (!glQueue) renderContext.reset(primaryRC->createShared()); m_queue.AddInitCommand(bind(&CoverageGenerator::InitializeThreadGL, this, renderContext, rm, glQueue)); m_queue.AddFinCommand(bind(&CoverageGenerator::FinalizeThreadGL, this, renderContext, rm)); m_queue.Start(); Settings::Get("IsBenchmarking", m_benchmarkInfo.m_isBenchmarking); m_currentCoverage = new CachedCoverageInfo(); m_backCoverage = new CachedCoverageInfo(); } CoverageGenerator::~CoverageGenerator() { LOG(LINFO, ("cancelling coverage thread")); ClearCoverage(); } void CoverageGenerator::Shutdown() { LOG(LINFO, ("shutdown resources")); m_stateInfo.SetSequenceID(numeric_limits<int>::max()); m_queue.CancelCommands(); m_queue.Cancel(); } void CoverageGenerator::InitializeThreadGL(shared_ptr<graphics::RenderContext> context, shared_ptr<graphics::ResourceManager> resourceManager, graphics::PacketsQueue * glQueue) { threads::MutexGuard g(m_stateInfo.m_mutex); LOG(LINFO, ("initializing CoverageGenerator on it's own thread.")); if (context) { context->makeCurrent(); context->startThreadDrawing(resourceManager->cacheThreadSlot()); } graphics::Screen::Params params; params.m_resourceManager = resourceManager; params.m_renderQueue = glQueue; params.m_threadSlot = resourceManager->cacheThreadSlot(); params.m_renderContext = context; params.m_storageType = graphics::EMediumStorage; params.m_textureType = graphics::EMediumTexture; m_cacheScreen.reset(new graphics::Screen(params)); } void CoverageGenerator::FinalizeThreadGL(shared_ptr<graphics::RenderContext> context, shared_ptr<graphics::ResourceManager> resourceManager) { if (context) context->endThreadDrawing(resourceManager->cacheThreadSlot()); } void CoverageGenerator::Pause() { m_stateInfo.Pause(); m_queue.CancelCommands(); } void CoverageGenerator::Resume() { m_stateInfo.Resume(); } void CoverageGenerator::InvalidateTiles(m2::AnyRectD const & r, int startScale) { if (m_stateInfo.m_sequenceID == numeric_limits<int>::max()) return; /// this automatically will skip the previous CoverScreen commands /// and MergeTiles commands from previously generated ScreenCoverages ++m_stateInfo.m_sequenceID; m_queue.AddCommand(bind(&CoverageGenerator::InvalidateTilesImpl, this, r, startScale)); } void CoverageGenerator::CoverScreen(ScreenBase const & screen, bool doForce) { if (screen == m_stateInfo.m_currentScreen && !doForce) return; if (m_stateInfo.m_sequenceID == numeric_limits<int>::max()) return; m_stateInfo.m_currentScreen = screen; ++m_stateInfo.m_sequenceID; m_queue.AddCommand(bind(&CoverageGenerator::CoverScreenImpl, this, _1, screen, m_stateInfo.m_sequenceID)); } void CoverageGenerator::MergeTile(Tiler::RectInfo const & rectInfo, int sequenceID) { m_queue.AddCommand(bind(&CoverageGenerator::MergeTileImpl, this, _1, rectInfo, sequenceID)); } void CoverageGenerator::FinishSequenceIfNeeded() { m_queue.AddCommand(bind(&CoverageGenerator::BenchmarkInfo::TryFinishSequence, &m_benchmarkInfo)); } void CoverageGenerator::Lock() { m_stateInfo.m_mutex.Lock(); } void CoverageGenerator::Unlock() { m_stateInfo.m_mutex.Unlock(); } void CoverageGenerator::Draw(graphics::Screen * s, ScreenBase const & screen) { math::Matrix<double, 3, 3> m = m_currentCoverage->m_screen.PtoGMatrix() * screen.GtoPMatrix(); ASSERT(m_currentCoverage, ()); if (m_currentCoverage->m_mainElements) s->drawDisplayList(m_currentCoverage->m_mainElements, m); if (m_currentCoverage->m_sharpElements) s->drawDisplayList(m_currentCoverage->m_sharpElements, m); if (m_benchmarkInfo.m_isBenchmarking) FinishSequenceIfNeeded(); } graphics::Overlay * CoverageGenerator::GetOverlay() const { return m_coverageInfo.m_overlay; } bool CoverageGenerator::IsEmptyDrawing() const { return (m_currentCoverage->m_renderLeafTilesCount <= 0) && m_currentCoverage->m_isEmptyDrawing; } bool CoverageGenerator::IsBackEmptyDrawing() const { return (m_backCoverage->m_renderLeafTilesCount <= 0) && m_backCoverage->m_isEmptyDrawing; } bool CoverageGenerator::DoForceUpdate() const { return m_stateInfo.m_needForceUpdate; } //////////////////////////////////////////////////// /// Benchmark support //////////////////////////////////////////////////// int CoverageGenerator::InsertBenchmarkFence() { return m_benchmarkInfo.InsertBenchmarkFence(); } void CoverageGenerator::JoinBenchmarkFence(int fenceID) { m_benchmarkInfo.JoinBenchmarkFence(fenceID); } //////////////////////////////////////////////////// /// On Coverage generator thread methods //////////////////////////////////////////////////// void CoverageGenerator::CoverScreenImpl(core::CommandsQueue::Environment const & env, ScreenBase const & screen, int sequenceID) { if (sequenceID < m_stateInfo.m_sequenceID) return; m_stateInfo.m_currentScreen = screen; m_backCoverage->m_screen = screen; m_coverageInfo.m_tiler.seed(screen, screen.GlobalRect().GlobalCenter(), m_coverageInfo.m_tileRenderer->TileSize()); ComputeCoverTasks(); bool const shouldSwap = !m_stateInfo.m_isPause && CacheCoverage(env); if (shouldSwap) { threads::MutexGuard g(m_stateInfo.m_mutex); swap(m_currentCoverage, m_backCoverage); } else { // we should skip all the following MergeTile commands ++m_stateInfo.m_sequenceID; } m_stateInfo.SetForceUpdate(!shouldSwap); m_windowHandle->invalidate(); } void CoverageGenerator::MergeTileImpl(core::CommandsQueue::Environment const & env, Tiler::RectInfo const & rectInfo, int sequenceID) { if (sequenceID < m_stateInfo.m_sequenceID) { m_coverageInfo.m_tileRenderer->RemoveActiveTile(rectInfo, sequenceID); return; } m_backCoverage->m_screen = m_stateInfo.m_currentScreen; m_backCoverage->m_isEmptyDrawing = m_currentCoverage->m_isEmptyDrawing; m_backCoverage->m_renderLeafTilesCount = m_currentCoverage->m_renderLeafTilesCount; MergeSingleTile(rectInfo); bool const shouldSwap = !m_stateInfo.m_isPause && CacheCoverage(env); if (shouldSwap) { threads::MutexGuard g(m_stateInfo.m_mutex); swap(m_currentCoverage, m_backCoverage); } m_benchmarkInfo.DecrementTileCount(sequenceID); m_stateInfo.SetForceUpdate(!shouldSwap); m_windowHandle->invalidate(); } void CoverageGenerator::InvalidateTilesImpl(m2::AnyRectD const & r, int startScale) { TileCache & tileCache = m_coverageInfo.m_tileRenderer->GetTileCache(); tileCache.Lock(); { threads::MutexGuard g(m_stateInfo.m_mutex); typedef buffer_vector<Tile const *, 8> vector8_t; vector8_t toRemove; for (CoverageInfo::TTileSet::const_iterator it = m_coverageInfo.m_tiles.begin(); it != m_coverageInfo.m_tiles.end(); ++it) { Tiler::RectInfo const & ri = (*it)->m_rectInfo; if (r.IsIntersect(m2::AnyRectD(ri.m_rect)) && (ri.m_tileScale >= startScale)) { toRemove.push_back(*it); tileCache.UnlockTile(ri); } } for (vector8_t::const_iterator it = toRemove.begin(); it != toRemove.end(); ++it) { m_coverageInfo.m_tiles.erase(*it); } } /// here we should copy elements as we've delete some of them later set<Tiler::RectInfo> k = tileCache.Keys(); for (set<Tiler::RectInfo>::const_iterator it = k.begin(); it != k.end(); ++it) { Tiler::RectInfo const & ri = *it; if ((ri.m_tileScale >= startScale) && r.IsIntersect(m2::AnyRectD(ri.m_rect))) { ASSERT(tileCache.LockCount(ri) == 0, ()); tileCache.Remove(ri); } } tileCache.Unlock(); MergeOverlay(); } //////////////////////////////////////////////////////////// /// Support methods //////////////////////////////////////////////////////////// void CoverageGenerator::ComputeCoverTasks() { m_backCoverage->m_isEmptyDrawing = false; m_backCoverage->m_renderLeafTilesCount = 0; vector<Tiler::RectInfo> allRects; allRects.reserve(16); buffer_vector<Tiler::RectInfo, 8> newRects; m_coverageInfo.m_tiler.tiles(allRects, GetPlatform().PreCachingDepth()); TileCache & tileCache = m_coverageInfo.m_tileRenderer->GetTileCache(); tileCache.Lock(); int const step = GetPlatform().PreCachingDepth() - 1; bool isEmptyDrawingBuf = true; CoverageInfo::TTileSet tiles; for (size_t i = 0; i < allRects.size(); ++i) { Tiler::RectInfo const & ri = allRects[i]; if (!((ri.m_tileScale == m_coverageInfo.m_tiler.tileScale() - step) || (ri.m_tileScale == m_coverageInfo.m_tiler.tileScale() ))) { continue; } if (tileCache.HasTile(ri)) { tileCache.TouchTile(ri); Tile const * tile = &tileCache.GetTile(ri); ASSERT(tiles.find(tile) == tiles.end(), ()); if (m_coverageInfo.m_tiler.isLeaf(ri)) isEmptyDrawingBuf &= tile->m_isEmptyDrawing; tiles.insert(tile); } else { newRects.push_back(ri); if (m_coverageInfo.m_tiler.isLeaf(ri)) ++m_backCoverage->m_renderLeafTilesCount; } } m_backCoverage->m_isEmptyDrawing = isEmptyDrawingBuf; /// computing difference between current and previous coverage /// tiles, that aren't in current coverage are unlocked to allow their deletion from TileCache /// tiles, that are new to the current coverage are added into m_tiles and locked in TileCache size_t firstTileForAdd = 0; buffer_vector<const Tile *, 64> diff_tiles; diff_tiles.reserve(m_coverageInfo.m_tiles.size() + tiles.size()); set_difference(m_coverageInfo.m_tiles.begin(), m_coverageInfo.m_tiles.end(), tiles.begin(), tiles.end(), back_inserter(diff_tiles), CoverageInfo::TTileSet::key_compare()); firstTileForAdd = diff_tiles.size(); set_difference(tiles.begin(), tiles.end(), m_coverageInfo.m_tiles.begin(), m_coverageInfo.m_tiles.end(), back_inserter(diff_tiles), CoverageInfo::TTileSet::key_compare()); for (size_t i = 0; i < firstTileForAdd; ++i) tileCache.UnlockTile(diff_tiles[i]->m_rectInfo); for (size_t i = firstTileForAdd; i < diff_tiles.size(); ++i) tileCache.LockTile(diff_tiles[i]->m_rectInfo); tileCache.Unlock(); m_coverageInfo.m_tiles = tiles; MergeOverlay(); /// clearing all old commands m_coverageInfo.m_tileRenderer->ClearCommands(); /// setting new sequenceID m_coverageInfo.m_tileRenderer->SetSequenceID(m_stateInfo.m_sequenceID); /// @todo After ClearCommands i think we have no commands to cancel. m_coverageInfo.m_tileRenderer->CancelCommands(); m_benchmarkInfo.m_tilesCount = newRects.size(); m_benchmarkInfo.m_benchmarkSequenceID = m_stateInfo.m_sequenceID; for (size_t i = 0; i < newRects.size(); ++i) { Tiler::RectInfo const & ri = newRects[i]; core::CommandsQueue::Chain chain; chain.addCommand(bind(&CoverageGenerator::MergeTile, this, ri, m_stateInfo.m_sequenceID)); m_coverageInfo.m_tileRenderer->AddCommand(ri, m_stateInfo.m_sequenceID, chain); } } void CoverageGenerator::MergeOverlay() { m_coverageInfo.m_overlay->lock(); m_coverageInfo.m_overlay->clear(); for (CoverageInfo::TTileSet::const_iterator it = m_coverageInfo.m_tiles.begin(); it != m_coverageInfo.m_tiles.end(); ++it) { Tiler::RectInfo const & ri = (*it)->m_rectInfo; if (m_coverageInfo.m_tiler.isLeaf(ri)) m_coverageInfo.m_overlay->merge(*(*it)->m_overlay, (*it)->m_tileScreen.PtoGMatrix() * m_stateInfo.m_currentScreen.GtoPMatrix()); } m_coverageInfo.m_overlay->unlock(); } void CoverageGenerator::MergeSingleTile(Tiler::RectInfo const & rectInfo) { m_coverageInfo.m_tileRenderer->CacheActiveTile(rectInfo); TileCache & tileCache = m_coverageInfo.m_tileRenderer->GetTileCache(); tileCache.Lock(); Tile const * tile = NULL; if (tileCache.HasTile(rectInfo)) { tileCache.LockTile(rectInfo); tile = &tileCache.GetTile(rectInfo); } if (tile != NULL) { m_coverageInfo.m_tiles.insert(tile); if (m_coverageInfo.m_tiler.isLeaf(rectInfo)) { m_backCoverage->m_isEmptyDrawing &= tile->m_isEmptyDrawing; m_backCoverage->m_renderLeafTilesCount--; } } tileCache.Unlock(); if (tile != NULL && m_coverageInfo.m_tiler.isLeaf(rectInfo)) { m_coverageInfo.m_overlay->lock(); m_coverageInfo.m_overlay->merge(*tile->m_overlay, tile->m_tileScreen.PtoGMatrix() * m_stateInfo.m_currentScreen.GtoPMatrix()); m_coverageInfo.m_overlay->unlock(); } } namespace { bool SharpnessComparator(shared_ptr<graphics::OverlayElement> const & e1, shared_ptr<graphics::OverlayElement> const & e2) { return e1->hasSharpGeometry() && (!e2->hasSharpGeometry()); } } bool CoverageGenerator::CacheCoverage(core::CommandsQueue::Environment const & env) { delete m_backCoverage->m_mainElements; delete m_backCoverage->m_sharpElements; m_backCoverage->m_mainElements = m_cacheScreen->createDisplayList(); m_backCoverage->m_sharpElements = m_cacheScreen->createDisplayList(); m_cacheScreen->setEnvironment(&env); m_cacheScreen->beginFrame(); m_cacheScreen->setDisplayList(m_backCoverage->m_mainElements); vector<graphics::BlitInfo> infos; for (CoverageInfo::TTileSet::const_iterator it = m_coverageInfo.m_tiles.begin(); it != m_coverageInfo.m_tiles.end(); ++it) { Tile const * tile = *it; size_t tileWidth = tile->m_renderTarget->width(); size_t tileHeight = tile->m_renderTarget->height(); graphics::BlitInfo bi; bi.m_matrix = tile->m_tileScreen.PtoGMatrix() * m_stateInfo.m_currentScreen.GtoPMatrix(); bi.m_srcRect = m2::RectI(0, 0, tileWidth - 2, tileHeight - 2); bi.m_texRect = m2::RectU(1, 1, tileWidth - 1, tileHeight - 1); bi.m_srcSurface = tile->m_renderTarget; infos.push_back(bi); } if (!infos.empty()) m_cacheScreen->blit(&infos[0], infos.size(), true, graphics::minDepth); math::Matrix<double, 3, 3> idM = math::Identity<double, 3>(); m_coverageInfo.m_overlay->lock(); vector<shared_ptr<graphics::OverlayElement> > overlayElements; overlayElements.reserve(m_coverageInfo.m_overlay->getElementsCount()); m_coverageInfo.m_overlay->forEach(MakeBackInsertFunctor(overlayElements)); sort(overlayElements.begin(), overlayElements.end(), SharpnessComparator); unsigned currentElement = 0; for (; currentElement < overlayElements.size(); ++currentElement) { shared_ptr<graphics::OverlayElement> const & elem = overlayElements[currentElement]; if (elem->hasSharpGeometry()) break; elem->draw(m_cacheScreen.get(), idM); } m_cacheScreen->applySharpStates(); m_cacheScreen->setDisplayList(m_backCoverage->m_sharpElements); for (; currentElement < overlayElements.size(); ++currentElement) overlayElements[currentElement]->draw(m_cacheScreen.get(), idM); m_coverageInfo.m_overlay->unlock(); m_cacheScreen->setDisplayList(0); m_cacheScreen->applyStates(); m_cacheScreen->endFrame(); /// completing commands that was immediately executed /// while recording of displayList(for example UnlockStorage) m_cacheScreen->completeCommands(); bool isCancelled = m_cacheScreen->isCancelled(); m_cacheScreen->setEnvironment(0); return !isCancelled; } void CoverageGenerator::ClearCoverage() { { m_coverageInfo.m_overlay->lock(); m_coverageInfo.m_overlay->clear(); m_coverageInfo.m_overlay->unlock(); } TileCache & tileCache = m_coverageInfo.m_tileRenderer->GetTileCache(); tileCache.Lock(); for (CoverageInfo::TTileSet::const_iterator it = m_coverageInfo.m_tiles.begin(); it != m_coverageInfo.m_tiles.end(); ++it) { Tiler::RectInfo const & ri = (*it)->m_rectInfo; tileCache.UnlockTile(ri); } tileCache.Unlock(); m_coverageInfo.m_tiles.clear(); delete m_currentCoverage; m_currentCoverage = 0; delete m_backCoverage; m_backCoverage = 0; } //////////////////////////////////////////////////////////// /// BenchmarkInfo //////////////////////////////////////////////////////////// CoverageGenerator::BenchmarkInfo::BenchmarkInfo() : m_benchmarkSequenceID(numeric_limits<int>::max()) , m_tilesCount(-1) , m_fenceManager(2) , m_currentFenceID(-1) , m_isBenchmarking(false) { } void CoverageGenerator::BenchmarkInfo::DecrementTileCount(int sequenceID) { if (!m_isBenchmarking) return; if (sequenceID < m_benchmarkSequenceID) { m_tilesCount = -1; return; } m_tilesCount -= 1; } int CoverageGenerator::BenchmarkInfo::InsertBenchmarkFence() { ASSERT(m_isBenchmarking, ("Only for benchmark mode")); m_currentFenceID = m_fenceManager.insertFence(); return m_currentFenceID; } void CoverageGenerator::BenchmarkInfo::JoinBenchmarkFence(int fenceID) { ASSERT(m_isBenchmarking, ("Only for benchmark mode")); CHECK(fenceID == m_currentFenceID, ("InsertBenchmarkFence without corresponding SignalBenchmarkFence detected")); m_fenceManager.joinFence(fenceID); } void CoverageGenerator::BenchmarkInfo::SignalBenchmarkFence() { ASSERT(m_isBenchmarking, ("Only for benchmark mode")); if (m_currentFenceID != -1) m_fenceManager.signalFence(m_currentFenceID); } void CoverageGenerator::BenchmarkInfo::TryFinishSequence() { if (m_tilesCount == 0) { m_tilesCount = -1; SignalBenchmarkFence(); } } //////////////////////////////////////////////////////////// /// StateInfo //////////////////////////////////////////////////////////// CoverageGenerator::StateInfo::StateInfo() : m_isPause(false) , m_needForceUpdate(false) , m_sequenceID(0) { } void CoverageGenerator::StateInfo::SetSequenceID(int sequenceID) { m_sequenceID = sequenceID; } void CoverageGenerator::StateInfo::SetForceUpdate(bool needForceUpdate) { m_needForceUpdate = needForceUpdate; } void CoverageGenerator::StateInfo::Pause() { m_isPause = true; } void CoverageGenerator::StateInfo::Resume() { m_isPause = false; m_needForceUpdate = true; } //////////////////////////////////////////////////////////// /// CoverageGenerator //////////////////////////////////////////////////////////// CoverageGenerator::CoverageInfo::CoverageInfo(TileRenderer *tileRenderer) : m_tileRenderer(tileRenderer) , m_overlay(new graphics::Overlay()) { m_overlay->setCouldOverlap(false); } CoverageGenerator::CoverageInfo::~CoverageInfo() { delete m_overlay; } CoverageGenerator::CachedCoverageInfo::CachedCoverageInfo() : m_mainElements(NULL) , m_sharpElements(NULL) , m_renderLeafTilesCount(0) , m_isEmptyDrawing(false) { } CoverageGenerator::CachedCoverageInfo::~CachedCoverageInfo() { delete m_mainElements; delete m_sharpElements; }
/* * Copyright 2008-2009 NVIDIA Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*! \file reduce.inl * \brief Inline file for reduce.h */ #pragma once // do not attempt to compile this file with any other compiler #ifdef __CUDACC__ #include <thrust/device_vector.h> #include <thrust/host_vector.h> #include <thrust/device_malloc.h> #include <thrust/device_free.h> #include <thrust/reduce.h> // for second level reduction #include <thrust/detail/device/cuda/block/reduce.h> namespace thrust { namespace detail { namespace device { namespace cuda { /* * Reduction using a single thread. Only used for small vectors. * */ template<typename InputFunctor, typename OutputType, typename BinaryFunction> __global__ void __thrust__serial_reduce_kernel(InputFunctor input, const size_t n, OutputType * block_results, BinaryFunction binary_op) { if( threadIdx.x == 0 ) { OutputType accum = input[0]; for(unsigned int i = 1; i < n; i++){ accum = binary_op(accum, input[i]); } block_results[0] = accum; } } // end __thrust__serial_reduce_kernel() /* * Reduce a vector of n elements using binary_op(op()) * * The order of reduction is not defined, so binary_op() should * be a commutative (and associative) operator such as * (integer) addition. Since floating point operations * do not completely satisfy these criteria, the result is * generally not the same as a consecutive reduction of * the elements. * * Uses the same pattern as reduce6() in the CUDA SDK * */ template<typename InputFunctor, typename OutputType, typename BinaryFunction, unsigned int BLOCK_SIZE> __global__ void __thrust__unordered_reduce_kernel(InputFunctor input, const unsigned int n, OutputType * block_results, BinaryFunction binary_op) { __shared__ unsigned char sdata_workaround[BLOCK_SIZE * sizeof(OutputType)]; OutputType *sdata = reinterpret_cast<OutputType*>(sdata_workaround); // perform first level of reduction, // write per-block results to global memory for second level reduction const unsigned int grid_size = BLOCK_SIZE * gridDim.x; unsigned int i = blockIdx.x * BLOCK_SIZE + threadIdx.x; // accumulate local result OutputType accum = input[i]; i += grid_size; while (i < n) { accum = binary_op(accum, input[i]); i += grid_size; } // copy local result to shared mem and perform reduction sdata[threadIdx.x] = accum; __syncthreads(); // wait for all writes to finish if (BLOCK_SIZE >= 512) { if (threadIdx.x < 256) { sdata[threadIdx.x] = binary_op(sdata[threadIdx.x], sdata[threadIdx.x + 256]); } __syncthreads(); } if (BLOCK_SIZE >= 256) { if (threadIdx.x < 128) { sdata[threadIdx.x] = binary_op(sdata[threadIdx.x], sdata[threadIdx.x + 128]); } __syncthreads(); } if (BLOCK_SIZE >= 128) { if (threadIdx.x < 64) { sdata[threadIdx.x] = binary_op(sdata[threadIdx.x], sdata[threadIdx.x + 64]); } __syncthreads(); } if (BLOCK_SIZE >= 64) { if (threadIdx.x < 32) { sdata[threadIdx.x] = binary_op(sdata[threadIdx.x], sdata[threadIdx.x + 32]); } __syncthreads(); } if (BLOCK_SIZE >= 32) { if (threadIdx.x < 16) { sdata[threadIdx.x] = binary_op(sdata[threadIdx.x], sdata[threadIdx.x + 16]); } __syncthreads(); } if (BLOCK_SIZE >= 16) { if (threadIdx.x < 8) { sdata[threadIdx.x] = binary_op(sdata[threadIdx.x], sdata[threadIdx.x + 8]); } __syncthreads(); } if (BLOCK_SIZE >= 8) { if (threadIdx.x < 4) { sdata[threadIdx.x] = binary_op(sdata[threadIdx.x], sdata[threadIdx.x + 4]); } __syncthreads(); } if (BLOCK_SIZE >= 4) { if (threadIdx.x < 2) { sdata[threadIdx.x] = binary_op(sdata[threadIdx.x], sdata[threadIdx.x + 2]); } __syncthreads(); } if (BLOCK_SIZE >= 2) { if (threadIdx.x < 1) { sdata[threadIdx.x] = binary_op(sdata[threadIdx.x], sdata[threadIdx.x + 1]); } __syncthreads(); } // XXX causes the following problem on CUDA 2.2 (Komrade issue #6) // Advisory: Cannot tell what pointer points to, assuming global memory space //accum = thrust::detail::block::reduce<OutputType,BinaryFunction,BLOCK_SIZE> // (sdata, threadIdx.x, binary_op); // write result for this block to global mem if (threadIdx.x == 0) block_results[blockIdx.x] = sdata[threadIdx.x]; } // end __thrust__unordered_reduce_kernel() template<typename InputFunctor, typename OutputType, typename BinaryFunction> OutputType reduce(InputFunctor input, const size_t n, const OutputType init, BinaryFunction binary_op) { const size_t BLOCK_SIZE = 256; // BLOCK_SIZE must be a power of 2 const size_t MAX_BLOCKS = 3 * experimental::arch::max_active_threads() / BLOCK_SIZE; unsigned int GRID_SIZE; // handle zero length array case first if( n == 0 ) return init; // TODO if n < UINT_MAX use unsigned int instead of size_t indices in kernel // kernels below assume n > 0 if( n < BLOCK_SIZE ) { GRID_SIZE = 1; } else { GRID_SIZE = std::min( (n / BLOCK_SIZE), MAX_BLOCKS); } // allocate storage for per-block results thrust::device_ptr<OutputType> block_results = thrust::device_malloc<OutputType>(GRID_SIZE); // do the gpu part if( n < BLOCK_SIZE ) { __thrust__serial_reduce_kernel<InputFunctor, OutputType, BinaryFunction> <<<GRID_SIZE, 1>>>(input, n, block_results.get(), binary_op); } else { __thrust__unordered_reduce_kernel<InputFunctor, OutputType, BinaryFunction, BLOCK_SIZE> <<<GRID_SIZE, BLOCK_SIZE>>>(input, n, block_results.get(), binary_op); } // copy work array to host thrust::host_vector<OutputType> host_work(block_results, block_results + GRID_SIZE); // free device work array thrust::device_free(block_results); // reduce on the host return thrust::reduce(host_work.begin(), host_work.end(), init, binary_op); } // end reduce() } // end namespace cuda } // end namespace device } // end namespace detail } // end namespace thrust #endif // __CUDACC__ Use raw_buffer in reduce. --HG-- extra : convert_revision : svn%3A83215879-3e5a-4751-8c9d-778f44bb06a5/trunk%40337 /* * Copyright 2008-2009 NVIDIA Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*! \file reduce.inl * \brief Inline file for reduce.h */ #pragma once // do not attempt to compile this file with any other compiler #ifdef __CUDACC__ #include <thrust/iterator/iterator_traits.h> #include <thrust/detail/raw_buffer.h> #include <thrust/reduce.h> // for second level reduction #include <thrust/detail/device/cuda/block/reduce.h> namespace thrust { namespace detail { namespace device { namespace cuda { /* * Reduction using a single thread. Only used for small vectors. * */ template<typename InputFunctor, typename OutputType, typename BinaryFunction> __global__ void __thrust__serial_reduce_kernel(InputFunctor input, const size_t n, OutputType * block_results, BinaryFunction binary_op) { if( threadIdx.x == 0 ) { OutputType accum = input[0]; for(unsigned int i = 1; i < n; i++){ accum = binary_op(accum, input[i]); } block_results[0] = accum; } } // end __thrust__serial_reduce_kernel() /* * Reduce a vector of n elements using binary_op(op()) * * The order of reduction is not defined, so binary_op() should * be a commutative (and associative) operator such as * (integer) addition. Since floating point operations * do not completely satisfy these criteria, the result is * generally not the same as a consecutive reduction of * the elements. * * Uses the same pattern as reduce6() in the CUDA SDK * */ template<typename InputFunctor, typename OutputType, typename BinaryFunction, unsigned int BLOCK_SIZE> __global__ void __thrust__unordered_reduce_kernel(InputFunctor input, const unsigned int n, OutputType * block_results, BinaryFunction binary_op) { __shared__ unsigned char sdata_workaround[BLOCK_SIZE * sizeof(OutputType)]; OutputType *sdata = reinterpret_cast<OutputType*>(sdata_workaround); // perform first level of reduction, // write per-block results to global memory for second level reduction const unsigned int grid_size = BLOCK_SIZE * gridDim.x; unsigned int i = blockIdx.x * BLOCK_SIZE + threadIdx.x; // accumulate local result OutputType accum = input[i]; i += grid_size; while (i < n) { accum = binary_op(accum, input[i]); i += grid_size; } // copy local result to shared mem and perform reduction sdata[threadIdx.x] = accum; __syncthreads(); // wait for all writes to finish if (BLOCK_SIZE >= 512) { if (threadIdx.x < 256) { sdata[threadIdx.x] = binary_op(sdata[threadIdx.x], sdata[threadIdx.x + 256]); } __syncthreads(); } if (BLOCK_SIZE >= 256) { if (threadIdx.x < 128) { sdata[threadIdx.x] = binary_op(sdata[threadIdx.x], sdata[threadIdx.x + 128]); } __syncthreads(); } if (BLOCK_SIZE >= 128) { if (threadIdx.x < 64) { sdata[threadIdx.x] = binary_op(sdata[threadIdx.x], sdata[threadIdx.x + 64]); } __syncthreads(); } if (BLOCK_SIZE >= 64) { if (threadIdx.x < 32) { sdata[threadIdx.x] = binary_op(sdata[threadIdx.x], sdata[threadIdx.x + 32]); } __syncthreads(); } if (BLOCK_SIZE >= 32) { if (threadIdx.x < 16) { sdata[threadIdx.x] = binary_op(sdata[threadIdx.x], sdata[threadIdx.x + 16]); } __syncthreads(); } if (BLOCK_SIZE >= 16) { if (threadIdx.x < 8) { sdata[threadIdx.x] = binary_op(sdata[threadIdx.x], sdata[threadIdx.x + 8]); } __syncthreads(); } if (BLOCK_SIZE >= 8) { if (threadIdx.x < 4) { sdata[threadIdx.x] = binary_op(sdata[threadIdx.x], sdata[threadIdx.x + 4]); } __syncthreads(); } if (BLOCK_SIZE >= 4) { if (threadIdx.x < 2) { sdata[threadIdx.x] = binary_op(sdata[threadIdx.x], sdata[threadIdx.x + 2]); } __syncthreads(); } if (BLOCK_SIZE >= 2) { if (threadIdx.x < 1) { sdata[threadIdx.x] = binary_op(sdata[threadIdx.x], sdata[threadIdx.x + 1]); } __syncthreads(); } // XXX causes the following problem on CUDA 2.2 (Komrade issue #6) // Advisory: Cannot tell what pointer points to, assuming global memory space //accum = thrust::detail::block::reduce<OutputType,BinaryFunction,BLOCK_SIZE> // (sdata, threadIdx.x, binary_op); // write result for this block to global mem if (threadIdx.x == 0) block_results[blockIdx.x] = sdata[threadIdx.x]; } // end __thrust__unordered_reduce_kernel() template<typename InputFunctor, typename OutputType, typename BinaryFunction> OutputType reduce(InputFunctor input, const size_t n, const OutputType init, BinaryFunction binary_op) { const size_t BLOCK_SIZE = 256; // BLOCK_SIZE must be a power of 2 const size_t MAX_BLOCKS = 3 * experimental::arch::max_active_threads() / BLOCK_SIZE; unsigned int GRID_SIZE; // handle zero length array case first if( n == 0 ) return init; // TODO if n < UINT_MAX use unsigned int instead of size_t indices in kernel // kernels below assume n > 0 if( n < BLOCK_SIZE ) { GRID_SIZE = 1; } else { GRID_SIZE = std::min( (n / BLOCK_SIZE), MAX_BLOCKS); } // allocate storage for per-block results raw_buffer<OutputType, experimental::space::device> block_results(GRID_SIZE); // do the gpu part if( n < BLOCK_SIZE ) { __thrust__serial_reduce_kernel<InputFunctor, OutputType, BinaryFunction> <<<GRID_SIZE, 1>>>(input, n, raw_pointer_cast(&block_results[0]), binary_op); } else { __thrust__unordered_reduce_kernel<InputFunctor, OutputType, BinaryFunction, BLOCK_SIZE> <<<GRID_SIZE, BLOCK_SIZE>>>(input, n, raw_pointer_cast(&block_results[0]), binary_op); } // copy work array to host raw_buffer<OutputType, experimental::space::host> host_work(block_results.begin(), block_results.end()); // reduce on the host return thrust::reduce(host_work.begin(), host_work.end(), init, binary_op); } // end reduce() } // end namespace cuda } // end namespace device } // end namespace detail } // end namespace thrust #endif // __CUDACC__
#include <gtest/gtest.h> #include <string> #include <vector> #include <cpr/cpr.h> #include "httpServer.hpp" using namespace cpr; static HttpServer* server = new HttpServer(); std::chrono::milliseconds sleep_time{50}; std::chrono::seconds zero{0}; int status_callback(int& status_code, Response r) { status_code = r.status_code; return r.status_code; } int status_callback_ref(int& status_code, const Response& r) { status_code = r.status_code; return r.status_code; } std::string text_callback(std::string& expected_text, Response r) { expected_text = r.text; return r.text; } std::string text_callback_ref(std::string& expected_text, const Response& r) { expected_text = r.text; return r.text; } TEST(CallbackGetTests, CallbackGetLambdaStatusTest) { Url url{server->GetBaseUrl() + "/hello.html"}; int status_code = 0; auto future = cpr::GetCallback( [&status_code](Response r) { status_code = r.status_code; return r.status_code; }, url); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(status_code, future.get()); } TEST(CallbackGetTests, CallbackGetLambdaTextTest) { Url url{server->GetBaseUrl() + "/hello.html"}; std::string expected_text{}; auto future = cpr::GetCallback( [&expected_text](Response r) { expected_text = r.text; return r.text; }, url); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(expected_text, future.get()); } TEST(CallbackGetTests, CallbackGetLambdaStatusReferenceTest) { Url url{server->GetBaseUrl() + "/hello.html"}; int status_code = 0; auto future = cpr::GetCallback( [&status_code](const Response& r) { status_code = r.status_code; return r.status_code; }, url); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(status_code, future.get()); } TEST(CallbackGetTests, CallbackGetLambdaTextReferenceTest) { Url url{server->GetBaseUrl() + "/hello.html"}; std::string expected_text{}; auto future = cpr::GetCallback( [&expected_text](const Response& r) { expected_text = r.text; return r.text; }, url); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(expected_text, future.get()); } TEST(CallbackGetTests, CallbackGetFunctionStatusTest) { Url url{server->GetBaseUrl() + "/hello.html"}; int status_code = 0; auto callback = std::function<int(Response)>( std::bind(status_callback, std::ref(status_code), std::placeholders::_1)); auto future = cpr::GetCallback(callback, url); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(status_code, future.get()); } TEST(CallbackGetTests, CallbackGetFunctionTextTest) { Url url{server->GetBaseUrl() + "/hello.html"}; std::string expected_text{}; auto callback = std::function<std::string(Response)>( std::bind(text_callback, std::ref(expected_text), std::placeholders::_1)); auto future = cpr::GetCallback(callback, url); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(expected_text, future.get()); } TEST(CallbackGetTests, CallbackGetFunctionStatusReferenceTest) { Url url{server->GetBaseUrl() + "/hello.html"}; int status_code = 0; auto callback = std::function<int(Response)>( std::bind(status_callback_ref, std::ref(status_code), std::placeholders::_1)); auto future = cpr::GetCallback(callback, url); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(status_code, future.get()); } TEST(CallbackGetTests, CallbackGetFunctionTextReferenceTest) { Url url{server->GetBaseUrl() + "/hello.html"}; std::string expected_text{}; auto callback = std::function<std::string(Response)>( std::bind(text_callback_ref, std::ref(expected_text), std::placeholders::_1)); auto future = cpr::GetCallback(callback, url); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(expected_text, future.get()); } TEST(CallbackDeleteTests, CallbackDeleteLambdaStatusTest) { Url url{server->GetBaseUrl() + "/delete.html"}; int status_code = 0; auto future = cpr::DeleteCallback( [&status_code](Response r) { status_code = r.status_code; return r.status_code; }, url); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(status_code, future.get()); } TEST(CallbackDeleteTests, CallbackDeleteLambdaTextTest) { Url url{server->GetBaseUrl() + "/delete.html"}; std::string expected_text{}; auto future = cpr::DeleteCallback( [&expected_text](Response r) { expected_text = r.text; return r.text; }, url); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(expected_text, future.get()); } TEST(CallbackDeleteTests, CallbackDeleteLambdaStatusReferenceTest) { Url url{server->GetBaseUrl() + "/delete.html"}; int status_code = 0; auto future = cpr::DeleteCallback( [&status_code](const Response& r) { status_code = r.status_code; return r.status_code; }, url); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(status_code, future.get()); } TEST(CallbackDeleteTests, CallbackDeleteLambdaTextReferenceTest) { Url url{server->GetBaseUrl() + "/delete.html"}; std::string expected_text{}; auto future = cpr::DeleteCallback( [&expected_text](const Response& r) { expected_text = r.text; return r.text; }, url); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(expected_text, future.get()); } TEST(CallbackDeleteTests, CallbackDeleteFunctionStatusTest) { Url url{server->GetBaseUrl() + "/delete.html"}; int status_code = 0; auto callback = std::function<int(Response)>( std::bind(status_callback, std::ref(status_code), std::placeholders::_1)); auto future = cpr::DeleteCallback(callback, url); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(status_code, future.get()); } TEST(CallbackDeleteTests, CallbackDeleteFunctionTextTest) { Url url{server->GetBaseUrl() + "/delete.html"}; std::string expected_text{}; auto callback = std::function<std::string(Response)>( std::bind(text_callback, std::ref(expected_text), std::placeholders::_1)); auto future = cpr::DeleteCallback(callback, url); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(expected_text, future.get()); } TEST(CallbackDeleteTests, CallbackDeleteFunctionStatusReferenceTest) { Url url{server->GetBaseUrl() + "/delete.html"}; int status_code = 0; auto callback = std::function<int(Response)>( std::bind(status_callback_ref, std::ref(status_code), std::placeholders::_1)); auto future = cpr::DeleteCallback(callback, url); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(status_code, future.get()); } TEST(CallbackDeleteTests, CallbackDeleteFunctionTextReferenceTest) { Url url{server->GetBaseUrl() + "/delete.html"}; std::string expected_text{}; auto callback = std::function<std::string(Response)>( std::bind(text_callback_ref, std::ref(expected_text), std::placeholders::_1)); auto future = cpr::DeleteCallback(callback, url); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(expected_text, future.get()); } TEST(CallbackHeadTests, CallbackHeadLambdaStatusTest) { Url url{server->GetBaseUrl() + "/hello.html"}; int status_code = 0; auto future = cpr::HeadCallback( [&status_code](Response r) { status_code = r.status_code; return r.status_code; }, url); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(status_code, future.get()); } TEST(CallbackHeadTests, CallbackHeadLambdaTextTest) { Url url{server->GetBaseUrl() + "/hello.html"}; std::string expected_text{}; auto future = cpr::HeadCallback( [&expected_text](Response r) { expected_text = r.text; return r.text; }, url); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(expected_text, future.get()); } TEST(CallbackHeadTests, CallbackHeadLambdaStatusReferenceTest) { Url url{server->GetBaseUrl() + "/hello.html"}; int status_code = 0; auto future = cpr::HeadCallback( [&status_code](const Response& r) { status_code = r.status_code; return r.status_code; }, url); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(status_code, future.get()); } TEST(CallbackHeadTests, CallbackHeadLambdaTextReferenceTest) { Url url{server->GetBaseUrl() + "/hello.html"}; std::string expected_text{}; auto future = cpr::HeadCallback( [&expected_text](const Response& r) { expected_text = r.text; return r.text; }, url); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(expected_text, future.get()); } TEST(CallbackHeadTests, CallbackHeadFunctionStatusTest) { Url url{server->GetBaseUrl() + "/hello.html"}; int status_code = 0; auto callback = std::function<int(Response)>( std::bind(status_callback, std::ref(status_code), std::placeholders::_1)); auto future = cpr::HeadCallback(callback, url); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(status_code, future.get()); } TEST(CallbackHeadTests, CallbackHeadFunctionTextTest) { Url url{server->GetBaseUrl() + "/hello.html"}; std::string expected_text{}; auto callback = std::function<std::string(Response)>( std::bind(text_callback, std::ref(expected_text), std::placeholders::_1)); auto future = cpr::HeadCallback(callback, url); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(expected_text, future.get()); } TEST(CallbackHeadTests, CallbackHeadFunctionStatusReferenceTest) { Url url{server->GetBaseUrl() + "/hello.html"}; int status_code = 0; auto callback = std::function<int(Response)>( std::bind(status_callback_ref, std::ref(status_code), std::placeholders::_1)); auto future = cpr::HeadCallback(callback, url); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(status_code, future.get()); } TEST(CallbackHeadTests, CallbackHeadFunctionTextReferenceTest) { Url url{server->GetBaseUrl() + "/hello.html"}; std::string expected_text{}; auto callback = std::function<std::string(Response)>( std::bind(text_callback_ref, std::ref(expected_text), std::placeholders::_1)); auto future = cpr::HeadCallback(callback, url); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(expected_text, future.get()); } TEST(CallbackPostTests, CallbackPostLambdaStatusTest) { Url url{server->GetBaseUrl() + "/url_post.html"}; Payload payload{{"x", "5"}}; int status_code = 0; auto future = cpr::PostCallback( [&status_code](Response r) { status_code = r.status_code; return r.status_code; }, url, payload); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(status_code, future.get()); } TEST(CallbackPostTests, CallbackPostLambdaTextTest) { Url url{server->GetBaseUrl() + "/url_post.html"}; Payload payload{{"x", "5"}}; std::string expected_text{}; auto future = cpr::PostCallback( [&expected_text](Response r) { expected_text = r.text; return r.text; }, url, payload); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(expected_text, future.get()); } TEST(CallbackPostTests, CallbackPostLambdaStatusReferenceTest) { Url url{server->GetBaseUrl() + "/url_post.html"}; Payload payload{{"x", "5"}}; int status_code = 0; auto future = cpr::PostCallback( [&status_code](const Response& r) { status_code = r.status_code; return r.status_code; }, url, payload); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(status_code, future.get()); } TEST(CallbackPostTests, CallbackPostLambdaTextReferenceTest) { Url url{server->GetBaseUrl() + "/url_post.html"}; Payload payload{{"x", "5"}}; std::string expected_text{}; auto future = cpr::PostCallback( [&expected_text](const Response& r) { expected_text = r.text; return r.text; }, url, payload); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(expected_text, future.get()); } TEST(CallbackPostTests, CallbackPostFunctionStatusTest) { Url url{server->GetBaseUrl() + "/url_post.html"}; Payload payload{{"x", "5"}}; int status_code = 0; auto callback = std::function<int(Response)>( std::bind(status_callback, std::ref(status_code), std::placeholders::_1)); auto future = cpr::PostCallback(callback, url, payload); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(status_code, future.get()); } TEST(CallbackPostTests, CallbackPostFunctionTextTest) { Url url{server->GetBaseUrl() + "/url_post.html"}; Payload payload{{"x", "5"}}; std::string expected_text{}; auto callback = std::function<std::string(Response)>( std::bind(text_callback, std::ref(expected_text), std::placeholders::_1)); auto future = cpr::PostCallback(callback, url, payload); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(expected_text, future.get()); } TEST(CallbackPostTests, CallbackPostFunctionStatusReferenceTest) { Url url{server->GetBaseUrl() + "/url_post.html"}; Payload payload{{"x", "5"}}; int status_code = 0; auto callback = std::function<int(Response)>( std::bind(status_callback_ref, std::ref(status_code), std::placeholders::_1)); auto future = cpr::PostCallback(callback, url, payload); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(status_code, future.get()); } TEST(CallbackPostTests, CallbackPostFunctionTextReferenceTest) { Url url{server->GetBaseUrl() + "/url_post.html"}; Payload payload{{"x", "5"}}; std::string expected_text{}; auto callback = std::function<std::string(Response)>( std::bind(text_callback_ref, std::ref(expected_text), std::placeholders::_1)); auto future = cpr::PostCallback(callback, url, payload); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(expected_text, future.get()); } TEST(CallbackPutTests, CallbackPutLambdaStatusTest) { Url url{server->GetBaseUrl() + "/url_post.html"}; Payload payload{{"x", "5"}}; int status_code = 0; auto future = cpr::PutCallback( [&status_code](Response r) { status_code = r.status_code; return r.status_code; }, url, payload); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(status_code, future.get()); } TEST(CallbackPutTests, CallbackPutLambdaTextTest) { Url url{server->GetBaseUrl() + "/url_post.html"}; Payload payload{{"x", "5"}}; std::string expected_text{}; auto future = cpr::PutCallback( [&expected_text](Response r) { expected_text = r.text; return r.text; }, url, payload); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(expected_text, future.get()); } TEST(CallbackPutTests, CallbackPutLambdaStatusReferenceTest) { Url url{server->GetBaseUrl() + "/url_post.html"}; Payload payload{{"x", "5"}}; int status_code = 0; auto future = cpr::PutCallback( [&status_code](const Response& r) { status_code = r.status_code; return r.status_code; }, url, payload); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(status_code, future.get()); } TEST(CallbackPutTests, CallbackPutLambdaTextReferenceTest) { Url url{server->GetBaseUrl() + "/url_post.html"}; Payload payload{{"x", "5"}}; std::string expected_text{}; auto future = cpr::PutCallback( [&expected_text](const Response& r) { expected_text = r.text; return r.text; }, url, payload); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(expected_text, future.get()); } TEST(CallbackPutTests, CallbackPutFunctionStatusTest) { Url url{server->GetBaseUrl() + "/url_post.html"}; Payload payload{{"x", "5"}}; int status_code = 0; auto callback = std::function<int(Response)>( std::bind(status_callback, std::ref(status_code), std::placeholders::_1)); auto future = cpr::PutCallback(callback, url, payload); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(status_code, future.get()); } TEST(CallbackPutTests, CallbackPutFunctionTextTest) { Url url{server->GetBaseUrl() + "/url_post.html"}; Payload payload{{"x", "5"}}; std::string expected_text{}; auto callback = std::function<std::string(Response)>( std::bind(text_callback, std::ref(expected_text), std::placeholders::_1)); auto future = cpr::PutCallback(callback, url, payload); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(expected_text, future.get()); } TEST(CallbackPutTests, CallbackPutFunctionStatusReferenceTest) { Url url{server->GetBaseUrl() + "/url_post.html"}; Payload payload{{"x", "5"}}; int status_code = 0; auto callback = std::function<int(Response)>( std::bind(status_callback_ref, std::ref(status_code), std::placeholders::_1)); auto future = cpr::PutCallback(callback, url, payload); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(status_code, future.get()); } TEST(CallbackPutTests, CallbackPutFunctionTextReferenceTest) { Url url{server->GetBaseUrl() + "/url_post.html"}; Payload payload{{"x", "5"}}; std::string expected_text{}; auto callback = std::function<std::string(Response)>( std::bind(text_callback_ref, std::ref(expected_text), std::placeholders::_1)); auto future = cpr::PutCallback(callback, url, payload); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(expected_text, future.get()); } TEST(CallbackOptionsTests, CallbackOptionsLambdaStatusTest) { Url url{server->GetBaseUrl() + "/hello.html"}; int status_code = 0; auto future = cpr::OptionsCallback( [&status_code](Response r) { status_code = r.status_code; return r.status_code; }, url); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(status_code, future.get()); } TEST(CallbackOptionsTests, CallbackOptionsLambdaTextTest) { Url url{server->GetBaseUrl() + "/hello.html"}; std::string expected_text{}; auto future = cpr::OptionsCallback( [&expected_text](Response r) { expected_text = r.text; return r.text; }, url); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(expected_text, future.get()); } TEST(CallbackOptionsTests, CallbackOptionsLambdaStatusReferenceTest) { Url url{server->GetBaseUrl() + "/hello.html"}; int status_code = 0; auto future = cpr::OptionsCallback( [&status_code](const Response& r) { status_code = r.status_code; return r.status_code; }, url); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(status_code, future.get()); } TEST(CallbackOptionsTests, CallbackOptionsLambdaTextReferenceTest) { Url url{server->GetBaseUrl() + "/hello.html"}; std::string expected_text{}; auto future = cpr::OptionsCallback( [&expected_text](const Response& r) { expected_text = r.text; return r.text; }, url); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(expected_text, future.get()); } TEST(CallbackOptionsTests, CallbackOptionsFunctionStatusTest) { Url url{server->GetBaseUrl() + "/hello.html"}; int status_code = 0; auto callback = std::function<int(Response)>( std::bind(status_callback, std::ref(status_code), std::placeholders::_1)); auto future = cpr::OptionsCallback(callback, url); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(status_code, future.get()); } TEST(CallbackOptionsTests, CallbackOptionsFunctionTextTest) { Url url{server->GetBaseUrl() + "/hello.html"}; std::string expected_text{}; auto callback = std::function<std::string(Response)>( std::bind(text_callback, std::ref(expected_text), std::placeholders::_1)); auto future = cpr::OptionsCallback(callback, url); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(expected_text, future.get()); } TEST(CallbackOptionsTests, CallbackOptionsFunctionStatusReferenceTest) { Url url{server->GetBaseUrl() + "/hello.html"}; int status_code = 0; auto callback = std::function<int(Response)>( std::bind(status_callback_ref, std::ref(status_code), std::placeholders::_1)); auto future = cpr::OptionsCallback(callback, url); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(status_code, future.get()); } TEST(CallbackOptionsTests, CallbackOptionsFunctionTextReferenceTest) { Url url{server->GetBaseUrl() + "/hello.html"}; std::string expected_text{}; auto callback = std::function<std::string(Response)>( std::bind(text_callback_ref, std::ref(expected_text), std::placeholders::_1)); auto future = cpr::OptionsCallback(callback, url); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(expected_text, future.get()); } TEST(CallbackPatchTests, CallbackPatchLambdaStatusTest) { Url url{server->GetBaseUrl() + "/url_post.html"}; Payload payload{{"x", "5"}}; int status_code = 0; auto future = cpr::PatchCallback( [&status_code](Response r) { status_code = r.status_code; return r.status_code; }, url, payload); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(status_code, future.get()); } TEST(CallbackPatchTests, CallbackPatchLambdaTextTest) { Url url{server->GetBaseUrl() + "/url_post.html"}; Payload payload{{"x", "5"}}; std::string expected_text{}; auto future = cpr::PatchCallback( [&expected_text](Response r) { expected_text = r.text; return r.text; }, url, payload); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(expected_text, future.get()); } TEST(CallbackPatchTests, CallbackPatchLambdaStatusReferenceTest) { Url url{server->GetBaseUrl() + "/url_post.html"}; Payload payload{{"x", "5"}}; int status_code = 0; auto future = cpr::PatchCallback( [&status_code](const Response& r) { status_code = r.status_code; return r.status_code; }, url, payload); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(status_code, future.get()); } TEST(CallbackPatchTests, CallbackPatchLambdaTextReferenceTest) { Url url{server->GetBaseUrl() + "/url_post.html"}; Payload payload{{"x", "5"}}; std::string expected_text{}; auto future = cpr::PatchCallback( [&expected_text](const Response& r) { expected_text = r.text; return r.text; }, url, payload); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(expected_text, future.get()); } TEST(CallbackPatchTests, CallbackPatchFunctionStatusTest) { Url url{server->GetBaseUrl() + "/url_post.html"}; Payload payload{{"x", "5"}}; int status_code = 0; auto callback = std::function<int(Response)>( std::bind(status_callback, std::ref(status_code), std::placeholders::_1)); auto future = cpr::PatchCallback(callback, url, payload); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(status_code, future.get()); } TEST(CallbackPatchTests, CallbackPatchFunctionTextTest) { Url url{server->GetBaseUrl() + "/url_post.html"}; Payload payload{{"x", "5"}}; std::string expected_text{}; auto callback = std::function<std::string(Response)>( std::bind(text_callback, std::ref(expected_text), std::placeholders::_1)); auto future = cpr::PatchCallback(callback, url, payload); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(expected_text, future.get()); } TEST(CallbackPatchTests, CallbackPatchFunctionStatusReferenceTest) { Url url{server->GetBaseUrl() + "/url_post.html"}; Payload payload{{"x", "5"}}; int status_code = 0; auto callback = std::function<int(Response)>( std::bind(status_callback_ref, std::ref(status_code), std::placeholders::_1)); auto future = cpr::PatchCallback(callback, url, payload); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(status_code, future.get()); } TEST(CallbackPatchTests, CallbackPatchFunctionTextReferenceTest) { Url url{server->GetBaseUrl() + "/url_post.html"}; Payload payload{{"x", "5"}}; std::string expected_text{}; auto callback = std::function<std::string(Response)>( std::bind(text_callback_ref, std::ref(expected_text), std::placeholders::_1)); auto future = cpr::PatchCallback(callback, url, payload); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(expected_text, future.get()); } TEST(CallbackDataTests, CallbackReadFunctionCancelTest) { Url url{server->GetBaseUrl() + "/url_post.html"}; Response response = cpr::Post(url, cpr::ReadCallback([](char* buffer, size_t & size) -> size_t { return false; })); EXPECT_EQ(response.error.code, ErrorCode::REQUEST_CANCELLED); } TEST(CallbackDataTests, CallbackReadFunctionTextTest) { Url url{server->GetBaseUrl() + "/url_post.html"}; std::string expected_text{ "{\n" " \"x\": 5\n" "}"}; unsigned count = 0; Response response = cpr::Post(url, cpr::ReadCallback{3, [&](char* buffer, size_t & size) -> size_t { std::string data; ++ count; switch (count) { case 1: data = "x="; break; case 2: data = "5"; break; default: return false; } std::copy(data.begin(), data.end(), buffer); size = data.size(); return true; }}); EXPECT_EQ(2, count); EXPECT_EQ(expected_text, response.text); } /* cesanta mongoose doesn't support chunked requests yet TEST(CallbackDataTests, CallbackReadFunctionChunkedTest) { Url url{server->GetBaseUrl() + "/url_post.html"}; std::string expected_text{ "{\n" " \"x\": 5\n" "}"}; unsigned count = 0; Response response = cpr::Post(url, cpr::ReadCallback{[&count](char* buffer, size_t & size) -> size_t { std::string data; ++ count; switch (count) { case 1: data = "x="; break; case 2: data = "5"; break; default: data = ""; break; } std::copy(data.begin(), data.end(), buffer); size = data.size(); return true; }}); EXPECT_EQ(3, count); EXPECT_EQ(expected_text, response.text); } */ TEST(CallbackDataTests, CallbackHeaderFunctionCancelTest) { Url url{server->GetBaseUrl() + "/url_post.html"}; Response response = Post(url, HeaderCallback{[](std::string header) -> bool { return false; }}); EXPECT_EQ(response.error.code, ErrorCode::REQUEST_CANCELLED); } TEST(CallbackDataTests, CallbackHeaderFunctionTextTest) { Url url{server->GetBaseUrl() + "/url_post.html"}; std::vector<std::string> expected_headers{ "HTTP/1.1 201 OK\r\n", "Content-Type: application/json\r\n", "\r\n" }; std::set<std::string> response_headers; Post(url, HeaderCallback{[&response_headers](std::string header) -> bool { response_headers.insert(header); return true; }}); for (std::string & header : expected_headers) { EXPECT_TRUE(response_headers.count(header)); } } TEST(CallbackDataTests, CallbackWriteFunctionCancelTest) { Url url{server->GetBaseUrl() + "/url_post.html"}; Response response = Post(url, WriteCallback{[](std::string header) -> bool { return false; }}); EXPECT_EQ(response.error.code, ErrorCode::REQUEST_CANCELLED); } TEST(CallbackDataTests, CallbackWriteFunctionTextTest) { Url url{server->GetBaseUrl() + "/url_post.html"}; std::string expected_text{ "{\n" " \"x\": 5\n" "}"}; std::string response_text; Post(url, Payload{{"x", "5"}}, WriteCallback{[&response_text](std::string header) -> bool { response_text.append(header); return true; }}); EXPECT_EQ(expected_text, response_text); } TEST(CallbackDataTests, CallbackProgressFunctionCancelTest) { Url url{server->GetBaseUrl() + "/url_post.html"}; Response response = Post(url, ProgressCallback{[](size_t downloadTotal, size_t downloadNow, size_t uploadTotal, size_t uploadNow) -> bool { return false; }}); EXPECT_EQ(response.error.code, ErrorCode::REQUEST_CANCELLED); } TEST(CallbackDataTests, CallbackProgressFunctionTotalTest) { Url url{server->GetBaseUrl() + "/url_post.html"}; Body body{"x=5"}; size_t response_upload = 0, response_download = 0; Response response = Post(url, body, ProgressCallback{[&](size_t downloadTotal, size_t downloadNow, size_t uploadTotal, size_t uploadNow) -> bool { response_upload = uploadTotal; response_download = downloadTotal; return true; }}); EXPECT_EQ(body.str().length(), response_upload); EXPECT_EQ(response.text.length(), response_download); } TEST(CallbackDataTests, CallbackDebugFunctionTextTest) { Url url{server->GetBaseUrl() + "/url_post.html"}; Body body{"x=5"}; std::string debug_body; Response response = Post(url, body, DebugCallback{[&](DebugCallback::InfoType type, std::string data) { if (type == DebugCallback::InfoType::DATA_OUT) { debug_body = data; } }}); EXPECT_EQ(body.str(), debug_body); } int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); ::testing::AddGlobalTestEnvironment(server); return RUN_ALL_TESTS(); } Added a test case for #517 #include <cstddef> #include <gtest/gtest.h> #include <string> #include <vector> #include <cpr/cpr.h> #include "cpr/cprtypes.h" #include "httpServer.hpp" using namespace cpr; static HttpServer* server = new HttpServer(); std::chrono::milliseconds sleep_time{50}; std::chrono::seconds zero{0}; int status_callback(int& status_code, Response r) { status_code = r.status_code; return r.status_code; } int status_callback_ref(int& status_code, const Response& r) { status_code = r.status_code; return r.status_code; } std::string text_callback(std::string& expected_text, Response r) { expected_text = r.text; return r.text; } std::string text_callback_ref(std::string& expected_text, const Response& r) { expected_text = r.text; return r.text; } TEST(CallbackGetTests, CallbackGetLambdaStatusTest) { Url url{server->GetBaseUrl() + "/hello.html"}; int status_code = 0; auto future = cpr::GetCallback( [&status_code](Response r) { status_code = r.status_code; return r.status_code; }, url); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(status_code, future.get()); } TEST(CallbackGetTests, CallbackGetLambdaTextTest) { Url url{server->GetBaseUrl() + "/hello.html"}; std::string expected_text{}; auto future = cpr::GetCallback( [&expected_text](Response r) { expected_text = r.text; return r.text; }, url); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(expected_text, future.get()); } TEST(CallbackGetTests, CallbackGetLambdaStatusReferenceTest) { Url url{server->GetBaseUrl() + "/hello.html"}; int status_code = 0; auto future = cpr::GetCallback( [&status_code](const Response& r) { status_code = r.status_code; return r.status_code; }, url); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(status_code, future.get()); } TEST(CallbackGetTests, CallbackGetLambdaTextReferenceTest) { Url url{server->GetBaseUrl() + "/hello.html"}; std::string expected_text{}; auto future = cpr::GetCallback( [&expected_text](const Response& r) { expected_text = r.text; return r.text; }, url); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(expected_text, future.get()); } TEST(CallbackGetTests, CallbackGetFunctionStatusTest) { Url url{server->GetBaseUrl() + "/hello.html"}; int status_code = 0; auto callback = std::function<int(Response)>( std::bind(status_callback, std::ref(status_code), std::placeholders::_1)); auto future = cpr::GetCallback(callback, url); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(status_code, future.get()); } TEST(CallbackGetTests, CallbackGetFunctionTextTest) { Url url{server->GetBaseUrl() + "/hello.html"}; std::string expected_text{}; auto callback = std::function<std::string(Response)>( std::bind(text_callback, std::ref(expected_text), std::placeholders::_1)); auto future = cpr::GetCallback(callback, url); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(expected_text, future.get()); } TEST(CallbackGetTests, CallbackGetFunctionStatusReferenceTest) { Url url{server->GetBaseUrl() + "/hello.html"}; int status_code = 0; auto callback = std::function<int(Response)>( std::bind(status_callback_ref, std::ref(status_code), std::placeholders::_1)); auto future = cpr::GetCallback(callback, url); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(status_code, future.get()); } TEST(CallbackGetTests, CallbackGetFunctionTextReferenceTest) { Url url{server->GetBaseUrl() + "/hello.html"}; std::string expected_text{}; auto callback = std::function<std::string(Response)>( std::bind(text_callback_ref, std::ref(expected_text), std::placeholders::_1)); auto future = cpr::GetCallback(callback, url); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(expected_text, future.get()); } TEST(CallbackDeleteTests, CallbackDeleteLambdaStatusTest) { Url url{server->GetBaseUrl() + "/delete.html"}; int status_code = 0; auto future = cpr::DeleteCallback( [&status_code](Response r) { status_code = r.status_code; return r.status_code; }, url); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(status_code, future.get()); } TEST(CallbackDeleteTests, CallbackDeleteLambdaTextTest) { Url url{server->GetBaseUrl() + "/delete.html"}; std::string expected_text{}; auto future = cpr::DeleteCallback( [&expected_text](Response r) { expected_text = r.text; return r.text; }, url); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(expected_text, future.get()); } TEST(CallbackDeleteTests, CallbackDeleteLambdaStatusReferenceTest) { Url url{server->GetBaseUrl() + "/delete.html"}; int status_code = 0; auto future = cpr::DeleteCallback( [&status_code](const Response& r) { status_code = r.status_code; return r.status_code; }, url); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(status_code, future.get()); } TEST(CallbackDeleteTests, CallbackDeleteLambdaTextReferenceTest) { Url url{server->GetBaseUrl() + "/delete.html"}; std::string expected_text{}; auto future = cpr::DeleteCallback( [&expected_text](const Response& r) { expected_text = r.text; return r.text; }, url); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(expected_text, future.get()); } TEST(CallbackDeleteTests, CallbackDeleteFunctionStatusTest) { Url url{server->GetBaseUrl() + "/delete.html"}; int status_code = 0; auto callback = std::function<int(Response)>( std::bind(status_callback, std::ref(status_code), std::placeholders::_1)); auto future = cpr::DeleteCallback(callback, url); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(status_code, future.get()); } TEST(CallbackDeleteTests, CallbackDeleteFunctionTextTest) { Url url{server->GetBaseUrl() + "/delete.html"}; std::string expected_text{}; auto callback = std::function<std::string(Response)>( std::bind(text_callback, std::ref(expected_text), std::placeholders::_1)); auto future = cpr::DeleteCallback(callback, url); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(expected_text, future.get()); } TEST(CallbackDeleteTests, CallbackDeleteFunctionStatusReferenceTest) { Url url{server->GetBaseUrl() + "/delete.html"}; int status_code = 0; auto callback = std::function<int(Response)>( std::bind(status_callback_ref, std::ref(status_code), std::placeholders::_1)); auto future = cpr::DeleteCallback(callback, url); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(status_code, future.get()); } TEST(CallbackDeleteTests, CallbackDeleteFunctionTextReferenceTest) { Url url{server->GetBaseUrl() + "/delete.html"}; std::string expected_text{}; auto callback = std::function<std::string(Response)>( std::bind(text_callback_ref, std::ref(expected_text), std::placeholders::_1)); auto future = cpr::DeleteCallback(callback, url); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(expected_text, future.get()); } TEST(CallbackHeadTests, CallbackHeadLambdaStatusTest) { Url url{server->GetBaseUrl() + "/hello.html"}; int status_code = 0; auto future = cpr::HeadCallback( [&status_code](Response r) { status_code = r.status_code; return r.status_code; }, url); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(status_code, future.get()); } TEST(CallbackHeadTests, CallbackHeadLambdaTextTest) { Url url{server->GetBaseUrl() + "/hello.html"}; std::string expected_text{}; auto future = cpr::HeadCallback( [&expected_text](Response r) { expected_text = r.text; return r.text; }, url); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(expected_text, future.get()); } TEST(CallbackHeadTests, CallbackHeadLambdaStatusReferenceTest) { Url url{server->GetBaseUrl() + "/hello.html"}; int status_code = 0; auto future = cpr::HeadCallback( [&status_code](const Response& r) { status_code = r.status_code; return r.status_code; }, url); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(status_code, future.get()); } TEST(CallbackHeadTests, CallbackHeadLambdaTextReferenceTest) { Url url{server->GetBaseUrl() + "/hello.html"}; std::string expected_text{}; auto future = cpr::HeadCallback( [&expected_text](const Response& r) { expected_text = r.text; return r.text; }, url); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(expected_text, future.get()); } TEST(CallbackHeadTests, CallbackHeadFunctionStatusTest) { Url url{server->GetBaseUrl() + "/hello.html"}; int status_code = 0; auto callback = std::function<int(Response)>( std::bind(status_callback, std::ref(status_code), std::placeholders::_1)); auto future = cpr::HeadCallback(callback, url); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(status_code, future.get()); } TEST(CallbackHeadTests, CallbackHeadFunctionTextTest) { Url url{server->GetBaseUrl() + "/hello.html"}; std::string expected_text{}; auto callback = std::function<std::string(Response)>( std::bind(text_callback, std::ref(expected_text), std::placeholders::_1)); auto future = cpr::HeadCallback(callback, url); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(expected_text, future.get()); } TEST(CallbackHeadTests, CallbackHeadFunctionStatusReferenceTest) { Url url{server->GetBaseUrl() + "/hello.html"}; int status_code = 0; auto callback = std::function<int(Response)>( std::bind(status_callback_ref, std::ref(status_code), std::placeholders::_1)); auto future = cpr::HeadCallback(callback, url); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(status_code, future.get()); } TEST(CallbackHeadTests, CallbackHeadFunctionTextReferenceTest) { Url url{server->GetBaseUrl() + "/hello.html"}; std::string expected_text{}; auto callback = std::function<std::string(Response)>( std::bind(text_callback_ref, std::ref(expected_text), std::placeholders::_1)); auto future = cpr::HeadCallback(callback, url); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(expected_text, future.get()); } TEST(CallbackPostTests, CallbackPostLambdaStatusTest) { Url url{server->GetBaseUrl() + "/url_post.html"}; Payload payload{{"x", "5"}}; int status_code = 0; auto future = cpr::PostCallback( [&status_code](Response r) { status_code = r.status_code; return r.status_code; }, url, payload); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(status_code, future.get()); } TEST(CallbackPostTests, CallbackPostLambdaTextTest) { Url url{server->GetBaseUrl() + "/url_post.html"}; Payload payload{{"x", "5"}}; std::string expected_text{}; auto future = cpr::PostCallback( [&expected_text](Response r) { expected_text = r.text; return r.text; }, url, payload); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(expected_text, future.get()); } TEST(CallbackPostTests, CallbackPostLambdaStatusReferenceTest) { Url url{server->GetBaseUrl() + "/url_post.html"}; Payload payload{{"x", "5"}}; int status_code = 0; auto future = cpr::PostCallback( [&status_code](const Response& r) { status_code = r.status_code; return r.status_code; }, url, payload); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(status_code, future.get()); } TEST(CallbackPostTests, CallbackPostLambdaTextReferenceTest) { Url url{server->GetBaseUrl() + "/url_post.html"}; Payload payload{{"x", "5"}}; std::string expected_text{}; auto future = cpr::PostCallback( [&expected_text](const Response& r) { expected_text = r.text; return r.text; }, url, payload); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(expected_text, future.get()); } TEST(CallbackPostTests, CallbackPostFunctionStatusTest) { Url url{server->GetBaseUrl() + "/url_post.html"}; Payload payload{{"x", "5"}}; int status_code = 0; auto callback = std::function<int(Response)>( std::bind(status_callback, std::ref(status_code), std::placeholders::_1)); auto future = cpr::PostCallback(callback, url, payload); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(status_code, future.get()); } TEST(CallbackPostTests, CallbackPostFunctionTextTest) { Url url{server->GetBaseUrl() + "/url_post.html"}; Payload payload{{"x", "5"}}; std::string expected_text{}; auto callback = std::function<std::string(Response)>( std::bind(text_callback, std::ref(expected_text), std::placeholders::_1)); auto future = cpr::PostCallback(callback, url, payload); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(expected_text, future.get()); } TEST(CallbackPostTests, CallbackPostFunctionStatusReferenceTest) { Url url{server->GetBaseUrl() + "/url_post.html"}; Payload payload{{"x", "5"}}; int status_code = 0; auto callback = std::function<int(Response)>( std::bind(status_callback_ref, std::ref(status_code), std::placeholders::_1)); auto future = cpr::PostCallback(callback, url, payload); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(status_code, future.get()); } TEST(CallbackPostTests, CallbackPostFunctionTextReferenceTest) { Url url{server->GetBaseUrl() + "/url_post.html"}; Payload payload{{"x", "5"}}; std::string expected_text{}; auto callback = std::function<std::string(Response)>( std::bind(text_callback_ref, std::ref(expected_text), std::placeholders::_1)); auto future = cpr::PostCallback(callback, url, payload); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(expected_text, future.get()); } TEST(CallbackPutTests, CallbackPutLambdaStatusTest) { Url url{server->GetBaseUrl() + "/url_post.html"}; Payload payload{{"x", "5"}}; int status_code = 0; auto future = cpr::PutCallback( [&status_code](Response r) { status_code = r.status_code; return r.status_code; }, url, payload); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(status_code, future.get()); } TEST(CallbackPutTests, CallbackPutLambdaTextTest) { Url url{server->GetBaseUrl() + "/url_post.html"}; Payload payload{{"x", "5"}}; std::string expected_text{}; auto future = cpr::PutCallback( [&expected_text](Response r) { expected_text = r.text; return r.text; }, url, payload); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(expected_text, future.get()); } TEST(CallbackPutTests, CallbackPutLambdaStatusReferenceTest) { Url url{server->GetBaseUrl() + "/url_post.html"}; Payload payload{{"x", "5"}}; int status_code = 0; auto future = cpr::PutCallback( [&status_code](const Response& r) { status_code = r.status_code; return r.status_code; }, url, payload); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(status_code, future.get()); } TEST(CallbackPutTests, CallbackPutLambdaTextReferenceTest) { Url url{server->GetBaseUrl() + "/url_post.html"}; Payload payload{{"x", "5"}}; std::string expected_text{}; auto future = cpr::PutCallback( [&expected_text](const Response& r) { expected_text = r.text; return r.text; }, url, payload); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(expected_text, future.get()); } TEST(CallbackPutTests, CallbackPutFunctionStatusTest) { Url url{server->GetBaseUrl() + "/url_post.html"}; Payload payload{{"x", "5"}}; int status_code = 0; auto callback = std::function<int(Response)>( std::bind(status_callback, std::ref(status_code), std::placeholders::_1)); auto future = cpr::PutCallback(callback, url, payload); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(status_code, future.get()); } TEST(CallbackPutTests, CallbackPutFunctionTextTest) { Url url{server->GetBaseUrl() + "/url_post.html"}; Payload payload{{"x", "5"}}; std::string expected_text{}; auto callback = std::function<std::string(Response)>( std::bind(text_callback, std::ref(expected_text), std::placeholders::_1)); auto future = cpr::PutCallback(callback, url, payload); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(expected_text, future.get()); } TEST(CallbackPutTests, CallbackPutFunctionStatusReferenceTest) { Url url{server->GetBaseUrl() + "/url_post.html"}; Payload payload{{"x", "5"}}; int status_code = 0; auto callback = std::function<int(Response)>( std::bind(status_callback_ref, std::ref(status_code), std::placeholders::_1)); auto future = cpr::PutCallback(callback, url, payload); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(status_code, future.get()); } TEST(CallbackPutTests, CallbackPutFunctionTextReferenceTest) { Url url{server->GetBaseUrl() + "/url_post.html"}; Payload payload{{"x", "5"}}; std::string expected_text{}; auto callback = std::function<std::string(Response)>( std::bind(text_callback_ref, std::ref(expected_text), std::placeholders::_1)); auto future = cpr::PutCallback(callback, url, payload); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(expected_text, future.get()); } TEST(CallbackOptionsTests, CallbackOptionsLambdaStatusTest) { Url url{server->GetBaseUrl() + "/hello.html"}; int status_code = 0; auto future = cpr::OptionsCallback( [&status_code](Response r) { status_code = r.status_code; return r.status_code; }, url); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(status_code, future.get()); } TEST(CallbackOptionsTests, CallbackOptionsLambdaTextTest) { Url url{server->GetBaseUrl() + "/hello.html"}; std::string expected_text{}; auto future = cpr::OptionsCallback( [&expected_text](Response r) { expected_text = r.text; return r.text; }, url); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(expected_text, future.get()); } TEST(CallbackOptionsTests, CallbackOptionsLambdaStatusReferenceTest) { Url url{server->GetBaseUrl() + "/hello.html"}; int status_code = 0; auto future = cpr::OptionsCallback( [&status_code](const Response& r) { status_code = r.status_code; return r.status_code; }, url); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(status_code, future.get()); } TEST(CallbackOptionsTests, CallbackOptionsLambdaTextReferenceTest) { Url url{server->GetBaseUrl() + "/hello.html"}; std::string expected_text{}; auto future = cpr::OptionsCallback( [&expected_text](const Response& r) { expected_text = r.text; return r.text; }, url); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(expected_text, future.get()); } TEST(CallbackOptionsTests, CallbackOptionsFunctionStatusTest) { Url url{server->GetBaseUrl() + "/hello.html"}; int status_code = 0; auto callback = std::function<int(Response)>( std::bind(status_callback, std::ref(status_code), std::placeholders::_1)); auto future = cpr::OptionsCallback(callback, url); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(status_code, future.get()); } TEST(CallbackOptionsTests, CallbackOptionsFunctionTextTest) { Url url{server->GetBaseUrl() + "/hello.html"}; std::string expected_text{}; auto callback = std::function<std::string(Response)>( std::bind(text_callback, std::ref(expected_text), std::placeholders::_1)); auto future = cpr::OptionsCallback(callback, url); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(expected_text, future.get()); } TEST(CallbackOptionsTests, CallbackOptionsFunctionStatusReferenceTest) { Url url{server->GetBaseUrl() + "/hello.html"}; int status_code = 0; auto callback = std::function<int(Response)>( std::bind(status_callback_ref, std::ref(status_code), std::placeholders::_1)); auto future = cpr::OptionsCallback(callback, url); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(status_code, future.get()); } TEST(CallbackOptionsTests, CallbackOptionsFunctionTextReferenceTest) { Url url{server->GetBaseUrl() + "/hello.html"}; std::string expected_text{}; auto callback = std::function<std::string(Response)>( std::bind(text_callback_ref, std::ref(expected_text), std::placeholders::_1)); auto future = cpr::OptionsCallback(callback, url); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(expected_text, future.get()); } TEST(CallbackPatchTests, CallbackPatchLambdaStatusTest) { Url url{server->GetBaseUrl() + "/url_post.html"}; Payload payload{{"x", "5"}}; int status_code = 0; auto future = cpr::PatchCallback( [&status_code](Response r) { status_code = r.status_code; return r.status_code; }, url, payload); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(status_code, future.get()); } TEST(CallbackPatchTests, CallbackPatchLambdaTextTest) { Url url{server->GetBaseUrl() + "/url_post.html"}; Payload payload{{"x", "5"}}; std::string expected_text{}; auto future = cpr::PatchCallback( [&expected_text](Response r) { expected_text = r.text; return r.text; }, url, payload); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(expected_text, future.get()); } TEST(CallbackPatchTests, CallbackPatchLambdaStatusReferenceTest) { Url url{server->GetBaseUrl() + "/url_post.html"}; Payload payload{{"x", "5"}}; int status_code = 0; auto future = cpr::PatchCallback( [&status_code](const Response& r) { status_code = r.status_code; return r.status_code; }, url, payload); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(status_code, future.get()); } TEST(CallbackPatchTests, CallbackPatchLambdaTextReferenceTest) { Url url{server->GetBaseUrl() + "/url_post.html"}; Payload payload{{"x", "5"}}; std::string expected_text{}; auto future = cpr::PatchCallback( [&expected_text](const Response& r) { expected_text = r.text; return r.text; }, url, payload); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(expected_text, future.get()); } TEST(CallbackPatchTests, CallbackPatchFunctionStatusTest) { Url url{server->GetBaseUrl() + "/url_post.html"}; Payload payload{{"x", "5"}}; int status_code = 0; auto callback = std::function<int(Response)>( std::bind(status_callback, std::ref(status_code), std::placeholders::_1)); auto future = cpr::PatchCallback(callback, url, payload); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(status_code, future.get()); } TEST(CallbackPatchTests, CallbackPatchFunctionTextTest) { Url url{server->GetBaseUrl() + "/url_post.html"}; Payload payload{{"x", "5"}}; std::string expected_text{}; auto callback = std::function<std::string(Response)>( std::bind(text_callback, std::ref(expected_text), std::placeholders::_1)); auto future = cpr::PatchCallback(callback, url, payload); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(expected_text, future.get()); } TEST(CallbackPatchTests, CallbackPatchFunctionStatusReferenceTest) { Url url{server->GetBaseUrl() + "/url_post.html"}; Payload payload{{"x", "5"}}; int status_code = 0; auto callback = std::function<int(Response)>( std::bind(status_callback_ref, std::ref(status_code), std::placeholders::_1)); auto future = cpr::PatchCallback(callback, url, payload); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(status_code, future.get()); } TEST(CallbackPatchTests, CallbackPatchFunctionTextReferenceTest) { Url url{server->GetBaseUrl() + "/url_post.html"}; Payload payload{{"x", "5"}}; std::string expected_text{}; auto callback = std::function<std::string(Response)>( std::bind(text_callback_ref, std::ref(expected_text), std::placeholders::_1)); auto future = cpr::PatchCallback(callback, url, payload); std::this_thread::sleep_for(sleep_time); EXPECT_EQ(future.wait_for(zero), std::future_status::ready); EXPECT_EQ(expected_text, future.get()); } TEST(CallbackDataTests, CallbackReadFunctionCancelTest) { Url url{server->GetBaseUrl() + "/url_post.html"}; Response response = cpr::Post(url, cpr::ReadCallback([](char* buffer, size_t & size) -> size_t { return false; })); EXPECT_EQ(response.error.code, ErrorCode::REQUEST_CANCELLED); } TEST(CallbackDataTests, CallbackReadFunctionTextTest) { Url url{server->GetBaseUrl() + "/url_post.html"}; std::string expected_text{ "{\n" " \"x\": 5\n" "}"}; unsigned count = 0; Response response = cpr::Post(url, cpr::ReadCallback{3, [&](char* buffer, size_t & size) -> size_t { std::string data; ++ count; switch (count) { case 1: data = "x="; break; case 2: data = "5"; break; default: return false; } std::copy(data.begin(), data.end(), buffer); size = data.size(); return true; }}); EXPECT_EQ(2, count); EXPECT_EQ(expected_text, response.text); } /** * Checks if the "Transfer-Encoding" header will be kept when using headers and a read callback. * Issue: https://github.com/whoshuu/cpr/issues/517 **/ TEST(CallbackDataTests, CallbackReadFunctionHeaderTest) { Url url{server->GetBaseUrl() + "/header_reflect.html"}; bool send = false; std::string data = "Test"; Response response = cpr::Post(url, cpr::ReadCallback{3, [&](char* buffer, size_t& size) -> size_t { if (!send) { std::copy(data.begin(), data.end(), buffer); size = data.size(); send = true; } else { size = 0; } return true; }}, Header{{"TestHeader", "42"}}); EXPECT_EQ(url, response.url); EXPECT_EQ(200, response.status_code); EXPECT_EQ(ErrorCode::OK, response.error.code); // Check Header: EXPECT_EQ(std::string{"42"}, response.header["TestHeader"]); // Set by us EXPECT_TRUE(response.header.find("TestHeader") != response.header.end()); EXPECT_EQ(std::string{"chunked"}, response.header["Transfer-Encoding"]); // Set by the read callback EXPECT_TRUE(response.header.find("Transfer-Encoding") != response.header.end()); } /* cesanta mongoose doesn't support chunked requests yet TEST(CallbackDataTests, CallbackReadFunctionChunkedTest) { Url url{server->GetBaseUrl() + "/url_post.html"}; std::string expected_text{ "{\n" " \"x\": 5\n" "}"}; unsigned count = 0; Response response = cpr::Post(url, cpr::ReadCallback{[&count](char* buffer, size_t & size) -> size_t { std::string data; ++ count; switch (count) { case 1: data = "x="; break; case 2: data = "5"; break; default: data = ""; break; } std::copy(data.begin(), data.end(), buffer); size = data.size(); return true; }}); EXPECT_EQ(3, count); EXPECT_EQ(expected_text, response.text); } */ TEST(CallbackDataTests, CallbackHeaderFunctionCancelTest) { Url url{server->GetBaseUrl() + "/url_post.html"}; Response response = Post(url, HeaderCallback{[](std::string header) -> bool { return false; }}); EXPECT_EQ(response.error.code, ErrorCode::REQUEST_CANCELLED); } TEST(CallbackDataTests, CallbackHeaderFunctionTextTest) { Url url{server->GetBaseUrl() + "/url_post.html"}; std::vector<std::string> expected_headers{ "HTTP/1.1 201 OK\r\n", "Content-Type: application/json\r\n", "\r\n" }; std::set<std::string> response_headers; Post(url, HeaderCallback{[&response_headers](std::string header) -> bool { response_headers.insert(header); return true; }}); for (std::string & header : expected_headers) { EXPECT_TRUE(response_headers.count(header)); } } TEST(CallbackDataTests, CallbackWriteFunctionCancelTest) { Url url{server->GetBaseUrl() + "/url_post.html"}; Response response = Post(url, WriteCallback{[](std::string header) -> bool { return false; }}); EXPECT_EQ(response.error.code, ErrorCode::REQUEST_CANCELLED); } TEST(CallbackDataTests, CallbackWriteFunctionTextTest) { Url url{server->GetBaseUrl() + "/url_post.html"}; std::string expected_text{ "{\n" " \"x\": 5\n" "}"}; std::string response_text; Post(url, Payload{{"x", "5"}}, WriteCallback{[&response_text](std::string header) -> bool { response_text.append(header); return true; }}); EXPECT_EQ(expected_text, response_text); } TEST(CallbackDataTests, CallbackProgressFunctionCancelTest) { Url url{server->GetBaseUrl() + "/url_post.html"}; Response response = Post(url, ProgressCallback{[](size_t downloadTotal, size_t downloadNow, size_t uploadTotal, size_t uploadNow) -> bool { return false; }}); EXPECT_EQ(response.error.code, ErrorCode::REQUEST_CANCELLED); } TEST(CallbackDataTests, CallbackProgressFunctionTotalTest) { Url url{server->GetBaseUrl() + "/url_post.html"}; Body body{"x=5"}; size_t response_upload = 0, response_download = 0; Response response = Post(url, body, ProgressCallback{[&](size_t downloadTotal, size_t downloadNow, size_t uploadTotal, size_t uploadNow) -> bool { response_upload = uploadTotal; response_download = downloadTotal; return true; }}); EXPECT_EQ(body.str().length(), response_upload); EXPECT_EQ(response.text.length(), response_download); } TEST(CallbackDataTests, CallbackDebugFunctionTextTest) { Url url{server->GetBaseUrl() + "/url_post.html"}; Body body{"x=5"}; std::string debug_body; Response response = Post(url, body, DebugCallback{[&](DebugCallback::InfoType type, std::string data) { if (type == DebugCallback::InfoType::DATA_OUT) { debug_body = data; } }}); EXPECT_EQ(body.str(), debug_body); } int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); ::testing::AddGlobalTestEnvironment(server); return RUN_ALL_TESTS(); }
/** @file @brief OSVR display configuration @date 2015 @author Sensics, Inc. <http://sensics.com> */ // Copyright 2015 Sensics, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Internal Includes #include "osvr_display_configuration.h" // Library/third-party includes #include <boost/units/io.hpp> #include <json/reader.h> #include <json/value.h> // Standard includes #include <cassert> #include <fstream> #include <iostream> // Included files that define built-in distortion meshes. #include "osvr_display_config_built_in_osvr_hdks.h" OSVRDisplayConfiguration::OSVRDisplayConfiguration() { // do nothing } OSVRDisplayConfiguration::OSVRDisplayConfiguration( const std::string& display_description) { parse(display_description); } inline void parseDistortionMonoPointMeshes( Json::Value const& distortion, osvr::renderkit::MonoPointDistortionMeshDescriptions& mesh) { Json::Value myDistortion = distortion; // See if we have the name of a built-in config to parse. If so, we open it // and grab its values to parse, replacing the ones that they sent // in. const Json::Value builtIn = distortion["mono_point_samples_built_in"]; if ((!builtIn.isNull()) && (builtIn.isString())) { // Read a Json value from the built-in config, then replace the // distortion mesh with that from the file. std::string builtInString; Json::Value builtInData; if (builtIn.asString() == "OSVR_HDK_13_V1") { builtInString = osvr_display_config_built_in_osvr_hdk13_v1; } else if (builtIn.asString() == "OSVR_HDK_13_V2") { builtInString = osvr_display_config_built_in_osvr_hdk13_v2; } else if (builtIn.asString() == "OSVR_HDK_20_V1") { builtInString = osvr_display_config_built_in_osvr_hdk20_v1; } else { std::cerr << "OSVRDisplayConfiguration::parse(): ERROR: Unrecognized " "mono_point_samples_built_in value: " << builtIn.asString() << "!\n"; throw DisplayConfigurationParseException( "Couldn't open external mono point file."); } Json::Reader reader; if (!reader.parse(builtInString, builtInData)) { std::cerr << "OSVRDisplayConfiguration::parse(): ERROR: Couldn't " "parse built-in configuration " << builtIn.asString() << "!\n"; std::cerr << "Errors: " << reader.getFormattedErrorMessages(); throw DisplayConfigurationParseException( "Couldn't parse external mono point file."); } myDistortion = builtInData["display"]["hmd"]["distortion"]; } // See if we have the name of an external file to parse. If so, we open it // and grab its values to parse, replacing the ones that they sent // in. const Json::Value externalFile = distortion["mono_point_samples_external_file"]; if ((!externalFile.isNull()) && (externalFile.isString())) { // Read a Json value from the external file, then replace the distortion // mesh with that from the file. Json::Value externalData; Json::Reader reader; std::ifstream fs; fs.open(externalFile.asString().c_str(), std::fstream::in); if (!fs.is_open()) { std::cerr << "OSVRDisplayConfiguration::parse(): ERROR: Couldn't " "open file " << externalFile.asString() << "!\n"; throw DisplayConfigurationParseException( "Couldn't open external mono point file."); } if (!reader.parse(fs, externalData)) { std::cerr << "OSVRDisplayConfiguration::parse(): ERROR: Couldn't " "parse file " << externalFile.asString() << "!\n"; std::cerr << "Errors: " << reader.getFormattedErrorMessages(); throw DisplayConfigurationParseException( "Couldn't parse external mono point file."); } myDistortion = externalData["display"]["hmd"]["distortion"]; fs.close(); } const Json::Value eyeArray = myDistortion["mono_point_samples"]; if (eyeArray.isNull() || eyeArray.empty()) { /// @todo A proper "no-op" default should be placed here, instead of /// erroring out. std::cerr << "OSVRDisplayConfiguration::parse(): ERROR: Couldn't find " "non-empty distortion mono point distortion!\n"; throw DisplayConfigurationParseException( "Couldn't find non-empty mono point distortion."); } mesh.clear(); for (auto& pointArray : eyeArray) { osvr::renderkit::MonoPointDistortionMeshDescription eye; if (pointArray.empty()) { /// @todo A proper "no-op" default should be placed here, instead of /// erroring out. std::cerr << "OSVRDisplayConfiguration::parse(): ERROR: Empty " << " distortion mono point distortion list for eye!\n"; throw DisplayConfigurationParseException( "Empty mono point distortion list for eye."); } for (auto& elt : pointArray) { std::array<std::array<double, 2>, 2> point; if ((elt.size() != 2) || (elt[0].size() != 2) || (elt[1].size() != 2)) { /// @todo A proper "no-op" default should be placed here, /// instead of erroring out. std::cerr << "OSVRDisplayConfiguration::parse(): ERROR: Malformed" << " distortion mono point distortion list entry!\n"; throw DisplayConfigurationParseException( "Malformed mono point distortion list entry."); } std::array<double, 2> in, out; in[0] = (elt[0][0].asDouble()); in[1] = (elt[0][1].asDouble()); out[0] = (elt[1][0].asDouble()); out[1] = (elt[1][1].asDouble()); point[0] = (in); point[1] = (out); eye.push_back(point); } mesh.push_back(eye); } } inline void parseDistortionRGBPointMeshes( Json::Value const& distortion, osvr::renderkit::RGBPointDistortionMeshDescriptions& mesh) { Json::Value myDistortion = distortion; // See if we have the name of an external file to parse. If so, we open it // and grab its values to parse. Otherwise, we parse the ones that they // sent in. const Json::Value externalFile = distortion["rgb_point_samples_external_file"]; if ((!externalFile.isNull()) && (externalFile.isString())) { // Read a Json value from the external file, then replace the distortion // mesh with that from the file. Json::Value externalData; Json::Reader reader; std::ifstream fs; fs.open(externalFile.asString().c_str(), std::fstream::in); if (!fs.is_open()) { std::cerr << "OSVRDisplayConfiguration::parse(): ERROR: Couldn't " "open file " << externalFile.asString() << "!\n"; throw DisplayConfigurationParseException( "Couldn't open external rgb point file."); } if (!reader.parse(fs, externalData)) { std::cerr << "OSVRDisplayConfiguration::parse(): ERROR: Couldn't " "parse file " << externalFile.asString() << "!\n"; std::cerr << "Errors: " << reader.getFormattedErrorMessages(); throw DisplayConfigurationParseException( "Couldn't parse external rgb point file."); } myDistortion = externalData["display"]["hmd"]["distortion"]; fs.close(); } std::array<std::string, 3> names = { "red_point_samples", "green_point_samples", "blue_point_samples"}; for (size_t clr = 0; clr < 3; clr++) { const Json::Value eyeArray = myDistortion[names[clr].c_str()]; if (eyeArray.isNull() || eyeArray.empty()) { /// @todo A proper "no-op" default should be placed here, instead of /// erroring out. std::cerr << "OSVRDisplayConfiguration::parse(): ERROR: Couldn't find " "non-empty distortion rgb point distortion for " << names[clr] << std::endl; throw DisplayConfigurationParseException( "Couldn't find non-empty rgb point distortion."); } mesh[clr].clear(); for (auto& pointArray : eyeArray) { osvr::renderkit::MonoPointDistortionMeshDescription eye; if (pointArray.empty()) { /// @todo A proper "no-op" default should be placed here, /// instead of /// erroring out. std::cerr << "OSVRDisplayConfiguration::parse(): ERROR: Empty " << " distortion rgb point distortion list for eye!" << std::endl; throw DisplayConfigurationParseException( "Empty rgb point distortion list for eye."); } for (auto& elt : pointArray) { std::array<std::array<double, 2>, 2> point; if ((elt.size() != 2) || (elt[0].size() != 2) || (elt[1].size() != 2)) { /// @todo A proper "no-op" default should be placed here, /// instead of erroring out. std::cerr << "OSVRDisplayConfiguration::parse(): ERROR: Malformed" << " distortion rgb point distortion list entry!" << std::endl; throw DisplayConfigurationParseException( "Malformed rgb point distortion list entry."); } std::array<double, 2> in, out; in[0] = (elt[0][0].asDouble()); in[1] = (elt[0][1].asDouble()); out[0] = (elt[1][0].asDouble()); out[1] = (elt[1][1].asDouble()); point[0] = (in); point[1] = (out); eye.push_back(point); } mesh[clr].push_back(eye); } } } inline void parseDistortionPolynomial(Json::Value const& distortion, std::string const& color, std::vector<float>& polynomial) { const Json::Value distortArray = distortion["polynomial_coeffs_" + color]; if (distortArray.isNull() || distortArray.empty()) { /// @todo A proper "no-op" default should be placed here, instead of /// erroring out. std::cerr << "OSVRDisplayConfiguration::parse(): ERROR: Couldn't find " "non-empty " << color << " distortion coefficient array!\n"; throw DisplayConfigurationParseException( "Couldn't find non-empty " + color + " distortion coefficient array."); } polynomial.clear(); for (auto& elt : distortArray) { polynomial.push_back(elt.asFloat()); } } /// Returns a resolution and if it should swap eyes. inline std::pair<OSVRDisplayConfiguration::Resolution, bool> parseResolution(Json::Value const& resolution) { // if there is more than 1 input, display descriptor right now // specifies one resolution value for both inputs. that may be // changed in the future OSVRDisplayConfiguration::Resolution res; res.video_inputs = resolution.get("video_inputs", 1).asInt(); // Window bounds res.width = resolution["width"].asInt(); res.height = resolution["height"].asInt(); // Display mode - Default to horiz side by side unless we have // multiple video inputs, then default to full screen (? seems // logical but not strictly what the json schema specifies) res.display_mode = (res.video_inputs > 1 ? OSVRDisplayConfiguration::FULL_SCREEN : OSVRDisplayConfiguration::HORIZONTAL_SIDE_BY_SIDE); auto const& display_mode = resolution["display_mode"]; if (display_mode.isString()) { const std::string display_mode_str = display_mode.asString(); if ("horz_side_by_side" == display_mode_str) { res.display_mode = OSVRDisplayConfiguration::HORIZONTAL_SIDE_BY_SIDE; } else if ("vert_side_by_side" == display_mode_str) { res.display_mode = OSVRDisplayConfiguration::VERTICAL_SIDE_BY_SIDE; } else if ("full_screen" == display_mode_str) { res.display_mode = OSVRDisplayConfiguration::FULL_SCREEN; } else { std::cerr << "OSVRDisplayConfiguration::parse(): WARNING: " "Unknown display mode string: " << display_mode_str << " (using default)\n"; } } auto const& eyeSwap = resolution["swap_eyes"]; auto doEyeSwap = !eyeSwap.isNull() && eyeSwap.asBool(); return std::make_pair(std::move(res), doEyeSwap); } void OSVRDisplayConfiguration::parse(const std::string& display_description) { Json::Value root; { Json::Reader reader; if (!reader.parse(display_description, root, false)) { std::cerr << "OSVRDisplayConfiguration::parse(): ERROR: Couldn't " "parse the display descriptor as JSON!\n"; throw DisplayConfigurationParseException( "Couldn't parse the display descriptor as JSON."); } } using namespace osvr; auto const& hmd = root["hmd"]; { auto const& fov = hmd["field_of_view"]; // Field of view m_monocularHorizontalFOV = util::Angle(fov["monocular_horizontal"].asDouble() * util::degrees); m_monocularVerticalFOV = util::Angle(fov["monocular_vertical"].asDouble() * util::degrees); m_overlapPercent = fov.get("overlap_percent", 100).asDouble() / 100.0; m_pitchTilt = util::Angle(fov.get("pitch_tilt", 0).asDouble() * util::degrees); } { // Device properties auto processDeviceData = [&](Json::Value const& devprops) { m_vendor = devprops["vendor"].asString(); m_model = devprops["model"].asString(); m_version = devprops["Version"].asString(); m_note = devprops["Note"].asString(); }; // In the canonical schema, this is where those properties live. // However, in some legacy directmode config files, they are in a // sub-object called "properties". Thus, we'll call the above lambda // with only one of the two. auto const& devprops = hmd["device"]; auto const& subproperties = devprops["properties"]; if (!subproperties.isNull() && !subproperties.empty()) { // legacy descriptor std::cerr << "OSVRDisplayConfiguration::parse(): WARNING: Your " "display descriptor is outdated (using an outdated " "schema) and may not work with all applications. " "Please check with your vendor or the OSVR community " "to get an updated one matching the most recent JSON " "Schema for display descriptors.\n"; processDeviceData(subproperties); } else { processDeviceData(devprops); } } { auto const& resolutions = hmd["resolutions"]; if (resolutions.isNull()) { std::cerr << "OSVRDisplayConfiguration::parse(): ERROR: Couldn't " "find resolutions array!\n"; throw DisplayConfigurationParseException( "Couldn't find resolutions array."); } bool first = true; for (auto const& resolution : resolutions) { Resolution res; bool swapEyes; std::tie(res, swapEyes) = parseResolution(resolution); m_resolutions.push_back(res); if (first) { m_swapEyes = swapEyes; first = false; } } if (m_resolutions.empty()) { // We couldn't find any appropriate resolution entries std::cerr << "OSVRDisplayConfiguration::parse(): ERROR: Couldn't " "find any appropriate resolutions.\n"; throw DisplayConfigurationParseException( "Couldn't find resolutions array or any appropriate " "resolutions."); return; } } { auto const& rendering = hmd["rendering"]; m_rightRoll = rendering.get("right_roll", 0).asDouble(); m_leftRoll = rendering.get("left_roll", 0).asDouble(); } { auto const& distortion = hmd["distortion"]; /// We will detect distortion type based on either the explicitly /// specified string or the presence of essential object members. m_distortionTypeString = distortion["type"].asString(); if (m_distortionTypeString == "rgb_symmetric_polynomials" || distortion.isMember("polynomial_coeffs_red")) { std::cout << "OSVRDisplayConfiguration::parse(): Using polynomial " "distortion.\n"; m_distortionType = RGB_SYMMETRIC_POLYNOMIALS; m_distortionDistanceScaleX = distortion.get("distance_scale_x", 1.f).asFloat(); m_distortionDistanceScaleY = distortion.get("distance_scale_y", 1.f).asFloat(); parseDistortionPolynomial(distortion, "red", m_distortionPolynomialRed); parseDistortionPolynomial(distortion, "green", m_distortionPolynomialGreen); parseDistortionPolynomial(distortion, "blue", m_distortionPolynomialBlue); } else if (m_distortionTypeString == "mono_point_samples" || distortion.isMember("mono_point_samples") || distortion.isMember("mono_point_samples_built_in") || distortion.isMember("mono_point_samples_external_file")) { std::cout << "OSVRDisplayConfiguration::parse(): Using mono point " "sample distortion.\n"; m_distortionType = MONO_POINT_SAMPLES; parseDistortionMonoPointMeshes(distortion, m_distortionMonoPointMesh); } else if (m_distortionTypeString == "rgb_point_samples" || distortion.isMember("rgb_point_samples") || distortion.isMember("rgb_point_samples_external_file")) { std::cout << "OSVRDisplayConfiguration::parse(): Using rgb point " "sample distortion.\n"; m_distortionType = RGB_POINT_SAMPLES; parseDistortionRGBPointMeshes(distortion, m_distortionRGBPointMesh); } else if (m_distortionTypeString == "rgb_k1_coefficients") { #if 0 // Simple distortion params ignored by RenderManager /// @todo how to use these, or use them if non-zero, to set up /// distortion? double k1_red = distortion.get("k1_red", 0).asDouble(); double k1_green = distortion.get("k1_green", 0).asDouble(); double k1_blue = distortion.get("k1_blue", 0).asDouble(); #endif m_distortionType = RGB_SYMMETRIC_POLYNOMIALS; m_distortionDistanceScaleX = 1.f; m_distortionDistanceScaleY = 1.f; m_distortionPolynomialRed = {0.f, 1.f}; m_distortionPolynomialGreen = {0.f, 1.f}; m_distortionPolynomialBlue = {0.f, 1.f}; } else if (!m_distortionTypeString.empty()) { std::cerr << "OSVRDisplayConfiguration::parse(): ERROR: Unrecognized " "distortion type: " << m_distortionTypeString << std::endl; throw DisplayConfigurationParseException( "Unrecognized distortion type: " + m_distortionTypeString); } else { std::cout << "OSVRDisplayConfiguration::parse(): No " "RenderManager-compatible distortion parameters " "found, falling back to an identity polynomial.\n"; m_distortionType = RGB_SYMMETRIC_POLYNOMIALS; m_distortionDistanceScaleX = 1.f; m_distortionDistanceScaleY = 1.f; m_distortionPolynomialRed = {0.f, 1.f}; m_distortionPolynomialGreen = {0.f, 1.f}; m_distortionPolynomialBlue = {0.f, 1.f}; } } { auto const& eyes = hmd["eyes"]; if (eyes.isNull()) { std::cerr << "OSVRDisplayConfiguration::parse(): ERROR: " "Couldn't find eyes array!\n"; throw DisplayConfigurationParseException( "Couldn't find eyes array."); } for (auto const& eye : eyes) { EyeInfo e; e.m_CenterProjX = eye.get("center_proj_x", 0.5).asDouble(); e.m_CenterProjY = eye.get("center_proj_y", 0.5).asDouble(); if (eye.isMember("rotate_180")) { auto const& rot = eye["rotate_180"]; if (rot.isBool()) { e.m_rotate180 = rot.asBool(); } else { e.m_rotate180 = (rot.asInt() != 0); } } m_eyes.push_back(e); } } } void OSVRDisplayConfiguration::print() const { std::cout << "Monocular horizontal FOV: " << m_monocularHorizontalFOV << std::endl; std::cout << "Monocular vertical FOV: " << m_monocularVerticalFOV << std::endl; std::cout << "Overlap percent: " << m_overlapPercent << "%" << std::endl; std::cout << "Pitch tilt: " << m_pitchTilt << std::endl; std::cout << "Resolution: " << activeResolution().width << " x " << activeResolution().height << std::endl; std::cout << "Video inputs: " << activeResolution().video_inputs << std::endl; std::cout << "Display mode: " << activeResolution().display_mode << std::endl; std::cout << "Right roll: " << m_rightRoll << std::endl; std::cout << "Left roll: " << m_leftRoll << std::endl; std::cout << "Number of eyes: " << m_eyes.size() << std::endl; for (std::vector<EyeInfo>::size_type i = 0; i < m_eyes.size(); ++i) { std::cout << "Eye " << i << ": " << std::endl; m_eyes[i].print(); } } std::string OSVRDisplayConfiguration::getVendor() const { return m_vendor; } std::string OSVRDisplayConfiguration::getModel() const { return m_model; } std::string OSVRDisplayConfiguration::getVersion() const { return m_version; } std::string OSVRDisplayConfiguration::getNote() const { return m_note; } int OSVRDisplayConfiguration::getNumDisplays() const { if (m_eyes.size() < 2) { return 1; } // OK, so two eyes now. if (activeResolution().display_mode == DisplayMode::FULL_SCREEN) { assert(activeResolution().video_inputs == 2); return 2; } return 1; } int OSVRDisplayConfiguration::getDisplayTop() const { return 0; } int OSVRDisplayConfiguration::getDisplayLeft() const { return 0; } int OSVRDisplayConfiguration::getDisplayWidth() const { return activeResolution().width; } int OSVRDisplayConfiguration::getDisplayHeight() const { return activeResolution().height; } OSVRDisplayConfiguration::DisplayMode OSVRDisplayConfiguration::getDisplayMode() const { return activeResolution().display_mode; } osvr::util::Angle OSVRDisplayConfiguration::getVerticalFOV() const { return m_monocularVerticalFOV; } osvr::util::Angle OSVRDisplayConfiguration::getHorizontalFOV() const { return m_monocularHorizontalFOV; } #if 0 double OSVRDisplayConfiguration::getVerticalFOV() const { return m_MonocularVerticalFOV; } double OSVRDisplayConfiguration::getVerticalFOVRadians() const { return m_MonocularVerticalFOV * M_PI / 180.0; } double OSVRDisplayConfiguration::getHorizontalFOV() const { return m_MonocularHorizontalFOV; } double OSVRDisplayConfiguration::getHorizontalFOVRadians() const { return m_MonocularHorizontalFOV * M_PI / 180.0; } #endif double OSVRDisplayConfiguration::getOverlapPercent() const { return m_overlapPercent; } osvr::util::Angle OSVRDisplayConfiguration::getPitchTilt() const { return m_pitchTilt; } double OSVRDisplayConfiguration::getIPDMeters() const { return m_IPDMeters; } bool OSVRDisplayConfiguration::getSwapEyes() const { return m_swapEyes; } std::string OSVRDisplayConfiguration::getDistortionTypeString() const { return m_distortionTypeString; } osvr::renderkit::MonoPointDistortionMeshDescriptions OSVRDisplayConfiguration::getDistortionMonoPointMeshes() const { return m_distortionMonoPointMesh; } osvr::renderkit::RGBPointDistortionMeshDescriptions OSVRDisplayConfiguration::getDistortionRGBPointMeshes() const { return m_distortionRGBPointMesh; } float OSVRDisplayConfiguration::getDistortionDistanceScaleX() const { return m_distortionDistanceScaleX; } float OSVRDisplayConfiguration::getDistortionDistanceScaleY() const { return m_distortionDistanceScaleY; } std::vector<float> const& OSVRDisplayConfiguration::getDistortionPolynomalRed() const { return m_distortionPolynomialRed; } std::vector<float> const& OSVRDisplayConfiguration::getDistortionPolynomalGreen() const { return m_distortionPolynomialGreen; } std::vector<float> const& OSVRDisplayConfiguration::getDistortionPolynomalBlue() const { return m_distortionPolynomialBlue; } std::vector<OSVRDisplayConfiguration::EyeInfo> const& OSVRDisplayConfiguration::getEyes() const { return m_eyes; } void OSVRDisplayConfiguration::EyeInfo::print() const { std::cout << "Center of projection (X): " << m_CenterProjX << std::endl; std::cout << "Center of projection (Y): " << m_CenterProjY << std::endl; std::cout << "Rotate by 180: " << m_rotate180 << std::endl; } Don't duplicate a Json::Value when we can just use (and looked like we're trying to use) a const reference. /** @file @brief OSVR display configuration @date 2015 @author Sensics, Inc. <http://sensics.com> */ // Copyright 2015 Sensics, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Internal Includes #include "osvr_display_configuration.h" // Library/third-party includes #include <boost/units/io.hpp> #include <json/reader.h> #include <json/value.h> // Standard includes #include <cassert> #include <fstream> #include <iostream> // Included files that define built-in distortion meshes. #include "osvr_display_config_built_in_osvr_hdks.h" OSVRDisplayConfiguration::OSVRDisplayConfiguration() { // do nothing } OSVRDisplayConfiguration::OSVRDisplayConfiguration( const std::string& display_description) { parse(display_description); } inline void parseDistortionMonoPointMeshes( Json::Value const& distortion, osvr::renderkit::MonoPointDistortionMeshDescriptions& mesh) { Json::Value myDistortion = distortion; // See if we have the name of a built-in config to parse. If so, we open it // and grab its values to parse, replacing the ones that they sent // in. Json::Value const& builtIn = distortion["mono_point_samples_built_in"]; if ((!builtIn.isNull()) && (builtIn.isString())) { // Read a Json value from the built-in config, then replace the // distortion mesh with that from the file. std::string builtInString; Json::Value builtInData; if (builtIn.asString() == "OSVR_HDK_13_V1") { builtInString = osvr_display_config_built_in_osvr_hdk13_v1; } else if (builtIn.asString() == "OSVR_HDK_13_V2") { builtInString = osvr_display_config_built_in_osvr_hdk13_v2; } else if (builtIn.asString() == "OSVR_HDK_20_V1") { builtInString = osvr_display_config_built_in_osvr_hdk20_v1; } else { std::cerr << "OSVRDisplayConfiguration::parse(): ERROR: Unrecognized " "mono_point_samples_built_in value: " << builtIn.asString() << "!\n"; throw DisplayConfigurationParseException( "Couldn't open external mono point file."); } Json::Reader reader; if (!reader.parse(builtInString, builtInData)) { std::cerr << "OSVRDisplayConfiguration::parse(): ERROR: Couldn't " "parse built-in configuration " << builtIn.asString() << "!\n"; std::cerr << "Errors: " << reader.getFormattedErrorMessages(); throw DisplayConfigurationParseException( "Couldn't parse external mono point file."); } myDistortion = builtInData["display"]["hmd"]["distortion"]; } // See if we have the name of an external file to parse. If so, we open it // and grab its values to parse, replacing the ones that they sent // in. const Json::Value externalFile = distortion["mono_point_samples_external_file"]; if ((!externalFile.isNull()) && (externalFile.isString())) { // Read a Json value from the external file, then replace the distortion // mesh with that from the file. Json::Value externalData; Json::Reader reader; std::ifstream fs; fs.open(externalFile.asString().c_str(), std::fstream::in); if (!fs.is_open()) { std::cerr << "OSVRDisplayConfiguration::parse(): ERROR: Couldn't " "open file " << externalFile.asString() << "!\n"; throw DisplayConfigurationParseException( "Couldn't open external mono point file."); } if (!reader.parse(fs, externalData)) { std::cerr << "OSVRDisplayConfiguration::parse(): ERROR: Couldn't " "parse file " << externalFile.asString() << "!\n"; std::cerr << "Errors: " << reader.getFormattedErrorMessages(); throw DisplayConfigurationParseException( "Couldn't parse external mono point file."); } myDistortion = externalData["display"]["hmd"]["distortion"]; fs.close(); } const Json::Value eyeArray = myDistortion["mono_point_samples"]; if (eyeArray.isNull() || eyeArray.empty()) { /// @todo A proper "no-op" default should be placed here, instead of /// erroring out. std::cerr << "OSVRDisplayConfiguration::parse(): ERROR: Couldn't find " "non-empty distortion mono point distortion!\n"; throw DisplayConfigurationParseException( "Couldn't find non-empty mono point distortion."); } mesh.clear(); for (auto& pointArray : eyeArray) { osvr::renderkit::MonoPointDistortionMeshDescription eye; if (pointArray.empty()) { /// @todo A proper "no-op" default should be placed here, instead of /// erroring out. std::cerr << "OSVRDisplayConfiguration::parse(): ERROR: Empty " << " distortion mono point distortion list for eye!\n"; throw DisplayConfigurationParseException( "Empty mono point distortion list for eye."); } for (auto& elt : pointArray) { std::array<std::array<double, 2>, 2> point; if ((elt.size() != 2) || (elt[0].size() != 2) || (elt[1].size() != 2)) { /// @todo A proper "no-op" default should be placed here, /// instead of erroring out. std::cerr << "OSVRDisplayConfiguration::parse(): ERROR: Malformed" << " distortion mono point distortion list entry!\n"; throw DisplayConfigurationParseException( "Malformed mono point distortion list entry."); } std::array<double, 2> in, out; in[0] = (elt[0][0].asDouble()); in[1] = (elt[0][1].asDouble()); out[0] = (elt[1][0].asDouble()); out[1] = (elt[1][1].asDouble()); point[0] = (in); point[1] = (out); eye.push_back(point); } mesh.push_back(eye); } } inline void parseDistortionRGBPointMeshes( Json::Value const& distortion, osvr::renderkit::RGBPointDistortionMeshDescriptions& mesh) { Json::Value myDistortion = distortion; // See if we have the name of an external file to parse. If so, we open it // and grab its values to parse. Otherwise, we parse the ones that they // sent in. const Json::Value externalFile = distortion["rgb_point_samples_external_file"]; if ((!externalFile.isNull()) && (externalFile.isString())) { // Read a Json value from the external file, then replace the distortion // mesh with that from the file. Json::Value externalData; Json::Reader reader; std::ifstream fs; fs.open(externalFile.asString().c_str(), std::fstream::in); if (!fs.is_open()) { std::cerr << "OSVRDisplayConfiguration::parse(): ERROR: Couldn't " "open file " << externalFile.asString() << "!\n"; throw DisplayConfigurationParseException( "Couldn't open external rgb point file."); } if (!reader.parse(fs, externalData)) { std::cerr << "OSVRDisplayConfiguration::parse(): ERROR: Couldn't " "parse file " << externalFile.asString() << "!\n"; std::cerr << "Errors: " << reader.getFormattedErrorMessages(); throw DisplayConfigurationParseException( "Couldn't parse external rgb point file."); } myDistortion = externalData["display"]["hmd"]["distortion"]; fs.close(); } std::array<std::string, 3> names = { "red_point_samples", "green_point_samples", "blue_point_samples"}; for (size_t clr = 0; clr < 3; clr++) { const Json::Value eyeArray = myDistortion[names[clr].c_str()]; if (eyeArray.isNull() || eyeArray.empty()) { /// @todo A proper "no-op" default should be placed here, instead of /// erroring out. std::cerr << "OSVRDisplayConfiguration::parse(): ERROR: Couldn't find " "non-empty distortion rgb point distortion for " << names[clr] << std::endl; throw DisplayConfigurationParseException( "Couldn't find non-empty rgb point distortion."); } mesh[clr].clear(); for (auto& pointArray : eyeArray) { osvr::renderkit::MonoPointDistortionMeshDescription eye; if (pointArray.empty()) { /// @todo A proper "no-op" default should be placed here, /// instead of /// erroring out. std::cerr << "OSVRDisplayConfiguration::parse(): ERROR: Empty " << " distortion rgb point distortion list for eye!" << std::endl; throw DisplayConfigurationParseException( "Empty rgb point distortion list for eye."); } for (auto& elt : pointArray) { std::array<std::array<double, 2>, 2> point; if ((elt.size() != 2) || (elt[0].size() != 2) || (elt[1].size() != 2)) { /// @todo A proper "no-op" default should be placed here, /// instead of erroring out. std::cerr << "OSVRDisplayConfiguration::parse(): ERROR: Malformed" << " distortion rgb point distortion list entry!" << std::endl; throw DisplayConfigurationParseException( "Malformed rgb point distortion list entry."); } std::array<double, 2> in, out; in[0] = (elt[0][0].asDouble()); in[1] = (elt[0][1].asDouble()); out[0] = (elt[1][0].asDouble()); out[1] = (elt[1][1].asDouble()); point[0] = (in); point[1] = (out); eye.push_back(point); } mesh[clr].push_back(eye); } } } inline void parseDistortionPolynomial(Json::Value const& distortion, std::string const& color, std::vector<float>& polynomial) { const Json::Value distortArray = distortion["polynomial_coeffs_" + color]; if (distortArray.isNull() || distortArray.empty()) { /// @todo A proper "no-op" default should be placed here, instead of /// erroring out. std::cerr << "OSVRDisplayConfiguration::parse(): ERROR: Couldn't find " "non-empty " << color << " distortion coefficient array!\n"; throw DisplayConfigurationParseException( "Couldn't find non-empty " + color + " distortion coefficient array."); } polynomial.clear(); for (auto& elt : distortArray) { polynomial.push_back(elt.asFloat()); } } /// Returns a resolution and if it should swap eyes. inline std::pair<OSVRDisplayConfiguration::Resolution, bool> parseResolution(Json::Value const& resolution) { // if there is more than 1 input, display descriptor right now // specifies one resolution value for both inputs. that may be // changed in the future OSVRDisplayConfiguration::Resolution res; res.video_inputs = resolution.get("video_inputs", 1).asInt(); // Window bounds res.width = resolution["width"].asInt(); res.height = resolution["height"].asInt(); // Display mode - Default to horiz side by side unless we have // multiple video inputs, then default to full screen (? seems // logical but not strictly what the json schema specifies) res.display_mode = (res.video_inputs > 1 ? OSVRDisplayConfiguration::FULL_SCREEN : OSVRDisplayConfiguration::HORIZONTAL_SIDE_BY_SIDE); auto const& display_mode = resolution["display_mode"]; if (display_mode.isString()) { const std::string display_mode_str = display_mode.asString(); if ("horz_side_by_side" == display_mode_str) { res.display_mode = OSVRDisplayConfiguration::HORIZONTAL_SIDE_BY_SIDE; } else if ("vert_side_by_side" == display_mode_str) { res.display_mode = OSVRDisplayConfiguration::VERTICAL_SIDE_BY_SIDE; } else if ("full_screen" == display_mode_str) { res.display_mode = OSVRDisplayConfiguration::FULL_SCREEN; } else { std::cerr << "OSVRDisplayConfiguration::parse(): WARNING: " "Unknown display mode string: " << display_mode_str << " (using default)\n"; } } auto const& eyeSwap = resolution["swap_eyes"]; auto doEyeSwap = !eyeSwap.isNull() && eyeSwap.asBool(); return std::make_pair(std::move(res), doEyeSwap); } void OSVRDisplayConfiguration::parse(const std::string& display_description) { Json::Value root; { Json::Reader reader; if (!reader.parse(display_description, root, false)) { std::cerr << "OSVRDisplayConfiguration::parse(): ERROR: Couldn't " "parse the display descriptor as JSON!\n"; throw DisplayConfigurationParseException( "Couldn't parse the display descriptor as JSON."); } } using namespace osvr; auto const& hmd = root["hmd"]; { auto const& fov = hmd["field_of_view"]; // Field of view m_monocularHorizontalFOV = util::Angle(fov["monocular_horizontal"].asDouble() * util::degrees); m_monocularVerticalFOV = util::Angle(fov["monocular_vertical"].asDouble() * util::degrees); m_overlapPercent = fov.get("overlap_percent", 100).asDouble() / 100.0; m_pitchTilt = util::Angle(fov.get("pitch_tilt", 0).asDouble() * util::degrees); } { // Device properties auto processDeviceData = [&](Json::Value const& devprops) { m_vendor = devprops["vendor"].asString(); m_model = devprops["model"].asString(); m_version = devprops["Version"].asString(); m_note = devprops["Note"].asString(); }; // In the canonical schema, this is where those properties live. // However, in some legacy directmode config files, they are in a // sub-object called "properties". Thus, we'll call the above lambda // with only one of the two. auto const& devprops = hmd["device"]; auto const& subproperties = devprops["properties"]; if (!subproperties.isNull() && !subproperties.empty()) { // legacy descriptor std::cerr << "OSVRDisplayConfiguration::parse(): WARNING: Your " "display descriptor is outdated (using an outdated " "schema) and may not work with all applications. " "Please check with your vendor or the OSVR community " "to get an updated one matching the most recent JSON " "Schema for display descriptors.\n"; processDeviceData(subproperties); } else { processDeviceData(devprops); } } { auto const& resolutions = hmd["resolutions"]; if (resolutions.isNull()) { std::cerr << "OSVRDisplayConfiguration::parse(): ERROR: Couldn't " "find resolutions array!\n"; throw DisplayConfigurationParseException( "Couldn't find resolutions array."); } bool first = true; for (auto const& resolution : resolutions) { Resolution res; bool swapEyes; std::tie(res, swapEyes) = parseResolution(resolution); m_resolutions.push_back(res); if (first) { m_swapEyes = swapEyes; first = false; } } if (m_resolutions.empty()) { // We couldn't find any appropriate resolution entries std::cerr << "OSVRDisplayConfiguration::parse(): ERROR: Couldn't " "find any appropriate resolutions.\n"; throw DisplayConfigurationParseException( "Couldn't find resolutions array or any appropriate " "resolutions."); return; } } { auto const& rendering = hmd["rendering"]; m_rightRoll = rendering.get("right_roll", 0).asDouble(); m_leftRoll = rendering.get("left_roll", 0).asDouble(); } { auto const& distortion = hmd["distortion"]; /// We will detect distortion type based on either the explicitly /// specified string or the presence of essential object members. m_distortionTypeString = distortion["type"].asString(); if (m_distortionTypeString == "rgb_symmetric_polynomials" || distortion.isMember("polynomial_coeffs_red")) { std::cout << "OSVRDisplayConfiguration::parse(): Using polynomial " "distortion.\n"; m_distortionType = RGB_SYMMETRIC_POLYNOMIALS; m_distortionDistanceScaleX = distortion.get("distance_scale_x", 1.f).asFloat(); m_distortionDistanceScaleY = distortion.get("distance_scale_y", 1.f).asFloat(); parseDistortionPolynomial(distortion, "red", m_distortionPolynomialRed); parseDistortionPolynomial(distortion, "green", m_distortionPolynomialGreen); parseDistortionPolynomial(distortion, "blue", m_distortionPolynomialBlue); } else if (m_distortionTypeString == "mono_point_samples" || distortion.isMember("mono_point_samples") || distortion.isMember("mono_point_samples_built_in") || distortion.isMember("mono_point_samples_external_file")) { std::cout << "OSVRDisplayConfiguration::parse(): Using mono point " "sample distortion.\n"; m_distortionType = MONO_POINT_SAMPLES; parseDistortionMonoPointMeshes(distortion, m_distortionMonoPointMesh); } else if (m_distortionTypeString == "rgb_point_samples" || distortion.isMember("rgb_point_samples") || distortion.isMember("rgb_point_samples_external_file")) { std::cout << "OSVRDisplayConfiguration::parse(): Using rgb point " "sample distortion.\n"; m_distortionType = RGB_POINT_SAMPLES; parseDistortionRGBPointMeshes(distortion, m_distortionRGBPointMesh); } else if (m_distortionTypeString == "rgb_k1_coefficients") { #if 0 // Simple distortion params ignored by RenderManager /// @todo how to use these, or use them if non-zero, to set up /// distortion? double k1_red = distortion.get("k1_red", 0).asDouble(); double k1_green = distortion.get("k1_green", 0).asDouble(); double k1_blue = distortion.get("k1_blue", 0).asDouble(); #endif m_distortionType = RGB_SYMMETRIC_POLYNOMIALS; m_distortionDistanceScaleX = 1.f; m_distortionDistanceScaleY = 1.f; m_distortionPolynomialRed = {0.f, 1.f}; m_distortionPolynomialGreen = {0.f, 1.f}; m_distortionPolynomialBlue = {0.f, 1.f}; } else if (!m_distortionTypeString.empty()) { std::cerr << "OSVRDisplayConfiguration::parse(): ERROR: Unrecognized " "distortion type: " << m_distortionTypeString << std::endl; throw DisplayConfigurationParseException( "Unrecognized distortion type: " + m_distortionTypeString); } else { std::cout << "OSVRDisplayConfiguration::parse(): No " "RenderManager-compatible distortion parameters " "found, falling back to an identity polynomial.\n"; m_distortionType = RGB_SYMMETRIC_POLYNOMIALS; m_distortionDistanceScaleX = 1.f; m_distortionDistanceScaleY = 1.f; m_distortionPolynomialRed = {0.f, 1.f}; m_distortionPolynomialGreen = {0.f, 1.f}; m_distortionPolynomialBlue = {0.f, 1.f}; } } { auto const& eyes = hmd["eyes"]; if (eyes.isNull()) { std::cerr << "OSVRDisplayConfiguration::parse(): ERROR: " "Couldn't find eyes array!\n"; throw DisplayConfigurationParseException( "Couldn't find eyes array."); } for (auto const& eye : eyes) { EyeInfo e; e.m_CenterProjX = eye.get("center_proj_x", 0.5).asDouble(); e.m_CenterProjY = eye.get("center_proj_y", 0.5).asDouble(); if (eye.isMember("rotate_180")) { auto const& rot = eye["rotate_180"]; if (rot.isBool()) { e.m_rotate180 = rot.asBool(); } else { e.m_rotate180 = (rot.asInt() != 0); } } m_eyes.push_back(e); } } } void OSVRDisplayConfiguration::print() const { std::cout << "Monocular horizontal FOV: " << m_monocularHorizontalFOV << std::endl; std::cout << "Monocular vertical FOV: " << m_monocularVerticalFOV << std::endl; std::cout << "Overlap percent: " << m_overlapPercent << "%" << std::endl; std::cout << "Pitch tilt: " << m_pitchTilt << std::endl; std::cout << "Resolution: " << activeResolution().width << " x " << activeResolution().height << std::endl; std::cout << "Video inputs: " << activeResolution().video_inputs << std::endl; std::cout << "Display mode: " << activeResolution().display_mode << std::endl; std::cout << "Right roll: " << m_rightRoll << std::endl; std::cout << "Left roll: " << m_leftRoll << std::endl; std::cout << "Number of eyes: " << m_eyes.size() << std::endl; for (std::vector<EyeInfo>::size_type i = 0; i < m_eyes.size(); ++i) { std::cout << "Eye " << i << ": " << std::endl; m_eyes[i].print(); } } std::string OSVRDisplayConfiguration::getVendor() const { return m_vendor; } std::string OSVRDisplayConfiguration::getModel() const { return m_model; } std::string OSVRDisplayConfiguration::getVersion() const { return m_version; } std::string OSVRDisplayConfiguration::getNote() const { return m_note; } int OSVRDisplayConfiguration::getNumDisplays() const { if (m_eyes.size() < 2) { return 1; } // OK, so two eyes now. if (activeResolution().display_mode == DisplayMode::FULL_SCREEN) { assert(activeResolution().video_inputs == 2); return 2; } return 1; } int OSVRDisplayConfiguration::getDisplayTop() const { return 0; } int OSVRDisplayConfiguration::getDisplayLeft() const { return 0; } int OSVRDisplayConfiguration::getDisplayWidth() const { return activeResolution().width; } int OSVRDisplayConfiguration::getDisplayHeight() const { return activeResolution().height; } OSVRDisplayConfiguration::DisplayMode OSVRDisplayConfiguration::getDisplayMode() const { return activeResolution().display_mode; } osvr::util::Angle OSVRDisplayConfiguration::getVerticalFOV() const { return m_monocularVerticalFOV; } osvr::util::Angle OSVRDisplayConfiguration::getHorizontalFOV() const { return m_monocularHorizontalFOV; } #if 0 double OSVRDisplayConfiguration::getVerticalFOV() const { return m_MonocularVerticalFOV; } double OSVRDisplayConfiguration::getVerticalFOVRadians() const { return m_MonocularVerticalFOV * M_PI / 180.0; } double OSVRDisplayConfiguration::getHorizontalFOV() const { return m_MonocularHorizontalFOV; } double OSVRDisplayConfiguration::getHorizontalFOVRadians() const { return m_MonocularHorizontalFOV * M_PI / 180.0; } #endif double OSVRDisplayConfiguration::getOverlapPercent() const { return m_overlapPercent; } osvr::util::Angle OSVRDisplayConfiguration::getPitchTilt() const { return m_pitchTilt; } double OSVRDisplayConfiguration::getIPDMeters() const { return m_IPDMeters; } bool OSVRDisplayConfiguration::getSwapEyes() const { return m_swapEyes; } std::string OSVRDisplayConfiguration::getDistortionTypeString() const { return m_distortionTypeString; } osvr::renderkit::MonoPointDistortionMeshDescriptions OSVRDisplayConfiguration::getDistortionMonoPointMeshes() const { return m_distortionMonoPointMesh; } osvr::renderkit::RGBPointDistortionMeshDescriptions OSVRDisplayConfiguration::getDistortionRGBPointMeshes() const { return m_distortionRGBPointMesh; } float OSVRDisplayConfiguration::getDistortionDistanceScaleX() const { return m_distortionDistanceScaleX; } float OSVRDisplayConfiguration::getDistortionDistanceScaleY() const { return m_distortionDistanceScaleY; } std::vector<float> const& OSVRDisplayConfiguration::getDistortionPolynomalRed() const { return m_distortionPolynomialRed; } std::vector<float> const& OSVRDisplayConfiguration::getDistortionPolynomalGreen() const { return m_distortionPolynomialGreen; } std::vector<float> const& OSVRDisplayConfiguration::getDistortionPolynomalBlue() const { return m_distortionPolynomialBlue; } std::vector<OSVRDisplayConfiguration::EyeInfo> const& OSVRDisplayConfiguration::getEyes() const { return m_eyes; } void OSVRDisplayConfiguration::EyeInfo::print() const { std::cout << "Center of projection (X): " << m_CenterProjX << std::endl; std::cout << "Center of projection (Y): " << m_CenterProjY << std::endl; std::cout << "Rotate by 180: " << m_rotate180 << std::endl; }
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #include <ZipPackageEntry.hxx> #include <com/sun/star/packages/zip/ZipConstants.hpp> #include <osl/diagnose.h> #include <ZipPackageFolder.hxx> #include <ZipPackageStream.hxx> #include <ContentInfo.hxx> #include <comphelper/storagehelper.hxx> using namespace com::sun::star; using namespace com::sun::star::uno; using namespace com::sun::star::lang; using namespace com::sun::star::container; using namespace com::sun::star::packages::zip; using namespace com::sun::star::packages::zip::ZipConstants; #if OSL_DEBUG_LEVEL > 0 #define THROW_WHERE SAL_WHERE #else #define THROW_WHERE "" #endif ZipPackageEntry::ZipPackageEntry() : mbIsFolder( false ) , mpParent ( NULL ) { } ZipPackageEntry::~ZipPackageEntry() { // When the entry is destroyed it must be already disconnected from the parent OSL_ENSURE( !mpParent, "The parent must be disconnected already! Memory corruption is possible!\n" ); } // XChild OUString SAL_CALL ZipPackageEntry::getName( ) throw(RuntimeException, std::exception) { return msName; } void SAL_CALL ZipPackageEntry::setName( const OUString& aName ) throw(RuntimeException, std::exception) { if ( mpParent && !msName.isEmpty() && mpParent->hasByName ( msName ) ) mpParent->removeByName ( msName ); // unfortunately no other exception than RuntimeException can be thrown here // usually the package is used through storage implementation, the problem should be detected there if ( !::comphelper::OStorageHelper::IsValidZipEntryFileName( aName, true ) ) throw RuntimeException(THROW_WHERE "Unexpected character is used in file name." ); msName = aName; if ( mpParent ) mpParent->doInsertByName ( this, false ); } uno::Reference< XInterface > SAL_CALL ZipPackageEntry::getParent( ) throw(RuntimeException, std::exception) { // return uno::Reference< XInterface >( xParent, UNO_QUERY ); return uno::Reference< XInterface >( static_cast< ::cppu::OWeakObject* >( mpParent ), UNO_QUERY ); } void ZipPackageEntry::doSetParent ( ZipPackageFolder * pNewParent, bool bInsert ) { // xParent = mpParent = pNewParent; mpParent = pNewParent; if ( bInsert && !msName.isEmpty() && !pNewParent->hasByName ( msName ) ) pNewParent->doInsertByName ( this, false ); } void SAL_CALL ZipPackageEntry::setParent( const uno::Reference< XInterface >& xNewParent ) throw(NoSupportException, RuntimeException, std::exception) { sal_Int64 nTest(0); uno::Reference < XUnoTunnel > xTunnel ( xNewParent, UNO_QUERY ); if ( !xNewParent.is() || ( nTest = xTunnel->getSomething ( ZipPackageFolder::static_getImplementationId () ) ) == 0 ) throw NoSupportException(THROW_WHERE ); ZipPackageFolder *pNewParent = reinterpret_cast < ZipPackageFolder * > ( nTest ); if ( pNewParent != mpParent ) { if ( mpParent && !msName.isEmpty() && mpParent->hasByName ( msName ) && mbAllowRemoveOnInsert ) mpParent->removeByName( msName ); doSetParent ( pNewParent, true ); } } //XPropertySet uno::Reference< beans::XPropertySetInfo > SAL_CALL ZipPackageEntry::getPropertySetInfo( ) throw(RuntimeException, std::exception) { return uno::Reference < beans::XPropertySetInfo > (); } void SAL_CALL ZipPackageEntry::addPropertyChangeListener( const OUString& /*aPropertyName*/, const uno::Reference< beans::XPropertyChangeListener >& /*xListener*/ ) throw(beans::UnknownPropertyException, WrappedTargetException, RuntimeException, std::exception) { } void SAL_CALL ZipPackageEntry::removePropertyChangeListener( const OUString& /*aPropertyName*/, const uno::Reference< beans::XPropertyChangeListener >& /*aListener*/ ) throw(beans::UnknownPropertyException, WrappedTargetException, RuntimeException, std::exception) { } void SAL_CALL ZipPackageEntry::addVetoableChangeListener( const OUString& /*PropertyName*/, const uno::Reference< beans::XVetoableChangeListener >& /*aListener*/ ) throw(beans::UnknownPropertyException, WrappedTargetException, RuntimeException, std::exception) { } void SAL_CALL ZipPackageEntry::removeVetoableChangeListener( const OUString& /*PropertyName*/, const uno::Reference< beans::XVetoableChangeListener >& /*aListener*/ ) throw(beans::UnknownPropertyException, WrappedTargetException, RuntimeException, std::exception) { } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ cid#1249676 Uninitialized scalar field Change-Id: I87df4e9c1d3f36afccf13aebfd95d1b4f3bfa655 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #include <ZipPackageEntry.hxx> #include <com/sun/star/packages/zip/ZipConstants.hpp> #include <osl/diagnose.h> #include <ZipPackageFolder.hxx> #include <ZipPackageStream.hxx> #include <ContentInfo.hxx> #include <comphelper/storagehelper.hxx> using namespace com::sun::star; using namespace com::sun::star::uno; using namespace com::sun::star::lang; using namespace com::sun::star::container; using namespace com::sun::star::packages::zip; using namespace com::sun::star::packages::zip::ZipConstants; #if OSL_DEBUG_LEVEL > 0 #define THROW_WHERE SAL_WHERE #else #define THROW_WHERE "" #endif ZipPackageEntry::ZipPackageEntry() : mbIsFolder( false ) , mbAllowRemoveOnInsert(false) , mpParent ( NULL ) , m_nFormat(0) { } ZipPackageEntry::~ZipPackageEntry() { // When the entry is destroyed it must be already disconnected from the parent OSL_ENSURE( !mpParent, "The parent must be disconnected already! Memory corruption is possible!\n" ); } // XChild OUString SAL_CALL ZipPackageEntry::getName( ) throw(RuntimeException, std::exception) { return msName; } void SAL_CALL ZipPackageEntry::setName( const OUString& aName ) throw(RuntimeException, std::exception) { if ( mpParent && !msName.isEmpty() && mpParent->hasByName ( msName ) ) mpParent->removeByName ( msName ); // unfortunately no other exception than RuntimeException can be thrown here // usually the package is used through storage implementation, the problem should be detected there if ( !::comphelper::OStorageHelper::IsValidZipEntryFileName( aName, true ) ) throw RuntimeException(THROW_WHERE "Unexpected character is used in file name." ); msName = aName; if ( mpParent ) mpParent->doInsertByName ( this, false ); } uno::Reference< XInterface > SAL_CALL ZipPackageEntry::getParent( ) throw(RuntimeException, std::exception) { // return uno::Reference< XInterface >( xParent, UNO_QUERY ); return uno::Reference< XInterface >( static_cast< ::cppu::OWeakObject* >( mpParent ), UNO_QUERY ); } void ZipPackageEntry::doSetParent ( ZipPackageFolder * pNewParent, bool bInsert ) { // xParent = mpParent = pNewParent; mpParent = pNewParent; if ( bInsert && !msName.isEmpty() && !pNewParent->hasByName ( msName ) ) pNewParent->doInsertByName ( this, false ); } void SAL_CALL ZipPackageEntry::setParent( const uno::Reference< XInterface >& xNewParent ) throw(NoSupportException, RuntimeException, std::exception) { sal_Int64 nTest(0); uno::Reference < XUnoTunnel > xTunnel ( xNewParent, UNO_QUERY ); if ( !xNewParent.is() || ( nTest = xTunnel->getSomething ( ZipPackageFolder::static_getImplementationId () ) ) == 0 ) throw NoSupportException(THROW_WHERE ); ZipPackageFolder *pNewParent = reinterpret_cast < ZipPackageFolder * > ( nTest ); if ( pNewParent != mpParent ) { if ( mpParent && !msName.isEmpty() && mpParent->hasByName ( msName ) && mbAllowRemoveOnInsert ) mpParent->removeByName( msName ); doSetParent ( pNewParent, true ); } } //XPropertySet uno::Reference< beans::XPropertySetInfo > SAL_CALL ZipPackageEntry::getPropertySetInfo( ) throw(RuntimeException, std::exception) { return uno::Reference < beans::XPropertySetInfo > (); } void SAL_CALL ZipPackageEntry::addPropertyChangeListener( const OUString& /*aPropertyName*/, const uno::Reference< beans::XPropertyChangeListener >& /*xListener*/ ) throw(beans::UnknownPropertyException, WrappedTargetException, RuntimeException, std::exception) { } void SAL_CALL ZipPackageEntry::removePropertyChangeListener( const OUString& /*aPropertyName*/, const uno::Reference< beans::XPropertyChangeListener >& /*aListener*/ ) throw(beans::UnknownPropertyException, WrappedTargetException, RuntimeException, std::exception) { } void SAL_CALL ZipPackageEntry::addVetoableChangeListener( const OUString& /*PropertyName*/, const uno::Reference< beans::XVetoableChangeListener >& /*aListener*/ ) throw(beans::UnknownPropertyException, WrappedTargetException, RuntimeException, std::exception) { } void SAL_CALL ZipPackageEntry::removeVetoableChangeListener( const OUString& /*PropertyName*/, const uno::Reference< beans::XVetoableChangeListener >& /*aListener*/ ) throw(beans::UnknownPropertyException, WrappedTargetException, RuntimeException, std::exception) { } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */
#include "multi_dimension_array.h" #include <vector> using std::vector; #include <stdio.h> #include <sys/time.h> int main() { size_t size = 2; const size_t rowlen = 5000; vector<size_t> dims; dims.resize(size, rowlen); vector<size_t> position; position.resize(size, 0); double **raw_array = new double*[rowlen]; double *flat_array = new double[rowlen * rowlen]; for (size_t i = 0; i < rowlen; ++i) { raw_array[i] = new double[rowlen]; for (size_t j = 0; j < rowlen; ++j) { raw_array[i][j] = 42.0; flat_array[i * rowlen + j] = 42.0; } } MultiDimensionArray<double> array(dims, 42.0); // ===== RAW ARRAY ===== // struct timeval begin, end, diff; gettimeofday(&begin, NULL); double sum = 0.0; for (size_t i = 0; i < rowlen; ++i) { for (size_t j = 0; j < rowlen; ++j) { sum += raw_array[i][j]; } } gettimeofday(&end, NULL); diff.tv_sec = end.tv_sec - begin.tv_sec; if (end.tv_usec < begin.tv_usec) { --diff.tv_sec; end.tv_usec += 1000000; } diff.tv_usec = end.tv_usec - begin.tv_usec; double seconds = diff.tv_sec + (diff.tv_usec / 1000000.0); fprintf(stderr, "raw array took %f seconds; sum=%f\n", seconds, sum); // ===== FLAT ARRAY ===== // gettimeofday(&begin, NULL); sum = 0.0; for (size_t i = 0; i < rowlen; ++i) { for (size_t j = 0; j < rowlen; ++j) { sum += flat_array[i * rowlen + j]; } } gettimeofday(&end, NULL); diff.tv_sec = end.tv_sec - begin.tv_sec; if (end.tv_usec < begin.tv_usec) { --diff.tv_sec; end.tv_usec += 1000000; } diff.tv_usec = end.tv_usec - begin.tv_usec; seconds = diff.tv_sec + (diff.tv_usec / 1000000.0); fprintf(stderr, "flat array took %f seconds; sum=%f\n", seconds, sum); // ===== MultiDimensionArray ===== // gettimeofday(&begin, NULL); sum = 0.0; for (size_t i = 0; i < rowlen; ++i) { position[0] = i; for (size_t j = 0; j < rowlen; ++j) { position[1] = j; sum += array.at(position); } } gettimeofday(&end, NULL); diff.tv_sec = end.tv_sec - begin.tv_sec; if (end.tv_usec < begin.tv_usec) { --diff.tv_sec; end.tv_usec += 1000000; } diff.tv_usec = end.tv_usec - begin.tv_usec; seconds = diff.tv_sec + (diff.tv_usec / 1000000.0); fprintf(stderr, "MultiDimensionArray took %f seconds; sum=%f\n", seconds, sum); return 0; } Added boost array test. #include "multi_dimension_array.h" #include <vector> using std::vector; #include <stdio.h> #include <sys/time.h> #include <boost/multi_array.hpp> int main() { size_t size = 2; const size_t rowlen = 5000; vector<size_t> dims; dims.resize(size, rowlen); vector<size_t> position; position.resize(size, 0); double **raw_array = new double*[rowlen]; double *flat_array = new double[rowlen * rowlen]; boost::multi_array<double, 2> boost_array(boost::extents[rowlen][rowlen]); for (size_t i = 0; i < rowlen; ++i) { raw_array[i] = new double[rowlen]; for (size_t j = 0; j < rowlen; ++j) { raw_array[i][j] = 42.0; flat_array[i * rowlen + j] = 42.0; boost_array[i][j] = 42.0; } } MultiDimensionArray<double> array(dims, 42.0); // ===== RAW ARRAY ===== // struct timeval begin, end, diff; gettimeofday(&begin, NULL); double sum = 0.0; for (size_t i = 0; i < rowlen; ++i) { for (size_t j = 0; j < rowlen; ++j) { sum += raw_array[i][j]; } } gettimeofday(&end, NULL); diff.tv_sec = end.tv_sec - begin.tv_sec; if (end.tv_usec < begin.tv_usec) { --diff.tv_sec; end.tv_usec += 1000000; } diff.tv_usec = end.tv_usec - begin.tv_usec; double seconds = diff.tv_sec + (diff.tv_usec / 1000000.0); fprintf(stderr, "raw array took %f seconds; sum=%f\n", seconds, sum); // ===== FLAT ARRAY ===== // gettimeofday(&begin, NULL); sum = 0.0; for (size_t i = 0; i < rowlen; ++i) { for (size_t j = 0; j < rowlen; ++j) { sum += flat_array[i * rowlen + j]; } } gettimeofday(&end, NULL); diff.tv_sec = end.tv_sec - begin.tv_sec; if (end.tv_usec < begin.tv_usec) { --diff.tv_sec; end.tv_usec += 1000000; } diff.tv_usec = end.tv_usec - begin.tv_usec; seconds = diff.tv_sec + (diff.tv_usec / 1000000.0); fprintf(stderr, "flat array took %f seconds; sum=%f\n", seconds, sum); // ===== MultiDimensionArray ===== // gettimeofday(&begin, NULL); sum = 0.0; for (size_t i = 0; i < rowlen; ++i) { position[0] = i; for (size_t j = 0; j < rowlen; ++j) { position[1] = j; sum += array.at(position); } } gettimeofday(&end, NULL); diff.tv_sec = end.tv_sec - begin.tv_sec; if (end.tv_usec < begin.tv_usec) { --diff.tv_sec; end.tv_usec += 1000000; } diff.tv_usec = end.tv_usec - begin.tv_usec; seconds = diff.tv_sec + (diff.tv_usec / 1000000.0); fprintf(stderr, "MultiDimensionArray took %f seconds; sum=%f\n", seconds, sum); // ===== boost::multi_array ===== // gettimeofday(&begin, NULL); sum = 0.0; for (size_t i = 0; i < rowlen; ++i) { for (size_t j = 0; j < rowlen; ++j) { sum += boost_array[i][j]; } } gettimeofday(&end, NULL); diff.tv_sec = end.tv_sec - begin.tv_sec; if (end.tv_usec < begin.tv_usec) { --diff.tv_sec; end.tv_usec += 1000000; } diff.tv_usec = end.tv_usec - begin.tv_usec; seconds = diff.tv_sec + (diff.tv_usec / 1000000.0); fprintf(stderr, "boost::multi_array took %f seconds; sum=%f\n", seconds, sum); return 0; }
// Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2018 The PIVX developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "init.h" #include "main.h" #include "addrman.h" #include "masternode-budget.h" #include "masternode-sync.h" #include "masternode.h" #include "masternodeman.h" #include "obfuscation.h" #include "util.h" #include <boost/filesystem.hpp> #include <boost/lexical_cast.hpp> CBudgetManager budget; CCriticalSection cs_budget; std::map<uint256, int64_t> askedForSourceProposalOrBudget; std::vector<CBudgetProposalBroadcast> vecImmatureBudgetProposals; std::vector<CFinalizedBudgetBroadcast> vecImmatureFinalizedBudgets; int nSubmittedFinalBudget; int GetBudgetPaymentCycleBlocks() { // Amount of blocks in a months period of time (using 1 minutes per) = (60*24*30) if (Params().NetworkID() == CBaseChainParams::MAIN) return 43200; //for testing purposes return 144; //ten times per day } bool IsBudgetCollateralValid(uint256 nTxCollateralHash, uint256 nExpectedHash, std::string& strError, int64_t& nTime, int& nConf, bool fBudgetFinalization) { CTransaction txCollateral; uint256 nBlockHash; if (!GetTransaction(nTxCollateralHash, txCollateral, nBlockHash, true)) { strError = strprintf("Can't find collateral tx %s", txCollateral.ToString()); LogPrint("mnbudget","CBudgetProposalBroadcast::IsBudgetCollateralValid - %s\n", strError); return false; } if (txCollateral.vout.size() < 1) return false; if (txCollateral.nLockTime != 0) return false; CScript findScript; findScript << OP_RETURN << ToByteVector(nExpectedHash); bool foundOpReturn = false; BOOST_FOREACH (const CTxOut o, txCollateral.vout) { if (!o.scriptPubKey.IsNormalPaymentScript() && !o.scriptPubKey.IsUnspendable()) { strError = strprintf("Invalid Script %s", txCollateral.ToString()); LogPrint("mnbudget","CBudgetProposalBroadcast::IsBudgetCollateralValid - %s\n", strError); return false; } if (fBudgetFinalization) { // Collateral for budget finalization // Note: there are still old valid budgets out there, but the check for the new 5 PIV finalization collateral // will also cover the old 50 PIV finalization collateral. LogPrint("mnbudget", "Final Budget: o.scriptPubKey(%s) == findScript(%s) ?\n", o.scriptPubKey.ToString(), findScript.ToString()); if (o.scriptPubKey == findScript) { LogPrint("mnbudget", "Final Budget: o.nValue(%ld) >= BUDGET_FEE_TX(%ld) ?\n", o.nValue, BUDGET_FEE_TX); if(o.nValue >= BUDGET_FEE_TX) { foundOpReturn = true; } } } else { // Collateral for normal budget proposal LogPrint("mnbudget", "Normal Budget: o.scriptPubKey(%s) == findScript(%s) ?\n", o.scriptPubKey.ToString(), findScript.ToString()); if (o.scriptPubKey == findScript) { LogPrint("mnbudget", "Normal Budget: o.nValue(%ld) >= PROPOSAL_FEE_TX(%ld) ?\n", o.nValue, PROPOSAL_FEE_TX); if(o.nValue >= PROPOSAL_FEE_TX) { foundOpReturn = true; } } } } if (!foundOpReturn) { strError = strprintf("Couldn't find opReturn %s in %s", nExpectedHash.ToString(), txCollateral.ToString()); LogPrint("mnbudget","CBudgetProposalBroadcast::IsBudgetCollateralValid - %s\n", strError); return false; } // RETRIEVE CONFIRMATIONS AND NTIME /* - nTime starts as zero and is passed-by-reference out of this function and stored in the external proposal - nTime is never validated via the hashing mechanism and comes from a full-validated source (the blockchain) */ int conf = GetIXConfirmations(nTxCollateralHash); if (nBlockHash != uint256(0)) { BlockMap::iterator mi = mapBlockIndex.find(nBlockHash); if (mi != mapBlockIndex.end() && (*mi).second) { CBlockIndex* pindex = (*mi).second; if (chainActive.Contains(pindex)) { conf += chainActive.Height() - pindex->nHeight + 1; nTime = pindex->nTime; } } } nConf = conf; //if we're syncing we won't have swiftTX information, so accept 1 confirmation if (conf >= Params().Budget_Fee_Confirmations()) { return true; } else { strError = strprintf("Collateral requires at least %d confirmations - %d confirmations", Params().Budget_Fee_Confirmations(), conf); LogPrint("mnbudget","CBudgetProposalBroadcast::IsBudgetCollateralValid - %s - %d confirmations\n", strError, conf); return false; } } void CBudgetManager::CheckOrphanVotes() { LOCK(cs); std::string strError = ""; std::map<uint256, CBudgetVote>::iterator it1 = mapOrphanMasternodeBudgetVotes.begin(); while (it1 != mapOrphanMasternodeBudgetVotes.end()) { if (budget.UpdateProposal(((*it1).second), NULL, strError)) { LogPrint("mnbudget","CBudgetManager::CheckOrphanVotes - Proposal/Budget is known, activating and removing orphan vote\n"); mapOrphanMasternodeBudgetVotes.erase(it1++); } else { ++it1; } } std::map<uint256, CFinalizedBudgetVote>::iterator it2 = mapOrphanFinalizedBudgetVotes.begin(); while (it2 != mapOrphanFinalizedBudgetVotes.end()) { if (budget.UpdateFinalizedBudget(((*it2).second), NULL, strError)) { LogPrint("mnbudget","CBudgetManager::CheckOrphanVotes - Proposal/Budget is known, activating and removing orphan vote\n"); mapOrphanFinalizedBudgetVotes.erase(it2++); } else { ++it2; } } LogPrint("mnbudget","CBudgetManager::CheckOrphanVotes - Done\n"); } void CBudgetManager::SubmitFinalBudget() { static int nSubmittedHeight = 0; // height at which final budget was submitted last time int nCurrentHeight; { TRY_LOCK(cs_main, locked); if (!locked) return; if (!chainActive.Tip()) return; nCurrentHeight = chainActive.Height(); } int nBlockStart = nCurrentHeight - nCurrentHeight % GetBudgetPaymentCycleBlocks() + GetBudgetPaymentCycleBlocks(); if (nSubmittedHeight >= nBlockStart){ LogPrint("mnbudget","CBudgetManager::SubmitFinalBudget - nSubmittedHeight(=%ld) < nBlockStart(=%ld) condition not fulfilled.\n", nSubmittedHeight, nBlockStart); return; } // Submit final budget during the last 2 days (2880 blocks) before payment for Mainnet, about 9 minutes (9 blocks) for Testnet int finalizationWindow = ((GetBudgetPaymentCycleBlocks() / 30) * 2); if (Params().NetworkID() == CBaseChainParams::TESTNET) { // NOTE: 9 blocks for testnet is way to short to have any masternode submit an automatic vote on the finalized(!) budget, // because those votes are only submitted/relayed once every 56 blocks in CFinalizedBudget::AutoCheck() finalizationWindow = 64; // 56 + 4 finalization confirmations + 4 minutes buffer for propagation } int nFinalizationStart = nBlockStart - finalizationWindow; int nOffsetToStart = nFinalizationStart - nCurrentHeight; if (nBlockStart - nCurrentHeight > finalizationWindow) { LogPrint("mnbudget","CBudgetManager::SubmitFinalBudget - Too early for finalization. Current block is %ld, next Superblock is %ld.\n", nCurrentHeight, nBlockStart); LogPrint("mnbudget","CBudgetManager::SubmitFinalBudget - First possible block for finalization: %ld. Last possible block for finalization: %ld. You have to wait for %ld block(s) until Budget finalization will be possible\n", nFinalizationStart, nBlockStart, nOffsetToStart); return; } std::vector<CBudgetProposal*> vBudgetProposals = budget.GetBudget(); std::string strBudgetName = "main"; std::vector<CTxBudgetPayment> vecTxBudgetPayments; for (unsigned int i = 0; i < vBudgetProposals.size(); i++) { CTxBudgetPayment txBudgetPayment; txBudgetPayment.nProposalHash = vBudgetProposals[i]->GetHash(); txBudgetPayment.payee = vBudgetProposals[i]->GetPayee(); txBudgetPayment.nAmount = vBudgetProposals[i]->GetAllotted(); vecTxBudgetPayments.push_back(txBudgetPayment); } if (vecTxBudgetPayments.size() < 1) { LogPrint("mnbudget","CBudgetManager::SubmitFinalBudget - Found No Proposals For Period\n"); return; } CFinalizedBudgetBroadcast tempBudget(strBudgetName, nBlockStart, vecTxBudgetPayments, 0); if (mapSeenFinalizedBudgets.count(tempBudget.GetHash())) { LogPrint("mnbudget","CBudgetManager::SubmitFinalBudget - Budget already exists - %s\n", tempBudget.GetHash().ToString()); nSubmittedHeight = nCurrentHeight; return; //already exists } //create fee tx CTransaction tx; uint256 txidCollateral; if (!mapCollateralTxids.count(tempBudget.GetHash())) { CWalletTx wtx; if (!pwalletMain->GetBudgetFinalizationCollateralTX(wtx, tempBudget.GetHash(), false)) { LogPrint("mnbudget","CBudgetManager::SubmitFinalBudget - Can't make collateral transaction\n"); return; } // Get our change address CReserveKey reservekey(pwalletMain); // Send the tx to the network. Do NOT use SwiftTx, locking might need too much time to propagate, especially for testnet pwalletMain->CommitTransaction(wtx, reservekey, "NO-ix"); tx = (CTransaction)wtx; txidCollateral = tx.GetHash(); mapCollateralTxids.insert(make_pair(tempBudget.GetHash(), txidCollateral)); } else { txidCollateral = mapCollateralTxids[tempBudget.GetHash()]; } int conf = GetIXConfirmations(txidCollateral); CTransaction txCollateral; uint256 nBlockHash; if (!GetTransaction(txidCollateral, txCollateral, nBlockHash, true)) { LogPrint("mnbudget","CBudgetManager::SubmitFinalBudget - Can't find collateral tx %s", txidCollateral.ToString()); return; } if (nBlockHash != uint256(0)) { BlockMap::iterator mi = mapBlockIndex.find(nBlockHash); if (mi != mapBlockIndex.end() && (*mi).second) { CBlockIndex* pindex = (*mi).second; if (chainActive.Contains(pindex)) { conf += chainActive.Height() - pindex->nHeight + 1; } } } /* Wait will we have 1 extra confirmation, otherwise some clients might reject this feeTX -- This function is tied to NewBlock, so we will propagate this budget while the block is also propagating */ if (conf < Params().Budget_Fee_Confirmations() + 1) { LogPrint("mnbudget","CBudgetManager::SubmitFinalBudget - Collateral requires at least %d confirmations - %s - %d confirmations\n", Params().Budget_Fee_Confirmations() + 1, txidCollateral.ToString(), conf); return; } //create the proposal incase we're the first to make it CFinalizedBudgetBroadcast finalizedBudgetBroadcast(strBudgetName, nBlockStart, vecTxBudgetPayments, txidCollateral); std::string strError = ""; if (!finalizedBudgetBroadcast.IsValid(strError)) { LogPrint("mnbudget","CBudgetManager::SubmitFinalBudget - Invalid finalized budget - %s \n", strError); return; } LOCK(cs); mapSeenFinalizedBudgets.insert(make_pair(finalizedBudgetBroadcast.GetHash(), finalizedBudgetBroadcast)); finalizedBudgetBroadcast.Relay(); budget.AddFinalizedBudget(finalizedBudgetBroadcast); nSubmittedHeight = nCurrentHeight; LogPrint("mnbudget","CBudgetManager::SubmitFinalBudget - Done! %s\n", finalizedBudgetBroadcast.GetHash().ToString()); } // // CBudgetDB // CBudgetDB::CBudgetDB() { pathDB = GetDataDir() / "budget.dat"; strMagicMessage = "MasternodeBudget"; } bool CBudgetDB::Write(const CBudgetManager& objToSave) { LOCK(objToSave.cs); int64_t nStart = GetTimeMillis(); // serialize, checksum data up to that point, then append checksum CDataStream ssObj(SER_DISK, CLIENT_VERSION); ssObj << strMagicMessage; // masternode cache file specific magic message ssObj << FLATDATA(Params().MessageStart()); // network specific magic number ssObj << objToSave; uint256 hash = Hash(ssObj.begin(), ssObj.end()); ssObj << hash; // open output file, and associate with CAutoFile FILE* file = fopen(pathDB.string().c_str(), "wb"); CAutoFile fileout(file, SER_DISK, CLIENT_VERSION); if (fileout.IsNull()) return error("%s : Failed to open file %s", __func__, pathDB.string()); // Write and commit header, data try { fileout << ssObj; } catch (std::exception& e) { return error("%s : Serialize or I/O error - %s", __func__, e.what()); } fileout.fclose(); LogPrint("mnbudget","Written info to budget.dat %dms\n", GetTimeMillis() - nStart); return true; } CBudgetDB::ReadResult CBudgetDB::Read(CBudgetManager& objToLoad, bool fDryRun) { LOCK(objToLoad.cs); int64_t nStart = GetTimeMillis(); // open input file, and associate with CAutoFile FILE* file = fopen(pathDB.string().c_str(), "rb"); CAutoFile filein(file, SER_DISK, CLIENT_VERSION); if (filein.IsNull()) { error("%s : Failed to open file %s", __func__, pathDB.string()); return FileError; } // use file size to size memory buffer int fileSize = boost::filesystem::file_size(pathDB); int dataSize = fileSize - sizeof(uint256); // Don't try to resize to a negative number if file is small if (dataSize < 0) dataSize = 0; vector<unsigned char> vchData; vchData.resize(dataSize); uint256 hashIn; // read data and checksum from file try { filein.read((char*)&vchData[0], dataSize); filein >> hashIn; } catch (std::exception& e) { error("%s : Deserialize or I/O error - %s", __func__, e.what()); return HashReadError; } filein.fclose(); CDataStream ssObj(vchData, SER_DISK, CLIENT_VERSION); // verify stored checksum matches input data uint256 hashTmp = Hash(ssObj.begin(), ssObj.end()); if (hashIn != hashTmp) { error("%s : Checksum mismatch, data corrupted", __func__); return IncorrectHash; } unsigned char pchMsgTmp[4]; std::string strMagicMessageTmp; try { // de-serialize file header (masternode cache file specific magic message) and .. ssObj >> strMagicMessageTmp; // ... verify the message matches predefined one if (strMagicMessage != strMagicMessageTmp) { error("%s : Invalid masternode cache magic message", __func__); return IncorrectMagicMessage; } // de-serialize file header (network specific magic number) and .. ssObj >> FLATDATA(pchMsgTmp); // ... verify the network matches ours if (memcmp(pchMsgTmp, Params().MessageStart(), sizeof(pchMsgTmp))) { error("%s : Invalid network magic number", __func__); return IncorrectMagicNumber; } // de-serialize data into CBudgetManager object ssObj >> objToLoad; } catch (std::exception& e) { objToLoad.Clear(); error("%s : Deserialize or I/O error - %s", __func__, e.what()); return IncorrectFormat; } LogPrint("mnbudget","Loaded info from budget.dat %dms\n", GetTimeMillis() - nStart); LogPrint("mnbudget"," %s\n", objToLoad.ToString()); if (!fDryRun) { LogPrint("mnbudget","Budget manager - cleaning....\n"); objToLoad.CheckAndRemove(); LogPrint("mnbudget","Budget manager - result:\n"); LogPrint("mnbudget"," %s\n", objToLoad.ToString()); } return Ok; } void DumpBudgets() { int64_t nStart = GetTimeMillis(); CBudgetDB budgetdb; CBudgetManager tempBudget; LogPrint("mnbudget","Verifying budget.dat format...\n"); CBudgetDB::ReadResult readResult = budgetdb.Read(tempBudget, true); // there was an error and it was not an error on file opening => do not proceed if (readResult == CBudgetDB::FileError) LogPrint("mnbudget","Missing budgets file - budget.dat, will try to recreate\n"); else if (readResult != CBudgetDB::Ok) { LogPrint("mnbudget","Error reading budget.dat: "); if (readResult == CBudgetDB::IncorrectFormat) LogPrint("mnbudget","magic is ok but data has invalid format, will try to recreate\n"); else { LogPrint("mnbudget","file format is unknown or invalid, please fix it manually\n"); return; } } LogPrint("mnbudget","Writting info to budget.dat...\n"); budgetdb.Write(budget); LogPrint("mnbudget","Budget dump finished %dms\n", GetTimeMillis() - nStart); } bool CBudgetManager::AddFinalizedBudget(CFinalizedBudget& finalizedBudget) { std::string strError = ""; if (!finalizedBudget.IsValid(strError)) return false; if (mapFinalizedBudgets.count(finalizedBudget.GetHash())) { return false; } mapFinalizedBudgets.insert(make_pair(finalizedBudget.GetHash(), finalizedBudget)); return true; } bool CBudgetManager::AddProposal(CBudgetProposal& budgetProposal) { LOCK(cs); std::string strError = ""; if (!budgetProposal.IsValid(strError)) { LogPrint("mnbudget","CBudgetManager::AddProposal - invalid budget proposal - %s\n", strError); return false; } if (mapProposals.count(budgetProposal.GetHash())) { return false; } mapProposals.insert(make_pair(budgetProposal.GetHash(), budgetProposal)); LogPrint("mnbudget","CBudgetManager::AddProposal - proposal %s added\n", budgetProposal.GetName ().c_str ()); return true; } void CBudgetManager::CheckAndRemove() { int nHeight = 0; // Add some verbosity once loading blocks from files has finished { TRY_LOCK(cs_main, locked); if ((locked) && (chainActive.Tip() != NULL)) { CBlockIndex* pindexPrev = chainActive.Tip(); if (pindexPrev) { nHeight = pindexPrev->nHeight; } } } LogPrint("mnbudget", "CBudgetManager::CheckAndRemove at Height=%d\n", nHeight); map<uint256, CFinalizedBudget> tmpMapFinalizedBudgets; map<uint256, CBudgetProposal> tmpMapProposals; std::string strError = ""; LogPrint("mnbudget", "CBudgetManager::CheckAndRemove - mapFinalizedBudgets cleanup - size before: %d\n", mapFinalizedBudgets.size()); std::map<uint256, CFinalizedBudget>::iterator it = mapFinalizedBudgets.begin(); while (it != mapFinalizedBudgets.end()) { CFinalizedBudget* pfinalizedBudget = &((*it).second); pfinalizedBudget->fValid = pfinalizedBudget->IsValid(strError); if (!strError.empty ()) { LogPrint("mnbudget","CBudgetManager::CheckAndRemove - Invalid finalized budget: %s\n", strError); } else { LogPrint("mnbudget","CBudgetManager::CheckAndRemove - Found valid finalized budget: %s %s\n", pfinalizedBudget->strBudgetName.c_str(), pfinalizedBudget->nFeeTXHash.ToString().c_str()); } if (pfinalizedBudget->fValid) { pfinalizedBudget->AutoCheck(); tmpMapFinalizedBudgets.insert(make_pair(pfinalizedBudget->GetHash(), *pfinalizedBudget)); } ++it; } LogPrint("mnbudget", "CBudgetManager::CheckAndRemove - mapProposals cleanup - size before: %d\n", mapProposals.size()); std::map<uint256, CBudgetProposal>::iterator it2 = mapProposals.begin(); while (it2 != mapProposals.end()) { CBudgetProposal* pbudgetProposal = &((*it2).second); pbudgetProposal->fValid = pbudgetProposal->IsValid(strError); if (!strError.empty ()) { LogPrint("mnbudget","CBudgetManager::CheckAndRemove - Invalid budget proposal - %s\n", strError); strError = ""; } else { LogPrint("mnbudget","CBudgetManager::CheckAndRemove - Found valid budget proposal: %s %s\n", pbudgetProposal->strProposalName.c_str(), pbudgetProposal->nFeeTXHash.ToString().c_str()); } if (pbudgetProposal->fValid) { tmpMapProposals.insert(make_pair(pbudgetProposal->GetHash(), *pbudgetProposal)); } ++it2; } // Remove invalid entries by overwriting complete map mapFinalizedBudgets.swap(tmpMapFinalizedBudgets); mapProposals.swap(tmpMapProposals); // clang doesn't accept copy assignemnts :-/ // mapFinalizedBudgets = tmpMapFinalizedBudgets; // mapProposals = tmpMapProposals; LogPrint("mnbudget", "CBudgetManager::CheckAndRemove - mapFinalizedBudgets cleanup - size after: %d\n", mapFinalizedBudgets.size()); LogPrint("mnbudget", "CBudgetManager::CheckAndRemove - mapProposals cleanup - size after: %d\n", mapProposals.size()); LogPrint("mnbudget","CBudgetManager::CheckAndRemove - PASSED\n"); } void CBudgetManager::FillBlockPayee(CMutableTransaction& txNew, CAmount nFees, bool fProofOfStake) { LOCK(cs); CBlockIndex* pindexPrev = chainActive.Tip(); if (!pindexPrev) return; int nHighestCount = 0; CScript payee; CAmount nAmount = 0; // ------- Grab The Highest Count std::map<uint256, CFinalizedBudget>::iterator it = mapFinalizedBudgets.begin(); while (it != mapFinalizedBudgets.end()) { CFinalizedBudget* pfinalizedBudget = &((*it).second); if (pfinalizedBudget->GetVoteCount() > nHighestCount && pindexPrev->nHeight + 1 >= pfinalizedBudget->GetBlockStart() && pindexPrev->nHeight + 1 <= pfinalizedBudget->GetBlockEnd() && pfinalizedBudget->GetPayeeAndAmount(pindexPrev->nHeight + 1, payee, nAmount)) { nHighestCount = pfinalizedBudget->GetVoteCount(); } ++it; } CAmount blockValue = GetBlockValue(pindexPrev->nHeight); if (fProofOfStake) { if (nHighestCount > 0) { unsigned int i = txNew.vout.size(); txNew.vout.resize(i + 1); txNew.vout[i].scriptPubKey = payee; txNew.vout[i].nValue = nAmount; CTxDestination address1; ExtractDestination(payee, address1); CBitcoinAddress address2(address1); LogPrint("mnbudget","CBudgetManager::FillBlockPayee - Budget payment to %s for %lld, nHighestCount = %d\n", address2.ToString(), nAmount, nHighestCount); } else { LogPrint("mnbudget","CBudgetManager::FillBlockPayee - No Budget payment, nHighestCount = %d\n", nHighestCount); } } else { //miners get the full amount on these blocks txNew.vout[0].nValue = blockValue; if (nHighestCount > 0) { txNew.vout.resize(2); //these are super blocks, so their value can be much larger than normal txNew.vout[1].scriptPubKey = payee; txNew.vout[1].nValue = nAmount; CTxDestination address1; ExtractDestination(payee, address1); CBitcoinAddress address2(address1); LogPrint("mnbudget","CBudgetManager::FillBlockPayee - Budget payment to %s for %lld\n", address2.ToString(), nAmount); } } } CFinalizedBudget* CBudgetManager::FindFinalizedBudget(uint256 nHash) { if (mapFinalizedBudgets.count(nHash)) return &mapFinalizedBudgets[nHash]; return NULL; } CBudgetProposal* CBudgetManager::FindProposal(const std::string& strProposalName) { //find the prop with the highest yes count int nYesCount = -99999; CBudgetProposal* pbudgetProposal = NULL; std::map<uint256, CBudgetProposal>::iterator it = mapProposals.begin(); while (it != mapProposals.end()) { if ((*it).second.strProposalName == strProposalName && (*it).second.GetYeas() > nYesCount) { pbudgetProposal = &((*it).second); nYesCount = pbudgetProposal->GetYeas(); } ++it; } if (nYesCount == -99999) return NULL; return pbudgetProposal; } CBudgetProposal* CBudgetManager::FindProposal(uint256 nHash) { LOCK(cs); if (mapProposals.count(nHash)) return &mapProposals[nHash]; return NULL; } bool CBudgetManager::IsBudgetPaymentBlock(int nBlockHeight) { int nHighestCount = -1; int nFivePercent = mnodeman.CountEnabled(ActiveProtocol()) / 20; std::map<uint256, CFinalizedBudget>::iterator it = mapFinalizedBudgets.begin(); while (it != mapFinalizedBudgets.end()) { CFinalizedBudget* pfinalizedBudget = &((*it).second); if (pfinalizedBudget->GetVoteCount() > nHighestCount && nBlockHeight >= pfinalizedBudget->GetBlockStart() && nBlockHeight <= pfinalizedBudget->GetBlockEnd()) { nHighestCount = pfinalizedBudget->GetVoteCount(); } ++it; } LogPrint("mnbudget","CBudgetManager::IsBudgetPaymentBlock() - nHighestCount: %lli, 5%% of Masternodes: %lli. Number of finalized budgets: %lli\n", nHighestCount, nFivePercent, mapFinalizedBudgets.size()); // If budget doesn't have 5% of the network votes, then we should pay a masternode instead if (nHighestCount > nFivePercent) return true; return false; } TrxValidationStatus CBudgetManager::IsTransactionValid(const CTransaction& txNew, int nBlockHeight) { LOCK(cs); TrxValidationStatus transactionStatus = TrxValidationStatus::InValid; int nHighestCount = 0; int nFivePercent = mnodeman.CountEnabled(ActiveProtocol()) / 20; std::vector<CFinalizedBudget*> ret; LogPrint("mnbudget","CBudgetManager::IsTransactionValid - checking %lli finalized budgets\n", mapFinalizedBudgets.size()); // ------- Grab The Highest Count std::map<uint256, CFinalizedBudget>::iterator it = mapFinalizedBudgets.begin(); while (it != mapFinalizedBudgets.end()) { CFinalizedBudget* pfinalizedBudget = &((*it).second); if (pfinalizedBudget->GetVoteCount() > nHighestCount && nBlockHeight >= pfinalizedBudget->GetBlockStart() && nBlockHeight <= pfinalizedBudget->GetBlockEnd()) { nHighestCount = pfinalizedBudget->GetVoteCount(); } ++it; } LogPrint("mnbudget","CBudgetManager::IsTransactionValid() - nHighestCount: %lli, 5%% of Masternodes: %lli mapFinalizedBudgets.size(): %ld\n", nHighestCount, nFivePercent, mapFinalizedBudgets.size()); /* If budget doesn't have 5% of the network votes, then we should pay a masternode instead */ if (nHighestCount < nFivePercent) return TrxValidationStatus::InValid; // check the highest finalized budgets (+/- 10% to assist in consensus) std::string strProposals = ""; int nCountThreshold = nHighestCount - mnodeman.CountEnabled(ActiveProtocol()) / 10; bool fThreshold = false; it = mapFinalizedBudgets.begin(); while (it != mapFinalizedBudgets.end()) { CFinalizedBudget* pfinalizedBudget = &((*it).second); strProposals = pfinalizedBudget->GetProposals(); LogPrint("mnbudget","CBudgetManager::IsTransactionValid - checking budget (%s) with blockstart %lli, blockend %lli, nBlockHeight %lli, votes %lli, nCountThreshold %lli\n", strProposals.c_str(), pfinalizedBudget->GetBlockStart(), pfinalizedBudget->GetBlockEnd(), nBlockHeight, pfinalizedBudget->GetVoteCount(), nCountThreshold); if (pfinalizedBudget->GetVoteCount() > nCountThreshold) { fThreshold = true; LogPrint("mnbudget","CBudgetManager::IsTransactionValid - GetVoteCount() > nCountThreshold passed\n"); if (nBlockHeight >= pfinalizedBudget->GetBlockStart() && nBlockHeight <= pfinalizedBudget->GetBlockEnd()) { LogPrint("mnbudget","CBudgetManager::IsTransactionValid - GetBlockStart() passed\n"); transactionStatus = pfinalizedBudget->IsTransactionValid(txNew, nBlockHeight); if (transactionStatus == TrxValidationStatus::Valid) { LogPrint("mnbudget","CBudgetManager::IsTransactionValid - pfinalizedBudget->IsTransactionValid() passed\n"); return TrxValidationStatus::Valid; } else { LogPrint("mnbudget","CBudgetManager::IsTransactionValid - pfinalizedBudget->IsTransactionValid() error\n"); } } else { LogPrint("mnbudget","CBudgetManager::IsTransactionValid - GetBlockStart() failed, budget is outside current payment cycle and will be ignored.\n"); } } ++it; } // If not enough masternodes autovoted for any of the finalized budgets pay a masternode instead if(!fThreshold) { transactionStatus = TrxValidationStatus::VoteThreshold; } // We looked through all of the known budgets return transactionStatus; } std::vector<CBudgetProposal*> CBudgetManager::GetAllProposals() { LOCK(cs); std::vector<CBudgetProposal*> vBudgetProposalRet; std::map<uint256, CBudgetProposal>::iterator it = mapProposals.begin(); while (it != mapProposals.end()) { (*it).second.CleanAndRemove(false); CBudgetProposal* pbudgetProposal = &((*it).second); vBudgetProposalRet.push_back(pbudgetProposal); ++it; } return vBudgetProposalRet; } // // Sort by votes, if there's a tie sort by their feeHash TX // struct sortProposalsByVotes { bool operator()(const std::pair<CBudgetProposal*, int>& left, const std::pair<CBudgetProposal*, int>& right) { if (left.second != right.second) return (left.second > right.second); return (left.first->nFeeTXHash > right.first->nFeeTXHash); } }; //Need to review this function std::vector<CBudgetProposal*> CBudgetManager::GetBudget() { LOCK(cs); // ------- Sort budgets by Yes Count std::vector<std::pair<CBudgetProposal*, int> > vBudgetPorposalsSort; std::map<uint256, CBudgetProposal>::iterator it = mapProposals.begin(); while (it != mapProposals.end()) { (*it).second.CleanAndRemove(false); vBudgetPorposalsSort.push_back(make_pair(&((*it).second), (*it).second.GetYeas() - (*it).second.GetNays())); ++it; } std::sort(vBudgetPorposalsSort.begin(), vBudgetPorposalsSort.end(), sortProposalsByVotes()); // ------- Grab The Budgets In Order std::vector<CBudgetProposal*> vBudgetProposalsRet; CAmount nBudgetAllocated = 0; CBlockIndex* pindexPrev = chainActive.Tip(); if (pindexPrev == NULL) return vBudgetProposalsRet; int nBlockStart = pindexPrev->nHeight - pindexPrev->nHeight % GetBudgetPaymentCycleBlocks() + GetBudgetPaymentCycleBlocks(); int nBlockEnd = nBlockStart + GetBudgetPaymentCycleBlocks() - 1; CAmount nTotalBudget = GetTotalBudget(nBlockStart); std::vector<std::pair<CBudgetProposal*, int> >::iterator it2 = vBudgetPorposalsSort.begin(); while (it2 != vBudgetPorposalsSort.end()) { CBudgetProposal* pbudgetProposal = (*it2).first; LogPrint("mnbudget","CBudgetManager::GetBudget() - Processing Budget %s\n", pbudgetProposal->strProposalName.c_str()); //prop start/end should be inside this period if (pbudgetProposal->fValid && pbudgetProposal->nBlockStart <= nBlockStart && pbudgetProposal->nBlockEnd >= nBlockEnd && pbudgetProposal->GetYeas() - pbudgetProposal->GetNays() > mnodeman.CountEnabled(ActiveProtocol()) / 10 && pbudgetProposal->IsEstablished()) { LogPrint("mnbudget","CBudgetManager::GetBudget() - Check 1 passed: valid=%d | %ld <= %ld | %ld >= %ld | Yeas=%d Nays=%d Count=%d | established=%d\n", pbudgetProposal->fValid, pbudgetProposal->nBlockStart, nBlockStart, pbudgetProposal->nBlockEnd, nBlockEnd, pbudgetProposal->GetYeas(), pbudgetProposal->GetNays(), mnodeman.CountEnabled(ActiveProtocol()) / 10, pbudgetProposal->IsEstablished()); if (pbudgetProposal->GetAmount() + nBudgetAllocated <= nTotalBudget) { pbudgetProposal->SetAllotted(pbudgetProposal->GetAmount()); nBudgetAllocated += pbudgetProposal->GetAmount(); vBudgetProposalsRet.push_back(pbudgetProposal); LogPrint("mnbudget","CBudgetManager::GetBudget() - Check 2 passed: Budget added\n"); } else { pbudgetProposal->SetAllotted(0); LogPrint("mnbudget","CBudgetManager::GetBudget() - Check 2 failed: no amount allotted\n"); } } else { LogPrint("mnbudget","CBudgetManager::GetBudget() - Check 1 failed: valid=%d | %ld <= %ld | %ld >= %ld | Yeas=%d Nays=%d Count=%d | established=%d\n", pbudgetProposal->fValid, pbudgetProposal->nBlockStart, nBlockStart, pbudgetProposal->nBlockEnd, nBlockEnd, pbudgetProposal->GetYeas(), pbudgetProposal->GetNays(), mnodeman.CountEnabled(ActiveProtocol()) / 10, pbudgetProposal->IsEstablished()); } ++it2; } return vBudgetProposalsRet; } struct sortFinalizedBudgetsByVotes { bool operator()(const std::pair<CFinalizedBudget*, int>& left, const std::pair<CFinalizedBudget*, int>& right) { return left.second > right.second; } }; std::vector<CFinalizedBudget*> CBudgetManager::GetFinalizedBudgets() { LOCK(cs); std::vector<CFinalizedBudget*> vFinalizedBudgetsRet; std::vector<std::pair<CFinalizedBudget*, int> > vFinalizedBudgetsSort; // ------- Grab The Budgets In Order std::map<uint256, CFinalizedBudget>::iterator it = mapFinalizedBudgets.begin(); while (it != mapFinalizedBudgets.end()) { CFinalizedBudget* pfinalizedBudget = &((*it).second); vFinalizedBudgetsSort.push_back(make_pair(pfinalizedBudget, pfinalizedBudget->GetVoteCount())); ++it; } std::sort(vFinalizedBudgetsSort.begin(), vFinalizedBudgetsSort.end(), sortFinalizedBudgetsByVotes()); std::vector<std::pair<CFinalizedBudget*, int> >::iterator it2 = vFinalizedBudgetsSort.begin(); while (it2 != vFinalizedBudgetsSort.end()) { vFinalizedBudgetsRet.push_back((*it2).first); ++it2; } return vFinalizedBudgetsRet; } std::string CBudgetManager::GetRequiredPaymentsString(int nBlockHeight) { LOCK(cs); std::string ret = "unknown-budget"; std::map<uint256, CFinalizedBudget>::iterator it = mapFinalizedBudgets.begin(); while (it != mapFinalizedBudgets.end()) { CFinalizedBudget* pfinalizedBudget = &((*it).second); if (nBlockHeight >= pfinalizedBudget->GetBlockStart() && nBlockHeight <= pfinalizedBudget->GetBlockEnd()) { CTxBudgetPayment payment; if (pfinalizedBudget->GetBudgetPaymentByBlock(nBlockHeight, payment)) { if (ret == "unknown-budget") { ret = payment.nProposalHash.ToString(); } else { ret += ","; ret += payment.nProposalHash.ToString(); } } else { LogPrint("mnbudget","CBudgetManager::GetRequiredPaymentsString - Couldn't find budget payment for block %d\n", nBlockHeight); } } ++it; } return ret; } CAmount CBudgetManager::GetTotalBudget(int nHeight) { if (chainActive.Tip() == NULL) return 0; if (Params().NetworkID() == CBaseChainParams::TESTNET) { CAmount nSubsidy = 500 * COIN; return ((nSubsidy / 100) * 10) * 146; } //get block value and calculate from that CAmount nSubsidy = 0; if (nHeight <= Params().LAST_POW_BLOCK() && nHeight >= 151200) { nSubsidy = 50 * COIN; } else if (nHeight <= 302399 && nHeight > Params().LAST_POW_BLOCK()) { nSubsidy = 50 * COIN; } else if (nHeight <= 345599 && nHeight >= 302400) { nSubsidy = 45 * COIN; } else if (nHeight <= 388799 && nHeight >= 345600) { nSubsidy = 40 * COIN; } else if (nHeight <= 431999 && nHeight >= 388800) { nSubsidy = 35 * COIN; } else if (nHeight <= 475199 && nHeight >= 432000) { nSubsidy = 30 * COIN; } else if (nHeight <= 518399 && nHeight >= 475200) { nSubsidy = 25 * COIN; } else if (nHeight <= 561599 && nHeight >= 518400) { nSubsidy = 20 * COIN; } else if (nHeight <= 604799 && nHeight >= 561600) { nSubsidy = 15 * COIN; } else if (nHeight <= 647999 && nHeight >= 604800) { nSubsidy = 10 * COIN; } else if (nHeight >= Params().Zerocoin_Block_V2_Start()) { nSubsidy = 10 * COIN; } else { nSubsidy = 5 * COIN; } // Amount of blocks in a months period of time (using 1 minutes per) = (60*24*30) if (nHeight <= 172800) { return 648000 * COIN; } else { return ((nSubsidy / 100) * 10) * 1440 * 30; } } void CBudgetManager::NewBlock() { TRY_LOCK(cs, fBudgetNewBlock); if (!fBudgetNewBlock) return; if (masternodeSync.RequestedMasternodeAssets <= MASTERNODE_SYNC_BUDGET) return; if (strBudgetMode == "suggest") { //suggest the budget we see SubmitFinalBudget(); } //this function should be called 1/14 blocks, allowing up to 100 votes per day on all proposals if (chainActive.Height() % 14 != 0) return; // incremental sync with our peers if (masternodeSync.IsSynced()) { LogPrint("mnbudget","CBudgetManager::NewBlock - incremental sync started\n"); if (chainActive.Height() % 1440 == rand() % 1440) { ClearSeen(); ResetSync(); } LOCK(cs_vNodes); BOOST_FOREACH (CNode* pnode, vNodes) if (pnode->nVersion >= ActiveProtocol()) Sync(pnode, 0, true); MarkSynced(); } CheckAndRemove(); //remove invalid votes once in a while (we have to check the signatures and validity of every vote, somewhat CPU intensive) LogPrint("mnbudget","CBudgetManager::NewBlock - askedForSourceProposalOrBudget cleanup - size: %d\n", askedForSourceProposalOrBudget.size()); std::map<uint256, int64_t>::iterator it = askedForSourceProposalOrBudget.begin(); while (it != askedForSourceProposalOrBudget.end()) { if ((*it).second > GetTime() - (60 * 60 * 24)) { ++it; } else { askedForSourceProposalOrBudget.erase(it++); } } LogPrint("mnbudget","CBudgetManager::NewBlock - mapProposals cleanup - size: %d\n", mapProposals.size()); std::map<uint256, CBudgetProposal>::iterator it2 = mapProposals.begin(); while (it2 != mapProposals.end()) { (*it2).second.CleanAndRemove(false); ++it2; } LogPrint("mnbudget","CBudgetManager::NewBlock - mapFinalizedBudgets cleanup - size: %d\n", mapFinalizedBudgets.size()); std::map<uint256, CFinalizedBudget>::iterator it3 = mapFinalizedBudgets.begin(); while (it3 != mapFinalizedBudgets.end()) { (*it3).second.CleanAndRemove(false); ++it3; } LogPrint("mnbudget","CBudgetManager::NewBlock - vecImmatureBudgetProposals cleanup - size: %d\n", vecImmatureBudgetProposals.size()); std::vector<CBudgetProposalBroadcast>::iterator it4 = vecImmatureBudgetProposals.begin(); while (it4 != vecImmatureBudgetProposals.end()) { std::string strError = ""; int nConf = 0; if (!IsBudgetCollateralValid((*it4).nFeeTXHash, (*it4).GetHash(), strError, (*it4).nTime, nConf)) { ++it4; continue; } if (!(*it4).IsValid(strError)) { LogPrint("mnbudget","mprop (immature) - invalid budget proposal - %s\n", strError); it4 = vecImmatureBudgetProposals.erase(it4); continue; } CBudgetProposal budgetProposal((*it4)); if (AddProposal(budgetProposal)) { (*it4).Relay(); } LogPrint("mnbudget","mprop (immature) - new budget - %s\n", (*it4).GetHash().ToString()); it4 = vecImmatureBudgetProposals.erase(it4); } LogPrint("mnbudget","CBudgetManager::NewBlock - vecImmatureFinalizedBudgets cleanup - size: %d\n", vecImmatureFinalizedBudgets.size()); std::vector<CFinalizedBudgetBroadcast>::iterator it5 = vecImmatureFinalizedBudgets.begin(); while (it5 != vecImmatureFinalizedBudgets.end()) { std::string strError = ""; int nConf = 0; if (!IsBudgetCollateralValid((*it5).nFeeTXHash, (*it5).GetHash(), strError, (*it5).nTime, nConf, true)) { ++it5; continue; } if (!(*it5).IsValid(strError)) { LogPrint("mnbudget","fbs (immature) - invalid finalized budget - %s\n", strError); it5 = vecImmatureFinalizedBudgets.erase(it5); continue; } LogPrint("mnbudget","fbs (immature) - new finalized budget - %s\n", (*it5).GetHash().ToString()); CFinalizedBudget finalizedBudget((*it5)); if (AddFinalizedBudget(finalizedBudget)) { (*it5).Relay(); } it5 = vecImmatureFinalizedBudgets.erase(it5); } LogPrint("mnbudget","CBudgetManager::NewBlock - PASSED\n"); } void CBudgetManager::ProcessMessage(CNode* pfrom, std::string& strCommand, CDataStream& vRecv) { // lite mode is not supported if (fLiteMode) return; if (!masternodeSync.IsBlockchainSynced()) return; LOCK(cs_budget); if (strCommand == "mnvs") { //Masternode vote sync uint256 nProp; vRecv >> nProp; if (Params().NetworkID() == CBaseChainParams::MAIN) { if (nProp == 0) { if (pfrom->HasFulfilledRequest("mnvs")) { LogPrint("mnbudget","mnvs - peer already asked me for the list\n"); Misbehaving(pfrom->GetId(), 20); return; } pfrom->FulfilledRequest("mnvs"); } } Sync(pfrom, nProp); LogPrint("mnbudget", "mnvs - Sent Masternode votes to peer %i\n", pfrom->GetId()); } if (strCommand == "mprop") { //Masternode Proposal CBudgetProposalBroadcast budgetProposalBroadcast; vRecv >> budgetProposalBroadcast; if (mapSeenMasternodeBudgetProposals.count(budgetProposalBroadcast.GetHash())) { masternodeSync.AddedBudgetItem(budgetProposalBroadcast.GetHash()); return; } std::string strError = ""; int nConf = 0; if (!IsBudgetCollateralValid(budgetProposalBroadcast.nFeeTXHash, budgetProposalBroadcast.GetHash(), strError, budgetProposalBroadcast.nTime, nConf)) { LogPrint("mnbudget","Proposal FeeTX is not valid - %s - %s\n", budgetProposalBroadcast.nFeeTXHash.ToString(), strError); if (nConf >= 1) vecImmatureBudgetProposals.push_back(budgetProposalBroadcast); return; } mapSeenMasternodeBudgetProposals.insert(make_pair(budgetProposalBroadcast.GetHash(), budgetProposalBroadcast)); if (!budgetProposalBroadcast.IsValid(strError)) { LogPrint("mnbudget","mprop - invalid budget proposal - %s\n", strError); return; } CBudgetProposal budgetProposal(budgetProposalBroadcast); if (AddProposal(budgetProposal)) { budgetProposalBroadcast.Relay(); } masternodeSync.AddedBudgetItem(budgetProposalBroadcast.GetHash()); LogPrint("mnbudget","mprop - new budget - %s\n", budgetProposalBroadcast.GetHash().ToString()); //We might have active votes for this proposal that are valid now CheckOrphanVotes(); } if (strCommand == "mvote") { //Masternode Vote CBudgetVote vote; vRecv >> vote; vote.fValid = true; if (mapSeenMasternodeBudgetVotes.count(vote.GetHash())) { masternodeSync.AddedBudgetItem(vote.GetHash()); return; } CMasternode* pmn = mnodeman.Find(vote.vin); if (pmn == NULL) { LogPrint("mnbudget","mvote - unknown masternode - vin: %s\n", vote.vin.prevout.hash.ToString()); mnodeman.AskForMN(pfrom, vote.vin); return; } mapSeenMasternodeBudgetVotes.insert(make_pair(vote.GetHash(), vote)); if (!vote.SignatureValid(true)) { LogPrint("mnbudget","mvote - signature invalid\n"); if (masternodeSync.IsSynced()) Misbehaving(pfrom->GetId(), 20); // it could just be a non-synced masternode mnodeman.AskForMN(pfrom, vote.vin); return; } std::string strError = ""; if (UpdateProposal(vote, pfrom, strError)) { vote.Relay(); masternodeSync.AddedBudgetItem(vote.GetHash()); } LogPrint("mnbudget","mvote - new budget vote for budget %s - %s\n", vote.nProposalHash.ToString(), vote.GetHash().ToString()); } if (strCommand == "fbs") { //Finalized Budget Suggestion CFinalizedBudgetBroadcast finalizedBudgetBroadcast; vRecv >> finalizedBudgetBroadcast; if (mapSeenFinalizedBudgets.count(finalizedBudgetBroadcast.GetHash())) { masternodeSync.AddedBudgetItem(finalizedBudgetBroadcast.GetHash()); return; } std::string strError = ""; int nConf = 0; if (!IsBudgetCollateralValid(finalizedBudgetBroadcast.nFeeTXHash, finalizedBudgetBroadcast.GetHash(), strError, finalizedBudgetBroadcast.nTime, nConf, true)) { LogPrint("mnbudget","fbs - Finalized Budget FeeTX is not valid - %s - %s\n", finalizedBudgetBroadcast.nFeeTXHash.ToString(), strError); if (nConf >= 1) vecImmatureFinalizedBudgets.push_back(finalizedBudgetBroadcast); return; } mapSeenFinalizedBudgets.insert(make_pair(finalizedBudgetBroadcast.GetHash(), finalizedBudgetBroadcast)); if (!finalizedBudgetBroadcast.IsValid(strError)) { LogPrint("mnbudget","fbs - invalid finalized budget - %s\n", strError); return; } LogPrint("mnbudget","fbs - new finalized budget - %s\n", finalizedBudgetBroadcast.GetHash().ToString()); CFinalizedBudget finalizedBudget(finalizedBudgetBroadcast); if (AddFinalizedBudget(finalizedBudget)) { finalizedBudgetBroadcast.Relay(); } masternodeSync.AddedBudgetItem(finalizedBudgetBroadcast.GetHash()); //we might have active votes for this budget that are now valid CheckOrphanVotes(); } if (strCommand == "fbvote") { //Finalized Budget Vote CFinalizedBudgetVote vote; vRecv >> vote; vote.fValid = true; if (mapSeenFinalizedBudgetVotes.count(vote.GetHash())) { masternodeSync.AddedBudgetItem(vote.GetHash()); return; } CMasternode* pmn = mnodeman.Find(vote.vin); if (pmn == NULL) { LogPrint("mnbudget", "fbvote - unknown masternode - vin: %s\n", vote.vin.prevout.hash.ToString()); mnodeman.AskForMN(pfrom, vote.vin); return; } mapSeenFinalizedBudgetVotes.insert(make_pair(vote.GetHash(), vote)); if (!vote.SignatureValid(true)) { LogPrint("mnbudget","fbvote - signature invalid\n"); if (masternodeSync.IsSynced()) Misbehaving(pfrom->GetId(), 20); // it could just be a non-synced masternode mnodeman.AskForMN(pfrom, vote.vin); return; } std::string strError = ""; if (UpdateFinalizedBudget(vote, pfrom, strError)) { vote.Relay(); masternodeSync.AddedBudgetItem(vote.GetHash()); LogPrint("mnbudget","fbvote - new finalized budget vote - %s\n", vote.GetHash().ToString()); } else { LogPrint("mnbudget","fbvote - rejected finalized budget vote - %s - %s\n", vote.GetHash().ToString(), strError); } } } bool CBudgetManager::PropExists(uint256 nHash) { if (mapProposals.count(nHash)) return true; return false; } //mark that a full sync is needed void CBudgetManager::ResetSync() { LOCK(cs); std::map<uint256, CBudgetProposalBroadcast>::iterator it1 = mapSeenMasternodeBudgetProposals.begin(); while (it1 != mapSeenMasternodeBudgetProposals.end()) { CBudgetProposal* pbudgetProposal = FindProposal((*it1).first); if (pbudgetProposal && pbudgetProposal->fValid) { //mark votes std::map<uint256, CBudgetVote>::iterator it2 = pbudgetProposal->mapVotes.begin(); while (it2 != pbudgetProposal->mapVotes.end()) { (*it2).second.fSynced = false; ++it2; } } ++it1; } std::map<uint256, CFinalizedBudgetBroadcast>::iterator it3 = mapSeenFinalizedBudgets.begin(); while (it3 != mapSeenFinalizedBudgets.end()) { CFinalizedBudget* pfinalizedBudget = FindFinalizedBudget((*it3).first); if (pfinalizedBudget && pfinalizedBudget->fValid) { //send votes std::map<uint256, CFinalizedBudgetVote>::iterator it4 = pfinalizedBudget->mapVotes.begin(); while (it4 != pfinalizedBudget->mapVotes.end()) { (*it4).second.fSynced = false; ++it4; } } ++it3; } } void CBudgetManager::MarkSynced() { LOCK(cs); /* Mark that we've sent all valid items */ std::map<uint256, CBudgetProposalBroadcast>::iterator it1 = mapSeenMasternodeBudgetProposals.begin(); while (it1 != mapSeenMasternodeBudgetProposals.end()) { CBudgetProposal* pbudgetProposal = FindProposal((*it1).first); if (pbudgetProposal && pbudgetProposal->fValid) { //mark votes std::map<uint256, CBudgetVote>::iterator it2 = pbudgetProposal->mapVotes.begin(); while (it2 != pbudgetProposal->mapVotes.end()) { if ((*it2).second.fValid) (*it2).second.fSynced = true; ++it2; } } ++it1; } std::map<uint256, CFinalizedBudgetBroadcast>::iterator it3 = mapSeenFinalizedBudgets.begin(); while (it3 != mapSeenFinalizedBudgets.end()) { CFinalizedBudget* pfinalizedBudget = FindFinalizedBudget((*it3).first); if (pfinalizedBudget && pfinalizedBudget->fValid) { //mark votes std::map<uint256, CFinalizedBudgetVote>::iterator it4 = pfinalizedBudget->mapVotes.begin(); while (it4 != pfinalizedBudget->mapVotes.end()) { if ((*it4).second.fValid) (*it4).second.fSynced = true; ++it4; } } ++it3; } } void CBudgetManager::Sync(CNode* pfrom, uint256 nProp, bool fPartial) { LOCK(cs); /* Sync with a client on the network -- This code checks each of the hash maps for all known budget proposals and finalized budget proposals, then checks them against the budget object to see if they're OK. If all checks pass, we'll send it to the peer. */ int nInvCount = 0; std::map<uint256, CBudgetProposalBroadcast>::iterator it1 = mapSeenMasternodeBudgetProposals.begin(); while (it1 != mapSeenMasternodeBudgetProposals.end()) { CBudgetProposal* pbudgetProposal = FindProposal((*it1).first); if (pbudgetProposal && pbudgetProposal->fValid && (nProp == 0 || (*it1).first == nProp)) { pfrom->PushInventory(CInv(MSG_BUDGET_PROPOSAL, (*it1).second.GetHash())); nInvCount++; //send votes std::map<uint256, CBudgetVote>::iterator it2 = pbudgetProposal->mapVotes.begin(); while (it2 != pbudgetProposal->mapVotes.end()) { if ((*it2).second.fValid) { if ((fPartial && !(*it2).second.fSynced) || !fPartial) { pfrom->PushInventory(CInv(MSG_BUDGET_VOTE, (*it2).second.GetHash())); nInvCount++; } } ++it2; } } ++it1; } pfrom->PushMessage("ssc", MASTERNODE_SYNC_BUDGET_PROP, nInvCount); LogPrint("mnbudget", "CBudgetManager::Sync - sent %d items\n", nInvCount); nInvCount = 0; std::map<uint256, CFinalizedBudgetBroadcast>::iterator it3 = mapSeenFinalizedBudgets.begin(); while (it3 != mapSeenFinalizedBudgets.end()) { CFinalizedBudget* pfinalizedBudget = FindFinalizedBudget((*it3).first); if (pfinalizedBudget && pfinalizedBudget->fValid && (nProp == 0 || (*it3).first == nProp)) { pfrom->PushInventory(CInv(MSG_BUDGET_FINALIZED, (*it3).second.GetHash())); nInvCount++; //send votes std::map<uint256, CFinalizedBudgetVote>::iterator it4 = pfinalizedBudget->mapVotes.begin(); while (it4 != pfinalizedBudget->mapVotes.end()) { if ((*it4).second.fValid) { if ((fPartial && !(*it4).second.fSynced) || !fPartial) { pfrom->PushInventory(CInv(MSG_BUDGET_FINALIZED_VOTE, (*it4).second.GetHash())); nInvCount++; } } ++it4; } } ++it3; } pfrom->PushMessage("ssc", MASTERNODE_SYNC_BUDGET_FIN, nInvCount); LogPrint("mnbudget", "CBudgetManager::Sync - sent %d items\n", nInvCount); } bool CBudgetManager::UpdateProposal(CBudgetVote& vote, CNode* pfrom, std::string& strError) { LOCK(cs); if (!mapProposals.count(vote.nProposalHash)) { if (pfrom) { // only ask for missing items after our syncing process is complete -- // otherwise we'll think a full sync succeeded when they return a result if (!masternodeSync.IsSynced()) return false; LogPrint("mnbudget","CBudgetManager::UpdateProposal - Unknown proposal %d, asking for source proposal\n", vote.nProposalHash.ToString()); mapOrphanMasternodeBudgetVotes[vote.nProposalHash] = vote; if (!askedForSourceProposalOrBudget.count(vote.nProposalHash)) { pfrom->PushMessage("mnvs", vote.nProposalHash); askedForSourceProposalOrBudget[vote.nProposalHash] = GetTime(); } } strError = "Proposal not found!"; return false; } return mapProposals[vote.nProposalHash].AddOrUpdateVote(vote, strError); } bool CBudgetManager::UpdateFinalizedBudget(CFinalizedBudgetVote& vote, CNode* pfrom, std::string& strError) { LOCK(cs); if (!mapFinalizedBudgets.count(vote.nBudgetHash)) { if (pfrom) { // only ask for missing items after our syncing process is complete -- // otherwise we'll think a full sync succeeded when they return a result if (!masternodeSync.IsSynced()) return false; LogPrint("mnbudget","CBudgetManager::UpdateFinalizedBudget - Unknown Finalized Proposal %s, asking for source budget\n", vote.nBudgetHash.ToString()); mapOrphanFinalizedBudgetVotes[vote.nBudgetHash] = vote; if (!askedForSourceProposalOrBudget.count(vote.nBudgetHash)) { pfrom->PushMessage("mnvs", vote.nBudgetHash); askedForSourceProposalOrBudget[vote.nBudgetHash] = GetTime(); } } strError = "Finalized Budget " + vote.nBudgetHash.ToString() + " not found!"; return false; } LogPrint("mnbudget","CBudgetManager::UpdateFinalizedBudget - Finalized Proposal %s added\n", vote.nBudgetHash.ToString()); return mapFinalizedBudgets[vote.nBudgetHash].AddOrUpdateVote(vote, strError); } CBudgetProposal::CBudgetProposal() { strProposalName = "unknown"; nBlockStart = 0; nBlockEnd = 0; nAmount = 0; nTime = 0; fValid = true; } CBudgetProposal::CBudgetProposal(std::string strProposalNameIn, std::string strURLIn, int nBlockStartIn, int nBlockEndIn, CScript addressIn, CAmount nAmountIn, uint256 nFeeTXHashIn) { strProposalName = strProposalNameIn; strURL = strURLIn; nBlockStart = nBlockStartIn; nBlockEnd = nBlockEndIn; address = addressIn; nAmount = nAmountIn; nFeeTXHash = nFeeTXHashIn; fValid = true; } CBudgetProposal::CBudgetProposal(const CBudgetProposal& other) { strProposalName = other.strProposalName; strURL = other.strURL; nBlockStart = other.nBlockStart; nBlockEnd = other.nBlockEnd; address = other.address; nAmount = other.nAmount; nTime = other.nTime; nFeeTXHash = other.nFeeTXHash; mapVotes = other.mapVotes; fValid = true; } bool CBudgetProposal::IsValid(std::string& strError, bool fCheckCollateral) { if (GetNays() - GetYeas() > mnodeman.CountEnabled(ActiveProtocol()) / 10) { strError = "Proposal " + strProposalName + ": Active removal"; return false; } if (nBlockStart < 0) { strError = "Invalid Proposal"; return false; } if (nBlockEnd < nBlockStart) { strError = "Proposal " + strProposalName + ": Invalid nBlockEnd (end before start)"; return false; } if (nAmount < 10 * COIN) { strError = "Proposal " + strProposalName + ": Invalid nAmount"; return false; } if (address == CScript()) { strError = "Proposal " + strProposalName + ": Invalid Payment Address"; return false; } if (fCheckCollateral) { int nConf = 0; if (!IsBudgetCollateralValid(nFeeTXHash, GetHash(), strError, nTime, nConf)) { strError = "Proposal " + strProposalName + ": Invalid collateral"; return false; } } /* TODO: There might be an issue with multisig in the coinbase on mainnet, we will add support for it in a future release. */ if (address.IsPayToScriptHash()) { strError = "Proposal " + strProposalName + ": Multisig is not currently supported."; return false; } //if proposal doesn't gain traction within 2 weeks, remove it // nTime not being saved correctly // -- TODO: We should keep track of the last time the proposal was valid, if it's invalid for 2 weeks, erase it // if(nTime + (60*60*24*2) < GetAdjustedTime()) { // if(GetYeas()-GetNays() < (mnodeman.CountEnabled(ActiveProtocol())/10)) { // strError = "Not enough support"; // return false; // } // } //can only pay out 10% of the possible coins (min value of coins) if (nAmount > budget.GetTotalBudget(nBlockStart)) { strError = "Proposal " + strProposalName + ": Payment more than max"; return false; } CBlockIndex* pindexPrev = chainActive.Tip(); if (pindexPrev == NULL) { strError = "Proposal " + strProposalName + ": Tip is NULL"; return true; } // Calculate maximum block this proposal will be valid, which is start of proposal + (number of payments * cycle) int nProposalEnd = GetBlockStart() + (GetBudgetPaymentCycleBlocks() * GetTotalPaymentCount()); // if (GetBlockEnd() < pindexPrev->nHeight - GetBudgetPaymentCycleBlocks() / 2) { if(nProposalEnd < pindexPrev->nHeight){ strError = "Proposal " + strProposalName + ": Invalid nBlockEnd (" + std::to_string(nProposalEnd) + ") < current height (" + std::to_string(pindexPrev->nHeight) + ")"; return false; } return true; } bool CBudgetProposal::AddOrUpdateVote(CBudgetVote& vote, std::string& strError) { std::string strAction = "New vote inserted:"; LOCK(cs); uint256 hash = vote.vin.prevout.GetHash(); if (mapVotes.count(hash)) { if (mapVotes[hash].nTime > vote.nTime) { strError = strprintf("new vote older than existing vote - %s\n", vote.GetHash().ToString()); LogPrint("mnbudget", "CBudgetProposal::AddOrUpdateVote - %s\n", strError); return false; } if (vote.nTime - mapVotes[hash].nTime < BUDGET_VOTE_UPDATE_MIN) { strError = strprintf("time between votes is too soon - %s - %lli sec < %lli sec\n", vote.GetHash().ToString(), vote.nTime - mapVotes[hash].nTime,BUDGET_VOTE_UPDATE_MIN); LogPrint("mnbudget", "CBudgetProposal::AddOrUpdateVote - %s\n", strError); return false; } strAction = "Existing vote updated:"; } if (vote.nTime > GetTime() + (60 * 60)) { strError = strprintf("new vote is too far ahead of current time - %s - nTime %lli - Max Time %lli\n", vote.GetHash().ToString(), vote.nTime, GetTime() + (60 * 60)); LogPrint("mnbudget", "CBudgetProposal::AddOrUpdateVote - %s\n", strError); return false; } mapVotes[hash] = vote; LogPrint("mnbudget", "CBudgetProposal::AddOrUpdateVote - %s %s\n", strAction.c_str(), vote.GetHash().ToString().c_str()); return true; } // If masternode voted for a proposal, but is now invalid -- remove the vote void CBudgetProposal::CleanAndRemove(bool fSignatureCheck) { std::map<uint256, CBudgetVote>::iterator it = mapVotes.begin(); while (it != mapVotes.end()) { (*it).second.fValid = (*it).second.SignatureValid(fSignatureCheck); ++it; } } double CBudgetProposal::GetRatio() { int yeas = 0; int nays = 0; std::map<uint256, CBudgetVote>::iterator it = mapVotes.begin(); while (it != mapVotes.end()) { if ((*it).second.nVote == VOTE_YES) yeas++; if ((*it).second.nVote == VOTE_NO) nays++; ++it; } if (yeas + nays == 0) return 0.0f; return ((double)(yeas) / (double)(yeas + nays)); } int CBudgetProposal::GetYeas() { int ret = 0; std::map<uint256, CBudgetVote>::iterator it = mapVotes.begin(); while (it != mapVotes.end()) { if ((*it).second.nVote == VOTE_YES && (*it).second.fValid) ret++; ++it; } return ret; } int CBudgetProposal::GetNays() { int ret = 0; std::map<uint256, CBudgetVote>::iterator it = mapVotes.begin(); while (it != mapVotes.end()) { if ((*it).second.nVote == VOTE_NO && (*it).second.fValid) ret++; ++it; } return ret; } int CBudgetProposal::GetAbstains() { int ret = 0; std::map<uint256, CBudgetVote>::iterator it = mapVotes.begin(); while (it != mapVotes.end()) { if ((*it).second.nVote == VOTE_ABSTAIN && (*it).second.fValid) ret++; ++it; } return ret; } int CBudgetProposal::GetBlockStartCycle() { //end block is half way through the next cycle (so the proposal will be removed much after the payment is sent) return nBlockStart - nBlockStart % GetBudgetPaymentCycleBlocks(); } int CBudgetProposal::GetBlockCurrentCycle() { CBlockIndex* pindexPrev = chainActive.Tip(); if (pindexPrev == NULL) return -1; if (pindexPrev->nHeight >= GetBlockEndCycle()) return -1; return pindexPrev->nHeight - pindexPrev->nHeight % GetBudgetPaymentCycleBlocks(); } int CBudgetProposal::GetBlockEndCycle() { // Right now single payment proposals have nBlockEnd have a cycle too early! // switch back if it break something else // end block is half way through the next cycle (so the proposal will be removed much after the payment is sent) // return nBlockEnd - GetBudgetPaymentCycleBlocks() / 2; // End block is half way through the next cycle (so the proposal will be removed much after the payment is sent) return nBlockEnd; } int CBudgetProposal::GetTotalPaymentCount() { return (GetBlockEndCycle() - GetBlockStartCycle()) / GetBudgetPaymentCycleBlocks(); } int CBudgetProposal::GetRemainingPaymentCount() { // If this budget starts in the future, this value will be wrong int nPayments = (GetBlockEndCycle() - GetBlockCurrentCycle()) / GetBudgetPaymentCycleBlocks() - 1; // Take the lowest value return std::min(nPayments, GetTotalPaymentCount()); } CBudgetProposalBroadcast::CBudgetProposalBroadcast(std::string strProposalNameIn, std::string strURLIn, int nPaymentCount, CScript addressIn, CAmount nAmountIn, int nBlockStartIn, uint256 nFeeTXHashIn) { strProposalName = strProposalNameIn; strURL = strURLIn; nBlockStart = nBlockStartIn; int nCycleStart = nBlockStart - nBlockStart % GetBudgetPaymentCycleBlocks(); // Right now single payment proposals have nBlockEnd have a cycle too early! // switch back if it break something else // calculate the end of the cycle for this vote, add half a cycle (vote will be deleted after that block) // nBlockEnd = nCycleStart + GetBudgetPaymentCycleBlocks() * nPaymentCount + GetBudgetPaymentCycleBlocks() / 2; // Calculate the end of the cycle for this vote, vote will be deleted after next cycle nBlockEnd = nCycleStart + (GetBudgetPaymentCycleBlocks() + 1) * nPaymentCount; address = addressIn; nAmount = nAmountIn; nFeeTXHash = nFeeTXHashIn; } void CBudgetProposalBroadcast::Relay() { CInv inv(MSG_BUDGET_PROPOSAL, GetHash()); RelayInv(inv); } CBudgetVote::CBudgetVote() { vin = CTxIn(); nProposalHash = 0; nVote = VOTE_ABSTAIN; nTime = 0; fValid = true; fSynced = false; } CBudgetVote::CBudgetVote(CTxIn vinIn, uint256 nProposalHashIn, int nVoteIn) { vin = vinIn; nProposalHash = nProposalHashIn; nVote = nVoteIn; nTime = GetAdjustedTime(); fValid = true; fSynced = false; } void CBudgetVote::Relay() { CInv inv(MSG_BUDGET_VOTE, GetHash()); RelayInv(inv); } bool CBudgetVote::Sign(CKey& keyMasternode, CPubKey& pubKeyMasternode) { // Choose coins to use CPubKey pubKeyCollateralAddress; CKey keyCollateralAddress; std::string errorMessage; std::string strMessage = vin.prevout.ToStringShort() + nProposalHash.ToString() + boost::lexical_cast<std::string>(nVote) + boost::lexical_cast<std::string>(nTime); if (!obfuScationSigner.SignMessage(strMessage, errorMessage, vchSig, keyMasternode)) { LogPrint("mnbudget","CBudgetVote::Sign - Error upon calling SignMessage"); return false; } if (!obfuScationSigner.VerifyMessage(pubKeyMasternode, vchSig, strMessage, errorMessage)) { LogPrint("mnbudget","CBudgetVote::Sign - Error upon calling VerifyMessage"); return false; } return true; } bool CBudgetVote::SignatureValid(bool fSignatureCheck) { std::string errorMessage; std::string strMessage = vin.prevout.ToStringShort() + nProposalHash.ToString() + boost::lexical_cast<std::string>(nVote) + boost::lexical_cast<std::string>(nTime); CMasternode* pmn = mnodeman.Find(vin); if (pmn == NULL) { if (fDebug){ LogPrint("mnbudget","CBudgetVote::SignatureValid() - Unknown Masternode - %s\n", vin.prevout.hash.ToString()); } return false; } if (!fSignatureCheck) return true; if (!obfuScationSigner.VerifyMessage(pmn->pubKeyMasternode, vchSig, strMessage, errorMessage)) { LogPrint("mnbudget","CBudgetVote::SignatureValid() - Verify message failed\n"); return false; } return true; } CFinalizedBudget::CFinalizedBudget() { strBudgetName = ""; nBlockStart = 0; vecBudgetPayments.clear(); mapVotes.clear(); nFeeTXHash = 0; nTime = 0; fValid = true; fAutoChecked = false; } CFinalizedBudget::CFinalizedBudget(const CFinalizedBudget& other) { strBudgetName = other.strBudgetName; nBlockStart = other.nBlockStart; vecBudgetPayments = other.vecBudgetPayments; mapVotes = other.mapVotes; nFeeTXHash = other.nFeeTXHash; nTime = other.nTime; fValid = true; fAutoChecked = false; } bool CFinalizedBudget::AddOrUpdateVote(CFinalizedBudgetVote& vote, std::string& strError) { LOCK(cs); uint256 hash = vote.vin.prevout.GetHash(); std::string strAction = "New vote inserted:"; if (mapVotes.count(hash)) { if (mapVotes[hash].nTime > vote.nTime) { strError = strprintf("new vote older than existing vote - %s\n", vote.GetHash().ToString()); LogPrint("mnbudget", "CFinalizedBudget::AddOrUpdateVote - %s\n", strError); return false; } if (vote.nTime - mapVotes[hash].nTime < BUDGET_VOTE_UPDATE_MIN) { strError = strprintf("time between votes is too soon - %s - %lli sec < %lli sec\n", vote.GetHash().ToString(), vote.nTime - mapVotes[hash].nTime,BUDGET_VOTE_UPDATE_MIN); LogPrint("mnbudget", "CFinalizedBudget::AddOrUpdateVote - %s\n", strError); return false; } strAction = "Existing vote updated:"; } if (vote.nTime > GetTime() + (60 * 60)) { strError = strprintf("new vote is too far ahead of current time - %s - nTime %lli - Max Time %lli\n", vote.GetHash().ToString(), vote.nTime, GetTime() + (60 * 60)); LogPrint("mnbudget", "CFinalizedBudget::AddOrUpdateVote - %s\n", strError); return false; } mapVotes[hash] = vote; LogPrint("mnbudget", "CFinalizedBudget::AddOrUpdateVote - %s %s\n", strAction.c_str(), vote.GetHash().ToString().c_str()); return true; } //evaluate if we should vote for this. Masternode only void CFinalizedBudget::AutoCheck() { LOCK(cs); CBlockIndex* pindexPrev = chainActive.Tip(); if (!pindexPrev) return; LogPrint("mnbudget","CFinalizedBudget::AutoCheck - %lli - %d\n", pindexPrev->nHeight, fAutoChecked); if (!fMasterNode || fAutoChecked) { LogPrint("mnbudget","CFinalizedBudget::AutoCheck fMasterNode=%d fAutoChecked=%d\n", fMasterNode, fAutoChecked); return; } // Do this 1 in 4 blocks -- spread out the voting activity // -- this function is only called every fourteenth block, so this is really 1 in 56 blocks if (rand() % 4 != 0) { LogPrint("mnbudget","CFinalizedBudget::AutoCheck - waiting\n"); return; } fAutoChecked = true; //we only need to check this once if (strBudgetMode == "auto") //only vote for exact matches { std::vector<CBudgetProposal*> vBudgetProposals = budget.GetBudget(); for (unsigned int i = 0; i < vecBudgetPayments.size(); i++) { LogPrint("mnbudget","CFinalizedBudget::AutoCheck Budget-Payments - nProp %d %s\n", i, vecBudgetPayments[i].nProposalHash.ToString()); LogPrint("mnbudget","CFinalizedBudget::AutoCheck Budget-Payments - Payee %d %s\n", i, vecBudgetPayments[i].payee.ToString()); LogPrint("mnbudget","CFinalizedBudget::AutoCheck Budget-Payments - nAmount %d %lli\n", i, vecBudgetPayments[i].nAmount); } for (unsigned int i = 0; i < vBudgetProposals.size(); i++) { LogPrint("mnbudget","CFinalizedBudget::AutoCheck Budget-Proposals - nProp %d %s\n", i, vBudgetProposals[i]->GetHash().ToString()); LogPrint("mnbudget","CFinalizedBudget::AutoCheck Budget-Proposals - Payee %d %s\n", i, vBudgetProposals[i]->GetPayee().ToString()); LogPrint("mnbudget","CFinalizedBudget::AutoCheck Budget-Proposals - nAmount %d %lli\n", i, vBudgetProposals[i]->GetAmount()); } if (vBudgetProposals.size() == 0) { LogPrint("mnbudget","CFinalizedBudget::AutoCheck - No Budget-Proposals found, aborting\n"); return; } if (vBudgetProposals.size() != vecBudgetPayments.size()) { LogPrint("mnbudget","CFinalizedBudget::AutoCheck - Budget-Proposal length (%ld) doesn't match Budget-Payment length (%ld).\n", vBudgetProposals.size(), vecBudgetPayments.size()); return; } for (unsigned int i = 0; i < vecBudgetPayments.size(); i++) { if (i > vBudgetProposals.size() - 1) { LogPrint("mnbudget","CFinalizedBudget::AutoCheck - Proposal size mismatch, i=%d > (vBudgetProposals.size() - 1)=%d\n", i, vBudgetProposals.size() - 1); return; } if (vecBudgetPayments[i].nProposalHash != vBudgetProposals[i]->GetHash()) { LogPrint("mnbudget","CFinalizedBudget::AutoCheck - item #%d doesn't match %s %s\n", i, vecBudgetPayments[i].nProposalHash.ToString(), vBudgetProposals[i]->GetHash().ToString()); return; } // if(vecBudgetPayments[i].payee != vBudgetProposals[i]->GetPayee()){ -- triggered with false positive if (vecBudgetPayments[i].payee.ToString() != vBudgetProposals[i]->GetPayee().ToString()) { LogPrint("mnbudget","CFinalizedBudget::AutoCheck - item #%d payee doesn't match %s %s\n", i, vecBudgetPayments[i].payee.ToString(), vBudgetProposals[i]->GetPayee().ToString()); return; } if (vecBudgetPayments[i].nAmount != vBudgetProposals[i]->GetAmount()) { LogPrint("mnbudget","CFinalizedBudget::AutoCheck - item #%d payee doesn't match %lli %lli\n", i, vecBudgetPayments[i].nAmount, vBudgetProposals[i]->GetAmount()); return; } } LogPrint("mnbudget","CFinalizedBudget::AutoCheck - Finalized Budget Matches! Submitting Vote.\n"); SubmitVote(); } } // If masternode voted for a proposal, but is now invalid -- remove the vote void CFinalizedBudget::CleanAndRemove(bool fSignatureCheck) { std::map<uint256, CFinalizedBudgetVote>::iterator it = mapVotes.begin(); while (it != mapVotes.end()) { (*it).second.fValid = (*it).second.SignatureValid(fSignatureCheck); ++it; } } CAmount CFinalizedBudget::GetTotalPayout() { CAmount ret = 0; for (unsigned int i = 0; i < vecBudgetPayments.size(); i++) { ret += vecBudgetPayments[i].nAmount; } return ret; } std::string CFinalizedBudget::GetProposals() { LOCK(cs); std::string ret = ""; BOOST_FOREACH (CTxBudgetPayment& budgetPayment, vecBudgetPayments) { CBudgetProposal* pbudgetProposal = budget.FindProposal(budgetPayment.nProposalHash); std::string token = budgetPayment.nProposalHash.ToString(); if (pbudgetProposal) token = pbudgetProposal->GetName(); if (ret == "") { ret = token; } else { ret += "," + token; } } return ret; } std::string CFinalizedBudget::GetStatus() { std::string retBadHashes = ""; std::string retBadPayeeOrAmount = ""; for (int nBlockHeight = GetBlockStart(); nBlockHeight <= GetBlockEnd(); nBlockHeight++) { CTxBudgetPayment budgetPayment; if (!GetBudgetPaymentByBlock(nBlockHeight, budgetPayment)) { LogPrint("mnbudget","CFinalizedBudget::GetStatus - Couldn't find budget payment for block %lld\n", nBlockHeight); continue; } CBudgetProposal* pbudgetProposal = budget.FindProposal(budgetPayment.nProposalHash); if (!pbudgetProposal) { if (retBadHashes == "") { retBadHashes = "Unknown proposal hash! Check this proposal before voting: " + budgetPayment.nProposalHash.ToString(); } else { retBadHashes += "," + budgetPayment.nProposalHash.ToString(); } } else { if (pbudgetProposal->GetPayee() != budgetPayment.payee || pbudgetProposal->GetAmount() != budgetPayment.nAmount) { if (retBadPayeeOrAmount == "") { retBadPayeeOrAmount = "Budget payee/nAmount doesn't match our proposal! " + budgetPayment.nProposalHash.ToString(); } else { retBadPayeeOrAmount += "," + budgetPayment.nProposalHash.ToString(); } } } } if (retBadHashes == "" && retBadPayeeOrAmount == "") return "OK"; return retBadHashes + retBadPayeeOrAmount; } bool CFinalizedBudget::IsValid(std::string& strError, bool fCheckCollateral) { // All(!) finalized budgets have the name "main", so get some additional information about them std::string strProposals = GetProposals(); // Must be the correct block for payment to happen (once a month) if (nBlockStart % GetBudgetPaymentCycleBlocks() != 0) { strError = "Invalid BlockStart"; return false; } // The following 2 checks check the same (basically if vecBudgetPayments.size() > 100) if (GetBlockEnd() - nBlockStart > 100) { strError = "Invalid BlockEnd"; return false; } if ((int)vecBudgetPayments.size() > 100) { strError = "Invalid budget payments count (too many)"; return false; } if (strBudgetName == "") { strError = "Invalid Budget Name"; return false; } if (nBlockStart == 0) { strError = "Budget " + strBudgetName + " (" + strProposals + ") Invalid BlockStart == 0"; return false; } if (nFeeTXHash == 0) { strError = "Budget " + strBudgetName + " (" + strProposals + ") Invalid FeeTx == 0"; return false; } // Can only pay out 10% of the possible coins (min value of coins) if (GetTotalPayout() > budget.GetTotalBudget(nBlockStart)) { strError = "Budget " + strBudgetName + " (" + strProposals + ") Invalid Payout (more than max)"; return false; } std::string strError2 = ""; if (fCheckCollateral) { int nConf = 0; if (!IsBudgetCollateralValid(nFeeTXHash, GetHash(), strError2, nTime, nConf, true)) { { strError = "Budget " + strBudgetName + " (" + strProposals + ") Invalid Collateral : " + strError2; return false; } } } // Remove obsolete finalized budgets after some time CBlockIndex* pindexPrev = chainActive.Tip(); if (pindexPrev == NULL) return true; // Get start of current budget-cycle int nCurrentHeight = chainActive.Height(); int nBlockStart = nCurrentHeight - nCurrentHeight % GetBudgetPaymentCycleBlocks() + GetBudgetPaymentCycleBlocks(); // Remove budgets where the last payment (from max. 100) ends before 2 budget-cycles before the current one int nMaxAge = nBlockStart - (2 * GetBudgetPaymentCycleBlocks()); if (GetBlockEnd() < nMaxAge) { strError = strprintf("Budget " + strBudgetName + " (" + strProposals + ") (ends at block %ld) too old and obsolete", GetBlockEnd()); return false; } return true; } bool CFinalizedBudget::IsPaidAlready(uint256 nProposalHash, int nBlockHeight) { // Remove budget-payments from former/future payment cycles map<uint256, int>::iterator it = mapPayment_History.begin(); int nPaidBlockHeight = 0; uint256 nOldProposalHash; for(it = mapPayment_History.begin(); it != mapPayment_History.end(); /* No incrementation needed */ ) { nPaidBlockHeight = (*it).second; if((nPaidBlockHeight < GetBlockStart()) || (nPaidBlockHeight > GetBlockEnd())) { nOldProposalHash = (*it).first; LogPrint("mnbudget", "CFinalizedBudget::IsPaidAlready - Budget Proposal %s, Block %d from old cycle deleted\n", nOldProposalHash.ToString().c_str(), nPaidBlockHeight); mapPayment_History.erase(it++); } else { ++it; } } // Now that we only have payments from the current payment cycle check if this budget was paid already if(mapPayment_History.count(nProposalHash) == 0) { // New proposal payment, insert into map for checks with later blocks from this cycle mapPayment_History.insert(std::pair<uint256, int>(nProposalHash, nBlockHeight)); LogPrint("mnbudget", "CFinalizedBudget::IsPaidAlready - Budget Proposal %s, Block %d added to payment history\n", nProposalHash.ToString().c_str(), nBlockHeight); return false; } // This budget was paid already -> reject transaction so it gets paid to a masternode instead return true; } TrxValidationStatus CFinalizedBudget::IsTransactionValid(const CTransaction& txNew, int nBlockHeight) { TrxValidationStatus transactionStatus = TrxValidationStatus::InValid; int nCurrentBudgetPayment = nBlockHeight - GetBlockStart(); if (nCurrentBudgetPayment < 0) { LogPrint("mnbudget","CFinalizedBudget::IsTransactionValid - Invalid block - height: %d start: %d\n", nBlockHeight, GetBlockStart()); return TrxValidationStatus::InValid; } if (nCurrentBudgetPayment > (int)vecBudgetPayments.size() - 1) { LogPrint("mnbudget","CFinalizedBudget::IsTransactionValid - Invalid last block - current budget payment: %d of %d\n", nCurrentBudgetPayment + 1, (int)vecBudgetPayments.size()); return TrxValidationStatus::InValid; } bool paid = false; BOOST_FOREACH (CTxOut out, txNew.vout) { LogPrint("mnbudget","CFinalizedBudget::IsTransactionValid - nCurrentBudgetPayment=%d, payee=%s == out.scriptPubKey=%s, amount=%ld == out.nValue=%ld\n", nCurrentBudgetPayment, vecBudgetPayments[nCurrentBudgetPayment].payee.ToString().c_str(), out.scriptPubKey.ToString().c_str(), vecBudgetPayments[nCurrentBudgetPayment].nAmount, out.nValue); if (vecBudgetPayments[nCurrentBudgetPayment].payee == out.scriptPubKey && vecBudgetPayments[nCurrentBudgetPayment].nAmount == out.nValue) { // Check if this proposal was paid already. If so, pay a masternode instead paid = IsPaidAlready(vecBudgetPayments[nCurrentBudgetPayment].nProposalHash, nBlockHeight); if(paid) { LogPrint("mnbudget","CFinalizedBudget::IsTransactionValid - Double Budget Payment of %d for proposal %d detected. Paying a masternode instead.\n", vecBudgetPayments[nCurrentBudgetPayment].nAmount, vecBudgetPayments[nCurrentBudgetPayment].nProposalHash.Get32()); // No matter what we've found before, stop all checks here. In future releases there might be more than one budget payment // per block, so even if the first one was not paid yet this one disables all budget payments for this block. transactionStatus = TrxValidationStatus::DoublePayment; break; } else { transactionStatus = TrxValidationStatus::Valid; LogPrint("mnbudget","CFinalizedBudget::IsTransactionValid - Found valid Budget Payment of %d for proposal %d\n", vecBudgetPayments[nCurrentBudgetPayment].nAmount, vecBudgetPayments[nCurrentBudgetPayment].nProposalHash.Get32()); } } } if (transactionStatus == TrxValidationStatus::InValid) { CTxDestination address1; ExtractDestination(vecBudgetPayments[nCurrentBudgetPayment].payee, address1); CBitcoinAddress address2(address1); LogPrint("mnbudget","CFinalizedBudget::IsTransactionValid - Missing required payment - %s: %d c: %d\n", address2.ToString(), vecBudgetPayments[nCurrentBudgetPayment].nAmount, nCurrentBudgetPayment); } return transactionStatus; } void CFinalizedBudget::SubmitVote() { CPubKey pubKeyMasternode; CKey keyMasternode; std::string errorMessage; if (!obfuScationSigner.SetKey(strMasterNodePrivKey, errorMessage, keyMasternode, pubKeyMasternode)) { LogPrint("mnbudget","CFinalizedBudget::SubmitVote - Error upon calling SetKey\n"); return; } CFinalizedBudgetVote vote(activeMasternode.vin, GetHash()); if (!vote.Sign(keyMasternode, pubKeyMasternode)) { LogPrint("mnbudget","CFinalizedBudget::SubmitVote - Failure to sign."); return; } std::string strError = ""; if (budget.UpdateFinalizedBudget(vote, NULL, strError)) { LogPrint("mnbudget","CFinalizedBudget::SubmitVote - new finalized budget vote - %s\n", vote.GetHash().ToString()); budget.mapSeenFinalizedBudgetVotes.insert(make_pair(vote.GetHash(), vote)); vote.Relay(); } else { LogPrint("mnbudget","CFinalizedBudget::SubmitVote : Error submitting vote - %s\n", strError); } } CFinalizedBudgetBroadcast::CFinalizedBudgetBroadcast() { strBudgetName = ""; nBlockStart = 0; vecBudgetPayments.clear(); mapVotes.clear(); vchSig.clear(); nFeeTXHash = 0; } CFinalizedBudgetBroadcast::CFinalizedBudgetBroadcast(const CFinalizedBudget& other) { strBudgetName = other.strBudgetName; nBlockStart = other.nBlockStart; BOOST_FOREACH (CTxBudgetPayment out, other.vecBudgetPayments) vecBudgetPayments.push_back(out); mapVotes = other.mapVotes; nFeeTXHash = other.nFeeTXHash; } CFinalizedBudgetBroadcast::CFinalizedBudgetBroadcast(std::string strBudgetNameIn, int nBlockStartIn, std::vector<CTxBudgetPayment> vecBudgetPaymentsIn, uint256 nFeeTXHashIn) { strBudgetName = strBudgetNameIn; nBlockStart = nBlockStartIn; BOOST_FOREACH (CTxBudgetPayment out, vecBudgetPaymentsIn) vecBudgetPayments.push_back(out); mapVotes.clear(); nFeeTXHash = nFeeTXHashIn; } void CFinalizedBudgetBroadcast::Relay() { CInv inv(MSG_BUDGET_FINALIZED, GetHash()); RelayInv(inv); } CFinalizedBudgetVote::CFinalizedBudgetVote() { vin = CTxIn(); nBudgetHash = 0; nTime = 0; vchSig.clear(); fValid = true; fSynced = false; } CFinalizedBudgetVote::CFinalizedBudgetVote(CTxIn vinIn, uint256 nBudgetHashIn) { vin = vinIn; nBudgetHash = nBudgetHashIn; nTime = GetAdjustedTime(); vchSig.clear(); fValid = true; fSynced = false; } void CFinalizedBudgetVote::Relay() { CInv inv(MSG_BUDGET_FINALIZED_VOTE, GetHash()); RelayInv(inv); } bool CFinalizedBudgetVote::Sign(CKey& keyMasternode, CPubKey& pubKeyMasternode) { // Choose coins to use CPubKey pubKeyCollateralAddress; CKey keyCollateralAddress; std::string errorMessage; std::string strMessage = vin.prevout.ToStringShort() + nBudgetHash.ToString() + boost::lexical_cast<std::string>(nTime); if (!obfuScationSigner.SignMessage(strMessage, errorMessage, vchSig, keyMasternode)) { LogPrint("mnbudget","CFinalizedBudgetVote::Sign - Error upon calling SignMessage"); return false; } if (!obfuScationSigner.VerifyMessage(pubKeyMasternode, vchSig, strMessage, errorMessage)) { LogPrint("mnbudget","CFinalizedBudgetVote::Sign - Error upon calling VerifyMessage"); return false; } return true; } bool CFinalizedBudgetVote::SignatureValid(bool fSignatureCheck) { std::string errorMessage; std::string strMessage = vin.prevout.ToStringShort() + nBudgetHash.ToString() + boost::lexical_cast<std::string>(nTime); CMasternode* pmn = mnodeman.Find(vin); if (pmn == NULL) { LogPrint("mnbudget","CFinalizedBudgetVote::SignatureValid() - Unknown Masternode %s\n", strMessage); return false; } if (!fSignatureCheck) return true; if (!obfuScationSigner.VerifyMessage(pmn->pubKeyMasternode, vchSig, strMessage, errorMessage)) { LogPrint("mnbudget","CFinalizedBudgetVote::SignatureValid() - Verify message failed %s %s\n", strMessage, errorMessage); return false; } return true; } std::string CBudgetManager::ToString() const { std::ostringstream info; info << "Proposals: " << (int)mapProposals.size() << ", Budgets: " << (int)mapFinalizedBudgets.size() << ", Seen Budgets: " << (int)mapSeenMasternodeBudgetProposals.size() << ", Seen Budget Votes: " << (int)mapSeenMasternodeBudgetVotes.size() << ", Seen Final Budgets: " << (int)mapSeenFinalizedBudgets.size() << ", Seen Final Budget Votes: " << (int)mapSeenFinalizedBudgetVotes.size(); return info.str(); } [Budget] Make sorting of finalized budgets deterministic // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2018 The PIVX developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "init.h" #include "main.h" #include "addrman.h" #include "masternode-budget.h" #include "masternode-sync.h" #include "masternode.h" #include "masternodeman.h" #include "obfuscation.h" #include "util.h" #include <boost/filesystem.hpp> #include <boost/lexical_cast.hpp> CBudgetManager budget; CCriticalSection cs_budget; std::map<uint256, int64_t> askedForSourceProposalOrBudget; std::vector<CBudgetProposalBroadcast> vecImmatureBudgetProposals; std::vector<CFinalizedBudgetBroadcast> vecImmatureFinalizedBudgets; int nSubmittedFinalBudget; int GetBudgetPaymentCycleBlocks() { // Amount of blocks in a months period of time (using 1 minutes per) = (60*24*30) if (Params().NetworkID() == CBaseChainParams::MAIN) return 43200; //for testing purposes return 144; //ten times per day } bool IsBudgetCollateralValid(uint256 nTxCollateralHash, uint256 nExpectedHash, std::string& strError, int64_t& nTime, int& nConf, bool fBudgetFinalization) { CTransaction txCollateral; uint256 nBlockHash; if (!GetTransaction(nTxCollateralHash, txCollateral, nBlockHash, true)) { strError = strprintf("Can't find collateral tx %s", txCollateral.ToString()); LogPrint("mnbudget","CBudgetProposalBroadcast::IsBudgetCollateralValid - %s\n", strError); return false; } if (txCollateral.vout.size() < 1) return false; if (txCollateral.nLockTime != 0) return false; CScript findScript; findScript << OP_RETURN << ToByteVector(nExpectedHash); bool foundOpReturn = false; BOOST_FOREACH (const CTxOut o, txCollateral.vout) { if (!o.scriptPubKey.IsNormalPaymentScript() && !o.scriptPubKey.IsUnspendable()) { strError = strprintf("Invalid Script %s", txCollateral.ToString()); LogPrint("mnbudget","CBudgetProposalBroadcast::IsBudgetCollateralValid - %s\n", strError); return false; } if (fBudgetFinalization) { // Collateral for budget finalization // Note: there are still old valid budgets out there, but the check for the new 5 PIV finalization collateral // will also cover the old 50 PIV finalization collateral. LogPrint("mnbudget", "Final Budget: o.scriptPubKey(%s) == findScript(%s) ?\n", o.scriptPubKey.ToString(), findScript.ToString()); if (o.scriptPubKey == findScript) { LogPrint("mnbudget", "Final Budget: o.nValue(%ld) >= BUDGET_FEE_TX(%ld) ?\n", o.nValue, BUDGET_FEE_TX); if(o.nValue >= BUDGET_FEE_TX) { foundOpReturn = true; } } } else { // Collateral for normal budget proposal LogPrint("mnbudget", "Normal Budget: o.scriptPubKey(%s) == findScript(%s) ?\n", o.scriptPubKey.ToString(), findScript.ToString()); if (o.scriptPubKey == findScript) { LogPrint("mnbudget", "Normal Budget: o.nValue(%ld) >= PROPOSAL_FEE_TX(%ld) ?\n", o.nValue, PROPOSAL_FEE_TX); if(o.nValue >= PROPOSAL_FEE_TX) { foundOpReturn = true; } } } } if (!foundOpReturn) { strError = strprintf("Couldn't find opReturn %s in %s", nExpectedHash.ToString(), txCollateral.ToString()); LogPrint("mnbudget","CBudgetProposalBroadcast::IsBudgetCollateralValid - %s\n", strError); return false; } // RETRIEVE CONFIRMATIONS AND NTIME /* - nTime starts as zero and is passed-by-reference out of this function and stored in the external proposal - nTime is never validated via the hashing mechanism and comes from a full-validated source (the blockchain) */ int conf = GetIXConfirmations(nTxCollateralHash); if (nBlockHash != uint256(0)) { BlockMap::iterator mi = mapBlockIndex.find(nBlockHash); if (mi != mapBlockIndex.end() && (*mi).second) { CBlockIndex* pindex = (*mi).second; if (chainActive.Contains(pindex)) { conf += chainActive.Height() - pindex->nHeight + 1; nTime = pindex->nTime; } } } nConf = conf; //if we're syncing we won't have swiftTX information, so accept 1 confirmation if (conf >= Params().Budget_Fee_Confirmations()) { return true; } else { strError = strprintf("Collateral requires at least %d confirmations - %d confirmations", Params().Budget_Fee_Confirmations(), conf); LogPrint("mnbudget","CBudgetProposalBroadcast::IsBudgetCollateralValid - %s - %d confirmations\n", strError, conf); return false; } } void CBudgetManager::CheckOrphanVotes() { LOCK(cs); std::string strError = ""; std::map<uint256, CBudgetVote>::iterator it1 = mapOrphanMasternodeBudgetVotes.begin(); while (it1 != mapOrphanMasternodeBudgetVotes.end()) { if (budget.UpdateProposal(((*it1).second), NULL, strError)) { LogPrint("mnbudget","CBudgetManager::CheckOrphanVotes - Proposal/Budget is known, activating and removing orphan vote\n"); mapOrphanMasternodeBudgetVotes.erase(it1++); } else { ++it1; } } std::map<uint256, CFinalizedBudgetVote>::iterator it2 = mapOrphanFinalizedBudgetVotes.begin(); while (it2 != mapOrphanFinalizedBudgetVotes.end()) { if (budget.UpdateFinalizedBudget(((*it2).second), NULL, strError)) { LogPrint("mnbudget","CBudgetManager::CheckOrphanVotes - Proposal/Budget is known, activating and removing orphan vote\n"); mapOrphanFinalizedBudgetVotes.erase(it2++); } else { ++it2; } } LogPrint("mnbudget","CBudgetManager::CheckOrphanVotes - Done\n"); } void CBudgetManager::SubmitFinalBudget() { static int nSubmittedHeight = 0; // height at which final budget was submitted last time int nCurrentHeight; { TRY_LOCK(cs_main, locked); if (!locked) return; if (!chainActive.Tip()) return; nCurrentHeight = chainActive.Height(); } int nBlockStart = nCurrentHeight - nCurrentHeight % GetBudgetPaymentCycleBlocks() + GetBudgetPaymentCycleBlocks(); if (nSubmittedHeight >= nBlockStart){ LogPrint("mnbudget","CBudgetManager::SubmitFinalBudget - nSubmittedHeight(=%ld) < nBlockStart(=%ld) condition not fulfilled.\n", nSubmittedHeight, nBlockStart); return; } // Submit final budget during the last 2 days (2880 blocks) before payment for Mainnet, about 9 minutes (9 blocks) for Testnet int finalizationWindow = ((GetBudgetPaymentCycleBlocks() / 30) * 2); if (Params().NetworkID() == CBaseChainParams::TESTNET) { // NOTE: 9 blocks for testnet is way to short to have any masternode submit an automatic vote on the finalized(!) budget, // because those votes are only submitted/relayed once every 56 blocks in CFinalizedBudget::AutoCheck() finalizationWindow = 64; // 56 + 4 finalization confirmations + 4 minutes buffer for propagation } int nFinalizationStart = nBlockStart - finalizationWindow; int nOffsetToStart = nFinalizationStart - nCurrentHeight; if (nBlockStart - nCurrentHeight > finalizationWindow) { LogPrint("mnbudget","CBudgetManager::SubmitFinalBudget - Too early for finalization. Current block is %ld, next Superblock is %ld.\n", nCurrentHeight, nBlockStart); LogPrint("mnbudget","CBudgetManager::SubmitFinalBudget - First possible block for finalization: %ld. Last possible block for finalization: %ld. You have to wait for %ld block(s) until Budget finalization will be possible\n", nFinalizationStart, nBlockStart, nOffsetToStart); return; } std::vector<CBudgetProposal*> vBudgetProposals = budget.GetBudget(); std::string strBudgetName = "main"; std::vector<CTxBudgetPayment> vecTxBudgetPayments; for (unsigned int i = 0; i < vBudgetProposals.size(); i++) { CTxBudgetPayment txBudgetPayment; txBudgetPayment.nProposalHash = vBudgetProposals[i]->GetHash(); txBudgetPayment.payee = vBudgetProposals[i]->GetPayee(); txBudgetPayment.nAmount = vBudgetProposals[i]->GetAllotted(); vecTxBudgetPayments.push_back(txBudgetPayment); } if (vecTxBudgetPayments.size() < 1) { LogPrint("mnbudget","CBudgetManager::SubmitFinalBudget - Found No Proposals For Period\n"); return; } CFinalizedBudgetBroadcast tempBudget(strBudgetName, nBlockStart, vecTxBudgetPayments, 0); if (mapSeenFinalizedBudgets.count(tempBudget.GetHash())) { LogPrint("mnbudget","CBudgetManager::SubmitFinalBudget - Budget already exists - %s\n", tempBudget.GetHash().ToString()); nSubmittedHeight = nCurrentHeight; return; //already exists } //create fee tx CTransaction tx; uint256 txidCollateral; if (!mapCollateralTxids.count(tempBudget.GetHash())) { CWalletTx wtx; if (!pwalletMain->GetBudgetFinalizationCollateralTX(wtx, tempBudget.GetHash(), false)) { LogPrint("mnbudget","CBudgetManager::SubmitFinalBudget - Can't make collateral transaction\n"); return; } // Get our change address CReserveKey reservekey(pwalletMain); // Send the tx to the network. Do NOT use SwiftTx, locking might need too much time to propagate, especially for testnet pwalletMain->CommitTransaction(wtx, reservekey, "NO-ix"); tx = (CTransaction)wtx; txidCollateral = tx.GetHash(); mapCollateralTxids.insert(make_pair(tempBudget.GetHash(), txidCollateral)); } else { txidCollateral = mapCollateralTxids[tempBudget.GetHash()]; } int conf = GetIXConfirmations(txidCollateral); CTransaction txCollateral; uint256 nBlockHash; if (!GetTransaction(txidCollateral, txCollateral, nBlockHash, true)) { LogPrint("mnbudget","CBudgetManager::SubmitFinalBudget - Can't find collateral tx %s", txidCollateral.ToString()); return; } if (nBlockHash != uint256(0)) { BlockMap::iterator mi = mapBlockIndex.find(nBlockHash); if (mi != mapBlockIndex.end() && (*mi).second) { CBlockIndex* pindex = (*mi).second; if (chainActive.Contains(pindex)) { conf += chainActive.Height() - pindex->nHeight + 1; } } } /* Wait will we have 1 extra confirmation, otherwise some clients might reject this feeTX -- This function is tied to NewBlock, so we will propagate this budget while the block is also propagating */ if (conf < Params().Budget_Fee_Confirmations() + 1) { LogPrint("mnbudget","CBudgetManager::SubmitFinalBudget - Collateral requires at least %d confirmations - %s - %d confirmations\n", Params().Budget_Fee_Confirmations() + 1, txidCollateral.ToString(), conf); return; } //create the proposal incase we're the first to make it CFinalizedBudgetBroadcast finalizedBudgetBroadcast(strBudgetName, nBlockStart, vecTxBudgetPayments, txidCollateral); std::string strError = ""; if (!finalizedBudgetBroadcast.IsValid(strError)) { LogPrint("mnbudget","CBudgetManager::SubmitFinalBudget - Invalid finalized budget - %s \n", strError); return; } LOCK(cs); mapSeenFinalizedBudgets.insert(make_pair(finalizedBudgetBroadcast.GetHash(), finalizedBudgetBroadcast)); finalizedBudgetBroadcast.Relay(); budget.AddFinalizedBudget(finalizedBudgetBroadcast); nSubmittedHeight = nCurrentHeight; LogPrint("mnbudget","CBudgetManager::SubmitFinalBudget - Done! %s\n", finalizedBudgetBroadcast.GetHash().ToString()); } // // CBudgetDB // CBudgetDB::CBudgetDB() { pathDB = GetDataDir() / "budget.dat"; strMagicMessage = "MasternodeBudget"; } bool CBudgetDB::Write(const CBudgetManager& objToSave) { LOCK(objToSave.cs); int64_t nStart = GetTimeMillis(); // serialize, checksum data up to that point, then append checksum CDataStream ssObj(SER_DISK, CLIENT_VERSION); ssObj << strMagicMessage; // masternode cache file specific magic message ssObj << FLATDATA(Params().MessageStart()); // network specific magic number ssObj << objToSave; uint256 hash = Hash(ssObj.begin(), ssObj.end()); ssObj << hash; // open output file, and associate with CAutoFile FILE* file = fopen(pathDB.string().c_str(), "wb"); CAutoFile fileout(file, SER_DISK, CLIENT_VERSION); if (fileout.IsNull()) return error("%s : Failed to open file %s", __func__, pathDB.string()); // Write and commit header, data try { fileout << ssObj; } catch (std::exception& e) { return error("%s : Serialize or I/O error - %s", __func__, e.what()); } fileout.fclose(); LogPrint("mnbudget","Written info to budget.dat %dms\n", GetTimeMillis() - nStart); return true; } CBudgetDB::ReadResult CBudgetDB::Read(CBudgetManager& objToLoad, bool fDryRun) { LOCK(objToLoad.cs); int64_t nStart = GetTimeMillis(); // open input file, and associate with CAutoFile FILE* file = fopen(pathDB.string().c_str(), "rb"); CAutoFile filein(file, SER_DISK, CLIENT_VERSION); if (filein.IsNull()) { error("%s : Failed to open file %s", __func__, pathDB.string()); return FileError; } // use file size to size memory buffer int fileSize = boost::filesystem::file_size(pathDB); int dataSize = fileSize - sizeof(uint256); // Don't try to resize to a negative number if file is small if (dataSize < 0) dataSize = 0; vector<unsigned char> vchData; vchData.resize(dataSize); uint256 hashIn; // read data and checksum from file try { filein.read((char*)&vchData[0], dataSize); filein >> hashIn; } catch (std::exception& e) { error("%s : Deserialize or I/O error - %s", __func__, e.what()); return HashReadError; } filein.fclose(); CDataStream ssObj(vchData, SER_DISK, CLIENT_VERSION); // verify stored checksum matches input data uint256 hashTmp = Hash(ssObj.begin(), ssObj.end()); if (hashIn != hashTmp) { error("%s : Checksum mismatch, data corrupted", __func__); return IncorrectHash; } unsigned char pchMsgTmp[4]; std::string strMagicMessageTmp; try { // de-serialize file header (masternode cache file specific magic message) and .. ssObj >> strMagicMessageTmp; // ... verify the message matches predefined one if (strMagicMessage != strMagicMessageTmp) { error("%s : Invalid masternode cache magic message", __func__); return IncorrectMagicMessage; } // de-serialize file header (network specific magic number) and .. ssObj >> FLATDATA(pchMsgTmp); // ... verify the network matches ours if (memcmp(pchMsgTmp, Params().MessageStart(), sizeof(pchMsgTmp))) { error("%s : Invalid network magic number", __func__); return IncorrectMagicNumber; } // de-serialize data into CBudgetManager object ssObj >> objToLoad; } catch (std::exception& e) { objToLoad.Clear(); error("%s : Deserialize or I/O error - %s", __func__, e.what()); return IncorrectFormat; } LogPrint("mnbudget","Loaded info from budget.dat %dms\n", GetTimeMillis() - nStart); LogPrint("mnbudget"," %s\n", objToLoad.ToString()); if (!fDryRun) { LogPrint("mnbudget","Budget manager - cleaning....\n"); objToLoad.CheckAndRemove(); LogPrint("mnbudget","Budget manager - result:\n"); LogPrint("mnbudget"," %s\n", objToLoad.ToString()); } return Ok; } void DumpBudgets() { int64_t nStart = GetTimeMillis(); CBudgetDB budgetdb; CBudgetManager tempBudget; LogPrint("mnbudget","Verifying budget.dat format...\n"); CBudgetDB::ReadResult readResult = budgetdb.Read(tempBudget, true); // there was an error and it was not an error on file opening => do not proceed if (readResult == CBudgetDB::FileError) LogPrint("mnbudget","Missing budgets file - budget.dat, will try to recreate\n"); else if (readResult != CBudgetDB::Ok) { LogPrint("mnbudget","Error reading budget.dat: "); if (readResult == CBudgetDB::IncorrectFormat) LogPrint("mnbudget","magic is ok but data has invalid format, will try to recreate\n"); else { LogPrint("mnbudget","file format is unknown or invalid, please fix it manually\n"); return; } } LogPrint("mnbudget","Writting info to budget.dat...\n"); budgetdb.Write(budget); LogPrint("mnbudget","Budget dump finished %dms\n", GetTimeMillis() - nStart); } bool CBudgetManager::AddFinalizedBudget(CFinalizedBudget& finalizedBudget) { std::string strError = ""; if (!finalizedBudget.IsValid(strError)) return false; if (mapFinalizedBudgets.count(finalizedBudget.GetHash())) { return false; } mapFinalizedBudgets.insert(make_pair(finalizedBudget.GetHash(), finalizedBudget)); return true; } bool CBudgetManager::AddProposal(CBudgetProposal& budgetProposal) { LOCK(cs); std::string strError = ""; if (!budgetProposal.IsValid(strError)) { LogPrint("mnbudget","CBudgetManager::AddProposal - invalid budget proposal - %s\n", strError); return false; } if (mapProposals.count(budgetProposal.GetHash())) { return false; } mapProposals.insert(make_pair(budgetProposal.GetHash(), budgetProposal)); LogPrint("mnbudget","CBudgetManager::AddProposal - proposal %s added\n", budgetProposal.GetName ().c_str ()); return true; } void CBudgetManager::CheckAndRemove() { int nHeight = 0; // Add some verbosity once loading blocks from files has finished { TRY_LOCK(cs_main, locked); if ((locked) && (chainActive.Tip() != NULL)) { CBlockIndex* pindexPrev = chainActive.Tip(); if (pindexPrev) { nHeight = pindexPrev->nHeight; } } } LogPrint("mnbudget", "CBudgetManager::CheckAndRemove at Height=%d\n", nHeight); map<uint256, CFinalizedBudget> tmpMapFinalizedBudgets; map<uint256, CBudgetProposal> tmpMapProposals; std::string strError = ""; LogPrint("mnbudget", "CBudgetManager::CheckAndRemove - mapFinalizedBudgets cleanup - size before: %d\n", mapFinalizedBudgets.size()); std::map<uint256, CFinalizedBudget>::iterator it = mapFinalizedBudgets.begin(); while (it != mapFinalizedBudgets.end()) { CFinalizedBudget* pfinalizedBudget = &((*it).second); pfinalizedBudget->fValid = pfinalizedBudget->IsValid(strError); if (!strError.empty ()) { LogPrint("mnbudget","CBudgetManager::CheckAndRemove - Invalid finalized budget: %s\n", strError); } else { LogPrint("mnbudget","CBudgetManager::CheckAndRemove - Found valid finalized budget: %s %s\n", pfinalizedBudget->strBudgetName.c_str(), pfinalizedBudget->nFeeTXHash.ToString().c_str()); } if (pfinalizedBudget->fValid) { pfinalizedBudget->AutoCheck(); tmpMapFinalizedBudgets.insert(make_pair(pfinalizedBudget->GetHash(), *pfinalizedBudget)); } ++it; } LogPrint("mnbudget", "CBudgetManager::CheckAndRemove - mapProposals cleanup - size before: %d\n", mapProposals.size()); std::map<uint256, CBudgetProposal>::iterator it2 = mapProposals.begin(); while (it2 != mapProposals.end()) { CBudgetProposal* pbudgetProposal = &((*it2).second); pbudgetProposal->fValid = pbudgetProposal->IsValid(strError); if (!strError.empty ()) { LogPrint("mnbudget","CBudgetManager::CheckAndRemove - Invalid budget proposal - %s\n", strError); strError = ""; } else { LogPrint("mnbudget","CBudgetManager::CheckAndRemove - Found valid budget proposal: %s %s\n", pbudgetProposal->strProposalName.c_str(), pbudgetProposal->nFeeTXHash.ToString().c_str()); } if (pbudgetProposal->fValid) { tmpMapProposals.insert(make_pair(pbudgetProposal->GetHash(), *pbudgetProposal)); } ++it2; } // Remove invalid entries by overwriting complete map mapFinalizedBudgets.swap(tmpMapFinalizedBudgets); mapProposals.swap(tmpMapProposals); // clang doesn't accept copy assignemnts :-/ // mapFinalizedBudgets = tmpMapFinalizedBudgets; // mapProposals = tmpMapProposals; LogPrint("mnbudget", "CBudgetManager::CheckAndRemove - mapFinalizedBudgets cleanup - size after: %d\n", mapFinalizedBudgets.size()); LogPrint("mnbudget", "CBudgetManager::CheckAndRemove - mapProposals cleanup - size after: %d\n", mapProposals.size()); LogPrint("mnbudget","CBudgetManager::CheckAndRemove - PASSED\n"); } void CBudgetManager::FillBlockPayee(CMutableTransaction& txNew, CAmount nFees, bool fProofOfStake) { LOCK(cs); CBlockIndex* pindexPrev = chainActive.Tip(); if (!pindexPrev) return; int nHighestCount = 0; CScript payee; CAmount nAmount = 0; // ------- Grab The Highest Count std::map<uint256, CFinalizedBudget>::iterator it = mapFinalizedBudgets.begin(); while (it != mapFinalizedBudgets.end()) { CFinalizedBudget* pfinalizedBudget = &((*it).second); if (pfinalizedBudget->GetVoteCount() > nHighestCount && pindexPrev->nHeight + 1 >= pfinalizedBudget->GetBlockStart() && pindexPrev->nHeight + 1 <= pfinalizedBudget->GetBlockEnd() && pfinalizedBudget->GetPayeeAndAmount(pindexPrev->nHeight + 1, payee, nAmount)) { nHighestCount = pfinalizedBudget->GetVoteCount(); } ++it; } CAmount blockValue = GetBlockValue(pindexPrev->nHeight); if (fProofOfStake) { if (nHighestCount > 0) { unsigned int i = txNew.vout.size(); txNew.vout.resize(i + 1); txNew.vout[i].scriptPubKey = payee; txNew.vout[i].nValue = nAmount; CTxDestination address1; ExtractDestination(payee, address1); CBitcoinAddress address2(address1); LogPrint("mnbudget","CBudgetManager::FillBlockPayee - Budget payment to %s for %lld, nHighestCount = %d\n", address2.ToString(), nAmount, nHighestCount); } else { LogPrint("mnbudget","CBudgetManager::FillBlockPayee - No Budget payment, nHighestCount = %d\n", nHighestCount); } } else { //miners get the full amount on these blocks txNew.vout[0].nValue = blockValue; if (nHighestCount > 0) { txNew.vout.resize(2); //these are super blocks, so their value can be much larger than normal txNew.vout[1].scriptPubKey = payee; txNew.vout[1].nValue = nAmount; CTxDestination address1; ExtractDestination(payee, address1); CBitcoinAddress address2(address1); LogPrint("mnbudget","CBudgetManager::FillBlockPayee - Budget payment to %s for %lld\n", address2.ToString(), nAmount); } } } CFinalizedBudget* CBudgetManager::FindFinalizedBudget(uint256 nHash) { if (mapFinalizedBudgets.count(nHash)) return &mapFinalizedBudgets[nHash]; return NULL; } CBudgetProposal* CBudgetManager::FindProposal(const std::string& strProposalName) { //find the prop with the highest yes count int nYesCount = -99999; CBudgetProposal* pbudgetProposal = NULL; std::map<uint256, CBudgetProposal>::iterator it = mapProposals.begin(); while (it != mapProposals.end()) { if ((*it).second.strProposalName == strProposalName && (*it).second.GetYeas() > nYesCount) { pbudgetProposal = &((*it).second); nYesCount = pbudgetProposal->GetYeas(); } ++it; } if (nYesCount == -99999) return NULL; return pbudgetProposal; } CBudgetProposal* CBudgetManager::FindProposal(uint256 nHash) { LOCK(cs); if (mapProposals.count(nHash)) return &mapProposals[nHash]; return NULL; } bool CBudgetManager::IsBudgetPaymentBlock(int nBlockHeight) { int nHighestCount = -1; int nFivePercent = mnodeman.CountEnabled(ActiveProtocol()) / 20; std::map<uint256, CFinalizedBudget>::iterator it = mapFinalizedBudgets.begin(); while (it != mapFinalizedBudgets.end()) { CFinalizedBudget* pfinalizedBudget = &((*it).second); if (pfinalizedBudget->GetVoteCount() > nHighestCount && nBlockHeight >= pfinalizedBudget->GetBlockStart() && nBlockHeight <= pfinalizedBudget->GetBlockEnd()) { nHighestCount = pfinalizedBudget->GetVoteCount(); } ++it; } LogPrint("mnbudget","CBudgetManager::IsBudgetPaymentBlock() - nHighestCount: %lli, 5%% of Masternodes: %lli. Number of finalized budgets: %lli\n", nHighestCount, nFivePercent, mapFinalizedBudgets.size()); // If budget doesn't have 5% of the network votes, then we should pay a masternode instead if (nHighestCount > nFivePercent) return true; return false; } TrxValidationStatus CBudgetManager::IsTransactionValid(const CTransaction& txNew, int nBlockHeight) { LOCK(cs); TrxValidationStatus transactionStatus = TrxValidationStatus::InValid; int nHighestCount = 0; int nFivePercent = mnodeman.CountEnabled(ActiveProtocol()) / 20; std::vector<CFinalizedBudget*> ret; LogPrint("mnbudget","CBudgetManager::IsTransactionValid - checking %lli finalized budgets\n", mapFinalizedBudgets.size()); // ------- Grab The Highest Count std::map<uint256, CFinalizedBudget>::iterator it = mapFinalizedBudgets.begin(); while (it != mapFinalizedBudgets.end()) { CFinalizedBudget* pfinalizedBudget = &((*it).second); if (pfinalizedBudget->GetVoteCount() > nHighestCount && nBlockHeight >= pfinalizedBudget->GetBlockStart() && nBlockHeight <= pfinalizedBudget->GetBlockEnd()) { nHighestCount = pfinalizedBudget->GetVoteCount(); } ++it; } LogPrint("mnbudget","CBudgetManager::IsTransactionValid() - nHighestCount: %lli, 5%% of Masternodes: %lli mapFinalizedBudgets.size(): %ld\n", nHighestCount, nFivePercent, mapFinalizedBudgets.size()); /* If budget doesn't have 5% of the network votes, then we should pay a masternode instead */ if (nHighestCount < nFivePercent) return TrxValidationStatus::InValid; // check the highest finalized budgets (+/- 10% to assist in consensus) std::string strProposals = ""; int nCountThreshold = nHighestCount - mnodeman.CountEnabled(ActiveProtocol()) / 10; bool fThreshold = false; it = mapFinalizedBudgets.begin(); while (it != mapFinalizedBudgets.end()) { CFinalizedBudget* pfinalizedBudget = &((*it).second); strProposals = pfinalizedBudget->GetProposals(); LogPrint("mnbudget","CBudgetManager::IsTransactionValid - checking budget (%s) with blockstart %lli, blockend %lli, nBlockHeight %lli, votes %lli, nCountThreshold %lli\n", strProposals.c_str(), pfinalizedBudget->GetBlockStart(), pfinalizedBudget->GetBlockEnd(), nBlockHeight, pfinalizedBudget->GetVoteCount(), nCountThreshold); if (pfinalizedBudget->GetVoteCount() > nCountThreshold) { fThreshold = true; LogPrint("mnbudget","CBudgetManager::IsTransactionValid - GetVoteCount() > nCountThreshold passed\n"); if (nBlockHeight >= pfinalizedBudget->GetBlockStart() && nBlockHeight <= pfinalizedBudget->GetBlockEnd()) { LogPrint("mnbudget","CBudgetManager::IsTransactionValid - GetBlockStart() passed\n"); transactionStatus = pfinalizedBudget->IsTransactionValid(txNew, nBlockHeight); if (transactionStatus == TrxValidationStatus::Valid) { LogPrint("mnbudget","CBudgetManager::IsTransactionValid - pfinalizedBudget->IsTransactionValid() passed\n"); return TrxValidationStatus::Valid; } else { LogPrint("mnbudget","CBudgetManager::IsTransactionValid - pfinalizedBudget->IsTransactionValid() error\n"); } } else { LogPrint("mnbudget","CBudgetManager::IsTransactionValid - GetBlockStart() failed, budget is outside current payment cycle and will be ignored.\n"); } } ++it; } // If not enough masternodes autovoted for any of the finalized budgets pay a masternode instead if(!fThreshold) { transactionStatus = TrxValidationStatus::VoteThreshold; } // We looked through all of the known budgets return transactionStatus; } std::vector<CBudgetProposal*> CBudgetManager::GetAllProposals() { LOCK(cs); std::vector<CBudgetProposal*> vBudgetProposalRet; std::map<uint256, CBudgetProposal>::iterator it = mapProposals.begin(); while (it != mapProposals.end()) { (*it).second.CleanAndRemove(false); CBudgetProposal* pbudgetProposal = &((*it).second); vBudgetProposalRet.push_back(pbudgetProposal); ++it; } return vBudgetProposalRet; } // // Sort by votes, if there's a tie sort by their feeHash TX // struct sortProposalsByVotes { bool operator()(const std::pair<CBudgetProposal*, int>& left, const std::pair<CBudgetProposal*, int>& right) { if (left.second != right.second) return (left.second > right.second); return (left.first->nFeeTXHash > right.first->nFeeTXHash); } }; //Need to review this function std::vector<CBudgetProposal*> CBudgetManager::GetBudget() { LOCK(cs); // ------- Sort budgets by Yes Count std::vector<std::pair<CBudgetProposal*, int> > vBudgetPorposalsSort; std::map<uint256, CBudgetProposal>::iterator it = mapProposals.begin(); while (it != mapProposals.end()) { (*it).second.CleanAndRemove(false); vBudgetPorposalsSort.push_back(make_pair(&((*it).second), (*it).second.GetYeas() - (*it).second.GetNays())); ++it; } std::sort(vBudgetPorposalsSort.begin(), vBudgetPorposalsSort.end(), sortProposalsByVotes()); // ------- Grab The Budgets In Order std::vector<CBudgetProposal*> vBudgetProposalsRet; CAmount nBudgetAllocated = 0; CBlockIndex* pindexPrev = chainActive.Tip(); if (pindexPrev == NULL) return vBudgetProposalsRet; int nBlockStart = pindexPrev->nHeight - pindexPrev->nHeight % GetBudgetPaymentCycleBlocks() + GetBudgetPaymentCycleBlocks(); int nBlockEnd = nBlockStart + GetBudgetPaymentCycleBlocks() - 1; CAmount nTotalBudget = GetTotalBudget(nBlockStart); std::vector<std::pair<CBudgetProposal*, int> >::iterator it2 = vBudgetPorposalsSort.begin(); while (it2 != vBudgetPorposalsSort.end()) { CBudgetProposal* pbudgetProposal = (*it2).first; LogPrint("mnbudget","CBudgetManager::GetBudget() - Processing Budget %s\n", pbudgetProposal->strProposalName.c_str()); //prop start/end should be inside this period if (pbudgetProposal->fValid && pbudgetProposal->nBlockStart <= nBlockStart && pbudgetProposal->nBlockEnd >= nBlockEnd && pbudgetProposal->GetYeas() - pbudgetProposal->GetNays() > mnodeman.CountEnabled(ActiveProtocol()) / 10 && pbudgetProposal->IsEstablished()) { LogPrint("mnbudget","CBudgetManager::GetBudget() - Check 1 passed: valid=%d | %ld <= %ld | %ld >= %ld | Yeas=%d Nays=%d Count=%d | established=%d\n", pbudgetProposal->fValid, pbudgetProposal->nBlockStart, nBlockStart, pbudgetProposal->nBlockEnd, nBlockEnd, pbudgetProposal->GetYeas(), pbudgetProposal->GetNays(), mnodeman.CountEnabled(ActiveProtocol()) / 10, pbudgetProposal->IsEstablished()); if (pbudgetProposal->GetAmount() + nBudgetAllocated <= nTotalBudget) { pbudgetProposal->SetAllotted(pbudgetProposal->GetAmount()); nBudgetAllocated += pbudgetProposal->GetAmount(); vBudgetProposalsRet.push_back(pbudgetProposal); LogPrint("mnbudget","CBudgetManager::GetBudget() - Check 2 passed: Budget added\n"); } else { pbudgetProposal->SetAllotted(0); LogPrint("mnbudget","CBudgetManager::GetBudget() - Check 2 failed: no amount allotted\n"); } } else { LogPrint("mnbudget","CBudgetManager::GetBudget() - Check 1 failed: valid=%d | %ld <= %ld | %ld >= %ld | Yeas=%d Nays=%d Count=%d | established=%d\n", pbudgetProposal->fValid, pbudgetProposal->nBlockStart, nBlockStart, pbudgetProposal->nBlockEnd, nBlockEnd, pbudgetProposal->GetYeas(), pbudgetProposal->GetNays(), mnodeman.CountEnabled(ActiveProtocol()) / 10, pbudgetProposal->IsEstablished()); } ++it2; } return vBudgetProposalsRet; } // Sort by votes, if there's a tie sort by their feeHash TX struct sortFinalizedBudgetsByVotes { bool operator()(const std::pair<CFinalizedBudget*, int>& left, const std::pair<CFinalizedBudget*, int>& right) { if (left.second != right.second) return left.second > right.second; return (left.first->nFeeTXHash > right.first->nFeeTXHash); } }; std::vector<CFinalizedBudget*> CBudgetManager::GetFinalizedBudgets() { LOCK(cs); std::vector<CFinalizedBudget*> vFinalizedBudgetsRet; std::vector<std::pair<CFinalizedBudget*, int> > vFinalizedBudgetsSort; // ------- Grab The Budgets In Order std::map<uint256, CFinalizedBudget>::iterator it = mapFinalizedBudgets.begin(); while (it != mapFinalizedBudgets.end()) { CFinalizedBudget* pfinalizedBudget = &((*it).second); vFinalizedBudgetsSort.push_back(make_pair(pfinalizedBudget, pfinalizedBudget->GetVoteCount())); ++it; } std::sort(vFinalizedBudgetsSort.begin(), vFinalizedBudgetsSort.end(), sortFinalizedBudgetsByVotes()); std::vector<std::pair<CFinalizedBudget*, int> >::iterator it2 = vFinalizedBudgetsSort.begin(); while (it2 != vFinalizedBudgetsSort.end()) { vFinalizedBudgetsRet.push_back((*it2).first); ++it2; } return vFinalizedBudgetsRet; } std::string CBudgetManager::GetRequiredPaymentsString(int nBlockHeight) { LOCK(cs); std::string ret = "unknown-budget"; std::map<uint256, CFinalizedBudget>::iterator it = mapFinalizedBudgets.begin(); while (it != mapFinalizedBudgets.end()) { CFinalizedBudget* pfinalizedBudget = &((*it).second); if (nBlockHeight >= pfinalizedBudget->GetBlockStart() && nBlockHeight <= pfinalizedBudget->GetBlockEnd()) { CTxBudgetPayment payment; if (pfinalizedBudget->GetBudgetPaymentByBlock(nBlockHeight, payment)) { if (ret == "unknown-budget") { ret = payment.nProposalHash.ToString(); } else { ret += ","; ret += payment.nProposalHash.ToString(); } } else { LogPrint("mnbudget","CBudgetManager::GetRequiredPaymentsString - Couldn't find budget payment for block %d\n", nBlockHeight); } } ++it; } return ret; } CAmount CBudgetManager::GetTotalBudget(int nHeight) { if (chainActive.Tip() == NULL) return 0; if (Params().NetworkID() == CBaseChainParams::TESTNET) { CAmount nSubsidy = 500 * COIN; return ((nSubsidy / 100) * 10) * 146; } //get block value and calculate from that CAmount nSubsidy = 0; if (nHeight <= Params().LAST_POW_BLOCK() && nHeight >= 151200) { nSubsidy = 50 * COIN; } else if (nHeight <= 302399 && nHeight > Params().LAST_POW_BLOCK()) { nSubsidy = 50 * COIN; } else if (nHeight <= 345599 && nHeight >= 302400) { nSubsidy = 45 * COIN; } else if (nHeight <= 388799 && nHeight >= 345600) { nSubsidy = 40 * COIN; } else if (nHeight <= 431999 && nHeight >= 388800) { nSubsidy = 35 * COIN; } else if (nHeight <= 475199 && nHeight >= 432000) { nSubsidy = 30 * COIN; } else if (nHeight <= 518399 && nHeight >= 475200) { nSubsidy = 25 * COIN; } else if (nHeight <= 561599 && nHeight >= 518400) { nSubsidy = 20 * COIN; } else if (nHeight <= 604799 && nHeight >= 561600) { nSubsidy = 15 * COIN; } else if (nHeight <= 647999 && nHeight >= 604800) { nSubsidy = 10 * COIN; } else if (nHeight >= Params().Zerocoin_Block_V2_Start()) { nSubsidy = 10 * COIN; } else { nSubsidy = 5 * COIN; } // Amount of blocks in a months period of time (using 1 minutes per) = (60*24*30) if (nHeight <= 172800) { return 648000 * COIN; } else { return ((nSubsidy / 100) * 10) * 1440 * 30; } } void CBudgetManager::NewBlock() { TRY_LOCK(cs, fBudgetNewBlock); if (!fBudgetNewBlock) return; if (masternodeSync.RequestedMasternodeAssets <= MASTERNODE_SYNC_BUDGET) return; if (strBudgetMode == "suggest") { //suggest the budget we see SubmitFinalBudget(); } //this function should be called 1/14 blocks, allowing up to 100 votes per day on all proposals if (chainActive.Height() % 14 != 0) return; // incremental sync with our peers if (masternodeSync.IsSynced()) { LogPrint("mnbudget","CBudgetManager::NewBlock - incremental sync started\n"); if (chainActive.Height() % 1440 == rand() % 1440) { ClearSeen(); ResetSync(); } LOCK(cs_vNodes); BOOST_FOREACH (CNode* pnode, vNodes) if (pnode->nVersion >= ActiveProtocol()) Sync(pnode, 0, true); MarkSynced(); } CheckAndRemove(); //remove invalid votes once in a while (we have to check the signatures and validity of every vote, somewhat CPU intensive) LogPrint("mnbudget","CBudgetManager::NewBlock - askedForSourceProposalOrBudget cleanup - size: %d\n", askedForSourceProposalOrBudget.size()); std::map<uint256, int64_t>::iterator it = askedForSourceProposalOrBudget.begin(); while (it != askedForSourceProposalOrBudget.end()) { if ((*it).second > GetTime() - (60 * 60 * 24)) { ++it; } else { askedForSourceProposalOrBudget.erase(it++); } } LogPrint("mnbudget","CBudgetManager::NewBlock - mapProposals cleanup - size: %d\n", mapProposals.size()); std::map<uint256, CBudgetProposal>::iterator it2 = mapProposals.begin(); while (it2 != mapProposals.end()) { (*it2).second.CleanAndRemove(false); ++it2; } LogPrint("mnbudget","CBudgetManager::NewBlock - mapFinalizedBudgets cleanup - size: %d\n", mapFinalizedBudgets.size()); std::map<uint256, CFinalizedBudget>::iterator it3 = mapFinalizedBudgets.begin(); while (it3 != mapFinalizedBudgets.end()) { (*it3).second.CleanAndRemove(false); ++it3; } LogPrint("mnbudget","CBudgetManager::NewBlock - vecImmatureBudgetProposals cleanup - size: %d\n", vecImmatureBudgetProposals.size()); std::vector<CBudgetProposalBroadcast>::iterator it4 = vecImmatureBudgetProposals.begin(); while (it4 != vecImmatureBudgetProposals.end()) { std::string strError = ""; int nConf = 0; if (!IsBudgetCollateralValid((*it4).nFeeTXHash, (*it4).GetHash(), strError, (*it4).nTime, nConf)) { ++it4; continue; } if (!(*it4).IsValid(strError)) { LogPrint("mnbudget","mprop (immature) - invalid budget proposal - %s\n", strError); it4 = vecImmatureBudgetProposals.erase(it4); continue; } CBudgetProposal budgetProposal((*it4)); if (AddProposal(budgetProposal)) { (*it4).Relay(); } LogPrint("mnbudget","mprop (immature) - new budget - %s\n", (*it4).GetHash().ToString()); it4 = vecImmatureBudgetProposals.erase(it4); } LogPrint("mnbudget","CBudgetManager::NewBlock - vecImmatureFinalizedBudgets cleanup - size: %d\n", vecImmatureFinalizedBudgets.size()); std::vector<CFinalizedBudgetBroadcast>::iterator it5 = vecImmatureFinalizedBudgets.begin(); while (it5 != vecImmatureFinalizedBudgets.end()) { std::string strError = ""; int nConf = 0; if (!IsBudgetCollateralValid((*it5).nFeeTXHash, (*it5).GetHash(), strError, (*it5).nTime, nConf, true)) { ++it5; continue; } if (!(*it5).IsValid(strError)) { LogPrint("mnbudget","fbs (immature) - invalid finalized budget - %s\n", strError); it5 = vecImmatureFinalizedBudgets.erase(it5); continue; } LogPrint("mnbudget","fbs (immature) - new finalized budget - %s\n", (*it5).GetHash().ToString()); CFinalizedBudget finalizedBudget((*it5)); if (AddFinalizedBudget(finalizedBudget)) { (*it5).Relay(); } it5 = vecImmatureFinalizedBudgets.erase(it5); } LogPrint("mnbudget","CBudgetManager::NewBlock - PASSED\n"); } void CBudgetManager::ProcessMessage(CNode* pfrom, std::string& strCommand, CDataStream& vRecv) { // lite mode is not supported if (fLiteMode) return; if (!masternodeSync.IsBlockchainSynced()) return; LOCK(cs_budget); if (strCommand == "mnvs") { //Masternode vote sync uint256 nProp; vRecv >> nProp; if (Params().NetworkID() == CBaseChainParams::MAIN) { if (nProp == 0) { if (pfrom->HasFulfilledRequest("mnvs")) { LogPrint("mnbudget","mnvs - peer already asked me for the list\n"); Misbehaving(pfrom->GetId(), 20); return; } pfrom->FulfilledRequest("mnvs"); } } Sync(pfrom, nProp); LogPrint("mnbudget", "mnvs - Sent Masternode votes to peer %i\n", pfrom->GetId()); } if (strCommand == "mprop") { //Masternode Proposal CBudgetProposalBroadcast budgetProposalBroadcast; vRecv >> budgetProposalBroadcast; if (mapSeenMasternodeBudgetProposals.count(budgetProposalBroadcast.GetHash())) { masternodeSync.AddedBudgetItem(budgetProposalBroadcast.GetHash()); return; } std::string strError = ""; int nConf = 0; if (!IsBudgetCollateralValid(budgetProposalBroadcast.nFeeTXHash, budgetProposalBroadcast.GetHash(), strError, budgetProposalBroadcast.nTime, nConf)) { LogPrint("mnbudget","Proposal FeeTX is not valid - %s - %s\n", budgetProposalBroadcast.nFeeTXHash.ToString(), strError); if (nConf >= 1) vecImmatureBudgetProposals.push_back(budgetProposalBroadcast); return; } mapSeenMasternodeBudgetProposals.insert(make_pair(budgetProposalBroadcast.GetHash(), budgetProposalBroadcast)); if (!budgetProposalBroadcast.IsValid(strError)) { LogPrint("mnbudget","mprop - invalid budget proposal - %s\n", strError); return; } CBudgetProposal budgetProposal(budgetProposalBroadcast); if (AddProposal(budgetProposal)) { budgetProposalBroadcast.Relay(); } masternodeSync.AddedBudgetItem(budgetProposalBroadcast.GetHash()); LogPrint("mnbudget","mprop - new budget - %s\n", budgetProposalBroadcast.GetHash().ToString()); //We might have active votes for this proposal that are valid now CheckOrphanVotes(); } if (strCommand == "mvote") { //Masternode Vote CBudgetVote vote; vRecv >> vote; vote.fValid = true; if (mapSeenMasternodeBudgetVotes.count(vote.GetHash())) { masternodeSync.AddedBudgetItem(vote.GetHash()); return; } CMasternode* pmn = mnodeman.Find(vote.vin); if (pmn == NULL) { LogPrint("mnbudget","mvote - unknown masternode - vin: %s\n", vote.vin.prevout.hash.ToString()); mnodeman.AskForMN(pfrom, vote.vin); return; } mapSeenMasternodeBudgetVotes.insert(make_pair(vote.GetHash(), vote)); if (!vote.SignatureValid(true)) { LogPrint("mnbudget","mvote - signature invalid\n"); if (masternodeSync.IsSynced()) Misbehaving(pfrom->GetId(), 20); // it could just be a non-synced masternode mnodeman.AskForMN(pfrom, vote.vin); return; } std::string strError = ""; if (UpdateProposal(vote, pfrom, strError)) { vote.Relay(); masternodeSync.AddedBudgetItem(vote.GetHash()); } LogPrint("mnbudget","mvote - new budget vote for budget %s - %s\n", vote.nProposalHash.ToString(), vote.GetHash().ToString()); } if (strCommand == "fbs") { //Finalized Budget Suggestion CFinalizedBudgetBroadcast finalizedBudgetBroadcast; vRecv >> finalizedBudgetBroadcast; if (mapSeenFinalizedBudgets.count(finalizedBudgetBroadcast.GetHash())) { masternodeSync.AddedBudgetItem(finalizedBudgetBroadcast.GetHash()); return; } std::string strError = ""; int nConf = 0; if (!IsBudgetCollateralValid(finalizedBudgetBroadcast.nFeeTXHash, finalizedBudgetBroadcast.GetHash(), strError, finalizedBudgetBroadcast.nTime, nConf, true)) { LogPrint("mnbudget","fbs - Finalized Budget FeeTX is not valid - %s - %s\n", finalizedBudgetBroadcast.nFeeTXHash.ToString(), strError); if (nConf >= 1) vecImmatureFinalizedBudgets.push_back(finalizedBudgetBroadcast); return; } mapSeenFinalizedBudgets.insert(make_pair(finalizedBudgetBroadcast.GetHash(), finalizedBudgetBroadcast)); if (!finalizedBudgetBroadcast.IsValid(strError)) { LogPrint("mnbudget","fbs - invalid finalized budget - %s\n", strError); return; } LogPrint("mnbudget","fbs - new finalized budget - %s\n", finalizedBudgetBroadcast.GetHash().ToString()); CFinalizedBudget finalizedBudget(finalizedBudgetBroadcast); if (AddFinalizedBudget(finalizedBudget)) { finalizedBudgetBroadcast.Relay(); } masternodeSync.AddedBudgetItem(finalizedBudgetBroadcast.GetHash()); //we might have active votes for this budget that are now valid CheckOrphanVotes(); } if (strCommand == "fbvote") { //Finalized Budget Vote CFinalizedBudgetVote vote; vRecv >> vote; vote.fValid = true; if (mapSeenFinalizedBudgetVotes.count(vote.GetHash())) { masternodeSync.AddedBudgetItem(vote.GetHash()); return; } CMasternode* pmn = mnodeman.Find(vote.vin); if (pmn == NULL) { LogPrint("mnbudget", "fbvote - unknown masternode - vin: %s\n", vote.vin.prevout.hash.ToString()); mnodeman.AskForMN(pfrom, vote.vin); return; } mapSeenFinalizedBudgetVotes.insert(make_pair(vote.GetHash(), vote)); if (!vote.SignatureValid(true)) { LogPrint("mnbudget","fbvote - signature invalid\n"); if (masternodeSync.IsSynced()) Misbehaving(pfrom->GetId(), 20); // it could just be a non-synced masternode mnodeman.AskForMN(pfrom, vote.vin); return; } std::string strError = ""; if (UpdateFinalizedBudget(vote, pfrom, strError)) { vote.Relay(); masternodeSync.AddedBudgetItem(vote.GetHash()); LogPrint("mnbudget","fbvote - new finalized budget vote - %s\n", vote.GetHash().ToString()); } else { LogPrint("mnbudget","fbvote - rejected finalized budget vote - %s - %s\n", vote.GetHash().ToString(), strError); } } } bool CBudgetManager::PropExists(uint256 nHash) { if (mapProposals.count(nHash)) return true; return false; } //mark that a full sync is needed void CBudgetManager::ResetSync() { LOCK(cs); std::map<uint256, CBudgetProposalBroadcast>::iterator it1 = mapSeenMasternodeBudgetProposals.begin(); while (it1 != mapSeenMasternodeBudgetProposals.end()) { CBudgetProposal* pbudgetProposal = FindProposal((*it1).first); if (pbudgetProposal && pbudgetProposal->fValid) { //mark votes std::map<uint256, CBudgetVote>::iterator it2 = pbudgetProposal->mapVotes.begin(); while (it2 != pbudgetProposal->mapVotes.end()) { (*it2).second.fSynced = false; ++it2; } } ++it1; } std::map<uint256, CFinalizedBudgetBroadcast>::iterator it3 = mapSeenFinalizedBudgets.begin(); while (it3 != mapSeenFinalizedBudgets.end()) { CFinalizedBudget* pfinalizedBudget = FindFinalizedBudget((*it3).first); if (pfinalizedBudget && pfinalizedBudget->fValid) { //send votes std::map<uint256, CFinalizedBudgetVote>::iterator it4 = pfinalizedBudget->mapVotes.begin(); while (it4 != pfinalizedBudget->mapVotes.end()) { (*it4).second.fSynced = false; ++it4; } } ++it3; } } void CBudgetManager::MarkSynced() { LOCK(cs); /* Mark that we've sent all valid items */ std::map<uint256, CBudgetProposalBroadcast>::iterator it1 = mapSeenMasternodeBudgetProposals.begin(); while (it1 != mapSeenMasternodeBudgetProposals.end()) { CBudgetProposal* pbudgetProposal = FindProposal((*it1).first); if (pbudgetProposal && pbudgetProposal->fValid) { //mark votes std::map<uint256, CBudgetVote>::iterator it2 = pbudgetProposal->mapVotes.begin(); while (it2 != pbudgetProposal->mapVotes.end()) { if ((*it2).second.fValid) (*it2).second.fSynced = true; ++it2; } } ++it1; } std::map<uint256, CFinalizedBudgetBroadcast>::iterator it3 = mapSeenFinalizedBudgets.begin(); while (it3 != mapSeenFinalizedBudgets.end()) { CFinalizedBudget* pfinalizedBudget = FindFinalizedBudget((*it3).first); if (pfinalizedBudget && pfinalizedBudget->fValid) { //mark votes std::map<uint256, CFinalizedBudgetVote>::iterator it4 = pfinalizedBudget->mapVotes.begin(); while (it4 != pfinalizedBudget->mapVotes.end()) { if ((*it4).second.fValid) (*it4).second.fSynced = true; ++it4; } } ++it3; } } void CBudgetManager::Sync(CNode* pfrom, uint256 nProp, bool fPartial) { LOCK(cs); /* Sync with a client on the network -- This code checks each of the hash maps for all known budget proposals and finalized budget proposals, then checks them against the budget object to see if they're OK. If all checks pass, we'll send it to the peer. */ int nInvCount = 0; std::map<uint256, CBudgetProposalBroadcast>::iterator it1 = mapSeenMasternodeBudgetProposals.begin(); while (it1 != mapSeenMasternodeBudgetProposals.end()) { CBudgetProposal* pbudgetProposal = FindProposal((*it1).first); if (pbudgetProposal && pbudgetProposal->fValid && (nProp == 0 || (*it1).first == nProp)) { pfrom->PushInventory(CInv(MSG_BUDGET_PROPOSAL, (*it1).second.GetHash())); nInvCount++; //send votes std::map<uint256, CBudgetVote>::iterator it2 = pbudgetProposal->mapVotes.begin(); while (it2 != pbudgetProposal->mapVotes.end()) { if ((*it2).second.fValid) { if ((fPartial && !(*it2).second.fSynced) || !fPartial) { pfrom->PushInventory(CInv(MSG_BUDGET_VOTE, (*it2).second.GetHash())); nInvCount++; } } ++it2; } } ++it1; } pfrom->PushMessage("ssc", MASTERNODE_SYNC_BUDGET_PROP, nInvCount); LogPrint("mnbudget", "CBudgetManager::Sync - sent %d items\n", nInvCount); nInvCount = 0; std::map<uint256, CFinalizedBudgetBroadcast>::iterator it3 = mapSeenFinalizedBudgets.begin(); while (it3 != mapSeenFinalizedBudgets.end()) { CFinalizedBudget* pfinalizedBudget = FindFinalizedBudget((*it3).first); if (pfinalizedBudget && pfinalizedBudget->fValid && (nProp == 0 || (*it3).first == nProp)) { pfrom->PushInventory(CInv(MSG_BUDGET_FINALIZED, (*it3).second.GetHash())); nInvCount++; //send votes std::map<uint256, CFinalizedBudgetVote>::iterator it4 = pfinalizedBudget->mapVotes.begin(); while (it4 != pfinalizedBudget->mapVotes.end()) { if ((*it4).second.fValid) { if ((fPartial && !(*it4).second.fSynced) || !fPartial) { pfrom->PushInventory(CInv(MSG_BUDGET_FINALIZED_VOTE, (*it4).second.GetHash())); nInvCount++; } } ++it4; } } ++it3; } pfrom->PushMessage("ssc", MASTERNODE_SYNC_BUDGET_FIN, nInvCount); LogPrint("mnbudget", "CBudgetManager::Sync - sent %d items\n", nInvCount); } bool CBudgetManager::UpdateProposal(CBudgetVote& vote, CNode* pfrom, std::string& strError) { LOCK(cs); if (!mapProposals.count(vote.nProposalHash)) { if (pfrom) { // only ask for missing items after our syncing process is complete -- // otherwise we'll think a full sync succeeded when they return a result if (!masternodeSync.IsSynced()) return false; LogPrint("mnbudget","CBudgetManager::UpdateProposal - Unknown proposal %d, asking for source proposal\n", vote.nProposalHash.ToString()); mapOrphanMasternodeBudgetVotes[vote.nProposalHash] = vote; if (!askedForSourceProposalOrBudget.count(vote.nProposalHash)) { pfrom->PushMessage("mnvs", vote.nProposalHash); askedForSourceProposalOrBudget[vote.nProposalHash] = GetTime(); } } strError = "Proposal not found!"; return false; } return mapProposals[vote.nProposalHash].AddOrUpdateVote(vote, strError); } bool CBudgetManager::UpdateFinalizedBudget(CFinalizedBudgetVote& vote, CNode* pfrom, std::string& strError) { LOCK(cs); if (!mapFinalizedBudgets.count(vote.nBudgetHash)) { if (pfrom) { // only ask for missing items after our syncing process is complete -- // otherwise we'll think a full sync succeeded when they return a result if (!masternodeSync.IsSynced()) return false; LogPrint("mnbudget","CBudgetManager::UpdateFinalizedBudget - Unknown Finalized Proposal %s, asking for source budget\n", vote.nBudgetHash.ToString()); mapOrphanFinalizedBudgetVotes[vote.nBudgetHash] = vote; if (!askedForSourceProposalOrBudget.count(vote.nBudgetHash)) { pfrom->PushMessage("mnvs", vote.nBudgetHash); askedForSourceProposalOrBudget[vote.nBudgetHash] = GetTime(); } } strError = "Finalized Budget " + vote.nBudgetHash.ToString() + " not found!"; return false; } LogPrint("mnbudget","CBudgetManager::UpdateFinalizedBudget - Finalized Proposal %s added\n", vote.nBudgetHash.ToString()); return mapFinalizedBudgets[vote.nBudgetHash].AddOrUpdateVote(vote, strError); } CBudgetProposal::CBudgetProposal() { strProposalName = "unknown"; nBlockStart = 0; nBlockEnd = 0; nAmount = 0; nTime = 0; fValid = true; } CBudgetProposal::CBudgetProposal(std::string strProposalNameIn, std::string strURLIn, int nBlockStartIn, int nBlockEndIn, CScript addressIn, CAmount nAmountIn, uint256 nFeeTXHashIn) { strProposalName = strProposalNameIn; strURL = strURLIn; nBlockStart = nBlockStartIn; nBlockEnd = nBlockEndIn; address = addressIn; nAmount = nAmountIn; nFeeTXHash = nFeeTXHashIn; fValid = true; } CBudgetProposal::CBudgetProposal(const CBudgetProposal& other) { strProposalName = other.strProposalName; strURL = other.strURL; nBlockStart = other.nBlockStart; nBlockEnd = other.nBlockEnd; address = other.address; nAmount = other.nAmount; nTime = other.nTime; nFeeTXHash = other.nFeeTXHash; mapVotes = other.mapVotes; fValid = true; } bool CBudgetProposal::IsValid(std::string& strError, bool fCheckCollateral) { if (GetNays() - GetYeas() > mnodeman.CountEnabled(ActiveProtocol()) / 10) { strError = "Proposal " + strProposalName + ": Active removal"; return false; } if (nBlockStart < 0) { strError = "Invalid Proposal"; return false; } if (nBlockEnd < nBlockStart) { strError = "Proposal " + strProposalName + ": Invalid nBlockEnd (end before start)"; return false; } if (nAmount < 10 * COIN) { strError = "Proposal " + strProposalName + ": Invalid nAmount"; return false; } if (address == CScript()) { strError = "Proposal " + strProposalName + ": Invalid Payment Address"; return false; } if (fCheckCollateral) { int nConf = 0; if (!IsBudgetCollateralValid(nFeeTXHash, GetHash(), strError, nTime, nConf)) { strError = "Proposal " + strProposalName + ": Invalid collateral"; return false; } } /* TODO: There might be an issue with multisig in the coinbase on mainnet, we will add support for it in a future release. */ if (address.IsPayToScriptHash()) { strError = "Proposal " + strProposalName + ": Multisig is not currently supported."; return false; } //if proposal doesn't gain traction within 2 weeks, remove it // nTime not being saved correctly // -- TODO: We should keep track of the last time the proposal was valid, if it's invalid for 2 weeks, erase it // if(nTime + (60*60*24*2) < GetAdjustedTime()) { // if(GetYeas()-GetNays() < (mnodeman.CountEnabled(ActiveProtocol())/10)) { // strError = "Not enough support"; // return false; // } // } //can only pay out 10% of the possible coins (min value of coins) if (nAmount > budget.GetTotalBudget(nBlockStart)) { strError = "Proposal " + strProposalName + ": Payment more than max"; return false; } CBlockIndex* pindexPrev = chainActive.Tip(); if (pindexPrev == NULL) { strError = "Proposal " + strProposalName + ": Tip is NULL"; return true; } // Calculate maximum block this proposal will be valid, which is start of proposal + (number of payments * cycle) int nProposalEnd = GetBlockStart() + (GetBudgetPaymentCycleBlocks() * GetTotalPaymentCount()); // if (GetBlockEnd() < pindexPrev->nHeight - GetBudgetPaymentCycleBlocks() / 2) { if(nProposalEnd < pindexPrev->nHeight){ strError = "Proposal " + strProposalName + ": Invalid nBlockEnd (" + std::to_string(nProposalEnd) + ") < current height (" + std::to_string(pindexPrev->nHeight) + ")"; return false; } return true; } bool CBudgetProposal::AddOrUpdateVote(CBudgetVote& vote, std::string& strError) { std::string strAction = "New vote inserted:"; LOCK(cs); uint256 hash = vote.vin.prevout.GetHash(); if (mapVotes.count(hash)) { if (mapVotes[hash].nTime > vote.nTime) { strError = strprintf("new vote older than existing vote - %s\n", vote.GetHash().ToString()); LogPrint("mnbudget", "CBudgetProposal::AddOrUpdateVote - %s\n", strError); return false; } if (vote.nTime - mapVotes[hash].nTime < BUDGET_VOTE_UPDATE_MIN) { strError = strprintf("time between votes is too soon - %s - %lli sec < %lli sec\n", vote.GetHash().ToString(), vote.nTime - mapVotes[hash].nTime,BUDGET_VOTE_UPDATE_MIN); LogPrint("mnbudget", "CBudgetProposal::AddOrUpdateVote - %s\n", strError); return false; } strAction = "Existing vote updated:"; } if (vote.nTime > GetTime() + (60 * 60)) { strError = strprintf("new vote is too far ahead of current time - %s - nTime %lli - Max Time %lli\n", vote.GetHash().ToString(), vote.nTime, GetTime() + (60 * 60)); LogPrint("mnbudget", "CBudgetProposal::AddOrUpdateVote - %s\n", strError); return false; } mapVotes[hash] = vote; LogPrint("mnbudget", "CBudgetProposal::AddOrUpdateVote - %s %s\n", strAction.c_str(), vote.GetHash().ToString().c_str()); return true; } // If masternode voted for a proposal, but is now invalid -- remove the vote void CBudgetProposal::CleanAndRemove(bool fSignatureCheck) { std::map<uint256, CBudgetVote>::iterator it = mapVotes.begin(); while (it != mapVotes.end()) { (*it).second.fValid = (*it).second.SignatureValid(fSignatureCheck); ++it; } } double CBudgetProposal::GetRatio() { int yeas = 0; int nays = 0; std::map<uint256, CBudgetVote>::iterator it = mapVotes.begin(); while (it != mapVotes.end()) { if ((*it).second.nVote == VOTE_YES) yeas++; if ((*it).second.nVote == VOTE_NO) nays++; ++it; } if (yeas + nays == 0) return 0.0f; return ((double)(yeas) / (double)(yeas + nays)); } int CBudgetProposal::GetYeas() { int ret = 0; std::map<uint256, CBudgetVote>::iterator it = mapVotes.begin(); while (it != mapVotes.end()) { if ((*it).second.nVote == VOTE_YES && (*it).second.fValid) ret++; ++it; } return ret; } int CBudgetProposal::GetNays() { int ret = 0; std::map<uint256, CBudgetVote>::iterator it = mapVotes.begin(); while (it != mapVotes.end()) { if ((*it).second.nVote == VOTE_NO && (*it).second.fValid) ret++; ++it; } return ret; } int CBudgetProposal::GetAbstains() { int ret = 0; std::map<uint256, CBudgetVote>::iterator it = mapVotes.begin(); while (it != mapVotes.end()) { if ((*it).second.nVote == VOTE_ABSTAIN && (*it).second.fValid) ret++; ++it; } return ret; } int CBudgetProposal::GetBlockStartCycle() { //end block is half way through the next cycle (so the proposal will be removed much after the payment is sent) return nBlockStart - nBlockStart % GetBudgetPaymentCycleBlocks(); } int CBudgetProposal::GetBlockCurrentCycle() { CBlockIndex* pindexPrev = chainActive.Tip(); if (pindexPrev == NULL) return -1; if (pindexPrev->nHeight >= GetBlockEndCycle()) return -1; return pindexPrev->nHeight - pindexPrev->nHeight % GetBudgetPaymentCycleBlocks(); } int CBudgetProposal::GetBlockEndCycle() { // Right now single payment proposals have nBlockEnd have a cycle too early! // switch back if it break something else // end block is half way through the next cycle (so the proposal will be removed much after the payment is sent) // return nBlockEnd - GetBudgetPaymentCycleBlocks() / 2; // End block is half way through the next cycle (so the proposal will be removed much after the payment is sent) return nBlockEnd; } int CBudgetProposal::GetTotalPaymentCount() { return (GetBlockEndCycle() - GetBlockStartCycle()) / GetBudgetPaymentCycleBlocks(); } int CBudgetProposal::GetRemainingPaymentCount() { // If this budget starts in the future, this value will be wrong int nPayments = (GetBlockEndCycle() - GetBlockCurrentCycle()) / GetBudgetPaymentCycleBlocks() - 1; // Take the lowest value return std::min(nPayments, GetTotalPaymentCount()); } CBudgetProposalBroadcast::CBudgetProposalBroadcast(std::string strProposalNameIn, std::string strURLIn, int nPaymentCount, CScript addressIn, CAmount nAmountIn, int nBlockStartIn, uint256 nFeeTXHashIn) { strProposalName = strProposalNameIn; strURL = strURLIn; nBlockStart = nBlockStartIn; int nCycleStart = nBlockStart - nBlockStart % GetBudgetPaymentCycleBlocks(); // Right now single payment proposals have nBlockEnd have a cycle too early! // switch back if it break something else // calculate the end of the cycle for this vote, add half a cycle (vote will be deleted after that block) // nBlockEnd = nCycleStart + GetBudgetPaymentCycleBlocks() * nPaymentCount + GetBudgetPaymentCycleBlocks() / 2; // Calculate the end of the cycle for this vote, vote will be deleted after next cycle nBlockEnd = nCycleStart + (GetBudgetPaymentCycleBlocks() + 1) * nPaymentCount; address = addressIn; nAmount = nAmountIn; nFeeTXHash = nFeeTXHashIn; } void CBudgetProposalBroadcast::Relay() { CInv inv(MSG_BUDGET_PROPOSAL, GetHash()); RelayInv(inv); } CBudgetVote::CBudgetVote() { vin = CTxIn(); nProposalHash = 0; nVote = VOTE_ABSTAIN; nTime = 0; fValid = true; fSynced = false; } CBudgetVote::CBudgetVote(CTxIn vinIn, uint256 nProposalHashIn, int nVoteIn) { vin = vinIn; nProposalHash = nProposalHashIn; nVote = nVoteIn; nTime = GetAdjustedTime(); fValid = true; fSynced = false; } void CBudgetVote::Relay() { CInv inv(MSG_BUDGET_VOTE, GetHash()); RelayInv(inv); } bool CBudgetVote::Sign(CKey& keyMasternode, CPubKey& pubKeyMasternode) { // Choose coins to use CPubKey pubKeyCollateralAddress; CKey keyCollateralAddress; std::string errorMessage; std::string strMessage = vin.prevout.ToStringShort() + nProposalHash.ToString() + boost::lexical_cast<std::string>(nVote) + boost::lexical_cast<std::string>(nTime); if (!obfuScationSigner.SignMessage(strMessage, errorMessage, vchSig, keyMasternode)) { LogPrint("mnbudget","CBudgetVote::Sign - Error upon calling SignMessage"); return false; } if (!obfuScationSigner.VerifyMessage(pubKeyMasternode, vchSig, strMessage, errorMessage)) { LogPrint("mnbudget","CBudgetVote::Sign - Error upon calling VerifyMessage"); return false; } return true; } bool CBudgetVote::SignatureValid(bool fSignatureCheck) { std::string errorMessage; std::string strMessage = vin.prevout.ToStringShort() + nProposalHash.ToString() + boost::lexical_cast<std::string>(nVote) + boost::lexical_cast<std::string>(nTime); CMasternode* pmn = mnodeman.Find(vin); if (pmn == NULL) { if (fDebug){ LogPrint("mnbudget","CBudgetVote::SignatureValid() - Unknown Masternode - %s\n", vin.prevout.hash.ToString()); } return false; } if (!fSignatureCheck) return true; if (!obfuScationSigner.VerifyMessage(pmn->pubKeyMasternode, vchSig, strMessage, errorMessage)) { LogPrint("mnbudget","CBudgetVote::SignatureValid() - Verify message failed\n"); return false; } return true; } CFinalizedBudget::CFinalizedBudget() { strBudgetName = ""; nBlockStart = 0; vecBudgetPayments.clear(); mapVotes.clear(); nFeeTXHash = 0; nTime = 0; fValid = true; fAutoChecked = false; } CFinalizedBudget::CFinalizedBudget(const CFinalizedBudget& other) { strBudgetName = other.strBudgetName; nBlockStart = other.nBlockStart; vecBudgetPayments = other.vecBudgetPayments; mapVotes = other.mapVotes; nFeeTXHash = other.nFeeTXHash; nTime = other.nTime; fValid = true; fAutoChecked = false; } bool CFinalizedBudget::AddOrUpdateVote(CFinalizedBudgetVote& vote, std::string& strError) { LOCK(cs); uint256 hash = vote.vin.prevout.GetHash(); std::string strAction = "New vote inserted:"; if (mapVotes.count(hash)) { if (mapVotes[hash].nTime > vote.nTime) { strError = strprintf("new vote older than existing vote - %s\n", vote.GetHash().ToString()); LogPrint("mnbudget", "CFinalizedBudget::AddOrUpdateVote - %s\n", strError); return false; } if (vote.nTime - mapVotes[hash].nTime < BUDGET_VOTE_UPDATE_MIN) { strError = strprintf("time between votes is too soon - %s - %lli sec < %lli sec\n", vote.GetHash().ToString(), vote.nTime - mapVotes[hash].nTime,BUDGET_VOTE_UPDATE_MIN); LogPrint("mnbudget", "CFinalizedBudget::AddOrUpdateVote - %s\n", strError); return false; } strAction = "Existing vote updated:"; } if (vote.nTime > GetTime() + (60 * 60)) { strError = strprintf("new vote is too far ahead of current time - %s - nTime %lli - Max Time %lli\n", vote.GetHash().ToString(), vote.nTime, GetTime() + (60 * 60)); LogPrint("mnbudget", "CFinalizedBudget::AddOrUpdateVote - %s\n", strError); return false; } mapVotes[hash] = vote; LogPrint("mnbudget", "CFinalizedBudget::AddOrUpdateVote - %s %s\n", strAction.c_str(), vote.GetHash().ToString().c_str()); return true; } //evaluate if we should vote for this. Masternode only void CFinalizedBudget::AutoCheck() { LOCK(cs); CBlockIndex* pindexPrev = chainActive.Tip(); if (!pindexPrev) return; LogPrint("mnbudget","CFinalizedBudget::AutoCheck - %lli - %d\n", pindexPrev->nHeight, fAutoChecked); if (!fMasterNode || fAutoChecked) { LogPrint("mnbudget","CFinalizedBudget::AutoCheck fMasterNode=%d fAutoChecked=%d\n", fMasterNode, fAutoChecked); return; } // Do this 1 in 4 blocks -- spread out the voting activity // -- this function is only called every fourteenth block, so this is really 1 in 56 blocks if (rand() % 4 != 0) { LogPrint("mnbudget","CFinalizedBudget::AutoCheck - waiting\n"); return; } fAutoChecked = true; //we only need to check this once if (strBudgetMode == "auto") //only vote for exact matches { std::vector<CBudgetProposal*> vBudgetProposals = budget.GetBudget(); for (unsigned int i = 0; i < vecBudgetPayments.size(); i++) { LogPrint("mnbudget","CFinalizedBudget::AutoCheck Budget-Payments - nProp %d %s\n", i, vecBudgetPayments[i].nProposalHash.ToString()); LogPrint("mnbudget","CFinalizedBudget::AutoCheck Budget-Payments - Payee %d %s\n", i, vecBudgetPayments[i].payee.ToString()); LogPrint("mnbudget","CFinalizedBudget::AutoCheck Budget-Payments - nAmount %d %lli\n", i, vecBudgetPayments[i].nAmount); } for (unsigned int i = 0; i < vBudgetProposals.size(); i++) { LogPrint("mnbudget","CFinalizedBudget::AutoCheck Budget-Proposals - nProp %d %s\n", i, vBudgetProposals[i]->GetHash().ToString()); LogPrint("mnbudget","CFinalizedBudget::AutoCheck Budget-Proposals - Payee %d %s\n", i, vBudgetProposals[i]->GetPayee().ToString()); LogPrint("mnbudget","CFinalizedBudget::AutoCheck Budget-Proposals - nAmount %d %lli\n", i, vBudgetProposals[i]->GetAmount()); } if (vBudgetProposals.size() == 0) { LogPrint("mnbudget","CFinalizedBudget::AutoCheck - No Budget-Proposals found, aborting\n"); return; } if (vBudgetProposals.size() != vecBudgetPayments.size()) { LogPrint("mnbudget","CFinalizedBudget::AutoCheck - Budget-Proposal length (%ld) doesn't match Budget-Payment length (%ld).\n", vBudgetProposals.size(), vecBudgetPayments.size()); return; } for (unsigned int i = 0; i < vecBudgetPayments.size(); i++) { if (i > vBudgetProposals.size() - 1) { LogPrint("mnbudget","CFinalizedBudget::AutoCheck - Proposal size mismatch, i=%d > (vBudgetProposals.size() - 1)=%d\n", i, vBudgetProposals.size() - 1); return; } if (vecBudgetPayments[i].nProposalHash != vBudgetProposals[i]->GetHash()) { LogPrint("mnbudget","CFinalizedBudget::AutoCheck - item #%d doesn't match %s %s\n", i, vecBudgetPayments[i].nProposalHash.ToString(), vBudgetProposals[i]->GetHash().ToString()); return; } // if(vecBudgetPayments[i].payee != vBudgetProposals[i]->GetPayee()){ -- triggered with false positive if (vecBudgetPayments[i].payee.ToString() != vBudgetProposals[i]->GetPayee().ToString()) { LogPrint("mnbudget","CFinalizedBudget::AutoCheck - item #%d payee doesn't match %s %s\n", i, vecBudgetPayments[i].payee.ToString(), vBudgetProposals[i]->GetPayee().ToString()); return; } if (vecBudgetPayments[i].nAmount != vBudgetProposals[i]->GetAmount()) { LogPrint("mnbudget","CFinalizedBudget::AutoCheck - item #%d payee doesn't match %lli %lli\n", i, vecBudgetPayments[i].nAmount, vBudgetProposals[i]->GetAmount()); return; } } LogPrint("mnbudget","CFinalizedBudget::AutoCheck - Finalized Budget Matches! Submitting Vote.\n"); SubmitVote(); } } // If masternode voted for a proposal, but is now invalid -- remove the vote void CFinalizedBudget::CleanAndRemove(bool fSignatureCheck) { std::map<uint256, CFinalizedBudgetVote>::iterator it = mapVotes.begin(); while (it != mapVotes.end()) { (*it).second.fValid = (*it).second.SignatureValid(fSignatureCheck); ++it; } } CAmount CFinalizedBudget::GetTotalPayout() { CAmount ret = 0; for (unsigned int i = 0; i < vecBudgetPayments.size(); i++) { ret += vecBudgetPayments[i].nAmount; } return ret; } std::string CFinalizedBudget::GetProposals() { LOCK(cs); std::string ret = ""; BOOST_FOREACH (CTxBudgetPayment& budgetPayment, vecBudgetPayments) { CBudgetProposal* pbudgetProposal = budget.FindProposal(budgetPayment.nProposalHash); std::string token = budgetPayment.nProposalHash.ToString(); if (pbudgetProposal) token = pbudgetProposal->GetName(); if (ret == "") { ret = token; } else { ret += "," + token; } } return ret; } std::string CFinalizedBudget::GetStatus() { std::string retBadHashes = ""; std::string retBadPayeeOrAmount = ""; for (int nBlockHeight = GetBlockStart(); nBlockHeight <= GetBlockEnd(); nBlockHeight++) { CTxBudgetPayment budgetPayment; if (!GetBudgetPaymentByBlock(nBlockHeight, budgetPayment)) { LogPrint("mnbudget","CFinalizedBudget::GetStatus - Couldn't find budget payment for block %lld\n", nBlockHeight); continue; } CBudgetProposal* pbudgetProposal = budget.FindProposal(budgetPayment.nProposalHash); if (!pbudgetProposal) { if (retBadHashes == "") { retBadHashes = "Unknown proposal hash! Check this proposal before voting: " + budgetPayment.nProposalHash.ToString(); } else { retBadHashes += "," + budgetPayment.nProposalHash.ToString(); } } else { if (pbudgetProposal->GetPayee() != budgetPayment.payee || pbudgetProposal->GetAmount() != budgetPayment.nAmount) { if (retBadPayeeOrAmount == "") { retBadPayeeOrAmount = "Budget payee/nAmount doesn't match our proposal! " + budgetPayment.nProposalHash.ToString(); } else { retBadPayeeOrAmount += "," + budgetPayment.nProposalHash.ToString(); } } } } if (retBadHashes == "" && retBadPayeeOrAmount == "") return "OK"; return retBadHashes + retBadPayeeOrAmount; } bool CFinalizedBudget::IsValid(std::string& strError, bool fCheckCollateral) { // All(!) finalized budgets have the name "main", so get some additional information about them std::string strProposals = GetProposals(); // Must be the correct block for payment to happen (once a month) if (nBlockStart % GetBudgetPaymentCycleBlocks() != 0) { strError = "Invalid BlockStart"; return false; } // The following 2 checks check the same (basically if vecBudgetPayments.size() > 100) if (GetBlockEnd() - nBlockStart > 100) { strError = "Invalid BlockEnd"; return false; } if ((int)vecBudgetPayments.size() > 100) { strError = "Invalid budget payments count (too many)"; return false; } if (strBudgetName == "") { strError = "Invalid Budget Name"; return false; } if (nBlockStart == 0) { strError = "Budget " + strBudgetName + " (" + strProposals + ") Invalid BlockStart == 0"; return false; } if (nFeeTXHash == 0) { strError = "Budget " + strBudgetName + " (" + strProposals + ") Invalid FeeTx == 0"; return false; } // Can only pay out 10% of the possible coins (min value of coins) if (GetTotalPayout() > budget.GetTotalBudget(nBlockStart)) { strError = "Budget " + strBudgetName + " (" + strProposals + ") Invalid Payout (more than max)"; return false; } std::string strError2 = ""; if (fCheckCollateral) { int nConf = 0; if (!IsBudgetCollateralValid(nFeeTXHash, GetHash(), strError2, nTime, nConf, true)) { { strError = "Budget " + strBudgetName + " (" + strProposals + ") Invalid Collateral : " + strError2; return false; } } } // Remove obsolete finalized budgets after some time CBlockIndex* pindexPrev = chainActive.Tip(); if (pindexPrev == NULL) return true; // Get start of current budget-cycle int nCurrentHeight = chainActive.Height(); int nBlockStart = nCurrentHeight - nCurrentHeight % GetBudgetPaymentCycleBlocks() + GetBudgetPaymentCycleBlocks(); // Remove budgets where the last payment (from max. 100) ends before 2 budget-cycles before the current one int nMaxAge = nBlockStart - (2 * GetBudgetPaymentCycleBlocks()); if (GetBlockEnd() < nMaxAge) { strError = strprintf("Budget " + strBudgetName + " (" + strProposals + ") (ends at block %ld) too old and obsolete", GetBlockEnd()); return false; } return true; } bool CFinalizedBudget::IsPaidAlready(uint256 nProposalHash, int nBlockHeight) { // Remove budget-payments from former/future payment cycles map<uint256, int>::iterator it = mapPayment_History.begin(); int nPaidBlockHeight = 0; uint256 nOldProposalHash; for(it = mapPayment_History.begin(); it != mapPayment_History.end(); /* No incrementation needed */ ) { nPaidBlockHeight = (*it).second; if((nPaidBlockHeight < GetBlockStart()) || (nPaidBlockHeight > GetBlockEnd())) { nOldProposalHash = (*it).first; LogPrint("mnbudget", "CFinalizedBudget::IsPaidAlready - Budget Proposal %s, Block %d from old cycle deleted\n", nOldProposalHash.ToString().c_str(), nPaidBlockHeight); mapPayment_History.erase(it++); } else { ++it; } } // Now that we only have payments from the current payment cycle check if this budget was paid already if(mapPayment_History.count(nProposalHash) == 0) { // New proposal payment, insert into map for checks with later blocks from this cycle mapPayment_History.insert(std::pair<uint256, int>(nProposalHash, nBlockHeight)); LogPrint("mnbudget", "CFinalizedBudget::IsPaidAlready - Budget Proposal %s, Block %d added to payment history\n", nProposalHash.ToString().c_str(), nBlockHeight); return false; } // This budget was paid already -> reject transaction so it gets paid to a masternode instead return true; } TrxValidationStatus CFinalizedBudget::IsTransactionValid(const CTransaction& txNew, int nBlockHeight) { TrxValidationStatus transactionStatus = TrxValidationStatus::InValid; int nCurrentBudgetPayment = nBlockHeight - GetBlockStart(); if (nCurrentBudgetPayment < 0) { LogPrint("mnbudget","CFinalizedBudget::IsTransactionValid - Invalid block - height: %d start: %d\n", nBlockHeight, GetBlockStart()); return TrxValidationStatus::InValid; } if (nCurrentBudgetPayment > (int)vecBudgetPayments.size() - 1) { LogPrint("mnbudget","CFinalizedBudget::IsTransactionValid - Invalid last block - current budget payment: %d of %d\n", nCurrentBudgetPayment + 1, (int)vecBudgetPayments.size()); return TrxValidationStatus::InValid; } bool paid = false; BOOST_FOREACH (CTxOut out, txNew.vout) { LogPrint("mnbudget","CFinalizedBudget::IsTransactionValid - nCurrentBudgetPayment=%d, payee=%s == out.scriptPubKey=%s, amount=%ld == out.nValue=%ld\n", nCurrentBudgetPayment, vecBudgetPayments[nCurrentBudgetPayment].payee.ToString().c_str(), out.scriptPubKey.ToString().c_str(), vecBudgetPayments[nCurrentBudgetPayment].nAmount, out.nValue); if (vecBudgetPayments[nCurrentBudgetPayment].payee == out.scriptPubKey && vecBudgetPayments[nCurrentBudgetPayment].nAmount == out.nValue) { // Check if this proposal was paid already. If so, pay a masternode instead paid = IsPaidAlready(vecBudgetPayments[nCurrentBudgetPayment].nProposalHash, nBlockHeight); if(paid) { LogPrint("mnbudget","CFinalizedBudget::IsTransactionValid - Double Budget Payment of %d for proposal %d detected. Paying a masternode instead.\n", vecBudgetPayments[nCurrentBudgetPayment].nAmount, vecBudgetPayments[nCurrentBudgetPayment].nProposalHash.Get32()); // No matter what we've found before, stop all checks here. In future releases there might be more than one budget payment // per block, so even if the first one was not paid yet this one disables all budget payments for this block. transactionStatus = TrxValidationStatus::DoublePayment; break; } else { transactionStatus = TrxValidationStatus::Valid; LogPrint("mnbudget","CFinalizedBudget::IsTransactionValid - Found valid Budget Payment of %d for proposal %d\n", vecBudgetPayments[nCurrentBudgetPayment].nAmount, vecBudgetPayments[nCurrentBudgetPayment].nProposalHash.Get32()); } } } if (transactionStatus == TrxValidationStatus::InValid) { CTxDestination address1; ExtractDestination(vecBudgetPayments[nCurrentBudgetPayment].payee, address1); CBitcoinAddress address2(address1); LogPrint("mnbudget","CFinalizedBudget::IsTransactionValid - Missing required payment - %s: %d c: %d\n", address2.ToString(), vecBudgetPayments[nCurrentBudgetPayment].nAmount, nCurrentBudgetPayment); } return transactionStatus; } void CFinalizedBudget::SubmitVote() { CPubKey pubKeyMasternode; CKey keyMasternode; std::string errorMessage; if (!obfuScationSigner.SetKey(strMasterNodePrivKey, errorMessage, keyMasternode, pubKeyMasternode)) { LogPrint("mnbudget","CFinalizedBudget::SubmitVote - Error upon calling SetKey\n"); return; } CFinalizedBudgetVote vote(activeMasternode.vin, GetHash()); if (!vote.Sign(keyMasternode, pubKeyMasternode)) { LogPrint("mnbudget","CFinalizedBudget::SubmitVote - Failure to sign."); return; } std::string strError = ""; if (budget.UpdateFinalizedBudget(vote, NULL, strError)) { LogPrint("mnbudget","CFinalizedBudget::SubmitVote - new finalized budget vote - %s\n", vote.GetHash().ToString()); budget.mapSeenFinalizedBudgetVotes.insert(make_pair(vote.GetHash(), vote)); vote.Relay(); } else { LogPrint("mnbudget","CFinalizedBudget::SubmitVote : Error submitting vote - %s\n", strError); } } CFinalizedBudgetBroadcast::CFinalizedBudgetBroadcast() { strBudgetName = ""; nBlockStart = 0; vecBudgetPayments.clear(); mapVotes.clear(); vchSig.clear(); nFeeTXHash = 0; } CFinalizedBudgetBroadcast::CFinalizedBudgetBroadcast(const CFinalizedBudget& other) { strBudgetName = other.strBudgetName; nBlockStart = other.nBlockStart; BOOST_FOREACH (CTxBudgetPayment out, other.vecBudgetPayments) vecBudgetPayments.push_back(out); mapVotes = other.mapVotes; nFeeTXHash = other.nFeeTXHash; } CFinalizedBudgetBroadcast::CFinalizedBudgetBroadcast(std::string strBudgetNameIn, int nBlockStartIn, std::vector<CTxBudgetPayment> vecBudgetPaymentsIn, uint256 nFeeTXHashIn) { strBudgetName = strBudgetNameIn; nBlockStart = nBlockStartIn; BOOST_FOREACH (CTxBudgetPayment out, vecBudgetPaymentsIn) vecBudgetPayments.push_back(out); mapVotes.clear(); nFeeTXHash = nFeeTXHashIn; } void CFinalizedBudgetBroadcast::Relay() { CInv inv(MSG_BUDGET_FINALIZED, GetHash()); RelayInv(inv); } CFinalizedBudgetVote::CFinalizedBudgetVote() { vin = CTxIn(); nBudgetHash = 0; nTime = 0; vchSig.clear(); fValid = true; fSynced = false; } CFinalizedBudgetVote::CFinalizedBudgetVote(CTxIn vinIn, uint256 nBudgetHashIn) { vin = vinIn; nBudgetHash = nBudgetHashIn; nTime = GetAdjustedTime(); vchSig.clear(); fValid = true; fSynced = false; } void CFinalizedBudgetVote::Relay() { CInv inv(MSG_BUDGET_FINALIZED_VOTE, GetHash()); RelayInv(inv); } bool CFinalizedBudgetVote::Sign(CKey& keyMasternode, CPubKey& pubKeyMasternode) { // Choose coins to use CPubKey pubKeyCollateralAddress; CKey keyCollateralAddress; std::string errorMessage; std::string strMessage = vin.prevout.ToStringShort() + nBudgetHash.ToString() + boost::lexical_cast<std::string>(nTime); if (!obfuScationSigner.SignMessage(strMessage, errorMessage, vchSig, keyMasternode)) { LogPrint("mnbudget","CFinalizedBudgetVote::Sign - Error upon calling SignMessage"); return false; } if (!obfuScationSigner.VerifyMessage(pubKeyMasternode, vchSig, strMessage, errorMessage)) { LogPrint("mnbudget","CFinalizedBudgetVote::Sign - Error upon calling VerifyMessage"); return false; } return true; } bool CFinalizedBudgetVote::SignatureValid(bool fSignatureCheck) { std::string errorMessage; std::string strMessage = vin.prevout.ToStringShort() + nBudgetHash.ToString() + boost::lexical_cast<std::string>(nTime); CMasternode* pmn = mnodeman.Find(vin); if (pmn == NULL) { LogPrint("mnbudget","CFinalizedBudgetVote::SignatureValid() - Unknown Masternode %s\n", strMessage); return false; } if (!fSignatureCheck) return true; if (!obfuScationSigner.VerifyMessage(pmn->pubKeyMasternode, vchSig, strMessage, errorMessage)) { LogPrint("mnbudget","CFinalizedBudgetVote::SignatureValid() - Verify message failed %s %s\n", strMessage, errorMessage); return false; } return true; } std::string CBudgetManager::ToString() const { std::ostringstream info; info << "Proposals: " << (int)mapProposals.size() << ", Budgets: " << (int)mapFinalizedBudgets.size() << ", Seen Budgets: " << (int)mapSeenMasternodeBudgetProposals.size() << ", Seen Budget Votes: " << (int)mapSeenMasternodeBudgetVotes.size() << ", Seen Final Budgets: " << (int)mapSeenFinalizedBudgets.size() << ", Seen Final Budget Votes: " << (int)mapSeenFinalizedBudgetVotes.size(); return info.str(); }
// Copyright (c) 2014-2015 The Crown developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "main.h" #include "init.h" #include "masternode-budget.h" #include "masternode.h" #include "legacysigner.h" #include "masternodeman.h" #include "masternode-sync.h" #include "util.h" #include "addrman.h" #include <boost/filesystem.hpp> #include <boost/lexical_cast.hpp> CBudgetManager budget; CCriticalSection cs_budget; std::map<uint256, int64_t> askedForSourceProposalOrBudget; std::vector<CBudgetProposalBroadcast> vecImmatureBudgetProposals; std::vector<CFinalizedBudgetBroadcast> vecImmatureFinalizedBudgets; CAmount BlocksBeforeSuperblockToSubmitFinalBudget() { assert(GetBudgetPaymentCycleBlocks() > 10); // Relatively 43200 / 30 = 1440, for testnet - equal to budget payment cycle if (Params().NetworkID() == CBaseChainParams::MAIN) return 1440 * 2; // aprox 2 days else return GetBudgetPaymentCycleBlocks() - 10; // 40 blocks for 50-block cycle } int GetBudgetPaymentCycleBlocks() { // Amount of blocks in a months period of time (using 1 minutes per) = (60*24*30)/1 if(Params().NetworkID() == CBaseChainParams::MAIN) return 43200; else return 50; //for testing purposes } bool IsBudgetCollateralValid(uint256 nTxCollateralHash, uint256 nExpectedHash, std::string& strError, int64_t& nTime, int& nConf) { CTransaction txCollateral; uint256 nBlockHash; if(!GetTransaction(nTxCollateralHash, txCollateral, nBlockHash, true)){ strError = strprintf("Can't find collateral tx %s", txCollateral.ToString()); LogPrintf ("CBudgetProposalBroadcast::IsBudgetCollateralValid - %s\n", strError); return false; } if(txCollateral.vout.size() < 1) return false; if(txCollateral.nLockTime != 0) return false; CScript findScript; findScript << OP_RETURN << ToByteVector(nExpectedHash); bool foundOpReturn = false; BOOST_FOREACH(const CTxOut o, txCollateral.vout){ if(!o.scriptPubKey.IsNormalPaymentScript() && !o.scriptPubKey.IsUnspendable()){ strError = strprintf("Invalid Script %s", txCollateral.ToString()); LogPrintf ("CBudgetProposalBroadcast::IsBudgetCollateralValid - %s\n", strError); return false; } if(o.scriptPubKey == findScript && o.nValue >= BUDGET_FEE_TX) foundOpReturn = true; } if(!foundOpReturn){ strError = strprintf("Couldn't find opReturn %s in %s", nExpectedHash.ToString(), txCollateral.ToString()); LogPrintf ("CBudgetProposalBroadcast::IsBudgetCollateralValid - %s\n", strError); return false; } // RETRIEVE CONFIRMATIONS AND NTIME /* - nTime starts as zero and is passed-by-reference out of this function and stored in the external proposal - nTime is never validated via the hashing mechanism and comes from a full-validated source (the blockchain) */ int conf = GetIXConfirmations(nTxCollateralHash); if (nBlockHash != uint256()) { BlockMap::iterator mi = mapBlockIndex.find(nBlockHash); if (mi != mapBlockIndex.end() && (*mi).second) { CBlockIndex* pindex = (*mi).second; if (chainActive.Contains(pindex)) { conf += chainActive.Height() - pindex->nHeight + 1; nTime = pindex->nTime; } } } nConf = conf; //if we're syncing we won't have instantX information, so accept 1 confirmation if(conf >= BUDGET_FEE_CONFIRMATIONS){ return true; } else { strError = strprintf("Collateral requires at least %d confirmations - %d confirmations", BUDGET_FEE_CONFIRMATIONS, conf); LogPrintf ("CBudgetProposalBroadcast::IsBudgetCollateralValid - %s - %d confirmations\n", strError, conf); return false; } } void CBudgetManager::CheckOrphanVotes() { LOCK(cs); std::string strError = ""; std::map<uint256, CBudgetVote>::iterator it1 = mapOrphanMasternodeBudgetVotes.begin(); while(it1 != mapOrphanMasternodeBudgetVotes.end()){ if(budget.UpdateProposal(((*it1).second), NULL, strError)){ LogPrintf("CBudgetManager::CheckOrphanVotes - Proposal/Budget is known, activating and removing orphan vote\n"); mapOrphanMasternodeBudgetVotes.erase(it1++); } else { ++it1; } } std::map<uint256, CFinalizedBudgetVote>::iterator it2 = mapOrphanFinalizedBudgetVotes.begin(); while(it2 != mapOrphanFinalizedBudgetVotes.end()){ if(budget.UpdateFinalizedBudget(((*it2).second),NULL, strError)){ LogPrintf("CBudgetManager::CheckOrphanVotes - Proposal/Budget is known, activating and removing orphan vote\n"); mapOrphanFinalizedBudgetVotes.erase(it2++); } else { ++it2; } } } void CBudgetManager::SubmitFinalBudget() { static int nSubmittedHeight = 0; // height at which final budget was submitted last time int nCurrentHeight; { TRY_LOCK(cs_main, locked); if(!locked) return; if(!chainActive.Tip()) return; nCurrentHeight = chainActive.Height(); } int nBlockStart = nCurrentHeight - nCurrentHeight % GetBudgetPaymentCycleBlocks() + GetBudgetPaymentCycleBlocks(); if(nSubmittedHeight >= nBlockStart) return; if(nBlockStart - nCurrentHeight > BlocksBeforeSuperblockToSubmitFinalBudget()) return; // allow submitting final budget only when 2 days left before payments std::vector<CBudgetProposal*> vBudgetProposals = budget.GetBudget(); std::string strBudgetName = "main"; std::vector<CTxBudgetPayment> vecTxBudgetPayments; for(unsigned int i = 0; i < vBudgetProposals.size(); i++){ CTxBudgetPayment txBudgetPayment; txBudgetPayment.nProposalHash = vBudgetProposals[i]->GetHash(); txBudgetPayment.payee = vBudgetProposals[i]->GetPayee(); txBudgetPayment.nAmount = vBudgetProposals[i]->GetAllotted(); vecTxBudgetPayments.push_back(txBudgetPayment); } if(vecTxBudgetPayments.size() < 1) { LogPrintf("CBudgetManager::SubmitFinalBudget - Found No Proposals For Period\n"); return; } CFinalizedBudgetBroadcast tempBudget(strBudgetName, nBlockStart, vecTxBudgetPayments, uint256()); if(mapSeenFinalizedBudgets.count(tempBudget.GetHash())) { LogPrintf("CBudgetManager::SubmitFinalBudget - Budget already exists - %s\n", tempBudget.GetHash().ToString()); nSubmittedHeight = nCurrentHeight; return; //already exists } //create fee tx CTransaction tx; uint256 txidCollateral; if(!mapCollateralTxids.count(tempBudget.GetHash())){ const bool useIX = false; CWalletTx wtx; if(!pwalletMain->GetBudgetSystemCollateralTX(wtx, tempBudget.GetHash(), useIX)){ LogPrintf("CBudgetManager::SubmitFinalBudget - Can't make collateral transaction\n"); return; } // make our change address CReserveKey reservekey(pwalletMain); //send the tx to the network pwalletMain->CommitTransaction(wtx, reservekey, useIX ? "ix" : "tx"); tx = (CTransaction)wtx; txidCollateral = tx.GetHash(); mapCollateralTxids.insert(make_pair(tempBudget.GetHash(), txidCollateral)); } else { txidCollateral = mapCollateralTxids[tempBudget.GetHash()]; } int conf = GetIXConfirmations(tx.GetHash()); CTransaction txCollateral; uint256 nBlockHash; if(!GetTransaction(txidCollateral, txCollateral, nBlockHash, true)) { LogPrintf ("CBudgetManager::SubmitFinalBudget - Can't find collateral tx %s", txidCollateral.ToString()); return; } if (nBlockHash != uint256()) { BlockMap::iterator mi = mapBlockIndex.find(nBlockHash); if (mi != mapBlockIndex.end() && (*mi).second) { CBlockIndex* pindex = (*mi).second; if (chainActive.Contains(pindex)) { conf += chainActive.Height() - pindex->nHeight + 1; } } } /* Wait will we have 1 extra confirmation, otherwise some clients might reject this feeTX -- This function is tied to NewBlock, so we will propagate this budget while the block is also propagating */ if(conf < BUDGET_FEE_CONFIRMATIONS+1){ LogPrintf ("CBudgetManager::SubmitFinalBudget - Collateral requires at least %d confirmations - %s - %d confirmations\n", BUDGET_FEE_CONFIRMATIONS+1, txidCollateral.ToString(), conf); return; } //create the proposal incase we're the first to make it CFinalizedBudgetBroadcast finalizedBudgetBroadcast(strBudgetName, nBlockStart, vecTxBudgetPayments, txidCollateral); std::string strError = ""; if(!finalizedBudgetBroadcast.IsValid(strError)){ LogPrintf("CBudgetManager::SubmitFinalBudget - Invalid finalized budget - %s \n", strError); return; } LOCK(cs); mapSeenFinalizedBudgets.insert(make_pair(finalizedBudgetBroadcast.GetHash(), finalizedBudgetBroadcast)); finalizedBudgetBroadcast.Relay(); budget.AddFinalizedBudget(finalizedBudgetBroadcast); nSubmittedHeight = nCurrentHeight; LogPrintf("CBudgetManager::SubmitFinalBudget - Done! %s\n", finalizedBudgetBroadcast.GetHash().ToString()); } // // CBudgetDB // CBudgetDB::CBudgetDB() : pathDB(GetDataDir() / "budget.dat") , strMagicMessage("MasternodeBudget") { } CBudgetDB::CBudgetDB(const boost::filesystem::path& dbPath) : pathDB(dbPath) , strMagicMessage("MasternodeBudget") { } bool CBudgetDB::Write(const CBudgetManager& objToSave) { LOCK(objToSave.cs); int64_t nStart = GetTimeMillis(); // serialize, checksum data up to that point, then append checksum CDataStream ssObj(SER_DISK, CLIENT_VERSION); ssObj << strMagicMessage; // masternode cache file specific magic message ssObj << FLATDATA(Params().MessageStart()); // network specific magic number ssObj << objToSave; uint256 hash = Hash(ssObj.begin(), ssObj.end()); ssObj << hash; // open output file, and associate with CAutoFile FILE *file = fopen(pathDB.string().c_str(), "wb"); CAutoFile fileout(file, SER_DISK, CLIENT_VERSION); if (fileout.IsNull()) return error("%s : Failed to open file %s", __func__, pathDB.string()); // Write and commit header, data try { fileout << ssObj; } catch (std::exception &e) { return error("%s : Serialize or I/O error - %s", __func__, e.what()); } fileout.fclose(); LogPrintf("Written info to budget.dat %dms\n", GetTimeMillis() - nStart); return true; } CBudgetDB::ReadResult CBudgetDB::Read(CBudgetManager& objToLoad, bool fDryRun) { LOCK(objToLoad.cs); int64_t nStart = GetTimeMillis(); // open input file, and associate with CAutoFile FILE *file = fopen(pathDB.string().c_str(), "rb"); CAutoFile filein(file, SER_DISK, CLIENT_VERSION); if (filein.IsNull()) { error("%s : Failed to open file %s", __func__, pathDB.string()); return FileError; } // use file size to size memory buffer int fileSize = boost::filesystem::file_size(pathDB); int dataSize = fileSize - sizeof(uint256); // Don't try to resize to a negative number if file is small if (dataSize < 0) dataSize = 0; vector<unsigned char> vchData; vchData.resize(dataSize); uint256 hashIn; // read data and checksum from file try { filein.read((char *)&vchData[0], dataSize); filein >> hashIn; } catch (std::exception &e) { error("%s : Deserialize or I/O error - %s", __func__, e.what()); return HashReadError; } filein.fclose(); CDataStream ssObj(vchData, SER_DISK, CLIENT_VERSION); // verify stored checksum matches input data uint256 hashTmp = Hash(ssObj.begin(), ssObj.end()); if (hashIn != hashTmp) { error("%s : Checksum mismatch, data corrupted", __func__); return IncorrectHash; } unsigned char pchMsgTmp[4]; std::string strMagicMessageTmp; try { // de-serialize file header (masternode cache file specific magic message) and .. ssObj >> strMagicMessageTmp; // ... verify the message matches predefined one if (strMagicMessage != strMagicMessageTmp) { error("%s : Invalid masternode cache magic message", __func__); return IncorrectMagicMessage; } // de-serialize file header (network specific magic number) and .. ssObj >> FLATDATA(pchMsgTmp); // ... verify the network matches ours if (memcmp(pchMsgTmp, Params().MessageStart(), sizeof(pchMsgTmp))) { error("%s : Invalid network magic number", __func__); return IncorrectMagicNumber; } // de-serialize data into CBudgetManager object ssObj >> objToLoad; } catch (std::exception &e) { objToLoad.Clear(); error("%s : Deserialize or I/O error - %s", __func__, e.what()); return IncorrectFormat; } LogPrintf("Loaded info from budget.dat %dms\n", GetTimeMillis() - nStart); LogPrintf(" %s\n", objToLoad.ToString()); if(!fDryRun) { LogPrintf("Budget manager - cleaning....\n"); objToLoad.CheckAndRemove(); LogPrintf("Budget manager - result:\n"); LogPrintf(" %s\n", objToLoad.ToString()); } return Ok; } void DumpBudgets() { int64_t nStart = GetTimeMillis(); CBudgetDB budgetdb; CBudgetManager tempBudget; LogPrintf("Verifying budget.dat format...\n"); CBudgetDB::ReadResult readResult = budgetdb.Read(tempBudget, true); // there was an error and it was not an error on file opening => do not proceed if (readResult == CBudgetDB::FileError) LogPrintf("Missing budgets file - budget.dat, will try to recreate\n"); else if (readResult != CBudgetDB::Ok) { LogPrintf("Error reading budget.dat: "); if(readResult == CBudgetDB::IncorrectFormat) LogPrintf("magic is ok but data has invalid format, will try to recreate\n"); else { LogPrintf("file format is unknown or invalid, please fix it manually\n"); return; } } LogPrintf("Writting info to budget.dat...\n"); budgetdb.Write(budget); LogPrintf("Budget dump finished %dms\n", GetTimeMillis() - nStart); } bool CBudgetManager::AddFinalizedBudget(CFinalizedBudget& finalizedBudget) { std::string strError = ""; if(!finalizedBudget.IsValid(strError)) return false; if(mapFinalizedBudgets.count(finalizedBudget.GetHash())) { return false; } mapFinalizedBudgets.insert(make_pair(finalizedBudget.GetHash(), finalizedBudget)); return true; } bool CBudgetManager::AddProposal(CBudgetProposal& budgetProposal) { LOCK(cs); std::string strError = ""; if(!budgetProposal.IsValid(strError)) { LogPrintf("CBudgetManager::AddProposal - invalid budget proposal - %s\n", strError); return false; } if(mapProposals.count(budgetProposal.GetHash())) { return false; } mapProposals.insert(make_pair(budgetProposal.GetHash(), budgetProposal)); return true; } void CBudgetManager::CheckAndRemove() { LogPrintf("CBudgetManager::CheckAndRemove\n"); std::string strError = ""; LogPrintf("CBudgetManager::CheckAndRemove - mapFinalizedBudgets cleanup - size: %d\n", mapFinalizedBudgets.size()); std::map<uint256, CFinalizedBudget>::iterator it = mapFinalizedBudgets.begin(); while(it != mapFinalizedBudgets.end()) { CFinalizedBudget* pfinalizedBudget = &((*it).second); pfinalizedBudget->fValid = pfinalizedBudget->IsValid(strError); LogPrintf("CBudgetManager::CheckAndRemove - pfinalizedBudget->IsValid - strError: %s\n", strError); if(pfinalizedBudget->fValid) { pfinalizedBudget->AutoCheck(); } ++it; } LogPrintf("CBudgetManager::CheckAndRemove - mapProposals cleanup - size: %d\n", mapProposals.size()); std::map<uint256, CBudgetProposal>::iterator it2 = mapProposals.begin(); while(it2 != mapProposals.end()) { CBudgetProposal* pbudgetProposal = &((*it2).second); pbudgetProposal->fValid = pbudgetProposal->IsValid(strError); ++it2; } LogPrintf("CBudgetManager::CheckAndRemove - PASSED\n"); } void CBudgetManager::FillBlockPayee(CMutableTransaction& txNew, CAmount nFees) { LOCK(cs); CBlockIndex* pindexPrev = chainActive.Tip(); if(!pindexPrev) return; int nHighestCount = 0; CScript payee; CAmount nAmount = 0; // ------- Grab The Highest Count std::map<uint256, CFinalizedBudget>::iterator it = mapFinalizedBudgets.begin(); while(it != mapFinalizedBudgets.end()) { CFinalizedBudget* pfinalizedBudget = &((*it).second); if(pfinalizedBudget->GetVoteCount() > nHighestCount && pindexPrev->nHeight + 1 >= pfinalizedBudget->GetBlockStart() && pindexPrev->nHeight + 1 <= pfinalizedBudget->GetBlockEnd() && pfinalizedBudget->GetPayeeAndAmount(pindexPrev->nHeight + 1, payee, nAmount)){ nHighestCount = pfinalizedBudget->GetVoteCount(); } ++it; } CAmount blockValue = GetBlockValue(pindexPrev->nBits, pindexPrev->nHeight, nFees); //miners get the full amount on these blocks txNew.vout[0].nValue = blockValue; if(nHighestCount > 0){ txNew.vout.resize(2); //these are super blocks, so their value can be much larger than normal txNew.vout[1].scriptPubKey = payee; txNew.vout[1].nValue = nAmount; CTxDestination address1; ExtractDestination(payee, address1); CBitcoinAddress address2(address1); LogPrintf("CBudgetManager::FillBlockPayee - Budget payment to %s for %lld\n", address2.ToString(), nAmount); } } CFinalizedBudget *CBudgetManager::FindFinalizedBudget(uint256 nHash) { if(mapFinalizedBudgets.count(nHash)) return &mapFinalizedBudgets[nHash]; return NULL; } CBudgetProposal *CBudgetManager::FindProposal(const std::string &strProposalName) { //find the prop with the highest yes count int nYesCount = -99999; CBudgetProposal* pbudgetProposal = NULL; std::map<uint256, CBudgetProposal>::iterator it = mapProposals.begin(); while(it != mapProposals.end()){ if((*it).second.strProposalName == strProposalName && (*it).second.GetYeas() > nYesCount){ pbudgetProposal = &((*it).second); nYesCount = pbudgetProposal->GetYeas(); } ++it; } if(nYesCount == -99999) return NULL; return pbudgetProposal; } CBudgetProposal *CBudgetManager::FindProposal(uint256 nHash) { LOCK(cs); if(mapProposals.count(nHash)) return &mapProposals[nHash]; return NULL; } bool CBudgetManager::IsBudgetPaymentBlock(int nBlockHeight) { int nHighestCount = -1; std::map<uint256, CFinalizedBudget>::iterator it = mapFinalizedBudgets.begin(); while(it != mapFinalizedBudgets.end()) { CFinalizedBudget* pfinalizedBudget = &((*it).second); if(pfinalizedBudget->GetVoteCount() > nHighestCount && nBlockHeight >= pfinalizedBudget->GetBlockStart() && nBlockHeight <= pfinalizedBudget->GetBlockEnd()){ nHighestCount = pfinalizedBudget->GetVoteCount(); } ++it; } /* If budget doesn't have 5% of the network votes, then we should pay a masternode instead */ if(20 * nHighestCount > mnodeman.CountEnabled(MIN_BUDGET_PEER_PROTO_VERSION)) return true; return false; } bool CBudgetManager::HasNextFinalizedBudget() { CBlockIndex* pindexPrev = chainActive.Tip(); if(!pindexPrev) return false; if(masternodeSync.IsBudgetFinEmpty()) return true; int nBlockStart = pindexPrev->nHeight - pindexPrev->nHeight % GetBudgetPaymentCycleBlocks() + GetBudgetPaymentCycleBlocks(); CAmount amount = 1440; if (Params().NetworkID() == CBaseChainParams::TESTNET) { // Relatively 43200 / 30 = 1440, for testnet 50 / 30 ~ 2 amount = 2; } if(nBlockStart - pindexPrev->nHeight > amount*2) return true; //we wouldn't have the budget yet if(budget.IsBudgetPaymentBlock(nBlockStart)) return true; LogPrintf("CBudgetManager::HasNextFinalizedBudget() - Client is missing budget - %lli\n", nBlockStart); return false; } bool CBudgetManager::IsTransactionValid(const CTransaction& txNew, int nBlockHeight) { LOCK(cs); int nHighestCount = 0; std::vector<CFinalizedBudget*> ret; // ------- Grab The Highest Count std::map<uint256, CFinalizedBudget>::iterator it = mapFinalizedBudgets.begin(); while(it != mapFinalizedBudgets.end()) { CFinalizedBudget* pfinalizedBudget = &((*it).second); if(pfinalizedBudget->GetVoteCount() > nHighestCount && nBlockHeight >= pfinalizedBudget->GetBlockStart() && nBlockHeight <= pfinalizedBudget->GetBlockEnd()){ nHighestCount = pfinalizedBudget->GetVoteCount(); } ++it; } /* If budget doesn't have 5% of the network votes, then we should pay a masternode instead */ if(20 * nHighestCount < mnodeman.CountEnabled(MIN_BUDGET_PEER_PROTO_VERSION)) return false; // check the highest finalized budgets (+/- 10% to assist in consensus) it = mapFinalizedBudgets.begin(); while(it != mapFinalizedBudgets.end()) { CFinalizedBudget* pfinalizedBudget = &((*it).second); if(10 * (nHighestCount - pfinalizedBudget->GetVoteCount()) < mnodeman.CountEnabled(MIN_BUDGET_PEER_PROTO_VERSION)){ if(nBlockHeight >= pfinalizedBudget->GetBlockStart() && nBlockHeight <= pfinalizedBudget->GetBlockEnd()){ if(pfinalizedBudget->IsTransactionValid(txNew, nBlockHeight)){ return true; } } } ++it; } //we looked through all of the known budgets return false; } std::vector<CBudgetProposal*> CBudgetManager::GetAllProposals() { LOCK(cs); std::vector<CBudgetProposal*> vBudgetProposalRet; std::map<uint256, CBudgetProposal>::iterator it = mapProposals.begin(); while(it != mapProposals.end()) { (*it).second.CleanAndRemove(false); CBudgetProposal* pbudgetProposal = &((*it).second); vBudgetProposalRet.push_back(pbudgetProposal); ++it; } return vBudgetProposalRet; } // // Sort by votes, if there's a tie sort by their feeHash TX // struct sortProposalsByVotes { bool operator()(const std::pair<CBudgetProposal*, int> &left, const std::pair<CBudgetProposal*, int> &right) { if( left.second != right.second) return (left.second > right.second); return (UintToArith256(left.first->nFeeTXHash) > UintToArith256(right.first->nFeeTXHash)); } }; //Need to review this function std::vector<CBudgetProposal*> CBudgetManager::GetBudget() { LOCK(cs); // ------- Sort budgets by Yes Count std::vector<std::pair<CBudgetProposal*, int> > vBudgetPorposalsSort; std::map<uint256, CBudgetProposal>::iterator it = mapProposals.begin(); while(it != mapProposals.end()){ (*it).second.CleanAndRemove(false); vBudgetPorposalsSort.push_back(make_pair(&((*it).second), (*it).second.GetYeas()-(*it).second.GetNays())); ++it; } std::sort(vBudgetPorposalsSort.begin(), vBudgetPorposalsSort.end(), sortProposalsByVotes()); // ------- Grab The Budgets In Order std::vector<CBudgetProposal*> vBudgetProposalsRet; CAmount nBudgetAllocated = 0; CBlockIndex* pindexPrev = chainActive.Tip(); if(pindexPrev == NULL) return vBudgetProposalsRet; int nBlockStart = pindexPrev->nHeight - pindexPrev->nHeight % GetBudgetPaymentCycleBlocks() + GetBudgetPaymentCycleBlocks(); int nBlockEnd = nBlockStart + GetBudgetPaymentCycleBlocks() - 1; CAmount nTotalBudget = GetTotalBudget(nBlockStart); std::vector<std::pair<CBudgetProposal*, int> >::iterator it2 = vBudgetPorposalsSort.begin(); while(it2 != vBudgetPorposalsSort.end()) { CBudgetProposal* pbudgetProposal = (*it2).first; //prop start/end should be inside this period if(pbudgetProposal->fValid && pbudgetProposal->nBlockStart <= nBlockStart && pbudgetProposal->nBlockEnd >= nBlockEnd && pbudgetProposal->GetYeas() - pbudgetProposal->GetNays() > mnodeman.CountEnabled(MIN_BUDGET_PEER_PROTO_VERSION)/10 && pbudgetProposal->IsEstablished()) { if(pbudgetProposal->GetAmount() + nBudgetAllocated <= nTotalBudget) { pbudgetProposal->SetAllotted(pbudgetProposal->GetAmount()); nBudgetAllocated += pbudgetProposal->GetAmount(); vBudgetProposalsRet.push_back(pbudgetProposal); } else { pbudgetProposal->SetAllotted(0); } } ++it2; } return vBudgetProposalsRet; } struct sortFinalizedBudgetsByVotes { bool operator()(const std::pair<CFinalizedBudget*, int> &left, const std::pair<CFinalizedBudget*, int> &right) { return left.second > right.second; } }; std::vector<CFinalizedBudget*> CBudgetManager::GetFinalizedBudgets() { LOCK(cs); std::vector<CFinalizedBudget*> vFinalizedBudgetsRet; std::vector<std::pair<CFinalizedBudget*, int> > vFinalizedBudgetsSort; // ------- Grab The Budgets In Order std::map<uint256, CFinalizedBudget>::iterator it = mapFinalizedBudgets.begin(); while(it != mapFinalizedBudgets.end()) { CFinalizedBudget* pfinalizedBudget = &((*it).second); vFinalizedBudgetsSort.push_back(make_pair(pfinalizedBudget, pfinalizedBudget->GetVoteCount())); ++it; } std::sort(vFinalizedBudgetsSort.begin(), vFinalizedBudgetsSort.end(), sortFinalizedBudgetsByVotes()); std::vector<std::pair<CFinalizedBudget*, int> >::iterator it2 = vFinalizedBudgetsSort.begin(); while(it2 != vFinalizedBudgetsSort.end()) { vFinalizedBudgetsRet.push_back((*it2).first); ++it2; } return vFinalizedBudgetsRet; } std::string CBudgetManager::GetRequiredPaymentsString(int nBlockHeight) { LOCK(cs); std::string ret = "unknown-budget"; std::map<uint256, CFinalizedBudget>::iterator it = mapFinalizedBudgets.begin(); while(it != mapFinalizedBudgets.end()) { CFinalizedBudget* pfinalizedBudget = &((*it).second); if(nBlockHeight >= pfinalizedBudget->GetBlockStart() && nBlockHeight <= pfinalizedBudget->GetBlockEnd()){ CTxBudgetPayment payment; if(pfinalizedBudget->GetBudgetPaymentByBlock(nBlockHeight, payment)){ if(ret == "unknown-budget"){ ret = payment.nProposalHash.ToString(); } else { ret += ","; ret += payment.nProposalHash.ToString(); } } else { LogPrintf("CBudgetManager::GetRequiredPaymentsString - Couldn't find budget payment for block %d\n", nBlockHeight); } } ++it; } return ret; } CAmount CBudgetManager::GetTotalBudget(int nHeight) { if(chainActive.Tip() == NULL) return 0; //get min block value and calculate from that CAmount nSubsidy = 10 * COIN; int halvings = nHeight / Params().SubsidyHalvingInterval(); // Subsidy is cut in half every 2,100,000 blocks which will occur approximately every 4 years. nSubsidy >>= halvings; // Amount of blocks in a months period of time (using 1 minutes per) = (60*24*30)/1 if(Params().NetworkID() == CBaseChainParams::MAIN) return ((nSubsidy/100)*10)*1440*30; //for testing purposes return ((nSubsidy/100)*10)*50; } void CBudgetManager::NewBlock() { TRY_LOCK(cs, fBudgetNewBlock); if(!fBudgetNewBlock) return; if (masternodeSync.RequestedMasternodeAssets <= MASTERNODE_SYNC_BUDGET) return; if (strBudgetMode == "suggest") { //suggest the budget we see SubmitFinalBudget(); } //this function should be called 1/6 blocks, allowing up to 100 votes per day on all proposals if(chainActive.Height() % 6 != 0) return; // incremental sync with our peers if(masternodeSync.IsSynced()){ LogPrintf("CBudgetManager::NewBlock - incremental sync started\n"); if(chainActive.Height() % 600 == rand() % 600) { ClearSeen(); ResetSync(); } LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) if(pnode->nVersion >= MIN_BUDGET_PEER_PROTO_VERSION) Sync(pnode, uint256(), true); MarkSynced(); } CheckAndRemove(); //remove invalid votes once in a while (we have to check the signatures and validity of every vote, somewhat CPU intensive) LogPrintf("CBudgetManager::NewBlock - askedForSourceProposalOrBudget cleanup - size: %d\n", askedForSourceProposalOrBudget.size()); std::map<uint256, int64_t>::iterator it = askedForSourceProposalOrBudget.begin(); while(it != askedForSourceProposalOrBudget.end()){ if((*it).second > GetTime() - (60*60*24)){ ++it; } else { askedForSourceProposalOrBudget.erase(it++); } } LogPrintf("CBudgetManager::NewBlock - mapProposals cleanup - size: %d\n", mapProposals.size()); std::map<uint256, CBudgetProposal>::iterator it2 = mapProposals.begin(); while(it2 != mapProposals.end()){ (*it2).second.CleanAndRemove(false); ++it2; } LogPrintf("CBudgetManager::NewBlock - mapFinalizedBudgets cleanup - size: %d\n", mapFinalizedBudgets.size()); std::map<uint256, CFinalizedBudget>::iterator it3 = mapFinalizedBudgets.begin(); while(it3 != mapFinalizedBudgets.end()){ (*it3).second.CleanAndRemove(false); ++it3; } LogPrintf("CBudgetManager::NewBlock - vecImmatureBudgetProposals cleanup - size: %d\n", vecImmatureBudgetProposals.size()); std::vector<CBudgetProposalBroadcast>::iterator it4 = vecImmatureBudgetProposals.begin(); while(it4 != vecImmatureBudgetProposals.end()) { std::string strError = ""; int nConf = 0; if(!IsBudgetCollateralValid((*it4).nFeeTXHash, (*it4).GetHash(), strError, (*it4).nTime, nConf)){ ++it4; continue; } if(!(*it4).IsValid(strError)) { LogPrintf("mprop (immature) - invalid budget proposal - %s\n", strError); it4 = vecImmatureBudgetProposals.erase(it4); continue; } CBudgetProposal budgetProposal((*it4)); if(AddProposal(budgetProposal)) {(*it4).Relay();} LogPrintf("mprop (immature) - new budget - %s\n", (*it4).GetHash().ToString()); it4 = vecImmatureBudgetProposals.erase(it4); } LogPrintf("CBudgetManager::NewBlock - vecImmatureFinalizedBudgets cleanup - size: %d\n", vecImmatureFinalizedBudgets.size()); std::vector<CFinalizedBudgetBroadcast>::iterator it5 = vecImmatureFinalizedBudgets.begin(); while(it5 != vecImmatureFinalizedBudgets.end()) { std::string strError = ""; int nConf = 0; if(!IsBudgetCollateralValid((*it5).nFeeTXHash, (*it5).GetHash(), strError, (*it5).nTime, nConf)){ ++it5; continue; } if(!(*it5).IsValid(strError)) { LogPrintf("fbs (immature) - invalid finalized budget - %s\n", strError); it5 = vecImmatureFinalizedBudgets.erase(it5); continue; } LogPrintf("fbs (immature) - new finalized budget - %s\n", (*it5).GetHash().ToString()); CFinalizedBudget finalizedBudget((*it5)); if(AddFinalizedBudget(finalizedBudget)) {(*it5).Relay();} it5 = vecImmatureFinalizedBudgets.erase(it5); } LogPrintf("CBudgetManager::NewBlock - PASSED\n"); } void CBudgetManager::ProcessMessage(CNode* pfrom, std::string& strCommand, CDataStream& vRecv) { // lite mode is not supported if(fLiteMode) return; if(!masternodeSync.IsBlockchainSynced()) return; LOCK(cs_budget); if (strCommand == "mnvs") { //Masternode vote sync uint256 nProp; vRecv >> nProp; if(Params().NetworkID() == CBaseChainParams::MAIN){ if(nProp.IsNull()) { if(pfrom->HasFulfilledRequest("mnvs")) { LogPrintf("mnvs - peer already asked me for the list\n"); Misbehaving(pfrom->GetId(), 20); return; } pfrom->FulfilledRequest("mnvs"); } } Sync(pfrom, nProp); LogPrintf("mnvs - Sent Masternode votes to %s\n", pfrom->addr.ToString()); } if (strCommand == "mprop") { //Masternode Proposal CBudgetProposalBroadcast budgetProposalBroadcast; vRecv >> budgetProposalBroadcast; if(mapSeenMasternodeBudgetProposals.count(budgetProposalBroadcast.GetHash())){ masternodeSync.AddedBudgetItem(budgetProposalBroadcast.GetHash()); return; } std::string strError = ""; int nConf = 0; if(!IsBudgetCollateralValid(budgetProposalBroadcast.nFeeTXHash, budgetProposalBroadcast.GetHash(), strError, budgetProposalBroadcast.nTime, nConf)){ LogPrintf("Proposal FeeTX is not valid - %s - %s\n", budgetProposalBroadcast.nFeeTXHash.ToString(), strError); if(nConf >= 1) vecImmatureBudgetProposals.push_back(budgetProposalBroadcast); return; } mapSeenMasternodeBudgetProposals.insert(make_pair(budgetProposalBroadcast.GetHash(), budgetProposalBroadcast)); if(!budgetProposalBroadcast.IsValid(strError)) { LogPrintf("mprop - invalid budget proposal - %s\n", strError); return; } CBudgetProposal budgetProposal(budgetProposalBroadcast); if(AddProposal(budgetProposal)) {budgetProposalBroadcast.Relay();} masternodeSync.AddedBudgetItem(budgetProposalBroadcast.GetHash()); LogPrintf("mprop - new budget - %s\n", budgetProposalBroadcast.GetHash().ToString()); //We might have active votes for this proposal that are valid now CheckOrphanVotes(); } if (strCommand == "mvote") { //Masternode Vote CBudgetVote vote; vRecv >> vote; vote.fValid = true; if(mapSeenMasternodeBudgetVotes.count(vote.GetHash())){ masternodeSync.AddedBudgetItem(vote.GetHash()); return; } CMasternode* pmn = mnodeman.Find(vote.vin); if(pmn == NULL) { LogPrint("mnbudget", "mvote - unknown masternode - vin: %s\n", vote.vin.ToString()); mnodeman.AskForMN(pfrom, vote.vin); return; } mapSeenMasternodeBudgetVotes.insert(make_pair(vote.GetHash(), vote)); if(!vote.SignatureValid(true)){ LogPrintf("mvote - signature invalid\n"); if(masternodeSync.IsSynced()) Misbehaving(pfrom->GetId(), 20); // it could just be a non-synced masternode mnodeman.AskForMN(pfrom, vote.vin); return; } std::string strError = ""; if(UpdateProposal(vote, pfrom, strError)) { vote.Relay(); masternodeSync.AddedBudgetItem(vote.GetHash()); } LogPrintf("mvote - new budget vote - %s\n", vote.GetHash().ToString()); } if (strCommand == "fbs") { //Finalized Budget Suggestion CFinalizedBudgetBroadcast finalizedBudgetBroadcast; vRecv >> finalizedBudgetBroadcast; if(mapSeenFinalizedBudgets.count(finalizedBudgetBroadcast.GetHash())){ masternodeSync.AddedBudgetItem(finalizedBudgetBroadcast.GetHash()); return; } std::string strError = ""; int nConf = 0; if(!IsBudgetCollateralValid(finalizedBudgetBroadcast.nFeeTXHash, finalizedBudgetBroadcast.GetHash(), strError, finalizedBudgetBroadcast.nTime, nConf)){ LogPrintf("Finalized Budget FeeTX is not valid - %s - %s\n", finalizedBudgetBroadcast.nFeeTXHash.ToString(), strError); if(nConf >= 1) vecImmatureFinalizedBudgets.push_back(finalizedBudgetBroadcast); return; } mapSeenFinalizedBudgets.insert(make_pair(finalizedBudgetBroadcast.GetHash(), finalizedBudgetBroadcast)); if(!finalizedBudgetBroadcast.IsValid(strError)) { LogPrintf("fbs - invalid finalized budget - %s\n", strError); return; } LogPrintf("fbs - new finalized budget - %s\n", finalizedBudgetBroadcast.GetHash().ToString()); CFinalizedBudget finalizedBudget(finalizedBudgetBroadcast); if(AddFinalizedBudget(finalizedBudget)) {finalizedBudgetBroadcast.Relay();} masternodeSync.AddedBudgetItem(finalizedBudgetBroadcast.GetHash()); //we might have active votes for this budget that are now valid CheckOrphanVotes(); } if (strCommand == "fbvote") { //Finalized Budget Vote CFinalizedBudgetVote vote; vRecv >> vote; vote.fValid = true; if(mapSeenFinalizedBudgetVotes.count(vote.GetHash())){ masternodeSync.AddedBudgetItem(vote.GetHash()); return; } CMasternode* pmn = mnodeman.Find(vote.vin); if(pmn == NULL) { LogPrint("mnbudget", "fbvote - unknown masternode - vin: %s\n", vote.vin.ToString()); mnodeman.AskForMN(pfrom, vote.vin); return; } mapSeenFinalizedBudgetVotes.insert(make_pair(vote.GetHash(), vote)); if(!vote.SignatureValid(true)){ LogPrintf("fbvote - signature invalid\n"); if(masternodeSync.IsSynced()) Misbehaving(pfrom->GetId(), 20); // it could just be a non-synced masternode mnodeman.AskForMN(pfrom, vote.vin); return; } std::string strError = ""; if(UpdateFinalizedBudget(vote, pfrom, strError)) { vote.Relay(); masternodeSync.AddedBudgetItem(vote.GetHash()); LogPrintf("fbvote - new finalized budget vote - %s\n", vote.GetHash().ToString()); } else { LogPrintf("fbvote - rejected finalized budget vote - %s - %s\n", vote.GetHash().ToString(), strError); } } } bool CBudgetManager::PropExists(uint256 nHash) { if(mapProposals.count(nHash)) return true; return false; } //mark that a full sync is needed void CBudgetManager::ResetSync() { LOCK(cs); std::map<uint256, CBudgetProposalBroadcast>::iterator it1 = mapSeenMasternodeBudgetProposals.begin(); while(it1 != mapSeenMasternodeBudgetProposals.end()){ CBudgetProposal* pbudgetProposal = FindProposal((*it1).first); if(pbudgetProposal && pbudgetProposal->fValid){ //mark votes std::map<uint256, CBudgetVote>::iterator it2 = pbudgetProposal->mapVotes.begin(); while(it2 != pbudgetProposal->mapVotes.end()){ (*it2).second.fSynced = false; ++it2; } } ++it1; } std::map<uint256, CFinalizedBudgetBroadcast>::iterator it3 = mapSeenFinalizedBudgets.begin(); while(it3 != mapSeenFinalizedBudgets.end()){ CFinalizedBudget* pfinalizedBudget = FindFinalizedBudget((*it3).first); if(pfinalizedBudget && pfinalizedBudget->fValid){ //send votes std::map<uint256, CFinalizedBudgetVote>::iterator it4 = pfinalizedBudget->mapVotes.begin(); while(it4 != pfinalizedBudget->mapVotes.end()){ (*it4).second.fSynced = false; ++it4; } } ++it3; } } void CBudgetManager::MarkSynced() { LOCK(cs); /* Mark that we've sent all valid items */ std::map<uint256, CBudgetProposalBroadcast>::iterator it1 = mapSeenMasternodeBudgetProposals.begin(); while(it1 != mapSeenMasternodeBudgetProposals.end()){ CBudgetProposal* pbudgetProposal = FindProposal((*it1).first); if(pbudgetProposal && pbudgetProposal->fValid){ //mark votes std::map<uint256, CBudgetVote>::iterator it2 = pbudgetProposal->mapVotes.begin(); while(it2 != pbudgetProposal->mapVotes.end()){ if((*it2).second.fValid) (*it2).second.fSynced = true; ++it2; } } ++it1; } std::map<uint256, CFinalizedBudgetBroadcast>::iterator it3 = mapSeenFinalizedBudgets.begin(); while(it3 != mapSeenFinalizedBudgets.end()){ CFinalizedBudget* pfinalizedBudget = FindFinalizedBudget((*it3).first); if(pfinalizedBudget && pfinalizedBudget->fValid){ //mark votes std::map<uint256, CFinalizedBudgetVote>::iterator it4 = pfinalizedBudget->mapVotes.begin(); while(it4 != pfinalizedBudget->mapVotes.end()){ if((*it4).second.fValid) (*it4).second.fSynced = true; ++it4; } } ++it3; } } void CBudgetManager::Sync(CNode* pfrom, uint256 nProp, bool fPartial) { LOCK(cs); /* Sync with a client on the network -- This code checks each of the hash maps for all known budget proposals and finalized budget proposals, then checks them against the budget object to see if they're OK. If all checks pass, we'll send it to the peer. */ int nInvCount = 0; std::map<uint256, CBudgetProposalBroadcast>::iterator it1 = mapSeenMasternodeBudgetProposals.begin(); while(it1 != mapSeenMasternodeBudgetProposals.end()){ CBudgetProposal* pbudgetProposal = FindProposal((*it1).first); if(pbudgetProposal && pbudgetProposal->fValid && (nProp.IsNull() || (*it1).first == nProp)){ pfrom->PushInventory(CInv(MSG_BUDGET_PROPOSAL, (*it1).second.GetHash())); nInvCount++; //send votes std::map<uint256, CBudgetVote>::iterator it2 = pbudgetProposal->mapVotes.begin(); while(it2 != pbudgetProposal->mapVotes.end()){ if((*it2).second.fValid){ if((fPartial && !(*it2).second.fSynced) || !fPartial) { pfrom->PushInventory(CInv(MSG_BUDGET_VOTE, (*it2).second.GetHash())); nInvCount++; } } ++it2; } } ++it1; } pfrom->PushMessage("ssc", MASTERNODE_SYNC_BUDGET_PROP, nInvCount); LogPrintf("CBudgetManager::Sync - sent %d items\n", nInvCount); nInvCount = 0; std::map<uint256, CFinalizedBudgetBroadcast>::iterator it3 = mapSeenFinalizedBudgets.begin(); while(it3 != mapSeenFinalizedBudgets.end()){ CFinalizedBudget* pfinalizedBudget = FindFinalizedBudget((*it3).first); if(pfinalizedBudget && pfinalizedBudget->fValid && (nProp.IsNull() || (*it3).first == nProp)){ pfrom->PushInventory(CInv(MSG_BUDGET_FINALIZED, (*it3).second.GetHash())); nInvCount++; //send votes std::map<uint256, CFinalizedBudgetVote>::iterator it4 = pfinalizedBudget->mapVotes.begin(); while(it4 != pfinalizedBudget->mapVotes.end()){ if((*it4).second.fValid) { if((fPartial && !(*it4).second.fSynced) || !fPartial) { pfrom->PushInventory(CInv(MSG_BUDGET_FINALIZED_VOTE, (*it4).second.GetHash())); nInvCount++; } } ++it4; } } ++it3; } pfrom->PushMessage("ssc", MASTERNODE_SYNC_BUDGET_FIN, nInvCount); LogPrintf("CBudgetManager::Sync - sent %d items\n", nInvCount); } bool CBudgetManager::UpdateProposal(CBudgetVote& vote, CNode* pfrom, std::string& strError) { LOCK(cs); if(!mapProposals.count(vote.nProposalHash)){ if(pfrom){ // only ask for missing items after our syncing process is complete -- // otherwise we'll think a full sync succeeded when they return a result if(!masternodeSync.IsSynced()) return false; LogPrintf("CBudgetManager::UpdateProposal - Unknown proposal %d, asking for source proposal\n", vote.nProposalHash.ToString()); mapOrphanMasternodeBudgetVotes[vote.nProposalHash] = vote; if(!askedForSourceProposalOrBudget.count(vote.nProposalHash)){ pfrom->PushMessage("mnvs", vote.nProposalHash); askedForSourceProposalOrBudget[vote.nProposalHash] = GetTime(); } } strError = "Proposal not found!"; return false; } auto proposal = mapProposals[vote.nProposalHash]; if(!proposal.AddOrUpdateVote(vote, strError)) return false; if (fMasterNode) { for (auto& fbpair: mapFinalizedBudgets) { auto& finalBudget = fbpair.second; if (finalBudget.IsValid() && !finalBudget.IsVoteSubmitted()) finalBudget.ResetAutoChecked(); } } return true; } bool CBudgetManager::UpdateFinalizedBudget(CFinalizedBudgetVote& vote, CNode* pfrom, std::string& strError) { LOCK(cs); if(!mapFinalizedBudgets.count(vote.nBudgetHash)){ if(pfrom){ // only ask for missing items after our syncing process is complete -- // otherwise we'll think a full sync succeeded when they return a result if(!masternodeSync.IsSynced()) return false; LogPrintf("CBudgetManager::UpdateFinalizedBudget - Unknown Finalized Proposal %s, asking for source budget\n", vote.nBudgetHash.ToString()); mapOrphanFinalizedBudgetVotes[vote.nBudgetHash] = vote; if(!askedForSourceProposalOrBudget.count(vote.nBudgetHash)){ pfrom->PushMessage("mnvs", vote.nBudgetHash); askedForSourceProposalOrBudget[vote.nBudgetHash] = GetTime(); } } strError = "Finalized Budget not found!"; return false; } return mapFinalizedBudgets[vote.nBudgetHash].AddOrUpdateVote(vote, strError); } CBudgetProposal::CBudgetProposal() { strProposalName = "unknown"; nBlockStart = 0; nBlockEnd = 0; nAmount = 0; nTime = 0; fValid = true; } CBudgetProposal::CBudgetProposal(std::string strProposalNameIn, std::string strURLIn, int nBlockStartIn, int nBlockEndIn, CScript addressIn, CAmount nAmountIn, uint256 nFeeTXHashIn) { strProposalName = strProposalNameIn; strURL = strURLIn; nBlockStart = nBlockStartIn; nBlockEnd = nBlockEndIn; address = addressIn; nAmount = nAmountIn; nFeeTXHash = nFeeTXHashIn; fValid = true; } CBudgetProposal::CBudgetProposal(const CBudgetProposal& other) { strProposalName = other.strProposalName; strURL = other.strURL; nBlockStart = other.nBlockStart; nBlockEnd = other.nBlockEnd; address = other.address; nAmount = other.nAmount; nTime = other.nTime; nFeeTXHash = other.nFeeTXHash; mapVotes = other.mapVotes; fValid = true; } bool CBudgetProposal::IsValid(std::string& strError, bool fCheckCollateral) { if(GetNays() - GetYeas() > mnodeman.CountEnabled(MIN_BUDGET_PEER_PROTO_VERSION)/10){ strError = "Active removal"; return false; } if(nBlockStart < 0) { strError = "Invalid Proposal"; return false; } if(nBlockEnd < nBlockStart) { strError = "Invalid nBlockEnd"; return false; } if(nAmount < 1*COIN) { strError = "Invalid nAmount"; return false; } if(address == CScript()) { strError = "Invalid Payment Address"; return false; } if(fCheckCollateral){ int nConf = 0; if(!IsBudgetCollateralValid(nFeeTXHash, GetHash(), strError, nTime, nConf)){ return false; } } /* TODO: There might be an issue with multisig in the coinbase on mainnet, we will add support for it in a future release. */ if(address.IsPayToScriptHash()) { strError = "Multisig is not currently supported."; return false; } //if proposal doesn't gain traction within 2 weeks, remove it // nTime not being saved correctly // -- TODO: We should keep track of the last time the proposal was valid, if it's invalid for 2 weeks, erase it // if(nTime + (60*60*24*2) < GetAdjustedTime()) { // if(GetYeas()-GetNays() < (mnodeman.CountEnabled(MIN_BUDGET_PEER_PROTO_VERSION)/10)) { // strError = "Not enough support"; // return false; // } // } //can only pay out 10% of the possible coins (min value of coins) if(nAmount > budget.GetTotalBudget(nBlockStart)) { strError = "Payment more than max"; return false; } CBlockIndex* pindexPrev = chainActive.Tip(); if(pindexPrev == NULL) {strError = "Tip is NULL"; return true;} if(GetBlockEnd() < pindexPrev->nHeight - GetBudgetPaymentCycleBlocks()/2 ) return false; return true; } bool CBudgetProposal::AddOrUpdateVote(CBudgetVote& vote, std::string& strError) { LOCK(cs); uint256 hash = vote.vin.prevout.GetHash(); if(mapVotes.count(hash)){ if(mapVotes[hash].nTime > vote.nTime){ strError = strprintf("new vote older than existing vote - %s\n", vote.GetHash().ToString()); LogPrint("mnbudget", "CBudgetProposal::AddOrUpdateVote - %s\n", strError); return false; } if(vote.nTime - mapVotes[hash].nTime < BUDGET_VOTE_UPDATE_MIN){ strError = strprintf("time between votes is too soon - %s - %lli\n", vote.GetHash().ToString(), vote.nTime - mapVotes[hash].nTime); LogPrint("mnbudget", "CBudgetProposal::AddOrUpdateVote - %s\n", strError); return false; } } if(vote.nTime > GetTime() + (60*60)){ strError = strprintf("new vote is too far ahead of current time - %s - nTime %lli - Max Time %lli\n", vote.GetHash().ToString(), vote.nTime, GetTime() + (60*60)); LogPrint("mnbudget", "CBudgetProposal::AddOrUpdateVote - %s\n", strError); return false; } mapVotes[hash] = vote; return true; } // If masternode voted for a proposal, but is now invalid -- remove the vote void CBudgetProposal::CleanAndRemove(bool fSignatureCheck) { std::map<uint256, CBudgetVote>::iterator it = mapVotes.begin(); while(it != mapVotes.end()) { (*it).second.fValid = (*it).second.SignatureValid(fSignatureCheck); ++it; } } double CBudgetProposal::GetRatio() const { int yeas = 0; int nays = 0; for (const auto& pair: mapVotes) { if (pair.second.nVote == VOTE_YES) ++yeas; if (pair.second.nVote == VOTE_NO) ++nays; } if(yeas + nays == 0) return 0.0f; return ((double)(yeas) / (double)(yeas+nays)); } int CBudgetProposal::GetYeas() const { int ret = 0; for (const auto& pair: mapVotes) { if (pair.second.nVote == VOTE_YES && pair.second.fValid) ++ret; } return ret; } int CBudgetProposal::GetNays() const { int ret = 0; for (const auto& pair: mapVotes) { if (pair.second.nVote == VOTE_NO && pair.second.fValid) ++ret; } return ret; } int CBudgetProposal::GetAbstains() const { int ret = 0; for (const auto& pair: mapVotes) { if (pair.second.nVote == VOTE_ABSTAIN && pair.second.fValid) ++ret; } return ret; } int CBudgetProposal::GetBlockStartCycle() const { //end block is half way through the next cycle (so the proposal will be removed much after the payment is sent) return nBlockStart - nBlockStart % GetBudgetPaymentCycleBlocks(); } int CBudgetProposal::GetBlockCurrentCycle() const { CBlockIndex* pindexPrev = chainActive.Tip(); if(pindexPrev == nullptr) return -1; if(pindexPrev->nHeight >= GetBlockEndCycle()) return -1; return pindexPrev->nHeight - pindexPrev->nHeight % GetBudgetPaymentCycleBlocks(); } int CBudgetProposal::GetBlockEndCycle() const { //end block is half way through the next cycle (so the proposal will be removed much after the payment is sent) return nBlockEnd - GetBudgetPaymentCycleBlocks() / 2; } int CBudgetProposal::GetTotalPaymentCount() const { return (GetBlockEndCycle() - GetBlockStartCycle()) / GetBudgetPaymentCycleBlocks(); } int CBudgetProposal::GetRemainingPaymentCount() const { // If this budget starts in the future, this value will be wrong int nPayments = (GetBlockEndCycle() - GetBlockCurrentCycle()) / GetBudgetPaymentCycleBlocks() - 1; // Take the lowest value return std::min(nPayments, GetTotalPaymentCount()); } CBudgetProposalBroadcast::CBudgetProposalBroadcast(std::string strProposalNameIn, std::string strURLIn, int nPaymentCount, CScript addressIn, CAmount nAmountIn, int nBlockStartIn, uint256 nFeeTXHashIn) { strProposalName = strProposalNameIn; strURL = strURLIn; nBlockStart = nBlockStartIn; int nCycleStart = nBlockStart - nBlockStart % GetBudgetPaymentCycleBlocks(); //calculate the end of the cycle for this vote, add half a cycle (vote will be deleted after that block) nBlockEnd = nCycleStart + GetBudgetPaymentCycleBlocks() * nPaymentCount + GetBudgetPaymentCycleBlocks()/2; address = addressIn; nAmount = nAmountIn; nFeeTXHash = nFeeTXHashIn; } void CBudgetProposalBroadcast::Relay() { CInv inv(MSG_BUDGET_PROPOSAL, GetHash()); RelayInv(inv, MIN_BUDGET_PEER_PROTO_VERSION); } CBudgetVote::CBudgetVote() { vin = CTxIn(); nProposalHash = uint256(); nVote = VOTE_ABSTAIN; nTime = 0; fValid = true; fSynced = false; } CBudgetVote::CBudgetVote(CTxIn vinIn, uint256 nProposalHashIn, int nVoteIn) { vin = vinIn; nProposalHash = nProposalHashIn; nVote = nVoteIn; nTime = GetAdjustedTime(); fValid = true; fSynced = false; } void CBudgetVote::Relay() { CInv inv(MSG_BUDGET_VOTE, GetHash()); RelayInv(inv, MIN_BUDGET_PEER_PROTO_VERSION); } bool CBudgetVote::Sign(CKey& keyMasternode, CPubKey& pubKeyMasternode) { // Choose coins to use CPubKey pubKeyCollateralAddress; CKey keyCollateralAddress; std::string errorMessage; std::string strMessage = vin.prevout.ToStringShort() + nProposalHash.ToString() + boost::lexical_cast<std::string>(nVote) + boost::lexical_cast<std::string>(nTime); if(!legacySigner.SignMessage(strMessage, errorMessage, vchSig, keyMasternode)) { LogPrintf("CBudgetVote::Sign - Error upon calling SignMessage"); return false; } if(!legacySigner.VerifyMessage(pubKeyMasternode, vchSig, strMessage, errorMessage)) { LogPrintf("CBudgetVote::Sign - Error upon calling VerifyMessage"); return false; } return true; } bool CBudgetVote::SignatureValid(bool fSignatureCheck) const { std::string errorMessage; std::string strMessage = vin.prevout.ToStringShort() + nProposalHash.ToString() + boost::lexical_cast<std::string>(nVote) + boost::lexical_cast<std::string>(nTime); CMasternode* pmn = mnodeman.Find(vin); if(pmn == NULL) { LogPrint("mnbudget", "CBudgetVote::SignatureValid() - Unknown Masternode - %s\n", vin.ToString()); return false; } if(!fSignatureCheck) return true; if(!legacySigner.VerifyMessage(pmn->pubkey2, vchSig, strMessage, errorMessage)) { LogPrintf("CBudgetVote::SignatureValid() - Verify message failed\n"); return false; } return true; } CFinalizedBudget::CFinalizedBudget() { strBudgetName = ""; nBlockStart = 0; vecBudgetPayments.clear(); mapVotes.clear(); nFeeTXHash = uint256(); nTime = 0; fValid = true; fAutoChecked = false; voteSubmittedTime = boost::none; } CFinalizedBudget::CFinalizedBudget(const CFinalizedBudget& other) { strBudgetName = other.strBudgetName; nBlockStart = other.nBlockStart; vecBudgetPayments = other.vecBudgetPayments; mapVotes = other.mapVotes; nFeeTXHash = other.nFeeTXHash; nTime = other.nTime; fValid = true; fAutoChecked = false; voteSubmittedTime = boost::none; } bool CFinalizedBudget::AddOrUpdateVote(const CFinalizedBudgetVote& vote, std::string& strError) { LOCK(cs); auto masternodeHash = vote.vin.prevout.GetHash(); auto voteHash = vote.GetHash(); auto found = mapVotes.find(masternodeHash); if(found != std::end(mapVotes)){ auto&& previousVote = found->second; if (previousVote.GetHash() == vote.GetHash()) { LogPrint("mnbudget", "CFinalizedBudget::AddOrUpdateVote - Already have the vote\n"); return true; } if(previousVote.nTime > vote.nTime) { strError = strprintf("new vote older than existing vote - %s\n", vote.GetHash().ToString()); LogPrint("mnbudget", "CFinalizedBudget::AddOrUpdateVote - %s\n", strError); return false; } if(vote.nTime - previousVote.nTime < FINAL_BUDGET_VOTE_UPDATE_MIN) { strError = strprintf("time between votes is too soon - %s - %lli\n", vote.GetHash().ToString(), vote.nTime - previousVote.nTime); LogPrint("mnbudget", "CFinalizedBudget::AddOrUpdateVote - %s\n", strError); return false; } } if(vote.nTime > GetTime() + (60*60)){ strError = strprintf("new vote is too far ahead of current time - %s - nTime %lli - Max Time %lli\n", vote.GetHash().ToString(), vote.nTime, GetTime() + (60*60)); LogPrint("mnbudget", "CFinalizedBudget::AddOrUpdateVote - %s\n", strError); return false; } mapVotes.insert(found, std::make_pair(masternodeHash, vote)); return true; } //evaluate if we should vote for this. Masternode only void CFinalizedBudget::AutoCheck() { LOCK(cs); CBlockIndex* pindexPrev = chainActive.Tip(); if(!pindexPrev) return; LogPrintf("CFinalizedBudget::AutoCheck - %lli - %d\n", pindexPrev->nHeight, fAutoChecked); if(!fMasterNode || fAutoChecked) return; //do this 1 in 4 blocks -- spread out the voting activity on mainnet // -- this function is only called every sixth block, so this is really 1 in 24 blocks if(Params().NetworkID() == CBaseChainParams::MAIN && rand() % 4 != 0) { LogPrintf("CFinalizedBudget::AutoCheck - waiting\n"); return; } // Auto-check votes with an interval that does not allow to submit votes to soon if (voteSubmittedTime && GetTime() - voteSubmittedTime.get() < FINAL_BUDGET_VOTE_UPDATE_MIN) return; fAutoChecked = true; //we only need to check this once if(strBudgetMode == "auto") //only vote for exact matches { std::vector<CBudgetProposal*> vBudgetProposals = budget.GetBudget(); for(unsigned int i = 0; i < vecBudgetPayments.size(); i++){ LogPrintf("CFinalizedBudget::AutoCheck - nProp %d %s\n", i, vecBudgetPayments[i].nProposalHash.ToString()); LogPrintf("CFinalizedBudget::AutoCheck - Payee %d %s\n", i, vecBudgetPayments[i].payee.ToString()); LogPrintf("CFinalizedBudget::AutoCheck - nAmount %d %lli\n", i, vecBudgetPayments[i].nAmount); } for(unsigned int i = 0; i < vBudgetProposals.size(); i++){ LogPrintf("CFinalizedBudget::AutoCheck - nProp %d %s\n", i, vBudgetProposals[i]->GetHash().ToString()); LogPrintf("CFinalizedBudget::AutoCheck - Payee %d %s\n", i, vBudgetProposals[i]->GetPayee().ToString()); LogPrintf("CFinalizedBudget::AutoCheck - nAmount %d %lli\n", i, vBudgetProposals[i]->GetAmount()); } if(vBudgetProposals.size() == 0) { LogPrintf("CFinalizedBudget::AutoCheck - Can't get Budget, aborting\n"); return; } if(vBudgetProposals.size() != vecBudgetPayments.size()) { LogPrintf("CFinalizedBudget::AutoCheck - Budget length doesn't match\n"); return; } for(unsigned int i = 0; i < vecBudgetPayments.size(); i++){ if(i > vBudgetProposals.size() - 1) { LogPrintf("CFinalizedBudget::AutoCheck - Vector size mismatch, aborting\n"); return; } if(vecBudgetPayments[i].nProposalHash != vBudgetProposals[i]->GetHash()){ LogPrintf("CFinalizedBudget::AutoCheck - item #%d doesn't match %s %s\n", i, vecBudgetPayments[i].nProposalHash.ToString(), vBudgetProposals[i]->GetHash().ToString()); return; } // if(vecBudgetPayments[i].payee != vBudgetProposals[i]->GetPayee()){ -- triggered with false positive if(vecBudgetPayments[i].payee.ToString() != vBudgetProposals[i]->GetPayee().ToString()){ LogPrintf("CFinalizedBudget::AutoCheck - item #%d payee doesn't match %s %s\n", i, vecBudgetPayments[i].payee.ToString(), vBudgetProposals[i]->GetPayee().ToString()); return; } if(vecBudgetPayments[i].nAmount != vBudgetProposals[i]->GetAmount()){ LogPrintf("CFinalizedBudget::AutoCheck - item #%d payee doesn't match %lli %lli\n", i, vecBudgetPayments[i].nAmount, vBudgetProposals[i]->GetAmount()); return; } } LogPrintf("CFinalizedBudget::AutoCheck - Finalized Budget Matches! Submitting Vote.\n"); SubmitVote(); } } // If masternode voted for a proposal, but is now invalid -- remove the vote void CFinalizedBudget::CleanAndRemove(bool fSignatureCheck) { std::map<uint256, CFinalizedBudgetVote>::iterator it = mapVotes.begin(); while(it != mapVotes.end()) { (*it).second.fValid = (*it).second.SignatureValid(fSignatureCheck); ++it; } } CAmount CFinalizedBudget::GetTotalPayout() const { CAmount ret = 0; for(unsigned int i = 0; i < vecBudgetPayments.size(); i++){ ret += vecBudgetPayments[i].nAmount; } return ret; } std::string CFinalizedBudget::GetProposals() { LOCK(cs); std::string ret = ""; BOOST_FOREACH(CTxBudgetPayment& budgetPayment, vecBudgetPayments){ CBudgetProposal* pbudgetProposal = budget.FindProposal(budgetPayment.nProposalHash); std::string token = budgetPayment.nProposalHash.ToString(); if(pbudgetProposal) token = pbudgetProposal->GetName(); if(ret == "") {ret = token;} else {ret += "," + token;} } return ret; } std::string CFinalizedBudget::GetStatus() const { std::string retBadHashes = ""; std::string retBadPayeeOrAmount = ""; for(int nBlockHeight = GetBlockStart(); nBlockHeight <= GetBlockEnd(); nBlockHeight++) { CTxBudgetPayment budgetPayment; if(!GetBudgetPaymentByBlock(nBlockHeight, budgetPayment)){ LogPrintf("CFinalizedBudget::GetStatus - Couldn't find budget payment for block %lld\n", nBlockHeight); continue; } CBudgetProposal* pbudgetProposal = budget.FindProposal(budgetPayment.nProposalHash); if(!pbudgetProposal){ if(retBadHashes == ""){ retBadHashes = "Unknown proposal hash! Check this proposal before voting" + budgetPayment.nProposalHash.ToString(); } else { retBadHashes += "," + budgetPayment.nProposalHash.ToString(); } } else { if(pbudgetProposal->GetPayee() != budgetPayment.payee || pbudgetProposal->GetAmount() != budgetPayment.nAmount) { if(retBadPayeeOrAmount == ""){ retBadPayeeOrAmount = "Budget payee/nAmount doesn't match our proposal! " + budgetPayment.nProposalHash.ToString(); } else { retBadPayeeOrAmount += "," + budgetPayment.nProposalHash.ToString(); } } } } if(retBadHashes == "" && retBadPayeeOrAmount == "") return "OK"; return retBadHashes + retBadPayeeOrAmount; } bool CFinalizedBudget::IsValid(std::string& strError, bool fCheckCollateral) const { //must be the correct block for payment to happen (once a month) if(nBlockStart % GetBudgetPaymentCycleBlocks() != 0) {strError = "Invalid BlockStart"; return false;} if(GetBlockEnd() - nBlockStart > 100) {strError = "Invalid BlockEnd"; return false;} if((int)vecBudgetPayments.size() > 100) {strError = "Invalid budget payments count (too many)"; return false;} if(strBudgetName == "") {strError = "Invalid Budget Name"; return false;} if(nBlockStart == 0) {strError = "Invalid BlockStart == 0"; return false;} if(nFeeTXHash.IsNull()) {strError = "Invalid FeeTx.IsNull()"; return false;} //can only pay out 10% of the possible coins (min value of coins) if(GetTotalPayout() > budget.GetTotalBudget(nBlockStart)) {strError = "Invalid Payout (more than max)"; return false;} std::string strError2 = ""; if(fCheckCollateral){ if (nTime == 0) LogPrintf("CFinalizedBudget::IsValid - ERROR: nTime == 0 is unexpected\n"); int nConf = 0; int64_t nTime; if(!IsBudgetCollateralValid(nFeeTXHash, GetHash(), strError2, nTime, nConf)){ {strError = "Invalid Collateral : " + strError2; return false;} } } //TODO: if N cycles old, invalid, invalid CBlockIndex* pindexPrev = chainActive.Tip(); if(pindexPrev == NULL) return true; if(nBlockStart < pindexPrev->nHeight-100) {strError = "Older than current blockHeight"; return false;} return true; } bool CFinalizedBudget::IsValid(bool fCheckCollateral) const { using namespace std::literals; auto dummy = ""s; return IsValid(dummy, fCheckCollateral); } void CFinalizedBudget::ResetAutoChecked() { if (!IsValid()) return; fAutoChecked = false; } bool CFinalizedBudget::IsTransactionValid(const CTransaction& txNew, int nBlockHeight) { int nCurrentBudgetPayment = nBlockHeight - GetBlockStart(); if(nCurrentBudgetPayment < 0) { LogPrintf("CFinalizedBudget::IsTransactionValid - Invalid block - height: %d start: %d\n", nBlockHeight, GetBlockStart()); return false; } if(nCurrentBudgetPayment > (int)vecBudgetPayments.size() - 1) { LogPrintf("CFinalizedBudget::IsTransactionValid - Invalid block - current budget payment: %d of %d\n", nCurrentBudgetPayment + 1, (int)vecBudgetPayments.size()); return false; } bool found = false; BOOST_FOREACH(CTxOut out, txNew.vout) { if(vecBudgetPayments[nCurrentBudgetPayment].payee == out.scriptPubKey && vecBudgetPayments[nCurrentBudgetPayment].nAmount == out.nValue) found = true; } if(!found) { CTxDestination address1; ExtractDestination(vecBudgetPayments[nCurrentBudgetPayment].payee, address1); CBitcoinAddress address2(address1); LogPrintf("CFinalizedBudget::IsTransactionValid - Missing required payment - %s: %d\n", address2.ToString(), vecBudgetPayments[nCurrentBudgetPayment].nAmount); } return found; } void CFinalizedBudget::SubmitVote() { CPubKey pubKeyMasternode; CKey keyMasternode; std::string errorMessage; if(!legacySigner.SetKey(strMasterNodePrivKey, errorMessage, keyMasternode, pubKeyMasternode)){ LogPrintf("CFinalizedBudget::SubmitVote - Error upon calling SetKey\n"); return; } CFinalizedBudgetVote vote(activeMasternode.vin, GetHash()); if(!vote.Sign(keyMasternode, pubKeyMasternode)){ LogPrintf("CFinalizedBudget::SubmitVote - Failure to sign."); return; } std::string strError = ""; if(budget.UpdateFinalizedBudget(vote, NULL, strError)){ LogPrintf("CFinalizedBudget::SubmitVote - new finalized budget vote - %s\n", vote.GetHash().ToString()); budget.mapSeenFinalizedBudgetVotes.insert(make_pair(vote.GetHash(), vote)); vote.Relay(); voteSubmittedTime = GetTime(); } else { LogPrintf("CFinalizedBudget::SubmitVote : Error submitting vote - %s\n", strError); } } CFinalizedBudgetBroadcast::CFinalizedBudgetBroadcast() { strBudgetName = ""; nBlockStart = 0; vecBudgetPayments.clear(); mapVotes.clear(); vchSig.clear(); nFeeTXHash = uint256(); } CFinalizedBudgetBroadcast::CFinalizedBudgetBroadcast(const CFinalizedBudget& other) { strBudgetName = other.strBudgetName; nBlockStart = other.nBlockStart; BOOST_FOREACH(CTxBudgetPayment out, other.vecBudgetPayments) vecBudgetPayments.push_back(out); mapVotes = other.mapVotes; nFeeTXHash = other.nFeeTXHash; } CFinalizedBudgetBroadcast::CFinalizedBudgetBroadcast(std::string strBudgetNameIn, int nBlockStartIn, std::vector<CTxBudgetPayment> vecBudgetPaymentsIn, uint256 nFeeTXHashIn) { strBudgetName = strBudgetNameIn; nBlockStart = nBlockStartIn; BOOST_FOREACH(CTxBudgetPayment out, vecBudgetPaymentsIn) vecBudgetPayments.push_back(out); mapVotes.clear(); nFeeTXHash = nFeeTXHashIn; } void CFinalizedBudgetBroadcast::Relay() { CInv inv(MSG_BUDGET_FINALIZED, GetHash()); RelayInv(inv, MIN_BUDGET_PEER_PROTO_VERSION); } CFinalizedBudgetVote::CFinalizedBudgetVote() { vin = CTxIn(); nBudgetHash = uint256(); nTime = 0; vchSig.clear(); fValid = true; fSynced = false; } CFinalizedBudgetVote::CFinalizedBudgetVote(CTxIn vinIn, uint256 nBudgetHashIn) { vin = vinIn; nBudgetHash = nBudgetHashIn; nTime = GetAdjustedTime(); vchSig.clear(); fValid = true; fSynced = false; } void CFinalizedBudgetVote::Relay() { CInv inv(MSG_BUDGET_FINALIZED_VOTE, GetHash()); RelayInv(inv, MIN_BUDGET_PEER_PROTO_VERSION); } bool CFinalizedBudgetVote::Sign(CKey& keyMasternode, CPubKey& pubKeyMasternode) { // Choose coins to use CPubKey pubKeyCollateralAddress; CKey keyCollateralAddress; std::string errorMessage; std::string strMessage = vin.prevout.ToStringShort() + nBudgetHash.ToString() + boost::lexical_cast<std::string>(nTime); if(!legacySigner.SignMessage(strMessage, errorMessage, vchSig, keyMasternode)) { LogPrintf("CFinalizedBudgetVote::Sign - Error upon calling SignMessage"); return false; } if(!legacySigner.VerifyMessage(pubKeyMasternode, vchSig, strMessage, errorMessage)) { LogPrintf("CFinalizedBudgetVote::Sign - Error upon calling VerifyMessage"); return false; } return true; } bool CFinalizedBudgetVote::SignatureValid(bool fSignatureCheck) { std::string errorMessage; std::string strMessage = vin.prevout.ToStringShort() + nBudgetHash.ToString() + boost::lexical_cast<std::string>(nTime); CMasternode* pmn = mnodeman.Find(vin); if(pmn == NULL) { LogPrint("mnbudget", "CFinalizedBudgetVote::SignatureValid() - Unknown Masternode\n"); return false; } if(!fSignatureCheck) return true; if(!legacySigner.VerifyMessage(pmn->pubkey2, vchSig, strMessage, errorMessage)) { LogPrintf("CFinalizedBudgetVote::SignatureValid() - Verify message failed\n"); return false; } return true; } std::string CBudgetManager::ToString() const { std::ostringstream info; info << "Proposals: " << (int)mapProposals.size() << ", Budgets: " << (int)mapFinalizedBudgets.size() << ", Seen Budgets: " << (int)mapSeenMasternodeBudgetProposals.size() << ", Seen Budget Votes: " << (int)mapSeenMasternodeBudgetVotes.size() << ", Seen Final Budgets: " << (int)mapSeenFinalizedBudgets.size() << ", Seen Final Budget Votes: " << (int)mapSeenFinalizedBudgetVotes.size(); return info.str(); } Remove string literals Couldn't get C++14 working Issue #79 // Copyright (c) 2014-2015 The Crown developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "main.h" #include "init.h" #include "masternode-budget.h" #include "masternode.h" #include "legacysigner.h" #include "masternodeman.h" #include "masternode-sync.h" #include "util.h" #include "addrman.h" #include <boost/filesystem.hpp> #include <boost/lexical_cast.hpp> CBudgetManager budget; CCriticalSection cs_budget; std::map<uint256, int64_t> askedForSourceProposalOrBudget; std::vector<CBudgetProposalBroadcast> vecImmatureBudgetProposals; std::vector<CFinalizedBudgetBroadcast> vecImmatureFinalizedBudgets; CAmount BlocksBeforeSuperblockToSubmitFinalBudget() { assert(GetBudgetPaymentCycleBlocks() > 10); // Relatively 43200 / 30 = 1440, for testnet - equal to budget payment cycle if (Params().NetworkID() == CBaseChainParams::MAIN) return 1440 * 2; // aprox 2 days else return GetBudgetPaymentCycleBlocks() - 10; // 40 blocks for 50-block cycle } int GetBudgetPaymentCycleBlocks() { // Amount of blocks in a months period of time (using 1 minutes per) = (60*24*30)/1 if(Params().NetworkID() == CBaseChainParams::MAIN) return 43200; else return 50; //for testing purposes } bool IsBudgetCollateralValid(uint256 nTxCollateralHash, uint256 nExpectedHash, std::string& strError, int64_t& nTime, int& nConf) { CTransaction txCollateral; uint256 nBlockHash; if(!GetTransaction(nTxCollateralHash, txCollateral, nBlockHash, true)){ strError = strprintf("Can't find collateral tx %s", txCollateral.ToString()); LogPrintf ("CBudgetProposalBroadcast::IsBudgetCollateralValid - %s\n", strError); return false; } if(txCollateral.vout.size() < 1) return false; if(txCollateral.nLockTime != 0) return false; CScript findScript; findScript << OP_RETURN << ToByteVector(nExpectedHash); bool foundOpReturn = false; BOOST_FOREACH(const CTxOut o, txCollateral.vout){ if(!o.scriptPubKey.IsNormalPaymentScript() && !o.scriptPubKey.IsUnspendable()){ strError = strprintf("Invalid Script %s", txCollateral.ToString()); LogPrintf ("CBudgetProposalBroadcast::IsBudgetCollateralValid - %s\n", strError); return false; } if(o.scriptPubKey == findScript && o.nValue >= BUDGET_FEE_TX) foundOpReturn = true; } if(!foundOpReturn){ strError = strprintf("Couldn't find opReturn %s in %s", nExpectedHash.ToString(), txCollateral.ToString()); LogPrintf ("CBudgetProposalBroadcast::IsBudgetCollateralValid - %s\n", strError); return false; } // RETRIEVE CONFIRMATIONS AND NTIME /* - nTime starts as zero and is passed-by-reference out of this function and stored in the external proposal - nTime is never validated via the hashing mechanism and comes from a full-validated source (the blockchain) */ int conf = GetIXConfirmations(nTxCollateralHash); if (nBlockHash != uint256()) { BlockMap::iterator mi = mapBlockIndex.find(nBlockHash); if (mi != mapBlockIndex.end() && (*mi).second) { CBlockIndex* pindex = (*mi).second; if (chainActive.Contains(pindex)) { conf += chainActive.Height() - pindex->nHeight + 1; nTime = pindex->nTime; } } } nConf = conf; //if we're syncing we won't have instantX information, so accept 1 confirmation if(conf >= BUDGET_FEE_CONFIRMATIONS){ return true; } else { strError = strprintf("Collateral requires at least %d confirmations - %d confirmations", BUDGET_FEE_CONFIRMATIONS, conf); LogPrintf ("CBudgetProposalBroadcast::IsBudgetCollateralValid - %s - %d confirmations\n", strError, conf); return false; } } void CBudgetManager::CheckOrphanVotes() { LOCK(cs); std::string strError = ""; std::map<uint256, CBudgetVote>::iterator it1 = mapOrphanMasternodeBudgetVotes.begin(); while(it1 != mapOrphanMasternodeBudgetVotes.end()){ if(budget.UpdateProposal(((*it1).second), NULL, strError)){ LogPrintf("CBudgetManager::CheckOrphanVotes - Proposal/Budget is known, activating and removing orphan vote\n"); mapOrphanMasternodeBudgetVotes.erase(it1++); } else { ++it1; } } std::map<uint256, CFinalizedBudgetVote>::iterator it2 = mapOrphanFinalizedBudgetVotes.begin(); while(it2 != mapOrphanFinalizedBudgetVotes.end()){ if(budget.UpdateFinalizedBudget(((*it2).second),NULL, strError)){ LogPrintf("CBudgetManager::CheckOrphanVotes - Proposal/Budget is known, activating and removing orphan vote\n"); mapOrphanFinalizedBudgetVotes.erase(it2++); } else { ++it2; } } } void CBudgetManager::SubmitFinalBudget() { static int nSubmittedHeight = 0; // height at which final budget was submitted last time int nCurrentHeight; { TRY_LOCK(cs_main, locked); if(!locked) return; if(!chainActive.Tip()) return; nCurrentHeight = chainActive.Height(); } int nBlockStart = nCurrentHeight - nCurrentHeight % GetBudgetPaymentCycleBlocks() + GetBudgetPaymentCycleBlocks(); if(nSubmittedHeight >= nBlockStart) return; if(nBlockStart - nCurrentHeight > BlocksBeforeSuperblockToSubmitFinalBudget()) return; // allow submitting final budget only when 2 days left before payments std::vector<CBudgetProposal*> vBudgetProposals = budget.GetBudget(); std::string strBudgetName = "main"; std::vector<CTxBudgetPayment> vecTxBudgetPayments; for(unsigned int i = 0; i < vBudgetProposals.size(); i++){ CTxBudgetPayment txBudgetPayment; txBudgetPayment.nProposalHash = vBudgetProposals[i]->GetHash(); txBudgetPayment.payee = vBudgetProposals[i]->GetPayee(); txBudgetPayment.nAmount = vBudgetProposals[i]->GetAllotted(); vecTxBudgetPayments.push_back(txBudgetPayment); } if(vecTxBudgetPayments.size() < 1) { LogPrintf("CBudgetManager::SubmitFinalBudget - Found No Proposals For Period\n"); return; } CFinalizedBudgetBroadcast tempBudget(strBudgetName, nBlockStart, vecTxBudgetPayments, uint256()); if(mapSeenFinalizedBudgets.count(tempBudget.GetHash())) { LogPrintf("CBudgetManager::SubmitFinalBudget - Budget already exists - %s\n", tempBudget.GetHash().ToString()); nSubmittedHeight = nCurrentHeight; return; //already exists } //create fee tx CTransaction tx; uint256 txidCollateral; if(!mapCollateralTxids.count(tempBudget.GetHash())){ const bool useIX = false; CWalletTx wtx; if(!pwalletMain->GetBudgetSystemCollateralTX(wtx, tempBudget.GetHash(), useIX)){ LogPrintf("CBudgetManager::SubmitFinalBudget - Can't make collateral transaction\n"); return; } // make our change address CReserveKey reservekey(pwalletMain); //send the tx to the network pwalletMain->CommitTransaction(wtx, reservekey, useIX ? "ix" : "tx"); tx = (CTransaction)wtx; txidCollateral = tx.GetHash(); mapCollateralTxids.insert(make_pair(tempBudget.GetHash(), txidCollateral)); } else { txidCollateral = mapCollateralTxids[tempBudget.GetHash()]; } int conf = GetIXConfirmations(tx.GetHash()); CTransaction txCollateral; uint256 nBlockHash; if(!GetTransaction(txidCollateral, txCollateral, nBlockHash, true)) { LogPrintf ("CBudgetManager::SubmitFinalBudget - Can't find collateral tx %s", txidCollateral.ToString()); return; } if (nBlockHash != uint256()) { BlockMap::iterator mi = mapBlockIndex.find(nBlockHash); if (mi != mapBlockIndex.end() && (*mi).second) { CBlockIndex* pindex = (*mi).second; if (chainActive.Contains(pindex)) { conf += chainActive.Height() - pindex->nHeight + 1; } } } /* Wait will we have 1 extra confirmation, otherwise some clients might reject this feeTX -- This function is tied to NewBlock, so we will propagate this budget while the block is also propagating */ if(conf < BUDGET_FEE_CONFIRMATIONS+1){ LogPrintf ("CBudgetManager::SubmitFinalBudget - Collateral requires at least %d confirmations - %s - %d confirmations\n", BUDGET_FEE_CONFIRMATIONS+1, txidCollateral.ToString(), conf); return; } //create the proposal incase we're the first to make it CFinalizedBudgetBroadcast finalizedBudgetBroadcast(strBudgetName, nBlockStart, vecTxBudgetPayments, txidCollateral); std::string strError = ""; if(!finalizedBudgetBroadcast.IsValid(strError)){ LogPrintf("CBudgetManager::SubmitFinalBudget - Invalid finalized budget - %s \n", strError); return; } LOCK(cs); mapSeenFinalizedBudgets.insert(make_pair(finalizedBudgetBroadcast.GetHash(), finalizedBudgetBroadcast)); finalizedBudgetBroadcast.Relay(); budget.AddFinalizedBudget(finalizedBudgetBroadcast); nSubmittedHeight = nCurrentHeight; LogPrintf("CBudgetManager::SubmitFinalBudget - Done! %s\n", finalizedBudgetBroadcast.GetHash().ToString()); } // // CBudgetDB // CBudgetDB::CBudgetDB() : pathDB(GetDataDir() / "budget.dat") , strMagicMessage("MasternodeBudget") { } CBudgetDB::CBudgetDB(const boost::filesystem::path& dbPath) : pathDB(dbPath) , strMagicMessage("MasternodeBudget") { } bool CBudgetDB::Write(const CBudgetManager& objToSave) { LOCK(objToSave.cs); int64_t nStart = GetTimeMillis(); // serialize, checksum data up to that point, then append checksum CDataStream ssObj(SER_DISK, CLIENT_VERSION); ssObj << strMagicMessage; // masternode cache file specific magic message ssObj << FLATDATA(Params().MessageStart()); // network specific magic number ssObj << objToSave; uint256 hash = Hash(ssObj.begin(), ssObj.end()); ssObj << hash; // open output file, and associate with CAutoFile FILE *file = fopen(pathDB.string().c_str(), "wb"); CAutoFile fileout(file, SER_DISK, CLIENT_VERSION); if (fileout.IsNull()) return error("%s : Failed to open file %s", __func__, pathDB.string()); // Write and commit header, data try { fileout << ssObj; } catch (std::exception &e) { return error("%s : Serialize or I/O error - %s", __func__, e.what()); } fileout.fclose(); LogPrintf("Written info to budget.dat %dms\n", GetTimeMillis() - nStart); return true; } CBudgetDB::ReadResult CBudgetDB::Read(CBudgetManager& objToLoad, bool fDryRun) { LOCK(objToLoad.cs); int64_t nStart = GetTimeMillis(); // open input file, and associate with CAutoFile FILE *file = fopen(pathDB.string().c_str(), "rb"); CAutoFile filein(file, SER_DISK, CLIENT_VERSION); if (filein.IsNull()) { error("%s : Failed to open file %s", __func__, pathDB.string()); return FileError; } // use file size to size memory buffer int fileSize = boost::filesystem::file_size(pathDB); int dataSize = fileSize - sizeof(uint256); // Don't try to resize to a negative number if file is small if (dataSize < 0) dataSize = 0; vector<unsigned char> vchData; vchData.resize(dataSize); uint256 hashIn; // read data and checksum from file try { filein.read((char *)&vchData[0], dataSize); filein >> hashIn; } catch (std::exception &e) { error("%s : Deserialize or I/O error - %s", __func__, e.what()); return HashReadError; } filein.fclose(); CDataStream ssObj(vchData, SER_DISK, CLIENT_VERSION); // verify stored checksum matches input data uint256 hashTmp = Hash(ssObj.begin(), ssObj.end()); if (hashIn != hashTmp) { error("%s : Checksum mismatch, data corrupted", __func__); return IncorrectHash; } unsigned char pchMsgTmp[4]; std::string strMagicMessageTmp; try { // de-serialize file header (masternode cache file specific magic message) and .. ssObj >> strMagicMessageTmp; // ... verify the message matches predefined one if (strMagicMessage != strMagicMessageTmp) { error("%s : Invalid masternode cache magic message", __func__); return IncorrectMagicMessage; } // de-serialize file header (network specific magic number) and .. ssObj >> FLATDATA(pchMsgTmp); // ... verify the network matches ours if (memcmp(pchMsgTmp, Params().MessageStart(), sizeof(pchMsgTmp))) { error("%s : Invalid network magic number", __func__); return IncorrectMagicNumber; } // de-serialize data into CBudgetManager object ssObj >> objToLoad; } catch (std::exception &e) { objToLoad.Clear(); error("%s : Deserialize or I/O error - %s", __func__, e.what()); return IncorrectFormat; } LogPrintf("Loaded info from budget.dat %dms\n", GetTimeMillis() - nStart); LogPrintf(" %s\n", objToLoad.ToString()); if(!fDryRun) { LogPrintf("Budget manager - cleaning....\n"); objToLoad.CheckAndRemove(); LogPrintf("Budget manager - result:\n"); LogPrintf(" %s\n", objToLoad.ToString()); } return Ok; } void DumpBudgets() { int64_t nStart = GetTimeMillis(); CBudgetDB budgetdb; CBudgetManager tempBudget; LogPrintf("Verifying budget.dat format...\n"); CBudgetDB::ReadResult readResult = budgetdb.Read(tempBudget, true); // there was an error and it was not an error on file opening => do not proceed if (readResult == CBudgetDB::FileError) LogPrintf("Missing budgets file - budget.dat, will try to recreate\n"); else if (readResult != CBudgetDB::Ok) { LogPrintf("Error reading budget.dat: "); if(readResult == CBudgetDB::IncorrectFormat) LogPrintf("magic is ok but data has invalid format, will try to recreate\n"); else { LogPrintf("file format is unknown or invalid, please fix it manually\n"); return; } } LogPrintf("Writting info to budget.dat...\n"); budgetdb.Write(budget); LogPrintf("Budget dump finished %dms\n", GetTimeMillis() - nStart); } bool CBudgetManager::AddFinalizedBudget(CFinalizedBudget& finalizedBudget) { std::string strError = ""; if(!finalizedBudget.IsValid(strError)) return false; if(mapFinalizedBudgets.count(finalizedBudget.GetHash())) { return false; } mapFinalizedBudgets.insert(make_pair(finalizedBudget.GetHash(), finalizedBudget)); return true; } bool CBudgetManager::AddProposal(CBudgetProposal& budgetProposal) { LOCK(cs); std::string strError = ""; if(!budgetProposal.IsValid(strError)) { LogPrintf("CBudgetManager::AddProposal - invalid budget proposal - %s\n", strError); return false; } if(mapProposals.count(budgetProposal.GetHash())) { return false; } mapProposals.insert(make_pair(budgetProposal.GetHash(), budgetProposal)); return true; } void CBudgetManager::CheckAndRemove() { LogPrintf("CBudgetManager::CheckAndRemove\n"); std::string strError = ""; LogPrintf("CBudgetManager::CheckAndRemove - mapFinalizedBudgets cleanup - size: %d\n", mapFinalizedBudgets.size()); std::map<uint256, CFinalizedBudget>::iterator it = mapFinalizedBudgets.begin(); while(it != mapFinalizedBudgets.end()) { CFinalizedBudget* pfinalizedBudget = &((*it).second); pfinalizedBudget->fValid = pfinalizedBudget->IsValid(strError); LogPrintf("CBudgetManager::CheckAndRemove - pfinalizedBudget->IsValid - strError: %s\n", strError); if(pfinalizedBudget->fValid) { pfinalizedBudget->AutoCheck(); } ++it; } LogPrintf("CBudgetManager::CheckAndRemove - mapProposals cleanup - size: %d\n", mapProposals.size()); std::map<uint256, CBudgetProposal>::iterator it2 = mapProposals.begin(); while(it2 != mapProposals.end()) { CBudgetProposal* pbudgetProposal = &((*it2).second); pbudgetProposal->fValid = pbudgetProposal->IsValid(strError); ++it2; } LogPrintf("CBudgetManager::CheckAndRemove - PASSED\n"); } void CBudgetManager::FillBlockPayee(CMutableTransaction& txNew, CAmount nFees) { LOCK(cs); CBlockIndex* pindexPrev = chainActive.Tip(); if(!pindexPrev) return; int nHighestCount = 0; CScript payee; CAmount nAmount = 0; // ------- Grab The Highest Count std::map<uint256, CFinalizedBudget>::iterator it = mapFinalizedBudgets.begin(); while(it != mapFinalizedBudgets.end()) { CFinalizedBudget* pfinalizedBudget = &((*it).second); if(pfinalizedBudget->GetVoteCount() > nHighestCount && pindexPrev->nHeight + 1 >= pfinalizedBudget->GetBlockStart() && pindexPrev->nHeight + 1 <= pfinalizedBudget->GetBlockEnd() && pfinalizedBudget->GetPayeeAndAmount(pindexPrev->nHeight + 1, payee, nAmount)){ nHighestCount = pfinalizedBudget->GetVoteCount(); } ++it; } CAmount blockValue = GetBlockValue(pindexPrev->nBits, pindexPrev->nHeight, nFees); //miners get the full amount on these blocks txNew.vout[0].nValue = blockValue; if(nHighestCount > 0){ txNew.vout.resize(2); //these are super blocks, so their value can be much larger than normal txNew.vout[1].scriptPubKey = payee; txNew.vout[1].nValue = nAmount; CTxDestination address1; ExtractDestination(payee, address1); CBitcoinAddress address2(address1); LogPrintf("CBudgetManager::FillBlockPayee - Budget payment to %s for %lld\n", address2.ToString(), nAmount); } } CFinalizedBudget *CBudgetManager::FindFinalizedBudget(uint256 nHash) { if(mapFinalizedBudgets.count(nHash)) return &mapFinalizedBudgets[nHash]; return NULL; } CBudgetProposal *CBudgetManager::FindProposal(const std::string &strProposalName) { //find the prop with the highest yes count int nYesCount = -99999; CBudgetProposal* pbudgetProposal = NULL; std::map<uint256, CBudgetProposal>::iterator it = mapProposals.begin(); while(it != mapProposals.end()){ if((*it).second.strProposalName == strProposalName && (*it).second.GetYeas() > nYesCount){ pbudgetProposal = &((*it).second); nYesCount = pbudgetProposal->GetYeas(); } ++it; } if(nYesCount == -99999) return NULL; return pbudgetProposal; } CBudgetProposal *CBudgetManager::FindProposal(uint256 nHash) { LOCK(cs); if(mapProposals.count(nHash)) return &mapProposals[nHash]; return NULL; } bool CBudgetManager::IsBudgetPaymentBlock(int nBlockHeight) { int nHighestCount = -1; std::map<uint256, CFinalizedBudget>::iterator it = mapFinalizedBudgets.begin(); while(it != mapFinalizedBudgets.end()) { CFinalizedBudget* pfinalizedBudget = &((*it).second); if(pfinalizedBudget->GetVoteCount() > nHighestCount && nBlockHeight >= pfinalizedBudget->GetBlockStart() && nBlockHeight <= pfinalizedBudget->GetBlockEnd()){ nHighestCount = pfinalizedBudget->GetVoteCount(); } ++it; } /* If budget doesn't have 5% of the network votes, then we should pay a masternode instead */ if(20 * nHighestCount > mnodeman.CountEnabled(MIN_BUDGET_PEER_PROTO_VERSION)) return true; return false; } bool CBudgetManager::HasNextFinalizedBudget() { CBlockIndex* pindexPrev = chainActive.Tip(); if(!pindexPrev) return false; if(masternodeSync.IsBudgetFinEmpty()) return true; int nBlockStart = pindexPrev->nHeight - pindexPrev->nHeight % GetBudgetPaymentCycleBlocks() + GetBudgetPaymentCycleBlocks(); CAmount amount = 1440; if (Params().NetworkID() == CBaseChainParams::TESTNET) { // Relatively 43200 / 30 = 1440, for testnet 50 / 30 ~ 2 amount = 2; } if(nBlockStart - pindexPrev->nHeight > amount*2) return true; //we wouldn't have the budget yet if(budget.IsBudgetPaymentBlock(nBlockStart)) return true; LogPrintf("CBudgetManager::HasNextFinalizedBudget() - Client is missing budget - %lli\n", nBlockStart); return false; } bool CBudgetManager::IsTransactionValid(const CTransaction& txNew, int nBlockHeight) { LOCK(cs); int nHighestCount = 0; std::vector<CFinalizedBudget*> ret; // ------- Grab The Highest Count std::map<uint256, CFinalizedBudget>::iterator it = mapFinalizedBudgets.begin(); while(it != mapFinalizedBudgets.end()) { CFinalizedBudget* pfinalizedBudget = &((*it).second); if(pfinalizedBudget->GetVoteCount() > nHighestCount && nBlockHeight >= pfinalizedBudget->GetBlockStart() && nBlockHeight <= pfinalizedBudget->GetBlockEnd()){ nHighestCount = pfinalizedBudget->GetVoteCount(); } ++it; } /* If budget doesn't have 5% of the network votes, then we should pay a masternode instead */ if(20 * nHighestCount < mnodeman.CountEnabled(MIN_BUDGET_PEER_PROTO_VERSION)) return false; // check the highest finalized budgets (+/- 10% to assist in consensus) it = mapFinalizedBudgets.begin(); while(it != mapFinalizedBudgets.end()) { CFinalizedBudget* pfinalizedBudget = &((*it).second); if(10 * (nHighestCount - pfinalizedBudget->GetVoteCount()) < mnodeman.CountEnabled(MIN_BUDGET_PEER_PROTO_VERSION)){ if(nBlockHeight >= pfinalizedBudget->GetBlockStart() && nBlockHeight <= pfinalizedBudget->GetBlockEnd()){ if(pfinalizedBudget->IsTransactionValid(txNew, nBlockHeight)){ return true; } } } ++it; } //we looked through all of the known budgets return false; } std::vector<CBudgetProposal*> CBudgetManager::GetAllProposals() { LOCK(cs); std::vector<CBudgetProposal*> vBudgetProposalRet; std::map<uint256, CBudgetProposal>::iterator it = mapProposals.begin(); while(it != mapProposals.end()) { (*it).second.CleanAndRemove(false); CBudgetProposal* pbudgetProposal = &((*it).second); vBudgetProposalRet.push_back(pbudgetProposal); ++it; } return vBudgetProposalRet; } // // Sort by votes, if there's a tie sort by their feeHash TX // struct sortProposalsByVotes { bool operator()(const std::pair<CBudgetProposal*, int> &left, const std::pair<CBudgetProposal*, int> &right) { if( left.second != right.second) return (left.second > right.second); return (UintToArith256(left.first->nFeeTXHash) > UintToArith256(right.first->nFeeTXHash)); } }; //Need to review this function std::vector<CBudgetProposal*> CBudgetManager::GetBudget() { LOCK(cs); // ------- Sort budgets by Yes Count std::vector<std::pair<CBudgetProposal*, int> > vBudgetPorposalsSort; std::map<uint256, CBudgetProposal>::iterator it = mapProposals.begin(); while(it != mapProposals.end()){ (*it).second.CleanAndRemove(false); vBudgetPorposalsSort.push_back(make_pair(&((*it).second), (*it).second.GetYeas()-(*it).second.GetNays())); ++it; } std::sort(vBudgetPorposalsSort.begin(), vBudgetPorposalsSort.end(), sortProposalsByVotes()); // ------- Grab The Budgets In Order std::vector<CBudgetProposal*> vBudgetProposalsRet; CAmount nBudgetAllocated = 0; CBlockIndex* pindexPrev = chainActive.Tip(); if(pindexPrev == NULL) return vBudgetProposalsRet; int nBlockStart = pindexPrev->nHeight - pindexPrev->nHeight % GetBudgetPaymentCycleBlocks() + GetBudgetPaymentCycleBlocks(); int nBlockEnd = nBlockStart + GetBudgetPaymentCycleBlocks() - 1; CAmount nTotalBudget = GetTotalBudget(nBlockStart); std::vector<std::pair<CBudgetProposal*, int> >::iterator it2 = vBudgetPorposalsSort.begin(); while(it2 != vBudgetPorposalsSort.end()) { CBudgetProposal* pbudgetProposal = (*it2).first; //prop start/end should be inside this period if(pbudgetProposal->fValid && pbudgetProposal->nBlockStart <= nBlockStart && pbudgetProposal->nBlockEnd >= nBlockEnd && pbudgetProposal->GetYeas() - pbudgetProposal->GetNays() > mnodeman.CountEnabled(MIN_BUDGET_PEER_PROTO_VERSION)/10 && pbudgetProposal->IsEstablished()) { if(pbudgetProposal->GetAmount() + nBudgetAllocated <= nTotalBudget) { pbudgetProposal->SetAllotted(pbudgetProposal->GetAmount()); nBudgetAllocated += pbudgetProposal->GetAmount(); vBudgetProposalsRet.push_back(pbudgetProposal); } else { pbudgetProposal->SetAllotted(0); } } ++it2; } return vBudgetProposalsRet; } struct sortFinalizedBudgetsByVotes { bool operator()(const std::pair<CFinalizedBudget*, int> &left, const std::pair<CFinalizedBudget*, int> &right) { return left.second > right.second; } }; std::vector<CFinalizedBudget*> CBudgetManager::GetFinalizedBudgets() { LOCK(cs); std::vector<CFinalizedBudget*> vFinalizedBudgetsRet; std::vector<std::pair<CFinalizedBudget*, int> > vFinalizedBudgetsSort; // ------- Grab The Budgets In Order std::map<uint256, CFinalizedBudget>::iterator it = mapFinalizedBudgets.begin(); while(it != mapFinalizedBudgets.end()) { CFinalizedBudget* pfinalizedBudget = &((*it).second); vFinalizedBudgetsSort.push_back(make_pair(pfinalizedBudget, pfinalizedBudget->GetVoteCount())); ++it; } std::sort(vFinalizedBudgetsSort.begin(), vFinalizedBudgetsSort.end(), sortFinalizedBudgetsByVotes()); std::vector<std::pair<CFinalizedBudget*, int> >::iterator it2 = vFinalizedBudgetsSort.begin(); while(it2 != vFinalizedBudgetsSort.end()) { vFinalizedBudgetsRet.push_back((*it2).first); ++it2; } return vFinalizedBudgetsRet; } std::string CBudgetManager::GetRequiredPaymentsString(int nBlockHeight) { LOCK(cs); std::string ret = "unknown-budget"; std::map<uint256, CFinalizedBudget>::iterator it = mapFinalizedBudgets.begin(); while(it != mapFinalizedBudgets.end()) { CFinalizedBudget* pfinalizedBudget = &((*it).second); if(nBlockHeight >= pfinalizedBudget->GetBlockStart() && nBlockHeight <= pfinalizedBudget->GetBlockEnd()){ CTxBudgetPayment payment; if(pfinalizedBudget->GetBudgetPaymentByBlock(nBlockHeight, payment)){ if(ret == "unknown-budget"){ ret = payment.nProposalHash.ToString(); } else { ret += ","; ret += payment.nProposalHash.ToString(); } } else { LogPrintf("CBudgetManager::GetRequiredPaymentsString - Couldn't find budget payment for block %d\n", nBlockHeight); } } ++it; } return ret; } CAmount CBudgetManager::GetTotalBudget(int nHeight) { if(chainActive.Tip() == NULL) return 0; //get min block value and calculate from that CAmount nSubsidy = 10 * COIN; int halvings = nHeight / Params().SubsidyHalvingInterval(); // Subsidy is cut in half every 2,100,000 blocks which will occur approximately every 4 years. nSubsidy >>= halvings; // Amount of blocks in a months period of time (using 1 minutes per) = (60*24*30)/1 if(Params().NetworkID() == CBaseChainParams::MAIN) return ((nSubsidy/100)*10)*1440*30; //for testing purposes return ((nSubsidy/100)*10)*50; } void CBudgetManager::NewBlock() { TRY_LOCK(cs, fBudgetNewBlock); if(!fBudgetNewBlock) return; if (masternodeSync.RequestedMasternodeAssets <= MASTERNODE_SYNC_BUDGET) return; if (strBudgetMode == "suggest") { //suggest the budget we see SubmitFinalBudget(); } //this function should be called 1/6 blocks, allowing up to 100 votes per day on all proposals if(chainActive.Height() % 6 != 0) return; // incremental sync with our peers if(masternodeSync.IsSynced()){ LogPrintf("CBudgetManager::NewBlock - incremental sync started\n"); if(chainActive.Height() % 600 == rand() % 600) { ClearSeen(); ResetSync(); } LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) if(pnode->nVersion >= MIN_BUDGET_PEER_PROTO_VERSION) Sync(pnode, uint256(), true); MarkSynced(); } CheckAndRemove(); //remove invalid votes once in a while (we have to check the signatures and validity of every vote, somewhat CPU intensive) LogPrintf("CBudgetManager::NewBlock - askedForSourceProposalOrBudget cleanup - size: %d\n", askedForSourceProposalOrBudget.size()); std::map<uint256, int64_t>::iterator it = askedForSourceProposalOrBudget.begin(); while(it != askedForSourceProposalOrBudget.end()){ if((*it).second > GetTime() - (60*60*24)){ ++it; } else { askedForSourceProposalOrBudget.erase(it++); } } LogPrintf("CBudgetManager::NewBlock - mapProposals cleanup - size: %d\n", mapProposals.size()); std::map<uint256, CBudgetProposal>::iterator it2 = mapProposals.begin(); while(it2 != mapProposals.end()){ (*it2).second.CleanAndRemove(false); ++it2; } LogPrintf("CBudgetManager::NewBlock - mapFinalizedBudgets cleanup - size: %d\n", mapFinalizedBudgets.size()); std::map<uint256, CFinalizedBudget>::iterator it3 = mapFinalizedBudgets.begin(); while(it3 != mapFinalizedBudgets.end()){ (*it3).second.CleanAndRemove(false); ++it3; } LogPrintf("CBudgetManager::NewBlock - vecImmatureBudgetProposals cleanup - size: %d\n", vecImmatureBudgetProposals.size()); std::vector<CBudgetProposalBroadcast>::iterator it4 = vecImmatureBudgetProposals.begin(); while(it4 != vecImmatureBudgetProposals.end()) { std::string strError = ""; int nConf = 0; if(!IsBudgetCollateralValid((*it4).nFeeTXHash, (*it4).GetHash(), strError, (*it4).nTime, nConf)){ ++it4; continue; } if(!(*it4).IsValid(strError)) { LogPrintf("mprop (immature) - invalid budget proposal - %s\n", strError); it4 = vecImmatureBudgetProposals.erase(it4); continue; } CBudgetProposal budgetProposal((*it4)); if(AddProposal(budgetProposal)) {(*it4).Relay();} LogPrintf("mprop (immature) - new budget - %s\n", (*it4).GetHash().ToString()); it4 = vecImmatureBudgetProposals.erase(it4); } LogPrintf("CBudgetManager::NewBlock - vecImmatureFinalizedBudgets cleanup - size: %d\n", vecImmatureFinalizedBudgets.size()); std::vector<CFinalizedBudgetBroadcast>::iterator it5 = vecImmatureFinalizedBudgets.begin(); while(it5 != vecImmatureFinalizedBudgets.end()) { std::string strError = ""; int nConf = 0; if(!IsBudgetCollateralValid((*it5).nFeeTXHash, (*it5).GetHash(), strError, (*it5).nTime, nConf)){ ++it5; continue; } if(!(*it5).IsValid(strError)) { LogPrintf("fbs (immature) - invalid finalized budget - %s\n", strError); it5 = vecImmatureFinalizedBudgets.erase(it5); continue; } LogPrintf("fbs (immature) - new finalized budget - %s\n", (*it5).GetHash().ToString()); CFinalizedBudget finalizedBudget((*it5)); if(AddFinalizedBudget(finalizedBudget)) {(*it5).Relay();} it5 = vecImmatureFinalizedBudgets.erase(it5); } LogPrintf("CBudgetManager::NewBlock - PASSED\n"); } void CBudgetManager::ProcessMessage(CNode* pfrom, std::string& strCommand, CDataStream& vRecv) { // lite mode is not supported if(fLiteMode) return; if(!masternodeSync.IsBlockchainSynced()) return; LOCK(cs_budget); if (strCommand == "mnvs") { //Masternode vote sync uint256 nProp; vRecv >> nProp; if(Params().NetworkID() == CBaseChainParams::MAIN){ if(nProp.IsNull()) { if(pfrom->HasFulfilledRequest("mnvs")) { LogPrintf("mnvs - peer already asked me for the list\n"); Misbehaving(pfrom->GetId(), 20); return; } pfrom->FulfilledRequest("mnvs"); } } Sync(pfrom, nProp); LogPrintf("mnvs - Sent Masternode votes to %s\n", pfrom->addr.ToString()); } if (strCommand == "mprop") { //Masternode Proposal CBudgetProposalBroadcast budgetProposalBroadcast; vRecv >> budgetProposalBroadcast; if(mapSeenMasternodeBudgetProposals.count(budgetProposalBroadcast.GetHash())){ masternodeSync.AddedBudgetItem(budgetProposalBroadcast.GetHash()); return; } std::string strError = ""; int nConf = 0; if(!IsBudgetCollateralValid(budgetProposalBroadcast.nFeeTXHash, budgetProposalBroadcast.GetHash(), strError, budgetProposalBroadcast.nTime, nConf)){ LogPrintf("Proposal FeeTX is not valid - %s - %s\n", budgetProposalBroadcast.nFeeTXHash.ToString(), strError); if(nConf >= 1) vecImmatureBudgetProposals.push_back(budgetProposalBroadcast); return; } mapSeenMasternodeBudgetProposals.insert(make_pair(budgetProposalBroadcast.GetHash(), budgetProposalBroadcast)); if(!budgetProposalBroadcast.IsValid(strError)) { LogPrintf("mprop - invalid budget proposal - %s\n", strError); return; } CBudgetProposal budgetProposal(budgetProposalBroadcast); if(AddProposal(budgetProposal)) {budgetProposalBroadcast.Relay();} masternodeSync.AddedBudgetItem(budgetProposalBroadcast.GetHash()); LogPrintf("mprop - new budget - %s\n", budgetProposalBroadcast.GetHash().ToString()); //We might have active votes for this proposal that are valid now CheckOrphanVotes(); } if (strCommand == "mvote") { //Masternode Vote CBudgetVote vote; vRecv >> vote; vote.fValid = true; if(mapSeenMasternodeBudgetVotes.count(vote.GetHash())){ masternodeSync.AddedBudgetItem(vote.GetHash()); return; } CMasternode* pmn = mnodeman.Find(vote.vin); if(pmn == NULL) { LogPrint("mnbudget", "mvote - unknown masternode - vin: %s\n", vote.vin.ToString()); mnodeman.AskForMN(pfrom, vote.vin); return; } mapSeenMasternodeBudgetVotes.insert(make_pair(vote.GetHash(), vote)); if(!vote.SignatureValid(true)){ LogPrintf("mvote - signature invalid\n"); if(masternodeSync.IsSynced()) Misbehaving(pfrom->GetId(), 20); // it could just be a non-synced masternode mnodeman.AskForMN(pfrom, vote.vin); return; } std::string strError = ""; if(UpdateProposal(vote, pfrom, strError)) { vote.Relay(); masternodeSync.AddedBudgetItem(vote.GetHash()); } LogPrintf("mvote - new budget vote - %s\n", vote.GetHash().ToString()); } if (strCommand == "fbs") { //Finalized Budget Suggestion CFinalizedBudgetBroadcast finalizedBudgetBroadcast; vRecv >> finalizedBudgetBroadcast; if(mapSeenFinalizedBudgets.count(finalizedBudgetBroadcast.GetHash())){ masternodeSync.AddedBudgetItem(finalizedBudgetBroadcast.GetHash()); return; } std::string strError = ""; int nConf = 0; if(!IsBudgetCollateralValid(finalizedBudgetBroadcast.nFeeTXHash, finalizedBudgetBroadcast.GetHash(), strError, finalizedBudgetBroadcast.nTime, nConf)){ LogPrintf("Finalized Budget FeeTX is not valid - %s - %s\n", finalizedBudgetBroadcast.nFeeTXHash.ToString(), strError); if(nConf >= 1) vecImmatureFinalizedBudgets.push_back(finalizedBudgetBroadcast); return; } mapSeenFinalizedBudgets.insert(make_pair(finalizedBudgetBroadcast.GetHash(), finalizedBudgetBroadcast)); if(!finalizedBudgetBroadcast.IsValid(strError)) { LogPrintf("fbs - invalid finalized budget - %s\n", strError); return; } LogPrintf("fbs - new finalized budget - %s\n", finalizedBudgetBroadcast.GetHash().ToString()); CFinalizedBudget finalizedBudget(finalizedBudgetBroadcast); if(AddFinalizedBudget(finalizedBudget)) {finalizedBudgetBroadcast.Relay();} masternodeSync.AddedBudgetItem(finalizedBudgetBroadcast.GetHash()); //we might have active votes for this budget that are now valid CheckOrphanVotes(); } if (strCommand == "fbvote") { //Finalized Budget Vote CFinalizedBudgetVote vote; vRecv >> vote; vote.fValid = true; if(mapSeenFinalizedBudgetVotes.count(vote.GetHash())){ masternodeSync.AddedBudgetItem(vote.GetHash()); return; } CMasternode* pmn = mnodeman.Find(vote.vin); if(pmn == NULL) { LogPrint("mnbudget", "fbvote - unknown masternode - vin: %s\n", vote.vin.ToString()); mnodeman.AskForMN(pfrom, vote.vin); return; } mapSeenFinalizedBudgetVotes.insert(make_pair(vote.GetHash(), vote)); if(!vote.SignatureValid(true)){ LogPrintf("fbvote - signature invalid\n"); if(masternodeSync.IsSynced()) Misbehaving(pfrom->GetId(), 20); // it could just be a non-synced masternode mnodeman.AskForMN(pfrom, vote.vin); return; } std::string strError = ""; if(UpdateFinalizedBudget(vote, pfrom, strError)) { vote.Relay(); masternodeSync.AddedBudgetItem(vote.GetHash()); LogPrintf("fbvote - new finalized budget vote - %s\n", vote.GetHash().ToString()); } else { LogPrintf("fbvote - rejected finalized budget vote - %s - %s\n", vote.GetHash().ToString(), strError); } } } bool CBudgetManager::PropExists(uint256 nHash) { if(mapProposals.count(nHash)) return true; return false; } //mark that a full sync is needed void CBudgetManager::ResetSync() { LOCK(cs); std::map<uint256, CBudgetProposalBroadcast>::iterator it1 = mapSeenMasternodeBudgetProposals.begin(); while(it1 != mapSeenMasternodeBudgetProposals.end()){ CBudgetProposal* pbudgetProposal = FindProposal((*it1).first); if(pbudgetProposal && pbudgetProposal->fValid){ //mark votes std::map<uint256, CBudgetVote>::iterator it2 = pbudgetProposal->mapVotes.begin(); while(it2 != pbudgetProposal->mapVotes.end()){ (*it2).second.fSynced = false; ++it2; } } ++it1; } std::map<uint256, CFinalizedBudgetBroadcast>::iterator it3 = mapSeenFinalizedBudgets.begin(); while(it3 != mapSeenFinalizedBudgets.end()){ CFinalizedBudget* pfinalizedBudget = FindFinalizedBudget((*it3).first); if(pfinalizedBudget && pfinalizedBudget->fValid){ //send votes std::map<uint256, CFinalizedBudgetVote>::iterator it4 = pfinalizedBudget->mapVotes.begin(); while(it4 != pfinalizedBudget->mapVotes.end()){ (*it4).second.fSynced = false; ++it4; } } ++it3; } } void CBudgetManager::MarkSynced() { LOCK(cs); /* Mark that we've sent all valid items */ std::map<uint256, CBudgetProposalBroadcast>::iterator it1 = mapSeenMasternodeBudgetProposals.begin(); while(it1 != mapSeenMasternodeBudgetProposals.end()){ CBudgetProposal* pbudgetProposal = FindProposal((*it1).first); if(pbudgetProposal && pbudgetProposal->fValid){ //mark votes std::map<uint256, CBudgetVote>::iterator it2 = pbudgetProposal->mapVotes.begin(); while(it2 != pbudgetProposal->mapVotes.end()){ if((*it2).second.fValid) (*it2).second.fSynced = true; ++it2; } } ++it1; } std::map<uint256, CFinalizedBudgetBroadcast>::iterator it3 = mapSeenFinalizedBudgets.begin(); while(it3 != mapSeenFinalizedBudgets.end()){ CFinalizedBudget* pfinalizedBudget = FindFinalizedBudget((*it3).first); if(pfinalizedBudget && pfinalizedBudget->fValid){ //mark votes std::map<uint256, CFinalizedBudgetVote>::iterator it4 = pfinalizedBudget->mapVotes.begin(); while(it4 != pfinalizedBudget->mapVotes.end()){ if((*it4).second.fValid) (*it4).second.fSynced = true; ++it4; } } ++it3; } } void CBudgetManager::Sync(CNode* pfrom, uint256 nProp, bool fPartial) { LOCK(cs); /* Sync with a client on the network -- This code checks each of the hash maps for all known budget proposals and finalized budget proposals, then checks them against the budget object to see if they're OK. If all checks pass, we'll send it to the peer. */ int nInvCount = 0; std::map<uint256, CBudgetProposalBroadcast>::iterator it1 = mapSeenMasternodeBudgetProposals.begin(); while(it1 != mapSeenMasternodeBudgetProposals.end()){ CBudgetProposal* pbudgetProposal = FindProposal((*it1).first); if(pbudgetProposal && pbudgetProposal->fValid && (nProp.IsNull() || (*it1).first == nProp)){ pfrom->PushInventory(CInv(MSG_BUDGET_PROPOSAL, (*it1).second.GetHash())); nInvCount++; //send votes std::map<uint256, CBudgetVote>::iterator it2 = pbudgetProposal->mapVotes.begin(); while(it2 != pbudgetProposal->mapVotes.end()){ if((*it2).second.fValid){ if((fPartial && !(*it2).second.fSynced) || !fPartial) { pfrom->PushInventory(CInv(MSG_BUDGET_VOTE, (*it2).second.GetHash())); nInvCount++; } } ++it2; } } ++it1; } pfrom->PushMessage("ssc", MASTERNODE_SYNC_BUDGET_PROP, nInvCount); LogPrintf("CBudgetManager::Sync - sent %d items\n", nInvCount); nInvCount = 0; std::map<uint256, CFinalizedBudgetBroadcast>::iterator it3 = mapSeenFinalizedBudgets.begin(); while(it3 != mapSeenFinalizedBudgets.end()){ CFinalizedBudget* pfinalizedBudget = FindFinalizedBudget((*it3).first); if(pfinalizedBudget && pfinalizedBudget->fValid && (nProp.IsNull() || (*it3).first == nProp)){ pfrom->PushInventory(CInv(MSG_BUDGET_FINALIZED, (*it3).second.GetHash())); nInvCount++; //send votes std::map<uint256, CFinalizedBudgetVote>::iterator it4 = pfinalizedBudget->mapVotes.begin(); while(it4 != pfinalizedBudget->mapVotes.end()){ if((*it4).second.fValid) { if((fPartial && !(*it4).second.fSynced) || !fPartial) { pfrom->PushInventory(CInv(MSG_BUDGET_FINALIZED_VOTE, (*it4).second.GetHash())); nInvCount++; } } ++it4; } } ++it3; } pfrom->PushMessage("ssc", MASTERNODE_SYNC_BUDGET_FIN, nInvCount); LogPrintf("CBudgetManager::Sync - sent %d items\n", nInvCount); } bool CBudgetManager::UpdateProposal(CBudgetVote& vote, CNode* pfrom, std::string& strError) { LOCK(cs); if(!mapProposals.count(vote.nProposalHash)){ if(pfrom){ // only ask for missing items after our syncing process is complete -- // otherwise we'll think a full sync succeeded when they return a result if(!masternodeSync.IsSynced()) return false; LogPrintf("CBudgetManager::UpdateProposal - Unknown proposal %d, asking for source proposal\n", vote.nProposalHash.ToString()); mapOrphanMasternodeBudgetVotes[vote.nProposalHash] = vote; if(!askedForSourceProposalOrBudget.count(vote.nProposalHash)){ pfrom->PushMessage("mnvs", vote.nProposalHash); askedForSourceProposalOrBudget[vote.nProposalHash] = GetTime(); } } strError = "Proposal not found!"; return false; } auto proposal = mapProposals[vote.nProposalHash]; if(!proposal.AddOrUpdateVote(vote, strError)) return false; if (fMasterNode) { for (auto& fbpair: mapFinalizedBudgets) { auto& finalBudget = fbpair.second; if (finalBudget.IsValid() && !finalBudget.IsVoteSubmitted()) finalBudget.ResetAutoChecked(); } } return true; } bool CBudgetManager::UpdateFinalizedBudget(CFinalizedBudgetVote& vote, CNode* pfrom, std::string& strError) { LOCK(cs); if(!mapFinalizedBudgets.count(vote.nBudgetHash)){ if(pfrom){ // only ask for missing items after our syncing process is complete -- // otherwise we'll think a full sync succeeded when they return a result if(!masternodeSync.IsSynced()) return false; LogPrintf("CBudgetManager::UpdateFinalizedBudget - Unknown Finalized Proposal %s, asking for source budget\n", vote.nBudgetHash.ToString()); mapOrphanFinalizedBudgetVotes[vote.nBudgetHash] = vote; if(!askedForSourceProposalOrBudget.count(vote.nBudgetHash)){ pfrom->PushMessage("mnvs", vote.nBudgetHash); askedForSourceProposalOrBudget[vote.nBudgetHash] = GetTime(); } } strError = "Finalized Budget not found!"; return false; } return mapFinalizedBudgets[vote.nBudgetHash].AddOrUpdateVote(vote, strError); } CBudgetProposal::CBudgetProposal() { strProposalName = "unknown"; nBlockStart = 0; nBlockEnd = 0; nAmount = 0; nTime = 0; fValid = true; } CBudgetProposal::CBudgetProposal(std::string strProposalNameIn, std::string strURLIn, int nBlockStartIn, int nBlockEndIn, CScript addressIn, CAmount nAmountIn, uint256 nFeeTXHashIn) { strProposalName = strProposalNameIn; strURL = strURLIn; nBlockStart = nBlockStartIn; nBlockEnd = nBlockEndIn; address = addressIn; nAmount = nAmountIn; nFeeTXHash = nFeeTXHashIn; fValid = true; } CBudgetProposal::CBudgetProposal(const CBudgetProposal& other) { strProposalName = other.strProposalName; strURL = other.strURL; nBlockStart = other.nBlockStart; nBlockEnd = other.nBlockEnd; address = other.address; nAmount = other.nAmount; nTime = other.nTime; nFeeTXHash = other.nFeeTXHash; mapVotes = other.mapVotes; fValid = true; } bool CBudgetProposal::IsValid(std::string& strError, bool fCheckCollateral) { if(GetNays() - GetYeas() > mnodeman.CountEnabled(MIN_BUDGET_PEER_PROTO_VERSION)/10){ strError = "Active removal"; return false; } if(nBlockStart < 0) { strError = "Invalid Proposal"; return false; } if(nBlockEnd < nBlockStart) { strError = "Invalid nBlockEnd"; return false; } if(nAmount < 1*COIN) { strError = "Invalid nAmount"; return false; } if(address == CScript()) { strError = "Invalid Payment Address"; return false; } if(fCheckCollateral){ int nConf = 0; if(!IsBudgetCollateralValid(nFeeTXHash, GetHash(), strError, nTime, nConf)){ return false; } } /* TODO: There might be an issue with multisig in the coinbase on mainnet, we will add support for it in a future release. */ if(address.IsPayToScriptHash()) { strError = "Multisig is not currently supported."; return false; } //if proposal doesn't gain traction within 2 weeks, remove it // nTime not being saved correctly // -- TODO: We should keep track of the last time the proposal was valid, if it's invalid for 2 weeks, erase it // if(nTime + (60*60*24*2) < GetAdjustedTime()) { // if(GetYeas()-GetNays() < (mnodeman.CountEnabled(MIN_BUDGET_PEER_PROTO_VERSION)/10)) { // strError = "Not enough support"; // return false; // } // } //can only pay out 10% of the possible coins (min value of coins) if(nAmount > budget.GetTotalBudget(nBlockStart)) { strError = "Payment more than max"; return false; } CBlockIndex* pindexPrev = chainActive.Tip(); if(pindexPrev == NULL) {strError = "Tip is NULL"; return true;} if(GetBlockEnd() < pindexPrev->nHeight - GetBudgetPaymentCycleBlocks()/2 ) return false; return true; } bool CBudgetProposal::AddOrUpdateVote(CBudgetVote& vote, std::string& strError) { LOCK(cs); uint256 hash = vote.vin.prevout.GetHash(); if(mapVotes.count(hash)){ if(mapVotes[hash].nTime > vote.nTime){ strError = strprintf("new vote older than existing vote - %s\n", vote.GetHash().ToString()); LogPrint("mnbudget", "CBudgetProposal::AddOrUpdateVote - %s\n", strError); return false; } if(vote.nTime - mapVotes[hash].nTime < BUDGET_VOTE_UPDATE_MIN){ strError = strprintf("time between votes is too soon - %s - %lli\n", vote.GetHash().ToString(), vote.nTime - mapVotes[hash].nTime); LogPrint("mnbudget", "CBudgetProposal::AddOrUpdateVote - %s\n", strError); return false; } } if(vote.nTime > GetTime() + (60*60)){ strError = strprintf("new vote is too far ahead of current time - %s - nTime %lli - Max Time %lli\n", vote.GetHash().ToString(), vote.nTime, GetTime() + (60*60)); LogPrint("mnbudget", "CBudgetProposal::AddOrUpdateVote - %s\n", strError); return false; } mapVotes[hash] = vote; return true; } // If masternode voted for a proposal, but is now invalid -- remove the vote void CBudgetProposal::CleanAndRemove(bool fSignatureCheck) { std::map<uint256, CBudgetVote>::iterator it = mapVotes.begin(); while(it != mapVotes.end()) { (*it).second.fValid = (*it).second.SignatureValid(fSignatureCheck); ++it; } } double CBudgetProposal::GetRatio() const { int yeas = 0; int nays = 0; for (const auto& pair: mapVotes) { if (pair.second.nVote == VOTE_YES) ++yeas; if (pair.second.nVote == VOTE_NO) ++nays; } if(yeas + nays == 0) return 0.0f; return ((double)(yeas) / (double)(yeas+nays)); } int CBudgetProposal::GetYeas() const { int ret = 0; for (const auto& pair: mapVotes) { if (pair.second.nVote == VOTE_YES && pair.second.fValid) ++ret; } return ret; } int CBudgetProposal::GetNays() const { int ret = 0; for (const auto& pair: mapVotes) { if (pair.second.nVote == VOTE_NO && pair.second.fValid) ++ret; } return ret; } int CBudgetProposal::GetAbstains() const { int ret = 0; for (const auto& pair: mapVotes) { if (pair.second.nVote == VOTE_ABSTAIN && pair.second.fValid) ++ret; } return ret; } int CBudgetProposal::GetBlockStartCycle() const { //end block is half way through the next cycle (so the proposal will be removed much after the payment is sent) return nBlockStart - nBlockStart % GetBudgetPaymentCycleBlocks(); } int CBudgetProposal::GetBlockCurrentCycle() const { CBlockIndex* pindexPrev = chainActive.Tip(); if(pindexPrev == nullptr) return -1; if(pindexPrev->nHeight >= GetBlockEndCycle()) return -1; return pindexPrev->nHeight - pindexPrev->nHeight % GetBudgetPaymentCycleBlocks(); } int CBudgetProposal::GetBlockEndCycle() const { //end block is half way through the next cycle (so the proposal will be removed much after the payment is sent) return nBlockEnd - GetBudgetPaymentCycleBlocks() / 2; } int CBudgetProposal::GetTotalPaymentCount() const { return (GetBlockEndCycle() - GetBlockStartCycle()) / GetBudgetPaymentCycleBlocks(); } int CBudgetProposal::GetRemainingPaymentCount() const { // If this budget starts in the future, this value will be wrong int nPayments = (GetBlockEndCycle() - GetBlockCurrentCycle()) / GetBudgetPaymentCycleBlocks() - 1; // Take the lowest value return std::min(nPayments, GetTotalPaymentCount()); } CBudgetProposalBroadcast::CBudgetProposalBroadcast(std::string strProposalNameIn, std::string strURLIn, int nPaymentCount, CScript addressIn, CAmount nAmountIn, int nBlockStartIn, uint256 nFeeTXHashIn) { strProposalName = strProposalNameIn; strURL = strURLIn; nBlockStart = nBlockStartIn; int nCycleStart = nBlockStart - nBlockStart % GetBudgetPaymentCycleBlocks(); //calculate the end of the cycle for this vote, add half a cycle (vote will be deleted after that block) nBlockEnd = nCycleStart + GetBudgetPaymentCycleBlocks() * nPaymentCount + GetBudgetPaymentCycleBlocks()/2; address = addressIn; nAmount = nAmountIn; nFeeTXHash = nFeeTXHashIn; } void CBudgetProposalBroadcast::Relay() { CInv inv(MSG_BUDGET_PROPOSAL, GetHash()); RelayInv(inv, MIN_BUDGET_PEER_PROTO_VERSION); } CBudgetVote::CBudgetVote() { vin = CTxIn(); nProposalHash = uint256(); nVote = VOTE_ABSTAIN; nTime = 0; fValid = true; fSynced = false; } CBudgetVote::CBudgetVote(CTxIn vinIn, uint256 nProposalHashIn, int nVoteIn) { vin = vinIn; nProposalHash = nProposalHashIn; nVote = nVoteIn; nTime = GetAdjustedTime(); fValid = true; fSynced = false; } void CBudgetVote::Relay() { CInv inv(MSG_BUDGET_VOTE, GetHash()); RelayInv(inv, MIN_BUDGET_PEER_PROTO_VERSION); } bool CBudgetVote::Sign(CKey& keyMasternode, CPubKey& pubKeyMasternode) { // Choose coins to use CPubKey pubKeyCollateralAddress; CKey keyCollateralAddress; std::string errorMessage; std::string strMessage = vin.prevout.ToStringShort() + nProposalHash.ToString() + boost::lexical_cast<std::string>(nVote) + boost::lexical_cast<std::string>(nTime); if(!legacySigner.SignMessage(strMessage, errorMessage, vchSig, keyMasternode)) { LogPrintf("CBudgetVote::Sign - Error upon calling SignMessage"); return false; } if(!legacySigner.VerifyMessage(pubKeyMasternode, vchSig, strMessage, errorMessage)) { LogPrintf("CBudgetVote::Sign - Error upon calling VerifyMessage"); return false; } return true; } bool CBudgetVote::SignatureValid(bool fSignatureCheck) const { std::string errorMessage; std::string strMessage = vin.prevout.ToStringShort() + nProposalHash.ToString() + boost::lexical_cast<std::string>(nVote) + boost::lexical_cast<std::string>(nTime); CMasternode* pmn = mnodeman.Find(vin); if(pmn == NULL) { LogPrint("mnbudget", "CBudgetVote::SignatureValid() - Unknown Masternode - %s\n", vin.ToString()); return false; } if(!fSignatureCheck) return true; if(!legacySigner.VerifyMessage(pmn->pubkey2, vchSig, strMessage, errorMessage)) { LogPrintf("CBudgetVote::SignatureValid() - Verify message failed\n"); return false; } return true; } CFinalizedBudget::CFinalizedBudget() { strBudgetName = ""; nBlockStart = 0; vecBudgetPayments.clear(); mapVotes.clear(); nFeeTXHash = uint256(); nTime = 0; fValid = true; fAutoChecked = false; voteSubmittedTime = boost::none; } CFinalizedBudget::CFinalizedBudget(const CFinalizedBudget& other) { strBudgetName = other.strBudgetName; nBlockStart = other.nBlockStart; vecBudgetPayments = other.vecBudgetPayments; mapVotes = other.mapVotes; nFeeTXHash = other.nFeeTXHash; nTime = other.nTime; fValid = true; fAutoChecked = false; voteSubmittedTime = boost::none; } bool CFinalizedBudget::AddOrUpdateVote(const CFinalizedBudgetVote& vote, std::string& strError) { LOCK(cs); auto masternodeHash = vote.vin.prevout.GetHash(); auto voteHash = vote.GetHash(); auto found = mapVotes.find(masternodeHash); if(found != std::end(mapVotes)){ auto&& previousVote = found->second; if (previousVote.GetHash() == vote.GetHash()) { LogPrint("mnbudget", "CFinalizedBudget::AddOrUpdateVote - Already have the vote\n"); return true; } if(previousVote.nTime > vote.nTime) { strError = strprintf("new vote older than existing vote - %s\n", vote.GetHash().ToString()); LogPrint("mnbudget", "CFinalizedBudget::AddOrUpdateVote - %s\n", strError); return false; } if(vote.nTime - previousVote.nTime < FINAL_BUDGET_VOTE_UPDATE_MIN) { strError = strprintf("time between votes is too soon - %s - %lli\n", vote.GetHash().ToString(), vote.nTime - previousVote.nTime); LogPrint("mnbudget", "CFinalizedBudget::AddOrUpdateVote - %s\n", strError); return false; } } if(vote.nTime > GetTime() + (60*60)){ strError = strprintf("new vote is too far ahead of current time - %s - nTime %lli - Max Time %lli\n", vote.GetHash().ToString(), vote.nTime, GetTime() + (60*60)); LogPrint("mnbudget", "CFinalizedBudget::AddOrUpdateVote - %s\n", strError); return false; } mapVotes.insert(found, std::make_pair(masternodeHash, vote)); return true; } //evaluate if we should vote for this. Masternode only void CFinalizedBudget::AutoCheck() { LOCK(cs); CBlockIndex* pindexPrev = chainActive.Tip(); if(!pindexPrev) return; LogPrintf("CFinalizedBudget::AutoCheck - %lli - %d\n", pindexPrev->nHeight, fAutoChecked); if(!fMasterNode || fAutoChecked) return; //do this 1 in 4 blocks -- spread out the voting activity on mainnet // -- this function is only called every sixth block, so this is really 1 in 24 blocks if(Params().NetworkID() == CBaseChainParams::MAIN && rand() % 4 != 0) { LogPrintf("CFinalizedBudget::AutoCheck - waiting\n"); return; } // Auto-check votes with an interval that does not allow to submit votes to soon if (voteSubmittedTime && GetTime() - voteSubmittedTime.get() < FINAL_BUDGET_VOTE_UPDATE_MIN) return; fAutoChecked = true; //we only need to check this once if(strBudgetMode == "auto") //only vote for exact matches { std::vector<CBudgetProposal*> vBudgetProposals = budget.GetBudget(); for(unsigned int i = 0; i < vecBudgetPayments.size(); i++){ LogPrintf("CFinalizedBudget::AutoCheck - nProp %d %s\n", i, vecBudgetPayments[i].nProposalHash.ToString()); LogPrintf("CFinalizedBudget::AutoCheck - Payee %d %s\n", i, vecBudgetPayments[i].payee.ToString()); LogPrintf("CFinalizedBudget::AutoCheck - nAmount %d %lli\n", i, vecBudgetPayments[i].nAmount); } for(unsigned int i = 0; i < vBudgetProposals.size(); i++){ LogPrintf("CFinalizedBudget::AutoCheck - nProp %d %s\n", i, vBudgetProposals[i]->GetHash().ToString()); LogPrintf("CFinalizedBudget::AutoCheck - Payee %d %s\n", i, vBudgetProposals[i]->GetPayee().ToString()); LogPrintf("CFinalizedBudget::AutoCheck - nAmount %d %lli\n", i, vBudgetProposals[i]->GetAmount()); } if(vBudgetProposals.size() == 0) { LogPrintf("CFinalizedBudget::AutoCheck - Can't get Budget, aborting\n"); return; } if(vBudgetProposals.size() != vecBudgetPayments.size()) { LogPrintf("CFinalizedBudget::AutoCheck - Budget length doesn't match\n"); return; } for(unsigned int i = 0; i < vecBudgetPayments.size(); i++){ if(i > vBudgetProposals.size() - 1) { LogPrintf("CFinalizedBudget::AutoCheck - Vector size mismatch, aborting\n"); return; } if(vecBudgetPayments[i].nProposalHash != vBudgetProposals[i]->GetHash()){ LogPrintf("CFinalizedBudget::AutoCheck - item #%d doesn't match %s %s\n", i, vecBudgetPayments[i].nProposalHash.ToString(), vBudgetProposals[i]->GetHash().ToString()); return; } // if(vecBudgetPayments[i].payee != vBudgetProposals[i]->GetPayee()){ -- triggered with false positive if(vecBudgetPayments[i].payee.ToString() != vBudgetProposals[i]->GetPayee().ToString()){ LogPrintf("CFinalizedBudget::AutoCheck - item #%d payee doesn't match %s %s\n", i, vecBudgetPayments[i].payee.ToString(), vBudgetProposals[i]->GetPayee().ToString()); return; } if(vecBudgetPayments[i].nAmount != vBudgetProposals[i]->GetAmount()){ LogPrintf("CFinalizedBudget::AutoCheck - item #%d payee doesn't match %lli %lli\n", i, vecBudgetPayments[i].nAmount, vBudgetProposals[i]->GetAmount()); return; } } LogPrintf("CFinalizedBudget::AutoCheck - Finalized Budget Matches! Submitting Vote.\n"); SubmitVote(); } } // If masternode voted for a proposal, but is now invalid -- remove the vote void CFinalizedBudget::CleanAndRemove(bool fSignatureCheck) { std::map<uint256, CFinalizedBudgetVote>::iterator it = mapVotes.begin(); while(it != mapVotes.end()) { (*it).second.fValid = (*it).second.SignatureValid(fSignatureCheck); ++it; } } CAmount CFinalizedBudget::GetTotalPayout() const { CAmount ret = 0; for(unsigned int i = 0; i < vecBudgetPayments.size(); i++){ ret += vecBudgetPayments[i].nAmount; } return ret; } std::string CFinalizedBudget::GetProposals() { LOCK(cs); std::string ret = ""; BOOST_FOREACH(CTxBudgetPayment& budgetPayment, vecBudgetPayments){ CBudgetProposal* pbudgetProposal = budget.FindProposal(budgetPayment.nProposalHash); std::string token = budgetPayment.nProposalHash.ToString(); if(pbudgetProposal) token = pbudgetProposal->GetName(); if(ret == "") {ret = token;} else {ret += "," + token;} } return ret; } std::string CFinalizedBudget::GetStatus() const { std::string retBadHashes = ""; std::string retBadPayeeOrAmount = ""; for(int nBlockHeight = GetBlockStart(); nBlockHeight <= GetBlockEnd(); nBlockHeight++) { CTxBudgetPayment budgetPayment; if(!GetBudgetPaymentByBlock(nBlockHeight, budgetPayment)){ LogPrintf("CFinalizedBudget::GetStatus - Couldn't find budget payment for block %lld\n", nBlockHeight); continue; } CBudgetProposal* pbudgetProposal = budget.FindProposal(budgetPayment.nProposalHash); if(!pbudgetProposal){ if(retBadHashes == ""){ retBadHashes = "Unknown proposal hash! Check this proposal before voting" + budgetPayment.nProposalHash.ToString(); } else { retBadHashes += "," + budgetPayment.nProposalHash.ToString(); } } else { if(pbudgetProposal->GetPayee() != budgetPayment.payee || pbudgetProposal->GetAmount() != budgetPayment.nAmount) { if(retBadPayeeOrAmount == ""){ retBadPayeeOrAmount = "Budget payee/nAmount doesn't match our proposal! " + budgetPayment.nProposalHash.ToString(); } else { retBadPayeeOrAmount += "," + budgetPayment.nProposalHash.ToString(); } } } } if(retBadHashes == "" && retBadPayeeOrAmount == "") return "OK"; return retBadHashes + retBadPayeeOrAmount; } bool CFinalizedBudget::IsValid(std::string& strError, bool fCheckCollateral) const { //must be the correct block for payment to happen (once a month) if(nBlockStart % GetBudgetPaymentCycleBlocks() != 0) {strError = "Invalid BlockStart"; return false;} if(GetBlockEnd() - nBlockStart > 100) {strError = "Invalid BlockEnd"; return false;} if((int)vecBudgetPayments.size() > 100) {strError = "Invalid budget payments count (too many)"; return false;} if(strBudgetName == "") {strError = "Invalid Budget Name"; return false;} if(nBlockStart == 0) {strError = "Invalid BlockStart == 0"; return false;} if(nFeeTXHash.IsNull()) {strError = "Invalid FeeTx.IsNull()"; return false;} //can only pay out 10% of the possible coins (min value of coins) if(GetTotalPayout() > budget.GetTotalBudget(nBlockStart)) {strError = "Invalid Payout (more than max)"; return false;} std::string strError2 = ""; if(fCheckCollateral){ if (nTime == 0) LogPrintf("CFinalizedBudget::IsValid - ERROR: nTime == 0 is unexpected\n"); int nConf = 0; int64_t nTime; if(!IsBudgetCollateralValid(nFeeTXHash, GetHash(), strError2, nTime, nConf)){ {strError = "Invalid Collateral : " + strError2; return false;} } } //TODO: if N cycles old, invalid, invalid CBlockIndex* pindexPrev = chainActive.Tip(); if(pindexPrev == NULL) return true; if(nBlockStart < pindexPrev->nHeight-100) {strError = "Older than current blockHeight"; return false;} return true; } bool CFinalizedBudget::IsValid(bool fCheckCollateral) const { auto dummy = std::string{}; return IsValid(dummy, fCheckCollateral); } void CFinalizedBudget::ResetAutoChecked() { if (!IsValid()) return; fAutoChecked = false; } bool CFinalizedBudget::IsTransactionValid(const CTransaction& txNew, int nBlockHeight) { int nCurrentBudgetPayment = nBlockHeight - GetBlockStart(); if(nCurrentBudgetPayment < 0) { LogPrintf("CFinalizedBudget::IsTransactionValid - Invalid block - height: %d start: %d\n", nBlockHeight, GetBlockStart()); return false; } if(nCurrentBudgetPayment > (int)vecBudgetPayments.size() - 1) { LogPrintf("CFinalizedBudget::IsTransactionValid - Invalid block - current budget payment: %d of %d\n", nCurrentBudgetPayment + 1, (int)vecBudgetPayments.size()); return false; } bool found = false; BOOST_FOREACH(CTxOut out, txNew.vout) { if(vecBudgetPayments[nCurrentBudgetPayment].payee == out.scriptPubKey && vecBudgetPayments[nCurrentBudgetPayment].nAmount == out.nValue) found = true; } if(!found) { CTxDestination address1; ExtractDestination(vecBudgetPayments[nCurrentBudgetPayment].payee, address1); CBitcoinAddress address2(address1); LogPrintf("CFinalizedBudget::IsTransactionValid - Missing required payment - %s: %d\n", address2.ToString(), vecBudgetPayments[nCurrentBudgetPayment].nAmount); } return found; } void CFinalizedBudget::SubmitVote() { CPubKey pubKeyMasternode; CKey keyMasternode; std::string errorMessage; if(!legacySigner.SetKey(strMasterNodePrivKey, errorMessage, keyMasternode, pubKeyMasternode)){ LogPrintf("CFinalizedBudget::SubmitVote - Error upon calling SetKey\n"); return; } CFinalizedBudgetVote vote(activeMasternode.vin, GetHash()); if(!vote.Sign(keyMasternode, pubKeyMasternode)){ LogPrintf("CFinalizedBudget::SubmitVote - Failure to sign."); return; } std::string strError = ""; if(budget.UpdateFinalizedBudget(vote, NULL, strError)){ LogPrintf("CFinalizedBudget::SubmitVote - new finalized budget vote - %s\n", vote.GetHash().ToString()); budget.mapSeenFinalizedBudgetVotes.insert(make_pair(vote.GetHash(), vote)); vote.Relay(); voteSubmittedTime = GetTime(); } else { LogPrintf("CFinalizedBudget::SubmitVote : Error submitting vote - %s\n", strError); } } CFinalizedBudgetBroadcast::CFinalizedBudgetBroadcast() { strBudgetName = ""; nBlockStart = 0; vecBudgetPayments.clear(); mapVotes.clear(); vchSig.clear(); nFeeTXHash = uint256(); } CFinalizedBudgetBroadcast::CFinalizedBudgetBroadcast(const CFinalizedBudget& other) { strBudgetName = other.strBudgetName; nBlockStart = other.nBlockStart; BOOST_FOREACH(CTxBudgetPayment out, other.vecBudgetPayments) vecBudgetPayments.push_back(out); mapVotes = other.mapVotes; nFeeTXHash = other.nFeeTXHash; } CFinalizedBudgetBroadcast::CFinalizedBudgetBroadcast(std::string strBudgetNameIn, int nBlockStartIn, std::vector<CTxBudgetPayment> vecBudgetPaymentsIn, uint256 nFeeTXHashIn) { strBudgetName = strBudgetNameIn; nBlockStart = nBlockStartIn; BOOST_FOREACH(CTxBudgetPayment out, vecBudgetPaymentsIn) vecBudgetPayments.push_back(out); mapVotes.clear(); nFeeTXHash = nFeeTXHashIn; } void CFinalizedBudgetBroadcast::Relay() { CInv inv(MSG_BUDGET_FINALIZED, GetHash()); RelayInv(inv, MIN_BUDGET_PEER_PROTO_VERSION); } CFinalizedBudgetVote::CFinalizedBudgetVote() { vin = CTxIn(); nBudgetHash = uint256(); nTime = 0; vchSig.clear(); fValid = true; fSynced = false; } CFinalizedBudgetVote::CFinalizedBudgetVote(CTxIn vinIn, uint256 nBudgetHashIn) { vin = vinIn; nBudgetHash = nBudgetHashIn; nTime = GetAdjustedTime(); vchSig.clear(); fValid = true; fSynced = false; } void CFinalizedBudgetVote::Relay() { CInv inv(MSG_BUDGET_FINALIZED_VOTE, GetHash()); RelayInv(inv, MIN_BUDGET_PEER_PROTO_VERSION); } bool CFinalizedBudgetVote::Sign(CKey& keyMasternode, CPubKey& pubKeyMasternode) { // Choose coins to use CPubKey pubKeyCollateralAddress; CKey keyCollateralAddress; std::string errorMessage; std::string strMessage = vin.prevout.ToStringShort() + nBudgetHash.ToString() + boost::lexical_cast<std::string>(nTime); if(!legacySigner.SignMessage(strMessage, errorMessage, vchSig, keyMasternode)) { LogPrintf("CFinalizedBudgetVote::Sign - Error upon calling SignMessage"); return false; } if(!legacySigner.VerifyMessage(pubKeyMasternode, vchSig, strMessage, errorMessage)) { LogPrintf("CFinalizedBudgetVote::Sign - Error upon calling VerifyMessage"); return false; } return true; } bool CFinalizedBudgetVote::SignatureValid(bool fSignatureCheck) { std::string errorMessage; std::string strMessage = vin.prevout.ToStringShort() + nBudgetHash.ToString() + boost::lexical_cast<std::string>(nTime); CMasternode* pmn = mnodeman.Find(vin); if(pmn == NULL) { LogPrint("mnbudget", "CFinalizedBudgetVote::SignatureValid() - Unknown Masternode\n"); return false; } if(!fSignatureCheck) return true; if(!legacySigner.VerifyMessage(pmn->pubkey2, vchSig, strMessage, errorMessage)) { LogPrintf("CFinalizedBudgetVote::SignatureValid() - Verify message failed\n"); return false; } return true; } std::string CBudgetManager::ToString() const { std::ostringstream info; info << "Proposals: " << (int)mapProposals.size() << ", Budgets: " << (int)mapFinalizedBudgets.size() << ", Seen Budgets: " << (int)mapSeenMasternodeBudgetProposals.size() << ", Seen Budget Votes: " << (int)mapSeenMasternodeBudgetVotes.size() << ", Seen Final Budgets: " << (int)mapSeenFinalizedBudgets.size() << ", Seen Final Budget Votes: " << (int)mapSeenFinalizedBudgetVotes.size(); return info.str(); }
/** * Copyright (c) 2016-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ #include "Transform.h" #include <algorithm> #include "Debug.h" #include "DexClass.h" #include "DexDebugInstruction.h" #include "DexInstruction.h" #include "WorkQueue.h" //////////////////////////////////////////////////////////////////////////////// std::mutex MethodTransform::s_lock; MethodTransform::FatMethodCache MethodTransform::s_cache; //////////////////////////////////////////////////////////////////////////////// void PostOrderSort::postorder(Block* b) { auto pos = m_visited.find(b); if (pos != m_visited.end()) { return; } m_visited.emplace_hint(pos, b); for (auto& s : b->succs()) { postorder(s); } m_postorder_list.emplace_back(b); } std::vector<Block*>&& PostOrderSort::get() { if (m_cfg.size() > 0) { postorder(m_cfg[0]); for (size_t i = 1; i < m_cfg.size(); i++) { if (m_cfg[i]->preds().size() == 0) postorder(m_cfg[i]); } } return std::move(m_postorder_list); } //////////////////////////////////////////////////////////////////////////////// MethodTransform::~MethodTransform() { m_fmethod->clear_and_dispose(FatMethodDisposer()); delete m_fmethod; for (auto block : m_blocks) { delete block; } } MethodTransform* MethodTransform::get_method_transform( DexMethod* method, bool want_cfg /* = false */ ) { { std::lock_guard<std::mutex> g(s_lock); auto it = s_cache.find(method); if (it != s_cache.end()) { MethodTransform* mt = it->second; return mt; } } FatMethod* fm = balloon(method); MethodTransform* mt = new MethodTransform(method, fm); if (want_cfg) { mt->build_cfg(); } { std::lock_guard<std::mutex> g(s_lock); s_cache[method] = mt; return mt; } } MethodTransform* MethodTransform::get_new_method(DexMethod* method) { return new MethodTransform(method, new FatMethod()); } namespace { typedef std::unordered_map<uint32_t, MethodItemEntry*> addr_mei_t; struct EncodeResult { bool success; DexOpcode newopcode; }; EncodeResult encode_offset(DexInstruction* insn, int32_t offset) { int bytecount = 4; if ((int32_t)((int8_t)(offset & 0xff)) == offset) { bytecount = 1; } else if ((int32_t)((int16_t)(offset & 0xffff)) == offset) { bytecount = 2; } auto op = insn->opcode(); if (is_conditional_branch(op)) { always_assert_log(bytecount <= 2, "Overflowed 16-bit encoding for offset in %s", SHOW(insn)); } if (is_goto(op)) { // Use the smallest encoding possible. auto newopcode = [&] { switch (bytecount) { case 1: return OPCODE_GOTO; case 2: return OPCODE_GOTO_16; case 4: return OPCODE_GOTO_32; } always_assert_log(false, "Invalid bytecount for %s", SHOW(insn)); }(); if (newopcode != op) { return {false, newopcode}; } } insn->set_offset(offset); return {true, op}; } static MethodItemEntry* get_target(MethodItemEntry* mei, addr_mei_t& addr_to_mei) { uint32_t base = mei->addr; int offset = mei->insn->offset(); uint32_t target = base + offset; always_assert_log( addr_to_mei.count(target) != 0, "Invalid opcode target %08x[%p](%08x) %08x in get_target %s\n", base, mei, offset, target, SHOW(mei->insn)); return addr_to_mei[target]; } static void insert_mentry_before(FatMethod* fm, MethodItemEntry* mentry, MethodItemEntry* dest) { if (dest == nullptr) { fm->push_back(*mentry); } else { fm->insert(fm->iterator_to(*dest), *mentry); } } static void insert_branch_target(FatMethod* fm, MethodItemEntry* target, MethodItemEntry* src) { BranchTarget* bt = new BranchTarget(); bt->type = BRANCH_SIMPLE; bt->src = src; MethodItemEntry* mentry = new MethodItemEntry(bt); ; insert_mentry_before(fm, mentry, target); } static void insert_fallthrough(FatMethod* fm, MethodItemEntry* dest) { MethodItemEntry* fallthrough = new MethodItemEntry(); insert_mentry_before(fm, fallthrough, dest); } static bool multi_target_compare_index(const BranchTarget* a, const BranchTarget* b) { return (a->index < b->index); } static bool multi_contains_gaps(const std::vector<BranchTarget*>& targets) { int32_t key = targets.front()->index; for (auto target : targets) { if (target->index != key) return true; key++; } return false; } static void insert_multi_branch_target(FatMethod* fm, int32_t index, MethodItemEntry* target, MethodItemEntry* src) { BranchTarget* bt = new BranchTarget(); bt->type = BRANCH_MULTI; bt->src = src; bt->index = index; MethodItemEntry* mentry = new MethodItemEntry(bt); insert_mentry_before(fm, mentry, target); } static void shard_multi_target(FatMethod* fm, DexOpcodeData* fopcode, MethodItemEntry* src, addr_mei_t& addr_to_mei) { const uint16_t* data = fopcode->data(); uint16_t entries = *data++; auto ftype = fopcode->opcode(); int32_t* idata = (int32_t*)data; uint32_t base = src->addr; if (ftype == FOPCODE_PACKED_SWITCH) { int32_t index = *idata++; for (int i = 0; i < entries; i++) { uint32_t targetaddr = base + *idata++; auto target = addr_to_mei[targetaddr]; insert_multi_branch_target(fm, index, target, src); index++; } } else if (ftype == FOPCODE_SPARSE_SWITCH) { int32_t* tdata = idata + entries; for (int i = 0; i < entries; i++) { int32_t index = *idata++; uint32_t targetaddr = base + *tdata++; auto target = addr_to_mei[targetaddr]; insert_multi_branch_target(fm, index, target, src); } } else { always_assert_log(false, "Bad fopcode 0x%04x in shard_multi_target", ftype); } } static void generate_branch_targets(FatMethod* fm, addr_mei_t& addr_to_mei) { for (auto miter = fm->begin(); miter != fm->end(); miter++) { MethodItemEntry* mentry = &*miter; if (mentry->type == MFLOW_OPCODE) { auto insn = mentry->insn; if (is_branch(insn->opcode())) { auto target = get_target(mentry, addr_to_mei); if (is_multi_branch(insn->opcode())) { auto fopcode = static_cast<DexOpcodeData*>(target->insn); shard_multi_target(fm, fopcode, mentry, addr_to_mei); fm->erase(fm->iterator_to(*target)); delete fopcode; addr_to_mei.erase(target->addr); } else { insert_branch_target(fm, target, mentry); } } } } } constexpr uint8_t kDebugFirstSpecial = 0x0a; constexpr uint8_t kDebugLineRange = 15; constexpr int8_t kDebugLineBase = -4; static void associate_debug_opcodes(FatMethod* fm, DexDebugItem* dbg, addr_mei_t& addr_to_mei) { uint32_t offset = 0; auto const& opcodes = dbg->get_instructions(); int32_t absolute_line = int32_t(dbg->get_line_start()); for (auto opcode : opcodes) { auto op = opcode->opcode(); TRACE(MTRANS, 5, "decode offset %08x %02x\n", offset, op); switch (op) { case DBG_ADVANCE_LINE: TRACE(MTRANS, 5, "Advance line %d\n", opcode->value()); absolute_line += opcode->value(); opcode->set_value(absolute_line); case DBG_END_LOCAL: case DBG_RESTART_LOCAL: case DBG_START_LOCAL: case DBG_START_LOCAL_EXTENDED: case DBG_SET_FILE: case DBG_END_SEQUENCE: case DBG_SET_PROLOGUE_END: case DBG_SET_EPILOGUE_BEGIN: { break; } case DBG_ADVANCE_PC: { offset += opcode->uvalue(); delete opcode; /* Ugh, messy, FIXME!!! */ continue; } default: { uint8_t adjustment = op; adjustment -= kDebugFirstSpecial; absolute_line += kDebugLineBase + (adjustment % kDebugLineRange); offset += adjustment / kDebugLineRange; opcode->set_uvalue(absolute_line); } } auto insert_point = addr_to_mei[offset]; if (!insert_point) { /* We don't have a way of emitting debug info for fopcodes. To * be honest, I'm not sure why DX emits them. We don't. */ TRACE(MTRANS, 5, "Warning..Skipping fopcode debug opcode\n"); continue; } MethodItemEntry* mentry = new MethodItemEntry(opcode); TRACE(MTRANS, 5, "insert at offset %08x %02x [%p][mentry%p]\n", offset, op, insert_point, mentry); insert_mentry_before(fm, mentry, insert_point); } } static bool order_try_entries(const MethodItemEntry* a, const MethodItemEntry* b) { return (a->tentry->order < b->tentry->order); } static void insert_try_entry(FatMethod* fm, TryEntryType type, DexTryItem* dti, MethodItemEntry* atmei, DexType* centry = nullptr, uint32_t order = 0) { TryEntry* tentry = new TryEntry(); tentry->type = type; tentry->tentry = dti; tentry->centry = centry; tentry->order = order; MethodItemEntry* mentry = new MethodItemEntry(tentry); insert_mentry_before(fm, mentry, atmei); } static void associate_try_items(FatMethod* fm, DexCode* code, addr_mei_t& addr_to_mei) { auto const& tries = code->get_tries(); for (auto tri : tries) { auto begin = addr_to_mei[tri->m_start_addr]; TRACE(MTRANS, 3, "try_start %08x mei %p\n", tri->m_start_addr, begin); insert_try_entry(fm, TRY_START, tri, begin); uint32_t lastaddr = tri->m_start_addr + tri->m_insn_count; auto end = addr_to_mei[lastaddr]; TRACE(MTRANS, 3, "try_end %08x mei %p\n", lastaddr, end); insert_try_entry(fm, TRY_END, tri, end); uint32_t order = 1; for (auto catz : tri->m_catches) { auto catzop = addr_to_mei[catz.second]; TRACE(MTRANS, 3, "try_catch %08x mei %p\n", catz.second, catzop); insert_try_entry(fm, TRY_CATCH, tri, catzop, catz.first, order++); } if (tri->m_catchall != DEX_NO_INDEX) { auto catzop = addr_to_mei[tri->m_catchall]; insert_try_entry(fm, TRY_CATCH, tri, catzop); } } } } FatMethod* MethodTransform::balloon(DexMethod* method) { auto code = method->get_code(); if (code == nullptr) { return nullptr; } TRACE(MTRANS, 2, "Ballooning %s\n", SHOW(method)); auto opcodes = code->get_instructions(); addr_mei_t addr_to_mei; FatMethod* fm = new FatMethod(); uint32_t addr = 0; for (auto opcode : opcodes) { MethodItemEntry* mei = new MethodItemEntry(opcode); fm->push_back(*mei); addr_to_mei[addr] = mei; mei->addr = addr; TRACE(MTRANS, 5, "%08x: %s[mei %p]\n", addr, SHOW(opcode), mei); addr += opcode->size(); } generate_branch_targets(fm, addr_to_mei); associate_try_items(fm, code, addr_to_mei); auto debugitem = code->get_debug_item(); if (debugitem) { associate_debug_opcodes(fm, debugitem, addr_to_mei); } return fm; } void MethodTransform::replace_opcode(DexInstruction* from, DexInstruction* to) { for (auto miter = m_fmethod->begin(); miter != m_fmethod->end(); miter++) { MethodItemEntry* mentry = &*miter; if (mentry->type == MFLOW_OPCODE && mentry->insn == from) { mentry->insn = to; delete from; return; } } always_assert_log( false, "No match found while replacing '%s' with '%s' in method %s", SHOW(from), SHOW(to), show_short(m_method).c_str()); } void MethodTransform::insert_after(DexInstruction* position, std::list<DexInstruction*>& opcodes) { /* The nullptr case handling is strange-ish..., this will not work as expected *if * a method has a branch target as it's first instruction. * * To handle this case sanely, we'd need to export a interface based on * MEI's probably. * */ for (auto const& mei : *m_fmethod) { if (mei.type == MFLOW_OPCODE && (position == nullptr || mei.insn == position)) { auto insertat = m_fmethod->iterator_to(mei); if (position != nullptr) insertat++; for (auto opcode : opcodes) { MethodItemEntry* mentry = new MethodItemEntry(opcode); m_fmethod->insert(insertat, *mentry); } return; } } always_assert_log(false, "No match found"); } void MethodTransform::remove_opcode(DexInstruction* insn) { for (auto const& mei : *m_fmethod) { if (mei.type == MFLOW_OPCODE && mei.insn == insn) { m_fmethod->erase(m_fmethod->iterator_to(mei)); delete insn; return; } } always_assert_log(false, "No match found while removing '%s' from method %s", SHOW(insn), show_short(m_method).c_str()); } FatMethod::iterator MethodTransform::main_block() { return m_fmethod->begin(); } FatMethod::iterator MethodTransform::insert(FatMethod::iterator cur, DexInstruction* insn) { MethodItemEntry* mentry = new MethodItemEntry(insn); return m_fmethod->insert(cur, *mentry); } FatMethod::iterator MethodTransform::make_if_block( FatMethod::iterator cur, DexInstruction* insn, FatMethod::iterator* false_block) { auto if_entry = new MethodItemEntry(insn); *false_block = m_fmethod->insert(cur, *if_entry); auto bt = new BranchTarget(); bt->src = if_entry; bt->type = BRANCH_SIMPLE; auto bentry = new MethodItemEntry(bt); return m_fmethod->insert(m_fmethod->end(), *bentry); } FatMethod::iterator MethodTransform::make_if_else_block( FatMethod::iterator cur, DexInstruction* insn, FatMethod::iterator* false_block, FatMethod::iterator* true_block) { // if block auto if_entry = new MethodItemEntry(insn); *false_block = m_fmethod->insert(cur, *if_entry); // end of else goto auto goto_entry = new MethodItemEntry(new DexInstruction(OPCODE_GOTO)); auto goto_it = m_fmethod->insert(m_fmethod->end(), *goto_entry); // main block auto main_bt = new BranchTarget(); main_bt->src = goto_entry; main_bt->type = BRANCH_SIMPLE; auto mb_entry = new MethodItemEntry(main_bt); auto main_block = m_fmethod->insert(goto_it, *mb_entry); // else block auto else_bt = new BranchTarget(); else_bt->src = if_entry; else_bt->type = BRANCH_SIMPLE; auto eb_entry = new MethodItemEntry(else_bt); *true_block = m_fmethod->insert(goto_it, *eb_entry); return main_block; } FatMethod::iterator MethodTransform::make_switch_block( FatMethod::iterator cur, DexInstruction* insn, FatMethod::iterator* default_block, std::map<int, FatMethod::iterator>& cases) { auto switch_entry = new MethodItemEntry(insn); *default_block = m_fmethod->insert(cur, *switch_entry); FatMethod::iterator main_block = *default_block; for (auto case_it = cases.begin(); case_it != cases.end(); ++case_it) { auto goto_entry = new MethodItemEntry(new DexInstruction(OPCODE_GOTO)); auto goto_it = m_fmethod->insert(m_fmethod->end(), *goto_entry); auto main_bt = new BranchTarget(); main_bt->src = goto_entry; main_bt->type = BRANCH_SIMPLE; auto mb_entry = new MethodItemEntry(main_bt); main_block = m_fmethod->insert(++main_block, *mb_entry); // case block auto case_bt = new BranchTarget(); case_bt->src = switch_entry; case_bt->index = case_it->first; case_bt->type = BRANCH_MULTI; auto eb_entry = new MethodItemEntry(case_bt); case_it->second = m_fmethod->insert(goto_it, *eb_entry); } return main_block; } namespace { using RegMap = std::unordered_map<uint16_t, uint16_t>; void remap_dest(DexInstruction* inst, const RegMap& reg_map) { if (!inst->dests_size()) return; if (inst->dest_is_src()) return; auto it = reg_map.find(inst->dest()); if (it == reg_map.end()) return; inst->set_dest(it->second); } void remap_srcs(DexInstruction* inst, const RegMap& reg_map) { for (unsigned i = 0; i < inst->srcs_size(); i++) { auto it = reg_map.find(inst->src(i)); if (it == reg_map.end()) continue; inst->set_src(i, it->second); } } void remap_debug(DexDebugInstruction* dbgop, const RegMap& reg_map) { switch (dbgop->opcode()) { case DBG_START_LOCAL: case DBG_START_LOCAL_EXTENDED: case DBG_END_LOCAL: case DBG_RESTART_LOCAL: { auto it = reg_map.find(dbgop->uvalue()); if (it == reg_map.end()) return; dbgop->set_uvalue(it->second); break; } default: break; } } void remap_registers(MethodItemEntry& mei, const RegMap& reg_map) { switch (mei.type) { case MFLOW_OPCODE: remap_dest(mei.insn, reg_map); remap_srcs(mei.insn, reg_map); break; case MFLOW_DEBUG: remap_debug(mei.dbgop, reg_map); break; default: break; } } void remap_registers(FatMethod* fmethod, const RegMap& reg_map) { for (auto& mei : *fmethod) { remap_registers(mei, reg_map); } } void remap_caller_regs(DexMethod* method, FatMethod* fmethod, uint16_t newregs) { RegMap reg_map; auto oldregs = method->get_code()->get_registers_size(); auto ins = method->get_code()->get_ins_size(); for (uint16_t i = 0; i < ins; ++i) { reg_map[oldregs - ins + i] = newregs - ins + i; } remap_registers(fmethod, reg_map); method->get_code()->set_registers_size(newregs); } void remap_callee_regs(DexInstruction* invoke, DexMethod* method, FatMethod* fmethod, uint16_t newregs) { RegMap reg_map; auto oldregs = method->get_code()->get_registers_size(); auto ins = method->get_code()->get_ins_size(); auto wc = invoke->arg_word_count(); always_assert(ins == wc); for (uint16_t i = 0; i < wc; ++i) { reg_map[oldregs - ins + i] = invoke->src(i); } remap_registers(fmethod, reg_map); method->get_code()->set_registers_size(newregs); } /** * Builds a register map for a callee. */ void build_remap_regs(RegMap& reg_map, DexInstruction* invoke, DexMethod* callee, uint16_t new_tmp_off) { auto oldregs = callee->get_code()->get_registers_size(); auto ins = callee->get_code()->get_ins_size(); auto wc = invoke->arg_word_count(); always_assert(ins == wc); // remap all local regs (not args) for (uint16_t i = 0; i < oldregs - ins; ++i) { reg_map[i] = new_tmp_off + i; } for (uint16_t i = 0; i < wc; ++i) { reg_map[oldregs - ins + i] = invoke->src(i); } } /** * Create a move instruction given a return instruction in a callee and * a move-result instruction in a caller. */ DexInstruction* move_result(DexInstruction* res, DexInstruction* move_res) { auto opcode = res->opcode(); always_assert(opcode != OPCODE_RETURN_VOID); DexInstruction* move; if (opcode == OPCODE_RETURN_OBJECT) { move = new DexInstruction(OPCODE_MOVE_OBJECT); } else if (opcode == OPCODE_RETURN_WIDE) { move = new DexInstruction(OPCODE_MOVE_WIDE); } else { always_assert(opcode == OPCODE_RETURN); move = new DexInstruction(OPCODE_MOVE); } move->set_dest(move_res->dest()); move->set_src(0, res->src(0)); return move; } /* We need to cleanup two cases: * Duplicate DBG_SET_PROLOGUE_END * Uninitialized parameters * * The parameter names are part of the debug info for the method. * The technically correct solution would be to make a start * local for each of them. However, that would also imply another * end local after the tail to correctly set what the register * is at the end. This would bloat the debug info parameters for * a corner case. * * Instead, we just delete locals lifetime information for parameters. * This is an exceedingly rare case triggered by goofy code that * reuses parameters as locals. */ void cleanup_callee_debug(FatMethod* fcallee) { std::unordered_set<uint16_t> valid_regs; auto it = fcallee->begin(); while (it != fcallee->end()) { auto& mei = *it++; if (mei.type == MFLOW_DEBUG) { switch(mei.dbgop->opcode()) { case DBG_SET_PROLOGUE_END: fcallee->erase(fcallee->iterator_to(mei)); break; case DBG_START_LOCAL: case DBG_START_LOCAL_EXTENDED: { auto reg = mei.dbgop->uvalue(); valid_regs.insert(reg); break; } case DBG_END_LOCAL: case DBG_RESTART_LOCAL: { auto reg = mei.dbgop->uvalue(); if (valid_regs.find(reg) == valid_regs.end()) { fcallee->erase(fcallee->iterator_to(mei)); } break; } default: break; } } } } MethodItemEntry* clone( MethodItemEntry* mei, std::unordered_map<MethodItemEntry*, MethodItemEntry*>& entry_map) { MethodItemEntry* cloned_mei; auto entry = entry_map.find(mei); if (entry != entry_map.end()) { return entry->second; } cloned_mei = new MethodItemEntry(*mei); entry_map[mei] = cloned_mei; switch (cloned_mei->type) { case MFLOW_TRY: cloned_mei->tentry = new TryEntry(*cloned_mei->tentry); cloned_mei->tentry->tentry = new DexTryItem(*cloned_mei->tentry->tentry); return cloned_mei; case MFLOW_OPCODE: cloned_mei->insn = cloned_mei->insn->clone(); return cloned_mei; case MFLOW_TARGET: cloned_mei->target = new BranchTarget(*cloned_mei->target); cloned_mei->target->src = clone(cloned_mei->target->src, entry_map); return cloned_mei; case MFLOW_DEBUG: cloned_mei->dbgop = cloned_mei->dbgop->clone(); return cloned_mei; case MFLOW_FALLTHROUGH: return cloned_mei; } not_reached(); } } void MethodTransform::inline_tail_call(DexMethod* caller, DexMethod* callee, DexInstruction* invoke) { TRACE(INL, 2, "caller: %s\ncallee: %s\n", SHOW(caller), SHOW(callee)); MethodTransformer tcaller(caller); MethodTransformer tcallee(callee); auto fcaller = tcaller->m_fmethod; auto fcallee = tcallee->m_fmethod; auto bregs = caller->get_code()->get_registers_size(); auto eregs = callee->get_code()->get_registers_size(); auto bins = caller->get_code()->get_ins_size(); auto eins = callee->get_code()->get_ins_size(); always_assert(bins >= eins); auto newregs = std::max(bregs, uint16_t(eregs + bins - eins)); always_assert(newregs <= 16); // Remap registers to account for possibly larger frame, more ins remap_caller_regs(caller, fcaller, newregs); remap_callee_regs(invoke, callee, fcallee, newregs); callee->get_code()->set_ins_size(bins); auto pos = std::find_if(fcaller->begin(), fcaller->end(), [invoke](const MethodItemEntry& mei) { return mei.type == MFLOW_OPCODE && mei.insn == invoke; }); cleanup_callee_debug(fcallee); auto it = fcallee->begin(); while (it != fcallee->end()) { auto& mei = *it++; fcallee->erase(fcallee->iterator_to(mei)); fcaller->insert(pos, mei); } // Delete the vestigial tail. while (pos != fcaller->end()) { if (pos->type == MFLOW_OPCODE) { pos = fcaller->erase_and_dispose(pos, FatMethodDisposer()); } else { ++pos; } } caller->get_code()->set_outs_size(callee->get_code()->get_outs_size()); } bool MethodTransform::inline_16regs(InlineContext& context, DexMethod *callee, DexOpcodeMethod *invoke) { TRACE(INL, 2, "caller: %s\ncallee: %s\n", SHOW(context.caller), SHOW(callee)); auto caller = context.caller; MethodTransformer mtcaller(caller); MethodTransformer mtcallee(callee); auto fcaller = mtcaller->m_fmethod; auto fcallee = mtcallee->m_fmethod; auto callee_code = callee->get_code(); auto temps_needed = callee_code->get_registers_size() - callee_code->get_ins_size(); uint16_t newregs = caller->get_code()->get_registers_size(); if (context.inline_regs_used < temps_needed) { newregs = newregs + temps_needed - context.inline_regs_used; if (newregs > 16) return false; remap_caller_regs(caller, fcaller, newregs); context.inline_regs_used = temps_needed; } RegMap callee_reg_map; build_remap_regs(callee_reg_map, invoke, callee, context.new_tmp_off); auto pos = std::find_if( fcaller->begin(), fcaller->end(), [invoke](const MethodItemEntry& mei) { return mei.type == MFLOW_OPCODE && mei.insn == invoke; }); // find the move-result after the invoke, if any. Must be the first // instruction after the invoke auto move_res = pos; while (move_res++ != fcaller->end() && move_res->type != MFLOW_OPCODE); if (!is_move_result(move_res->insn->opcode())) { move_res = fcaller->end(); } // Skip dbg prologue in callee, we don't need two. auto it = fcallee->begin(); if (it->type == MFLOW_DEBUG && it->dbgop->opcode() == DBG_SET_PROLOGUE_END) { ++it; } // Copy the callee up to the return. Everything else we push at the end // of the caller // We need a map of MethodItemEntry we have created because a branch // points to another MethodItemEntry which may have been created or not std::unordered_map<MethodItemEntry*, MethodItemEntry*> entry_map; while (it != fcallee->end()) { auto mei = clone(&*it, entry_map); remap_registers(*mei, callee_reg_map); it++; if (mei->type == MFLOW_OPCODE && is_return(mei->insn->opcode())) { if (move_res != fcaller->end()) { DexInstruction* move = move_result(mei->insn, move_res->insn); auto move_mei = new MethodItemEntry(move); fcaller->insert(pos, *move_mei); delete mei->insn; delete mei; } break; } else { fcaller->insert(pos, *mei); } } // remove invoke fcaller->erase_and_dispose(pos, FatMethodDisposer()); // remove move_result if (move_res != fcaller->end()) { fcaller->erase_and_dispose(move_res, FatMethodDisposer()); } while (it != fcallee->end()) { auto mei = clone(&*it, entry_map); remap_registers(*mei, callee_reg_map); it++; fcaller->push_back(*mei); } // adjust method header caller->get_code()->set_registers_size(newregs); caller->get_code()->set_outs_size( std::max(callee->get_code()->get_outs_size(), caller->get_code()->get_outs_size())); return true; } namespace { bool end_of_block(const FatMethod* fm, FatMethod::iterator it, bool in_try) { auto next = std::next(it); if (next == fm->end()) { return true; } if (next->type == MFLOW_TARGET || next->type == MFLOW_TRY) { return true; } if (it->type != MFLOW_OPCODE) { return false; } if (is_branch(it->insn->opcode())) { return true; } if (in_try && may_throw(it->insn->opcode())) { return true; } return false; } } bool ends_with_may_throw(Block* p) { for (auto last = p->rbegin(); last != p->rend(); ++last) { if (last->type != MFLOW_OPCODE) { continue; } return may_throw(last->insn->opcode()); } return true; } void MethodTransform::build_cfg() { // Find the block boundaries std::unordered_map<MethodItemEntry*, std::vector<Block*>> branch_to_targets; std::vector<std::pair<DexTryItem*, Block*>> try_ends; std::unordered_map<DexTryItem*, std::vector<Block*>> try_catches; size_t id = 0; bool in_try = false; m_blocks.emplace_back(new Block(id++)); m_blocks.back()->m_begin = m_fmethod->begin(); // The first block can be a branch target. auto begin = m_fmethod->begin(); if (begin->type == MFLOW_TARGET) { branch_to_targets[begin->target->src].push_back(m_blocks.back()); } for (auto it = m_fmethod->begin(); it != m_fmethod->end(); ++it) { if (it->type == MFLOW_TRY) { if (it->tentry->type == TRY_START) { in_try = true; } else if (it->tentry->type == TRY_END) { in_try = false; } } if (!end_of_block(m_fmethod, it, in_try)) { continue; } // End the current block. auto next = std::next(it); if (next == m_fmethod->end()) { m_blocks.back()->m_end = next; continue; } // Start a new block at the next MethodItem. auto next_block = new Block(id++); if (next->type == MFLOW_OPCODE) { insert_fallthrough(m_fmethod, &*next); next = std::next(it); } m_blocks.back()->m_end = next; next_block->m_begin = next; m_blocks.emplace_back(next_block); // Record branch targets to add edges in the next pass. if (next->type == MFLOW_TARGET) { branch_to_targets[next->target->src].push_back(next_block); continue; } // Record try/catch blocks to add edges in the next pass. if (next->type == MFLOW_TRY) { if (next->tentry->type == TRY_END) { try_ends.emplace_back(next->tentry->tentry, next_block); } else if (next->tentry->type == TRY_CATCH) { try_catches[next->tentry->tentry].push_back(next_block); } } } // Link the blocks together with edges for (auto it = m_blocks.begin(); it != m_blocks.end(); ++it) { // Set outgoing edge if last MIE falls through auto lastmei = (*it)->rbegin(); bool fallthrough = true; if (lastmei->type == MFLOW_OPCODE) { auto lastop = lastmei->insn->opcode(); if (is_goto(lastop) || is_conditional_branch(lastop) || is_multi_branch(lastop)) { fallthrough = !is_goto(lastop); auto const& targets = branch_to_targets[&*lastmei]; for (auto target : targets) { (*it)->m_succs.push_back(target); target->m_preds.push_back(*it); } } else if (is_return(lastop) || lastop == OPCODE_THROW) { fallthrough = false; } } if (fallthrough && std::next(it) != m_blocks.end()) { Block* next = *std::next(it); (*it)->m_succs.push_back(next); next->m_preds.push_back(*it); } } /* * Now add the catch edges. Every block inside a try-start/try-end region * gets an edge to every catch block. This simplifies dataflow analysis * since you can always get the exception state by looking at successors, * without any additional analysis. * * NB: This algorithm assumes that a try-start/try-end region will consist of * sequentially-numbered blocks, which is guaranteed because catch regions * are contiguous in the bytecode, and we generate blocks in bytecode order. */ for (auto tep : try_ends) { auto tryitem = tep.first; auto tryendblock = tep.second; size_t bid = tryendblock->id(); always_assert(bid > 0); --bid; while (true) { auto block = m_blocks[bid]; if (ends_with_may_throw(block)) { auto& catches = try_catches[tryitem]; for (auto catchblock : catches) { block->m_succs.push_back(catchblock); catchblock->m_preds.push_back(block); } } auto begin = block->begin(); if (begin->type == MFLOW_TRY) { auto tentry = begin->tentry; if (tentry->type == TRY_START && tentry->tentry == tryitem) { break; } } always_assert_log(bid > 0, "No beginning of try region found"); --bid; } } TRACE(CFG, 5, "%s\n", show(m_method).c_str()); TRACE(CFG, 5, "%s", show(m_blocks).c_str()); } void MethodTransform::sync_all() { std::vector<MethodTransform*> transforms; for (auto& centry : s_cache) { transforms.push_back(centry.second); } std::vector<WorkItem<MethodTransform>> workitems(transforms.size()); auto mt_sync = [](MethodTransform* mt) { mt->sync(); }; for (size_t i = 0; i < transforms.size(); i++) { workitems[i].init(mt_sync, transforms[i]); } WorkQueue wq; wq.run_work_items(&workitems[0], workitems.size()); } void MethodTransform::sync() { while (try_sync() == false) ; { std::lock_guard<std::mutex> g(s_lock); s_cache.erase(m_method); } delete this; } bool MethodTransform::try_sync() { TRACE(MTRANS, 5, "Syncing %s\n", SHOW(m_method)); auto code = m_method->get_code(); auto& opout = code->get_instructions(); opout.clear(); uint32_t addr = 0; addr_mei_t addr_to_mei; // Step 1, regenerate opcode list for the method, and // and calculate the opcode entries address offsets. TRACE(MTRANS, 5, "Emitting opcodes\n"); for (auto miter = m_fmethod->begin(); miter != m_fmethod->end(); miter++) { MethodItemEntry* mentry = &*miter; TRACE(MTRANS, 5, "Analyzing mentry %p\n", mentry); mentry->addr = addr; if (mentry->type == MFLOW_OPCODE) { if ((mentry->insn->opcode() == FOPCODE_FILLED_ARRAY) && (addr & 1)) { opout.push_back(new DexInstruction(OPCODE_NOP)); ++addr; } addr_to_mei[addr] = mentry; TRACE(MTRANS, 5, "Emitting mentry %p at %08x\n", mentry, addr); opout.push_back(mentry->insn); addr += mentry->insn->size(); } } // Step 2, recalculate branches..., save off multi-branch data. TRACE(MTRANS, 5, "Recalculating branches\n"); std::vector<MethodItemEntry*> multi_branches; std::unordered_map<MethodItemEntry*, std::vector<BranchTarget*>> multis; std::unordered_map<BranchTarget*, uint32_t> multi_targets; std::unordered_map<DexTryItem*, std::vector<MethodItemEntry*>> try_items; for (auto miter = m_fmethod->begin(); miter != m_fmethod->end(); miter++) { MethodItemEntry* mentry = &*miter; if (mentry->type == MFLOW_OPCODE) { auto opcode = mentry->insn->opcode(); if (is_branch(opcode) && is_multi_branch(opcode)) { multi_branches.push_back(mentry); } } if (mentry->type == MFLOW_TARGET) { BranchTarget* bt = mentry->target; if (bt->type == BRANCH_MULTI) { multis[bt->src].push_back(bt); multi_targets[bt] = mentry->addr; // We can't fix the primary switch opcodes address until we emit // the fopcode, which comes later. } else if (bt->type == BRANCH_SIMPLE) { MethodItemEntry* tomutate = bt->src; int32_t branchoffset = mentry->addr - tomutate->addr; if ((tomutate->insn->opcode() == OPCODE_FILL_ARRAY_DATA) && (mentry->addr & 1)) { ++branchoffset; // account for nop spacer } auto encode_result = encode_offset(tomutate->insn, branchoffset); if (!encode_result.success) { auto inst = tomutate->insn; tomutate->insn = new DexInstruction(encode_result.newopcode); delete inst; return false; } } } if (mentry->type == MFLOW_TRY) { try_items[mentry->tentry->tentry].push_back(mentry); } } TRACE(MTRANS, 5, "Emitting multi-branches\n"); // Step 3, generate multi-branch fopcodes for (auto multiopcode : multi_branches) { auto targets = multis[multiopcode]; std::sort(targets.begin(), targets.end(), multi_target_compare_index); if (multi_contains_gaps(targets)) { // Emit sparse. int count = (targets.size() * 4) + 2; uint16_t sparse_payload[count]; sparse_payload[0] = FOPCODE_SPARSE_SWITCH; sparse_payload[1] = targets.size(); uint32_t* spkeys = (uint32_t*)&sparse_payload[2]; uint32_t* sptargets = (uint32_t*)&sparse_payload[2 + (targets.size() * 2)]; for (auto target : targets) { *spkeys++ = target->index; *sptargets++ = multi_targets[target] - multiopcode->addr; } // Emit align nop if (addr & 1) { DexInstruction* nop = new DexInstruction(0); opout.push_back(nop); addr++; } // Insert the new fopcode... DexInstruction* fop = new DexOpcodeData(sparse_payload, count - 1); opout.push_back(fop); // re-write the source opcode with the address of the // fopcode, increment the address of the fopcode. encode_offset(multiopcode->insn, addr - multiopcode->addr); multiopcode->insn->set_opcode(OPCODE_SPARSE_SWITCH); addr += count; } else { // Emit packed. int count = (targets.size() * 2) + 4; uint16_t packed_payload[count]; packed_payload[0] = FOPCODE_PACKED_SWITCH; packed_payload[1] = targets.size(); uint32_t* psdata = (uint32_t*)&packed_payload[2]; *psdata++ = targets.front()->index; for (auto target : targets) { *psdata++ = multi_targets[target] - multiopcode->addr; } // Emit align nop if (addr & 1) { DexInstruction* nop = new DexInstruction(0); opout.push_back(nop); addr++; } // Insert the new fopcode... DexInstruction* fop = new DexOpcodeData(packed_payload, count - 1); opout.push_back(fop); // re-write the source opcode with the address of the // fopcode, increment the address of the fopcode. encode_offset(multiopcode->insn, addr - multiopcode->addr); multiopcode->insn->set_opcode(OPCODE_PACKED_SWITCH); addr += count; } } // Step 4, emit debug opcodes TRACE(MTRANS, 5, "Emitting debug opcodes\n"); auto debugitem = code->get_debug_item(); if (debugitem) { auto& dopout = debugitem->get_instructions(); int32_t absolute_line = int32_t(debugitem->get_line_start()); dopout.clear(); uint32_t daddr = 0; for (auto miter = m_fmethod->begin(); miter != m_fmethod->end(); miter++) { MethodItemEntry* mentry = &*miter; if (mentry->type == MFLOW_DEBUG) { auto dbgop = mentry->dbgop; auto op = dbgop->opcode(); switch (op) { case DBG_END_LOCAL: case DBG_RESTART_LOCAL: case DBG_START_LOCAL: case DBG_START_LOCAL_EXTENDED: case DBG_SET_FILE: case DBG_END_SEQUENCE: case DBG_SET_PROLOGUE_END: case DBG_SET_EPILOGUE_BEGIN: break; case DBG_ADVANCE_LINE: { auto diff = dbgop->value() - absolute_line; dbgop->set_value(diff); absolute_line += diff; break; } case DBG_ADVANCE_PC: { uint32_t advance = mentry->addr - daddr; dbgop->set_uvalue(advance); daddr += advance; break; } default: { auto line_adjust = dbgop->value() - absolute_line; auto addr_adjust = mentry->addr - daddr; absolute_line += line_adjust; if (line_adjust < kDebugLineBase || line_adjust >= (kDebugLineRange + kDebugLineBase)) { dopout.push_back(new DexDebugInstruction(DBG_ADVANCE_LINE, line_adjust)); line_adjust = 0; } auto special = (line_adjust - kDebugLineBase) + (addr_adjust * kDebugLineRange) + kDebugFirstSpecial; if (special > 0xff) { dopout.push_back( new DexDebugInstruction(DBG_ADVANCE_PC, uint32_t(addr_adjust))); addr_adjust = 0; special = line_adjust - kDebugLineBase + kDebugFirstSpecial; } dbgop->set_opcode(static_cast<DexDebugItemOpcode>(special)); dbgop->set_uvalue(DEX_NO_INDEX); daddr = mentry->addr; break; } } TRACE(MTRANS, 5, "emit: %08x:%02x\n", daddr, dbgop->opcode()); dopout.push_back(dbgop); } } } // Step 5, try/catch blocks auto& tries = code->get_tries(); tries.clear(); for (auto tryitem : try_items) { DexTryItem* dextry = tryitem.first; auto& tryentries = tryitem.second; sort(tryentries.begin(), tryentries.end(), order_try_entries); dextry->m_catches.clear(); MethodItemEntry* try_start = nullptr; bool suppress = false; for (auto tryentry : tryentries) { switch (tryentry->tentry->type) { case TRY_START: dextry->m_start_addr = tryentry->addr; try_start = tryentry; break; case TRY_END: assert(try_start != nullptr); assert(try_start->addr <= tryentry->addr); dextry->m_insn_count = tryentry->addr - try_start->addr; if (dextry->m_insn_count == 0) { suppress = true; } break; case TRY_CATCH: if (tryentry->tentry->centry == nullptr) { /* Catch all */ dextry->m_catchall = tryentry->addr; } else { dextry->m_catches.push_back( std::make_pair(tryentry->tentry->centry, tryentry->addr)); } break; default: always_assert_log(false, "Invalid try entry type"); } } if (!suppress) { tries.push_back(dextry); } } std::sort(tries.begin(), tries.end(), [](const DexTryItem* a, const DexTryItem* b) { return a->m_start_addr < b->m_start_addr; }); return true; } Fix UB in reading opcode data Summary: We're reading unaligned int32_t's from a uint16_t*. This is undefined behavior; the "correct" way is to use memcpy. Or to align the buffer, but since the data opcodes hold arbitrary 16-bit nibbles, it seems better to do the former. Reviewed By: dariorussi Differential Revision: D3314739 fbshipit-source-id: b244c0212a15b45e71936b961ec3484be0d1e596 /** * Copyright (c) 2016-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ #include "Transform.h" #include <algorithm> #include "Debug.h" #include "DexClass.h" #include "DexDebugInstruction.h" #include "DexInstruction.h" #include "WorkQueue.h" //////////////////////////////////////////////////////////////////////////////// std::mutex MethodTransform::s_lock; MethodTransform::FatMethodCache MethodTransform::s_cache; //////////////////////////////////////////////////////////////////////////////// void PostOrderSort::postorder(Block* b) { auto pos = m_visited.find(b); if (pos != m_visited.end()) { return; } m_visited.emplace_hint(pos, b); for (auto& s : b->succs()) { postorder(s); } m_postorder_list.emplace_back(b); } std::vector<Block*>&& PostOrderSort::get() { if (m_cfg.size() > 0) { postorder(m_cfg[0]); for (size_t i = 1; i < m_cfg.size(); i++) { if (m_cfg[i]->preds().size() == 0) postorder(m_cfg[i]); } } return std::move(m_postorder_list); } //////////////////////////////////////////////////////////////////////////////// MethodTransform::~MethodTransform() { m_fmethod->clear_and_dispose(FatMethodDisposer()); delete m_fmethod; for (auto block : m_blocks) { delete block; } } MethodTransform* MethodTransform::get_method_transform( DexMethod* method, bool want_cfg /* = false */ ) { { std::lock_guard<std::mutex> g(s_lock); auto it = s_cache.find(method); if (it != s_cache.end()) { MethodTransform* mt = it->second; return mt; } } FatMethod* fm = balloon(method); MethodTransform* mt = new MethodTransform(method, fm); if (want_cfg) { mt->build_cfg(); } { std::lock_guard<std::mutex> g(s_lock); s_cache[method] = mt; return mt; } } MethodTransform* MethodTransform::get_new_method(DexMethod* method) { return new MethodTransform(method, new FatMethod()); } namespace { typedef std::unordered_map<uint32_t, MethodItemEntry*> addr_mei_t; struct EncodeResult { bool success; DexOpcode newopcode; }; EncodeResult encode_offset(DexInstruction* insn, int32_t offset) { int bytecount = 4; if ((int32_t)((int8_t)(offset & 0xff)) == offset) { bytecount = 1; } else if ((int32_t)((int16_t)(offset & 0xffff)) == offset) { bytecount = 2; } auto op = insn->opcode(); if (is_conditional_branch(op)) { always_assert_log(bytecount <= 2, "Overflowed 16-bit encoding for offset in %s", SHOW(insn)); } if (is_goto(op)) { // Use the smallest encoding possible. auto newopcode = [&] { switch (bytecount) { case 1: return OPCODE_GOTO; case 2: return OPCODE_GOTO_16; case 4: return OPCODE_GOTO_32; } always_assert_log(false, "Invalid bytecount for %s", SHOW(insn)); }(); if (newopcode != op) { return {false, newopcode}; } } insn->set_offset(offset); return {true, op}; } static MethodItemEntry* get_target(MethodItemEntry* mei, addr_mei_t& addr_to_mei) { uint32_t base = mei->addr; int offset = mei->insn->offset(); uint32_t target = base + offset; always_assert_log( addr_to_mei.count(target) != 0, "Invalid opcode target %08x[%p](%08x) %08x in get_target %s\n", base, mei, offset, target, SHOW(mei->insn)); return addr_to_mei[target]; } static void insert_mentry_before(FatMethod* fm, MethodItemEntry* mentry, MethodItemEntry* dest) { if (dest == nullptr) { fm->push_back(*mentry); } else { fm->insert(fm->iterator_to(*dest), *mentry); } } static void insert_branch_target(FatMethod* fm, MethodItemEntry* target, MethodItemEntry* src) { BranchTarget* bt = new BranchTarget(); bt->type = BRANCH_SIMPLE; bt->src = src; MethodItemEntry* mentry = new MethodItemEntry(bt); ; insert_mentry_before(fm, mentry, target); } static void insert_fallthrough(FatMethod* fm, MethodItemEntry* dest) { MethodItemEntry* fallthrough = new MethodItemEntry(); insert_mentry_before(fm, fallthrough, dest); } static bool multi_target_compare_index(const BranchTarget* a, const BranchTarget* b) { return (a->index < b->index); } static bool multi_contains_gaps(const std::vector<BranchTarget*>& targets) { int32_t key = targets.front()->index; for (auto target : targets) { if (target->index != key) return true; key++; } return false; } static void insert_multi_branch_target(FatMethod* fm, int32_t index, MethodItemEntry* target, MethodItemEntry* src) { BranchTarget* bt = new BranchTarget(); bt->type = BRANCH_MULTI; bt->src = src; bt->index = index; MethodItemEntry* mentry = new MethodItemEntry(bt); insert_mentry_before(fm, mentry, target); } static int32_t read_int32(const uint16_t*& data) { int32_t result; memcpy(&result, data, sizeof(int32_t)); data += 2; return result; } static void shard_multi_target(FatMethod* fm, DexOpcodeData* fopcode, MethodItemEntry* src, addr_mei_t& addr_to_mei) { const uint16_t* data = fopcode->data(); uint16_t entries = *data++; auto ftype = fopcode->opcode(); uint32_t base = src->addr; if (ftype == FOPCODE_PACKED_SWITCH) { int32_t index = read_int32(data); for (int i = 0; i < entries; i++) { uint32_t targetaddr = base + read_int32(data); auto target = addr_to_mei[targetaddr]; insert_multi_branch_target(fm, index, target, src); index++; } } else if (ftype == FOPCODE_SPARSE_SWITCH) { const uint16_t* tdata = data + 2 * entries; // entries are 32b for (int i = 0; i < entries; i++) { int32_t index = read_int32(data); uint32_t targetaddr = base + read_int32(tdata); auto target = addr_to_mei[targetaddr]; insert_multi_branch_target(fm, index, target, src); } } else { always_assert_log(false, "Bad fopcode 0x%04x in shard_multi_target", ftype); } } static void generate_branch_targets(FatMethod* fm, addr_mei_t& addr_to_mei) { for (auto miter = fm->begin(); miter != fm->end(); miter++) { MethodItemEntry* mentry = &*miter; if (mentry->type == MFLOW_OPCODE) { auto insn = mentry->insn; if (is_branch(insn->opcode())) { auto target = get_target(mentry, addr_to_mei); if (is_multi_branch(insn->opcode())) { auto fopcode = static_cast<DexOpcodeData*>(target->insn); shard_multi_target(fm, fopcode, mentry, addr_to_mei); fm->erase(fm->iterator_to(*target)); delete fopcode; addr_to_mei.erase(target->addr); } else { insert_branch_target(fm, target, mentry); } } } } } constexpr uint8_t kDebugFirstSpecial = 0x0a; constexpr uint8_t kDebugLineRange = 15; constexpr int8_t kDebugLineBase = -4; static void associate_debug_opcodes(FatMethod* fm, DexDebugItem* dbg, addr_mei_t& addr_to_mei) { uint32_t offset = 0; auto const& opcodes = dbg->get_instructions(); int32_t absolute_line = int32_t(dbg->get_line_start()); for (auto opcode : opcodes) { auto op = opcode->opcode(); TRACE(MTRANS, 5, "decode offset %08x %02x\n", offset, op); switch (op) { case DBG_ADVANCE_LINE: TRACE(MTRANS, 5, "Advance line %d\n", opcode->value()); absolute_line += opcode->value(); opcode->set_value(absolute_line); case DBG_END_LOCAL: case DBG_RESTART_LOCAL: case DBG_START_LOCAL: case DBG_START_LOCAL_EXTENDED: case DBG_SET_FILE: case DBG_END_SEQUENCE: case DBG_SET_PROLOGUE_END: case DBG_SET_EPILOGUE_BEGIN: { break; } case DBG_ADVANCE_PC: { offset += opcode->uvalue(); delete opcode; /* Ugh, messy, FIXME!!! */ continue; } default: { uint8_t adjustment = op; adjustment -= kDebugFirstSpecial; absolute_line += kDebugLineBase + (adjustment % kDebugLineRange); offset += adjustment / kDebugLineRange; opcode->set_uvalue(absolute_line); } } auto insert_point = addr_to_mei[offset]; if (!insert_point) { /* We don't have a way of emitting debug info for fopcodes. To * be honest, I'm not sure why DX emits them. We don't. */ TRACE(MTRANS, 5, "Warning..Skipping fopcode debug opcode\n"); continue; } MethodItemEntry* mentry = new MethodItemEntry(opcode); TRACE(MTRANS, 5, "insert at offset %08x %02x [%p][mentry%p]\n", offset, op, insert_point, mentry); insert_mentry_before(fm, mentry, insert_point); } } static bool order_try_entries(const MethodItemEntry* a, const MethodItemEntry* b) { return (a->tentry->order < b->tentry->order); } static void insert_try_entry(FatMethod* fm, TryEntryType type, DexTryItem* dti, MethodItemEntry* atmei, DexType* centry = nullptr, uint32_t order = 0) { TryEntry* tentry = new TryEntry(); tentry->type = type; tentry->tentry = dti; tentry->centry = centry; tentry->order = order; MethodItemEntry* mentry = new MethodItemEntry(tentry); insert_mentry_before(fm, mentry, atmei); } static void associate_try_items(FatMethod* fm, DexCode* code, addr_mei_t& addr_to_mei) { auto const& tries = code->get_tries(); for (auto tri : tries) { auto begin = addr_to_mei[tri->m_start_addr]; TRACE(MTRANS, 3, "try_start %08x mei %p\n", tri->m_start_addr, begin); insert_try_entry(fm, TRY_START, tri, begin); uint32_t lastaddr = tri->m_start_addr + tri->m_insn_count; auto end = addr_to_mei[lastaddr]; TRACE(MTRANS, 3, "try_end %08x mei %p\n", lastaddr, end); insert_try_entry(fm, TRY_END, tri, end); uint32_t order = 1; for (auto catz : tri->m_catches) { auto catzop = addr_to_mei[catz.second]; TRACE(MTRANS, 3, "try_catch %08x mei %p\n", catz.second, catzop); insert_try_entry(fm, TRY_CATCH, tri, catzop, catz.first, order++); } if (tri->m_catchall != DEX_NO_INDEX) { auto catzop = addr_to_mei[tri->m_catchall]; insert_try_entry(fm, TRY_CATCH, tri, catzop); } } } } FatMethod* MethodTransform::balloon(DexMethod* method) { auto code = method->get_code(); if (code == nullptr) { return nullptr; } TRACE(MTRANS, 2, "Ballooning %s\n", SHOW(method)); auto opcodes = code->get_instructions(); addr_mei_t addr_to_mei; FatMethod* fm = new FatMethod(); uint32_t addr = 0; for (auto opcode : opcodes) { MethodItemEntry* mei = new MethodItemEntry(opcode); fm->push_back(*mei); addr_to_mei[addr] = mei; mei->addr = addr; TRACE(MTRANS, 5, "%08x: %s[mei %p]\n", addr, SHOW(opcode), mei); addr += opcode->size(); } generate_branch_targets(fm, addr_to_mei); associate_try_items(fm, code, addr_to_mei); auto debugitem = code->get_debug_item(); if (debugitem) { associate_debug_opcodes(fm, debugitem, addr_to_mei); } return fm; } void MethodTransform::replace_opcode(DexInstruction* from, DexInstruction* to) { for (auto miter = m_fmethod->begin(); miter != m_fmethod->end(); miter++) { MethodItemEntry* mentry = &*miter; if (mentry->type == MFLOW_OPCODE && mentry->insn == from) { mentry->insn = to; delete from; return; } } always_assert_log( false, "No match found while replacing '%s' with '%s' in method %s", SHOW(from), SHOW(to), show_short(m_method).c_str()); } void MethodTransform::insert_after(DexInstruction* position, std::list<DexInstruction*>& opcodes) { /* The nullptr case handling is strange-ish..., this will not work as expected *if * a method has a branch target as it's first instruction. * * To handle this case sanely, we'd need to export a interface based on * MEI's probably. * */ for (auto const& mei : *m_fmethod) { if (mei.type == MFLOW_OPCODE && (position == nullptr || mei.insn == position)) { auto insertat = m_fmethod->iterator_to(mei); if (position != nullptr) insertat++; for (auto opcode : opcodes) { MethodItemEntry* mentry = new MethodItemEntry(opcode); m_fmethod->insert(insertat, *mentry); } return; } } always_assert_log(false, "No match found"); } void MethodTransform::remove_opcode(DexInstruction* insn) { for (auto const& mei : *m_fmethod) { if (mei.type == MFLOW_OPCODE && mei.insn == insn) { m_fmethod->erase(m_fmethod->iterator_to(mei)); delete insn; return; } } always_assert_log(false, "No match found while removing '%s' from method %s", SHOW(insn), show_short(m_method).c_str()); } FatMethod::iterator MethodTransform::main_block() { return m_fmethod->begin(); } FatMethod::iterator MethodTransform::insert(FatMethod::iterator cur, DexInstruction* insn) { MethodItemEntry* mentry = new MethodItemEntry(insn); return m_fmethod->insert(cur, *mentry); } FatMethod::iterator MethodTransform::make_if_block( FatMethod::iterator cur, DexInstruction* insn, FatMethod::iterator* false_block) { auto if_entry = new MethodItemEntry(insn); *false_block = m_fmethod->insert(cur, *if_entry); auto bt = new BranchTarget(); bt->src = if_entry; bt->type = BRANCH_SIMPLE; auto bentry = new MethodItemEntry(bt); return m_fmethod->insert(m_fmethod->end(), *bentry); } FatMethod::iterator MethodTransform::make_if_else_block( FatMethod::iterator cur, DexInstruction* insn, FatMethod::iterator* false_block, FatMethod::iterator* true_block) { // if block auto if_entry = new MethodItemEntry(insn); *false_block = m_fmethod->insert(cur, *if_entry); // end of else goto auto goto_entry = new MethodItemEntry(new DexInstruction(OPCODE_GOTO)); auto goto_it = m_fmethod->insert(m_fmethod->end(), *goto_entry); // main block auto main_bt = new BranchTarget(); main_bt->src = goto_entry; main_bt->type = BRANCH_SIMPLE; auto mb_entry = new MethodItemEntry(main_bt); auto main_block = m_fmethod->insert(goto_it, *mb_entry); // else block auto else_bt = new BranchTarget(); else_bt->src = if_entry; else_bt->type = BRANCH_SIMPLE; auto eb_entry = new MethodItemEntry(else_bt); *true_block = m_fmethod->insert(goto_it, *eb_entry); return main_block; } FatMethod::iterator MethodTransform::make_switch_block( FatMethod::iterator cur, DexInstruction* insn, FatMethod::iterator* default_block, std::map<int, FatMethod::iterator>& cases) { auto switch_entry = new MethodItemEntry(insn); *default_block = m_fmethod->insert(cur, *switch_entry); FatMethod::iterator main_block = *default_block; for (auto case_it = cases.begin(); case_it != cases.end(); ++case_it) { auto goto_entry = new MethodItemEntry(new DexInstruction(OPCODE_GOTO)); auto goto_it = m_fmethod->insert(m_fmethod->end(), *goto_entry); auto main_bt = new BranchTarget(); main_bt->src = goto_entry; main_bt->type = BRANCH_SIMPLE; auto mb_entry = new MethodItemEntry(main_bt); main_block = m_fmethod->insert(++main_block, *mb_entry); // case block auto case_bt = new BranchTarget(); case_bt->src = switch_entry; case_bt->index = case_it->first; case_bt->type = BRANCH_MULTI; auto eb_entry = new MethodItemEntry(case_bt); case_it->second = m_fmethod->insert(goto_it, *eb_entry); } return main_block; } namespace { using RegMap = std::unordered_map<uint16_t, uint16_t>; void remap_dest(DexInstruction* inst, const RegMap& reg_map) { if (!inst->dests_size()) return; if (inst->dest_is_src()) return; auto it = reg_map.find(inst->dest()); if (it == reg_map.end()) return; inst->set_dest(it->second); } void remap_srcs(DexInstruction* inst, const RegMap& reg_map) { for (unsigned i = 0; i < inst->srcs_size(); i++) { auto it = reg_map.find(inst->src(i)); if (it == reg_map.end()) continue; inst->set_src(i, it->second); } } void remap_debug(DexDebugInstruction* dbgop, const RegMap& reg_map) { switch (dbgop->opcode()) { case DBG_START_LOCAL: case DBG_START_LOCAL_EXTENDED: case DBG_END_LOCAL: case DBG_RESTART_LOCAL: { auto it = reg_map.find(dbgop->uvalue()); if (it == reg_map.end()) return; dbgop->set_uvalue(it->second); break; } default: break; } } void remap_registers(MethodItemEntry& mei, const RegMap& reg_map) { switch (mei.type) { case MFLOW_OPCODE: remap_dest(mei.insn, reg_map); remap_srcs(mei.insn, reg_map); break; case MFLOW_DEBUG: remap_debug(mei.dbgop, reg_map); break; default: break; } } void remap_registers(FatMethod* fmethod, const RegMap& reg_map) { for (auto& mei : *fmethod) { remap_registers(mei, reg_map); } } void remap_caller_regs(DexMethod* method, FatMethod* fmethod, uint16_t newregs) { RegMap reg_map; auto oldregs = method->get_code()->get_registers_size(); auto ins = method->get_code()->get_ins_size(); for (uint16_t i = 0; i < ins; ++i) { reg_map[oldregs - ins + i] = newregs - ins + i; } remap_registers(fmethod, reg_map); method->get_code()->set_registers_size(newregs); } void remap_callee_regs(DexInstruction* invoke, DexMethod* method, FatMethod* fmethod, uint16_t newregs) { RegMap reg_map; auto oldregs = method->get_code()->get_registers_size(); auto ins = method->get_code()->get_ins_size(); auto wc = invoke->arg_word_count(); always_assert(ins == wc); for (uint16_t i = 0; i < wc; ++i) { reg_map[oldregs - ins + i] = invoke->src(i); } remap_registers(fmethod, reg_map); method->get_code()->set_registers_size(newregs); } /** * Builds a register map for a callee. */ void build_remap_regs(RegMap& reg_map, DexInstruction* invoke, DexMethod* callee, uint16_t new_tmp_off) { auto oldregs = callee->get_code()->get_registers_size(); auto ins = callee->get_code()->get_ins_size(); auto wc = invoke->arg_word_count(); always_assert(ins == wc); // remap all local regs (not args) for (uint16_t i = 0; i < oldregs - ins; ++i) { reg_map[i] = new_tmp_off + i; } for (uint16_t i = 0; i < wc; ++i) { reg_map[oldregs - ins + i] = invoke->src(i); } } /** * Create a move instruction given a return instruction in a callee and * a move-result instruction in a caller. */ DexInstruction* move_result(DexInstruction* res, DexInstruction* move_res) { auto opcode = res->opcode(); always_assert(opcode != OPCODE_RETURN_VOID); DexInstruction* move; if (opcode == OPCODE_RETURN_OBJECT) { move = new DexInstruction(OPCODE_MOVE_OBJECT); } else if (opcode == OPCODE_RETURN_WIDE) { move = new DexInstruction(OPCODE_MOVE_WIDE); } else { always_assert(opcode == OPCODE_RETURN); move = new DexInstruction(OPCODE_MOVE); } move->set_dest(move_res->dest()); move->set_src(0, res->src(0)); return move; } /* We need to cleanup two cases: * Duplicate DBG_SET_PROLOGUE_END * Uninitialized parameters * * The parameter names are part of the debug info for the method. * The technically correct solution would be to make a start * local for each of them. However, that would also imply another * end local after the tail to correctly set what the register * is at the end. This would bloat the debug info parameters for * a corner case. * * Instead, we just delete locals lifetime information for parameters. * This is an exceedingly rare case triggered by goofy code that * reuses parameters as locals. */ void cleanup_callee_debug(FatMethod* fcallee) { std::unordered_set<uint16_t> valid_regs; auto it = fcallee->begin(); while (it != fcallee->end()) { auto& mei = *it++; if (mei.type == MFLOW_DEBUG) { switch(mei.dbgop->opcode()) { case DBG_SET_PROLOGUE_END: fcallee->erase(fcallee->iterator_to(mei)); break; case DBG_START_LOCAL: case DBG_START_LOCAL_EXTENDED: { auto reg = mei.dbgop->uvalue(); valid_regs.insert(reg); break; } case DBG_END_LOCAL: case DBG_RESTART_LOCAL: { auto reg = mei.dbgop->uvalue(); if (valid_regs.find(reg) == valid_regs.end()) { fcallee->erase(fcallee->iterator_to(mei)); } break; } default: break; } } } } MethodItemEntry* clone( MethodItemEntry* mei, std::unordered_map<MethodItemEntry*, MethodItemEntry*>& entry_map) { MethodItemEntry* cloned_mei; auto entry = entry_map.find(mei); if (entry != entry_map.end()) { return entry->second; } cloned_mei = new MethodItemEntry(*mei); entry_map[mei] = cloned_mei; switch (cloned_mei->type) { case MFLOW_TRY: cloned_mei->tentry = new TryEntry(*cloned_mei->tentry); cloned_mei->tentry->tentry = new DexTryItem(*cloned_mei->tentry->tentry); return cloned_mei; case MFLOW_OPCODE: cloned_mei->insn = cloned_mei->insn->clone(); return cloned_mei; case MFLOW_TARGET: cloned_mei->target = new BranchTarget(*cloned_mei->target); cloned_mei->target->src = clone(cloned_mei->target->src, entry_map); return cloned_mei; case MFLOW_DEBUG: cloned_mei->dbgop = cloned_mei->dbgop->clone(); return cloned_mei; case MFLOW_FALLTHROUGH: return cloned_mei; } not_reached(); } } void MethodTransform::inline_tail_call(DexMethod* caller, DexMethod* callee, DexInstruction* invoke) { TRACE(INL, 2, "caller: %s\ncallee: %s\n", SHOW(caller), SHOW(callee)); MethodTransformer tcaller(caller); MethodTransformer tcallee(callee); auto fcaller = tcaller->m_fmethod; auto fcallee = tcallee->m_fmethod; auto bregs = caller->get_code()->get_registers_size(); auto eregs = callee->get_code()->get_registers_size(); auto bins = caller->get_code()->get_ins_size(); auto eins = callee->get_code()->get_ins_size(); always_assert(bins >= eins); auto newregs = std::max(bregs, uint16_t(eregs + bins - eins)); always_assert(newregs <= 16); // Remap registers to account for possibly larger frame, more ins remap_caller_regs(caller, fcaller, newregs); remap_callee_regs(invoke, callee, fcallee, newregs); callee->get_code()->set_ins_size(bins); auto pos = std::find_if(fcaller->begin(), fcaller->end(), [invoke](const MethodItemEntry& mei) { return mei.type == MFLOW_OPCODE && mei.insn == invoke; }); cleanup_callee_debug(fcallee); auto it = fcallee->begin(); while (it != fcallee->end()) { auto& mei = *it++; fcallee->erase(fcallee->iterator_to(mei)); fcaller->insert(pos, mei); } // Delete the vestigial tail. while (pos != fcaller->end()) { if (pos->type == MFLOW_OPCODE) { pos = fcaller->erase_and_dispose(pos, FatMethodDisposer()); } else { ++pos; } } caller->get_code()->set_outs_size(callee->get_code()->get_outs_size()); } bool MethodTransform::inline_16regs(InlineContext& context, DexMethod *callee, DexOpcodeMethod *invoke) { TRACE(INL, 2, "caller: %s\ncallee: %s\n", SHOW(context.caller), SHOW(callee)); auto caller = context.caller; MethodTransformer mtcaller(caller); MethodTransformer mtcallee(callee); auto fcaller = mtcaller->m_fmethod; auto fcallee = mtcallee->m_fmethod; auto callee_code = callee->get_code(); auto temps_needed = callee_code->get_registers_size() - callee_code->get_ins_size(); uint16_t newregs = caller->get_code()->get_registers_size(); if (context.inline_regs_used < temps_needed) { newregs = newregs + temps_needed - context.inline_regs_used; if (newregs > 16) return false; remap_caller_regs(caller, fcaller, newregs); context.inline_regs_used = temps_needed; } RegMap callee_reg_map; build_remap_regs(callee_reg_map, invoke, callee, context.new_tmp_off); auto pos = std::find_if( fcaller->begin(), fcaller->end(), [invoke](const MethodItemEntry& mei) { return mei.type == MFLOW_OPCODE && mei.insn == invoke; }); // find the move-result after the invoke, if any. Must be the first // instruction after the invoke auto move_res = pos; while (move_res++ != fcaller->end() && move_res->type != MFLOW_OPCODE); if (!is_move_result(move_res->insn->opcode())) { move_res = fcaller->end(); } // Skip dbg prologue in callee, we don't need two. auto it = fcallee->begin(); if (it->type == MFLOW_DEBUG && it->dbgop->opcode() == DBG_SET_PROLOGUE_END) { ++it; } // Copy the callee up to the return. Everything else we push at the end // of the caller // We need a map of MethodItemEntry we have created because a branch // points to another MethodItemEntry which may have been created or not std::unordered_map<MethodItemEntry*, MethodItemEntry*> entry_map; while (it != fcallee->end()) { auto mei = clone(&*it, entry_map); remap_registers(*mei, callee_reg_map); it++; if (mei->type == MFLOW_OPCODE && is_return(mei->insn->opcode())) { if (move_res != fcaller->end()) { DexInstruction* move = move_result(mei->insn, move_res->insn); auto move_mei = new MethodItemEntry(move); fcaller->insert(pos, *move_mei); delete mei->insn; delete mei; } break; } else { fcaller->insert(pos, *mei); } } // remove invoke fcaller->erase_and_dispose(pos, FatMethodDisposer()); // remove move_result if (move_res != fcaller->end()) { fcaller->erase_and_dispose(move_res, FatMethodDisposer()); } while (it != fcallee->end()) { auto mei = clone(&*it, entry_map); remap_registers(*mei, callee_reg_map); it++; fcaller->push_back(*mei); } // adjust method header caller->get_code()->set_registers_size(newregs); caller->get_code()->set_outs_size( std::max(callee->get_code()->get_outs_size(), caller->get_code()->get_outs_size())); return true; } namespace { bool end_of_block(const FatMethod* fm, FatMethod::iterator it, bool in_try) { auto next = std::next(it); if (next == fm->end()) { return true; } if (next->type == MFLOW_TARGET || next->type == MFLOW_TRY) { return true; } if (it->type != MFLOW_OPCODE) { return false; } if (is_branch(it->insn->opcode())) { return true; } if (in_try && may_throw(it->insn->opcode())) { return true; } return false; } } bool ends_with_may_throw(Block* p) { for (auto last = p->rbegin(); last != p->rend(); ++last) { if (last->type != MFLOW_OPCODE) { continue; } return may_throw(last->insn->opcode()); } return true; } void MethodTransform::build_cfg() { // Find the block boundaries std::unordered_map<MethodItemEntry*, std::vector<Block*>> branch_to_targets; std::vector<std::pair<DexTryItem*, Block*>> try_ends; std::unordered_map<DexTryItem*, std::vector<Block*>> try_catches; size_t id = 0; bool in_try = false; m_blocks.emplace_back(new Block(id++)); m_blocks.back()->m_begin = m_fmethod->begin(); // The first block can be a branch target. auto begin = m_fmethod->begin(); if (begin->type == MFLOW_TARGET) { branch_to_targets[begin->target->src].push_back(m_blocks.back()); } for (auto it = m_fmethod->begin(); it != m_fmethod->end(); ++it) { if (it->type == MFLOW_TRY) { if (it->tentry->type == TRY_START) { in_try = true; } else if (it->tentry->type == TRY_END) { in_try = false; } } if (!end_of_block(m_fmethod, it, in_try)) { continue; } // End the current block. auto next = std::next(it); if (next == m_fmethod->end()) { m_blocks.back()->m_end = next; continue; } // Start a new block at the next MethodItem. auto next_block = new Block(id++); if (next->type == MFLOW_OPCODE) { insert_fallthrough(m_fmethod, &*next); next = std::next(it); } m_blocks.back()->m_end = next; next_block->m_begin = next; m_blocks.emplace_back(next_block); // Record branch targets to add edges in the next pass. if (next->type == MFLOW_TARGET) { branch_to_targets[next->target->src].push_back(next_block); continue; } // Record try/catch blocks to add edges in the next pass. if (next->type == MFLOW_TRY) { if (next->tentry->type == TRY_END) { try_ends.emplace_back(next->tentry->tentry, next_block); } else if (next->tentry->type == TRY_CATCH) { try_catches[next->tentry->tentry].push_back(next_block); } } } // Link the blocks together with edges for (auto it = m_blocks.begin(); it != m_blocks.end(); ++it) { // Set outgoing edge if last MIE falls through auto lastmei = (*it)->rbegin(); bool fallthrough = true; if (lastmei->type == MFLOW_OPCODE) { auto lastop = lastmei->insn->opcode(); if (is_goto(lastop) || is_conditional_branch(lastop) || is_multi_branch(lastop)) { fallthrough = !is_goto(lastop); auto const& targets = branch_to_targets[&*lastmei]; for (auto target : targets) { (*it)->m_succs.push_back(target); target->m_preds.push_back(*it); } } else if (is_return(lastop) || lastop == OPCODE_THROW) { fallthrough = false; } } if (fallthrough && std::next(it) != m_blocks.end()) { Block* next = *std::next(it); (*it)->m_succs.push_back(next); next->m_preds.push_back(*it); } } /* * Now add the catch edges. Every block inside a try-start/try-end region * gets an edge to every catch block. This simplifies dataflow analysis * since you can always get the exception state by looking at successors, * without any additional analysis. * * NB: This algorithm assumes that a try-start/try-end region will consist of * sequentially-numbered blocks, which is guaranteed because catch regions * are contiguous in the bytecode, and we generate blocks in bytecode order. */ for (auto tep : try_ends) { auto tryitem = tep.first; auto tryendblock = tep.second; size_t bid = tryendblock->id(); always_assert(bid > 0); --bid; while (true) { auto block = m_blocks[bid]; if (ends_with_may_throw(block)) { auto& catches = try_catches[tryitem]; for (auto catchblock : catches) { block->m_succs.push_back(catchblock); catchblock->m_preds.push_back(block); } } auto begin = block->begin(); if (begin->type == MFLOW_TRY) { auto tentry = begin->tentry; if (tentry->type == TRY_START && tentry->tentry == tryitem) { break; } } always_assert_log(bid > 0, "No beginning of try region found"); --bid; } } TRACE(CFG, 5, "%s\n", show(m_method).c_str()); TRACE(CFG, 5, "%s", show(m_blocks).c_str()); } void MethodTransform::sync_all() { std::vector<MethodTransform*> transforms; for (auto& centry : s_cache) { transforms.push_back(centry.second); } std::vector<WorkItem<MethodTransform>> workitems(transforms.size()); auto mt_sync = [](MethodTransform* mt) { mt->sync(); }; for (size_t i = 0; i < transforms.size(); i++) { workitems[i].init(mt_sync, transforms[i]); } WorkQueue wq; wq.run_work_items(&workitems[0], workitems.size()); } void MethodTransform::sync() { while (try_sync() == false) ; { std::lock_guard<std::mutex> g(s_lock); s_cache.erase(m_method); } delete this; } bool MethodTransform::try_sync() { TRACE(MTRANS, 5, "Syncing %s\n", SHOW(m_method)); auto code = m_method->get_code(); auto& opout = code->get_instructions(); opout.clear(); uint32_t addr = 0; addr_mei_t addr_to_mei; // Step 1, regenerate opcode list for the method, and // and calculate the opcode entries address offsets. TRACE(MTRANS, 5, "Emitting opcodes\n"); for (auto miter = m_fmethod->begin(); miter != m_fmethod->end(); miter++) { MethodItemEntry* mentry = &*miter; TRACE(MTRANS, 5, "Analyzing mentry %p\n", mentry); mentry->addr = addr; if (mentry->type == MFLOW_OPCODE) { if ((mentry->insn->opcode() == FOPCODE_FILLED_ARRAY) && (addr & 1)) { opout.push_back(new DexInstruction(OPCODE_NOP)); ++addr; } addr_to_mei[addr] = mentry; TRACE(MTRANS, 5, "Emitting mentry %p at %08x\n", mentry, addr); opout.push_back(mentry->insn); addr += mentry->insn->size(); } } // Step 2, recalculate branches..., save off multi-branch data. TRACE(MTRANS, 5, "Recalculating branches\n"); std::vector<MethodItemEntry*> multi_branches; std::unordered_map<MethodItemEntry*, std::vector<BranchTarget*>> multis; std::unordered_map<BranchTarget*, uint32_t> multi_targets; std::unordered_map<DexTryItem*, std::vector<MethodItemEntry*>> try_items; for (auto miter = m_fmethod->begin(); miter != m_fmethod->end(); miter++) { MethodItemEntry* mentry = &*miter; if (mentry->type == MFLOW_OPCODE) { auto opcode = mentry->insn->opcode(); if (is_branch(opcode) && is_multi_branch(opcode)) { multi_branches.push_back(mentry); } } if (mentry->type == MFLOW_TARGET) { BranchTarget* bt = mentry->target; if (bt->type == BRANCH_MULTI) { multis[bt->src].push_back(bt); multi_targets[bt] = mentry->addr; // We can't fix the primary switch opcodes address until we emit // the fopcode, which comes later. } else if (bt->type == BRANCH_SIMPLE) { MethodItemEntry* tomutate = bt->src; int32_t branchoffset = mentry->addr - tomutate->addr; if ((tomutate->insn->opcode() == OPCODE_FILL_ARRAY_DATA) && (mentry->addr & 1)) { ++branchoffset; // account for nop spacer } auto encode_result = encode_offset(tomutate->insn, branchoffset); if (!encode_result.success) { auto inst = tomutate->insn; tomutate->insn = new DexInstruction(encode_result.newopcode); delete inst; return false; } } } if (mentry->type == MFLOW_TRY) { try_items[mentry->tentry->tentry].push_back(mentry); } } TRACE(MTRANS, 5, "Emitting multi-branches\n"); // Step 3, generate multi-branch fopcodes for (auto multiopcode : multi_branches) { auto targets = multis[multiopcode]; std::sort(targets.begin(), targets.end(), multi_target_compare_index); if (multi_contains_gaps(targets)) { // Emit sparse. int count = (targets.size() * 4) + 2; uint16_t sparse_payload[count]; sparse_payload[0] = FOPCODE_SPARSE_SWITCH; sparse_payload[1] = targets.size(); uint32_t* spkeys = (uint32_t*)&sparse_payload[2]; uint32_t* sptargets = (uint32_t*)&sparse_payload[2 + (targets.size() * 2)]; for (auto target : targets) { *spkeys++ = target->index; *sptargets++ = multi_targets[target] - multiopcode->addr; } // Emit align nop if (addr & 1) { DexInstruction* nop = new DexInstruction(0); opout.push_back(nop); addr++; } // Insert the new fopcode... DexInstruction* fop = new DexOpcodeData(sparse_payload, count - 1); opout.push_back(fop); // re-write the source opcode with the address of the // fopcode, increment the address of the fopcode. encode_offset(multiopcode->insn, addr - multiopcode->addr); multiopcode->insn->set_opcode(OPCODE_SPARSE_SWITCH); addr += count; } else { // Emit packed. int count = (targets.size() * 2) + 4; uint16_t packed_payload[count]; packed_payload[0] = FOPCODE_PACKED_SWITCH; packed_payload[1] = targets.size(); uint32_t* psdata = (uint32_t*)&packed_payload[2]; *psdata++ = targets.front()->index; for (auto target : targets) { *psdata++ = multi_targets[target] - multiopcode->addr; } // Emit align nop if (addr & 1) { DexInstruction* nop = new DexInstruction(0); opout.push_back(nop); addr++; } // Insert the new fopcode... DexInstruction* fop = new DexOpcodeData(packed_payload, count - 1); opout.push_back(fop); // re-write the source opcode with the address of the // fopcode, increment the address of the fopcode. encode_offset(multiopcode->insn, addr - multiopcode->addr); multiopcode->insn->set_opcode(OPCODE_PACKED_SWITCH); addr += count; } } // Step 4, emit debug opcodes TRACE(MTRANS, 5, "Emitting debug opcodes\n"); auto debugitem = code->get_debug_item(); if (debugitem) { auto& dopout = debugitem->get_instructions(); int32_t absolute_line = int32_t(debugitem->get_line_start()); dopout.clear(); uint32_t daddr = 0; for (auto miter = m_fmethod->begin(); miter != m_fmethod->end(); miter++) { MethodItemEntry* mentry = &*miter; if (mentry->type == MFLOW_DEBUG) { auto dbgop = mentry->dbgop; auto op = dbgop->opcode(); switch (op) { case DBG_END_LOCAL: case DBG_RESTART_LOCAL: case DBG_START_LOCAL: case DBG_START_LOCAL_EXTENDED: case DBG_SET_FILE: case DBG_END_SEQUENCE: case DBG_SET_PROLOGUE_END: case DBG_SET_EPILOGUE_BEGIN: break; case DBG_ADVANCE_LINE: { auto diff = dbgop->value() - absolute_line; dbgop->set_value(diff); absolute_line += diff; break; } case DBG_ADVANCE_PC: { uint32_t advance = mentry->addr - daddr; dbgop->set_uvalue(advance); daddr += advance; break; } default: { auto line_adjust = dbgop->value() - absolute_line; auto addr_adjust = mentry->addr - daddr; absolute_line += line_adjust; if (line_adjust < kDebugLineBase || line_adjust >= (kDebugLineRange + kDebugLineBase)) { dopout.push_back(new DexDebugInstruction(DBG_ADVANCE_LINE, line_adjust)); line_adjust = 0; } auto special = (line_adjust - kDebugLineBase) + (addr_adjust * kDebugLineRange) + kDebugFirstSpecial; if (special > 0xff) { dopout.push_back( new DexDebugInstruction(DBG_ADVANCE_PC, uint32_t(addr_adjust))); addr_adjust = 0; special = line_adjust - kDebugLineBase + kDebugFirstSpecial; } dbgop->set_opcode(static_cast<DexDebugItemOpcode>(special)); dbgop->set_uvalue(DEX_NO_INDEX); daddr = mentry->addr; break; } } TRACE(MTRANS, 5, "emit: %08x:%02x\n", daddr, dbgop->opcode()); dopout.push_back(dbgop); } } } // Step 5, try/catch blocks auto& tries = code->get_tries(); tries.clear(); for (auto tryitem : try_items) { DexTryItem* dextry = tryitem.first; auto& tryentries = tryitem.second; sort(tryentries.begin(), tryentries.end(), order_try_entries); dextry->m_catches.clear(); MethodItemEntry* try_start = nullptr; bool suppress = false; for (auto tryentry : tryentries) { switch (tryentry->tentry->type) { case TRY_START: dextry->m_start_addr = tryentry->addr; try_start = tryentry; break; case TRY_END: assert(try_start != nullptr); assert(try_start->addr <= tryentry->addr); dextry->m_insn_count = tryentry->addr - try_start->addr; if (dextry->m_insn_count == 0) { suppress = true; } break; case TRY_CATCH: if (tryentry->tentry->centry == nullptr) { /* Catch all */ dextry->m_catchall = tryentry->addr; } else { dextry->m_catches.push_back( std::make_pair(tryentry->tentry->centry, tryentry->addr)); } break; default: always_assert_log(false, "Invalid try entry type"); } } if (!suppress) { tries.push_back(dextry); } } std::sort(tries.begin(), tries.end(), [](const DexTryItem* a, const DexTryItem* b) { return a->m_start_addr < b->m_start_addr; }); return true; }
// MouseSensitivityTweak.cpp : Defines the entry point for the console application. // #include <Windows.h> #include <tchar.h> #define MIN_SPEED 1 #define MAX_SPEED 20 #define DEF_SPEED 10 BOOL IsSpeedValid(int nSpeed) { return ((nSpeed >= MIN_SPEED) && (nSpeed <= MAX_SPEED)) ? TRUE : FALSE; } int GetMouseSpeed() { int nSpeed = 0; BOOL fResult = SystemParametersInfo(SPI_GETMOUSESPEED, // Get mouse information 0, // Not used &nSpeed, // Holds mouse speed 0); if (!fResult || !IsSpeedValid(nSpeed)) { return -1; } return nSpeed; } BOOL SetMouseSpeed(int nSpeed) { if (!IsSpeedValid(nSpeed)) { return FALSE; } int nOldSpeed = GetMouseSpeed(); if (nOldSpeed == nSpeed) { return TRUE; } BOOL fResult = SystemParametersInfo(SPI_SETMOUSESPEED, // Get mouse information 0, // Not used PVOID(nSpeed), // Holds mouse speed SPIF_SENDCHANGE); // Broadcasts the WM_SETTINGCHANGE message return fResult; } // Usage MouseSensitivityTweak <speed> // Ex: // MouseSensitivityTweak 16 int _tmain(int argc, _TCHAR* argv[]) { int nSpeed = DEF_SPEED; if (argc != 2) { return 0; } nSpeed = _wtoi(argv[1]); return SetMouseSpeed(nSpeed); } Remove tabs // MouseSensitivityTweak.cpp : Defines the entry point for the console application. // #include <Windows.h> #include <tchar.h> #define MIN_SPEED 1 #define MAX_SPEED 20 #define DEF_SPEED 10 BOOL IsSpeedValid(int nSpeed) { return ((nSpeed >= MIN_SPEED) && (nSpeed <= MAX_SPEED)) ? TRUE : FALSE; } int GetMouseSpeed() { int nSpeed = 0; BOOL fResult = SystemParametersInfo(SPI_GETMOUSESPEED, // Get mouse information 0, // Not used &nSpeed, // Holds mouse speed 0); if (!fResult || !IsSpeedValid(nSpeed)) { return -1; } return nSpeed; } BOOL SetMouseSpeed(int nSpeed) { if (!IsSpeedValid(nSpeed)) { return FALSE; } int nOldSpeed = GetMouseSpeed(); if (nOldSpeed == nSpeed) { return TRUE; } BOOL fResult = SystemParametersInfo(SPI_SETMOUSESPEED, // Get mouse information 0, // Not used PVOID(nSpeed), // Holds mouse speed SPIF_SENDCHANGE); // Broadcasts the WM_SETTINGCHANGE message return fResult; } // Usage MouseSensitivityTweak <speed> // Ex: // MouseSensitivityTweak 16 int _tmain(int argc, _TCHAR* argv[]) { int nSpeed = DEF_SPEED; if (argc != 2) { return 0; } nSpeed = _wtoi(argv[1]); return SetMouseSpeed(nSpeed); }
/*************************************************************************** * Copyright 1998-2013 by authors (see AUTHORS.txt) * * * * This file is part of LuxRender. * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.* * See the License for the specific language governing permissions and * * limitations under the License. * ***************************************************************************/ #include "boost/format.hpp" #include "slg/engines/bidirvmcpu/bidirvmcpu.h" using namespace std; using namespace luxrays; using namespace slg; void HashGrid::Build(vector<vector<PathVertexVM> > &pathsVertices, const float radius) { // Reset statistic counters //mergeHitsV2V = 0; //mergeHitsV2S = 0; //mergeHitsS2S = 0; radius2 = radius * radius; // Build the vertices bounding box vertexCount = 0; vertexBBox = BBox(); for (u_int i = 0; i < pathsVertices.size(); ++i) { vertexCount += pathsVertices[i].size(); for (u_int j = 0; j < pathsVertices[i].size(); ++j) vertexBBox = Union(vertexBBox, pathsVertices[i][j].bsdf.hitPoint.p); } if (vertexCount <= 0) return; vertexBBox.Expand(radius + DEFAULT_EPSILON_STATIC); // Calculate the size of the grid cell const float cellSize = radius * 2.f; invCellSize = 1.f / cellSize; gridSize = vertexCount; cellEnds.resize(gridSize); fill(cellEnds.begin(), cellEnds.end(), 0); lightVertices.resize(gridSize, NULL); for (u_int i = 0, k = 0; i < pathsVertices.size(); ++i) { for (u_int j = 0; j < pathsVertices[i].size(); ++j, ++k) { const PathVertexVM *vertex = &pathsVertices[i][j]; cellEnds[Hash(vertex->bsdf.hitPoint.p)]++; } } int sum = 0; for (u_int i = 0; i < cellEnds.size(); ++i) { int temp = cellEnds[i]; cellEnds[i] = sum; sum += temp; } for (u_int i = 0; i < pathsVertices.size(); ++i) { for (u_int j = 0; j < pathsVertices[i].size(); ++j) { const PathVertexVM *vertex = &pathsVertices[i][j]; const int targetIdx = cellEnds[Hash(vertex->bsdf.hitPoint.p)]++; lightVertices[targetIdx] = vertex; } } } void HashGrid::Process(const BiDirVMCPURenderThread *thread, const PathVertexVM &eyeVertex, Spectrum *radiance) const { if ((vertexCount <= 0) || !vertexBBox.Inside(eyeVertex.bsdf.hitPoint.p)) return; const Vector distMin = eyeVertex.bsdf.hitPoint.p - vertexBBox.pMin; const Vector cellPoint = invCellSize * distMin; const Vector coordFloor(floorf(cellPoint.x), floorf(cellPoint.y), floorf(cellPoint.z)); const int px = int(coordFloor.x); const int py = int(coordFloor.y); const int pz = int(coordFloor.z); const Vector fractCoord = cellPoint - coordFloor; const int pxo = px + ((fractCoord.x < .5f) ? -1 : +1); const int pyo = py + ((fractCoord.y < .5f) ? -1 : +1); const int pzo = pz + ((fractCoord.z < .5f) ? -1 : +1); int i0, i1; HashRange(Hash(px, py, pz), &i0, &i1); Process(thread, eyeVertex, i0, i1, radiance); HashRange(Hash(px, py, pzo), &i0, &i1); Process(thread, eyeVertex, i0, i1, radiance); HashRange(Hash(px, pyo, pz), &i0, &i1); Process(thread, eyeVertex, i0, i1, radiance); HashRange(Hash(px, pyo, pzo), &i0, &i1); Process(thread, eyeVertex, i0, i1, radiance); HashRange(Hash(pxo, py, pz), &i0, &i1); Process(thread, eyeVertex, i0, i1, radiance); HashRange(Hash(pxo, py, pzo), &i0, &i1); Process(thread, eyeVertex, i0, i1, radiance); HashRange(Hash(pxo, pyo, pz), &i0, &i1); Process(thread, eyeVertex, i0, i1, radiance); HashRange(Hash(pxo, pyo, pzo), &i0, &i1); Process(thread, eyeVertex, i0, i1, radiance); } void HashGrid::Process(const BiDirVMCPURenderThread *thread, const PathVertexVM &eyeVertex, const int i0, const int i1, Spectrum *radiance) const { for (int i = i0; i < i1; ++i) { const PathVertexVM *lightVertex = lightVertices[i]; Process(thread, eyeVertex, lightVertex, radiance); } } void HashGrid::Process(const BiDirVMCPURenderThread *thread, const PathVertexVM &eyeVertex, const PathVertexVM *lightVertex, Spectrum *radiance) const { const float distance2 = (lightVertex->bsdf.hitPoint.p - eyeVertex.bsdf.hitPoint.p).LengthSquared(); if (distance2 <= radius2) { float eyeBsdfPdfW, eyeBsdfRevPdfW; BSDFEvent eyeEvent; // I need to remove the dotN term from the result (see below) Spectrum eyeBsdfEval = eyeVertex.bsdf.Evaluate(lightVertex->bsdf.hitPoint.fixedDir, &eyeEvent, &eyeBsdfPdfW, &eyeBsdfRevPdfW); if(eyeBsdfEval.Black()) return; // Volume BSDF doesn't multiply BSDF::Evaluate() by dotN so I need // to remove the term only if it isn't a Volume if (!eyeVertex.bsdf.IsVolume()) eyeBsdfEval /= AbsDot(lightVertex->bsdf.hitPoint.fixedDir, eyeVertex.bsdf.hitPoint.geometryN); BiDirVMCPURenderEngine *engine = (BiDirVMCPURenderEngine *)thread->renderEngine; if (eyeVertex.depth >= engine->rrDepth) { // Russian Roulette const float prob = RenderEngine::RussianRouletteProb(eyeBsdfEval, engine->rrImportanceCap); eyeBsdfPdfW *= prob; eyeBsdfRevPdfW *= prob; // Note: SmallVCM uses light prob here } // MIS weights const float weightLight = lightVertex->dVCM * thread->misVcWeightFactor + lightVertex->dVM * BiDirVMCPURenderThread::MIS(eyeBsdfPdfW); const float weightCamera = eyeVertex.dVCM * thread->misVcWeightFactor + eyeVertex.dVM * BiDirVMCPURenderThread::MIS(eyeBsdfRevPdfW); const float misWeight = 1.f / (weightLight + 1.f + weightCamera); *radiance += (thread->vmNormalization * misWeight) * eyeVertex.throughput * eyeBsdfEval * lightVertex->throughput; // Statistics /*if (eyeVertex.bsdf.IsVolume()) { if (lightVertex->bsdf.IsVolume()) ++mergeHitsV2V; else ++mergeHitsV2S; } else { if (lightVertex->bsdf.IsVolume()) ++mergeHitsV2S; else ++mergeHitsS2S; }*/ } } /*void HashGrid::PrintStatistics() const { const double mergeTotal = mergeHitsV2V + mergeHitsV2S + mergeHitsS2S; if (mergeTotal == 0.f) cout << "Volume2Volume = 0 Volume2Surface = 0 Volume2Volume = 0\n"; else cout << boost::format("Volume2Volume = %d (%.2f%%) Volume2Surface = %d (%.2f%%) Surface2Surface = %d (%.2f%%)") % mergeHitsV2V % (100.0 * mergeHitsV2V / mergeTotal) % mergeHitsV2S % (100.0 * mergeHitsV2S / mergeTotal) % mergeHitsS2S % (100.0 * mergeHitsS2S / mergeTotal) << "\n"; }*/ Use correct boost/format.hpp include /*************************************************************************** * Copyright 1998-2013 by authors (see AUTHORS.txt) * * * * This file is part of LuxRender. * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.* * See the License for the specific language governing permissions and * * limitations under the License. * ***************************************************************************/ #include <boost/format.hpp> #include "slg/engines/bidirvmcpu/bidirvmcpu.h" using namespace std; using namespace luxrays; using namespace slg; void HashGrid::Build(vector<vector<PathVertexVM> > &pathsVertices, const float radius) { // Reset statistic counters //mergeHitsV2V = 0; //mergeHitsV2S = 0; //mergeHitsS2S = 0; radius2 = radius * radius; // Build the vertices bounding box vertexCount = 0; vertexBBox = BBox(); for (u_int i = 0; i < pathsVertices.size(); ++i) { vertexCount += pathsVertices[i].size(); for (u_int j = 0; j < pathsVertices[i].size(); ++j) vertexBBox = Union(vertexBBox, pathsVertices[i][j].bsdf.hitPoint.p); } if (vertexCount <= 0) return; vertexBBox.Expand(radius + DEFAULT_EPSILON_STATIC); // Calculate the size of the grid cell const float cellSize = radius * 2.f; invCellSize = 1.f / cellSize; gridSize = vertexCount; cellEnds.resize(gridSize); fill(cellEnds.begin(), cellEnds.end(), 0); lightVertices.resize(gridSize, NULL); for (u_int i = 0, k = 0; i < pathsVertices.size(); ++i) { for (u_int j = 0; j < pathsVertices[i].size(); ++j, ++k) { const PathVertexVM *vertex = &pathsVertices[i][j]; cellEnds[Hash(vertex->bsdf.hitPoint.p)]++; } } int sum = 0; for (u_int i = 0; i < cellEnds.size(); ++i) { int temp = cellEnds[i]; cellEnds[i] = sum; sum += temp; } for (u_int i = 0; i < pathsVertices.size(); ++i) { for (u_int j = 0; j < pathsVertices[i].size(); ++j) { const PathVertexVM *vertex = &pathsVertices[i][j]; const int targetIdx = cellEnds[Hash(vertex->bsdf.hitPoint.p)]++; lightVertices[targetIdx] = vertex; } } } void HashGrid::Process(const BiDirVMCPURenderThread *thread, const PathVertexVM &eyeVertex, Spectrum *radiance) const { if ((vertexCount <= 0) || !vertexBBox.Inside(eyeVertex.bsdf.hitPoint.p)) return; const Vector distMin = eyeVertex.bsdf.hitPoint.p - vertexBBox.pMin; const Vector cellPoint = invCellSize * distMin; const Vector coordFloor(floorf(cellPoint.x), floorf(cellPoint.y), floorf(cellPoint.z)); const int px = int(coordFloor.x); const int py = int(coordFloor.y); const int pz = int(coordFloor.z); const Vector fractCoord = cellPoint - coordFloor; const int pxo = px + ((fractCoord.x < .5f) ? -1 : +1); const int pyo = py + ((fractCoord.y < .5f) ? -1 : +1); const int pzo = pz + ((fractCoord.z < .5f) ? -1 : +1); int i0, i1; HashRange(Hash(px, py, pz), &i0, &i1); Process(thread, eyeVertex, i0, i1, radiance); HashRange(Hash(px, py, pzo), &i0, &i1); Process(thread, eyeVertex, i0, i1, radiance); HashRange(Hash(px, pyo, pz), &i0, &i1); Process(thread, eyeVertex, i0, i1, radiance); HashRange(Hash(px, pyo, pzo), &i0, &i1); Process(thread, eyeVertex, i0, i1, radiance); HashRange(Hash(pxo, py, pz), &i0, &i1); Process(thread, eyeVertex, i0, i1, radiance); HashRange(Hash(pxo, py, pzo), &i0, &i1); Process(thread, eyeVertex, i0, i1, radiance); HashRange(Hash(pxo, pyo, pz), &i0, &i1); Process(thread, eyeVertex, i0, i1, radiance); HashRange(Hash(pxo, pyo, pzo), &i0, &i1); Process(thread, eyeVertex, i0, i1, radiance); } void HashGrid::Process(const BiDirVMCPURenderThread *thread, const PathVertexVM &eyeVertex, const int i0, const int i1, Spectrum *radiance) const { for (int i = i0; i < i1; ++i) { const PathVertexVM *lightVertex = lightVertices[i]; Process(thread, eyeVertex, lightVertex, radiance); } } void HashGrid::Process(const BiDirVMCPURenderThread *thread, const PathVertexVM &eyeVertex, const PathVertexVM *lightVertex, Spectrum *radiance) const { const float distance2 = (lightVertex->bsdf.hitPoint.p - eyeVertex.bsdf.hitPoint.p).LengthSquared(); if (distance2 <= radius2) { float eyeBsdfPdfW, eyeBsdfRevPdfW; BSDFEvent eyeEvent; // I need to remove the dotN term from the result (see below) Spectrum eyeBsdfEval = eyeVertex.bsdf.Evaluate(lightVertex->bsdf.hitPoint.fixedDir, &eyeEvent, &eyeBsdfPdfW, &eyeBsdfRevPdfW); if(eyeBsdfEval.Black()) return; // Volume BSDF doesn't multiply BSDF::Evaluate() by dotN so I need // to remove the term only if it isn't a Volume if (!eyeVertex.bsdf.IsVolume()) eyeBsdfEval /= AbsDot(lightVertex->bsdf.hitPoint.fixedDir, eyeVertex.bsdf.hitPoint.geometryN); BiDirVMCPURenderEngine *engine = (BiDirVMCPURenderEngine *)thread->renderEngine; if (eyeVertex.depth >= engine->rrDepth) { // Russian Roulette const float prob = RenderEngine::RussianRouletteProb(eyeBsdfEval, engine->rrImportanceCap); eyeBsdfPdfW *= prob; eyeBsdfRevPdfW *= prob; // Note: SmallVCM uses light prob here } // MIS weights const float weightLight = lightVertex->dVCM * thread->misVcWeightFactor + lightVertex->dVM * BiDirVMCPURenderThread::MIS(eyeBsdfPdfW); const float weightCamera = eyeVertex.dVCM * thread->misVcWeightFactor + eyeVertex.dVM * BiDirVMCPURenderThread::MIS(eyeBsdfRevPdfW); const float misWeight = 1.f / (weightLight + 1.f + weightCamera); *radiance += (thread->vmNormalization * misWeight) * eyeVertex.throughput * eyeBsdfEval * lightVertex->throughput; // Statistics /*if (eyeVertex.bsdf.IsVolume()) { if (lightVertex->bsdf.IsVolume()) ++mergeHitsV2V; else ++mergeHitsV2S; } else { if (lightVertex->bsdf.IsVolume()) ++mergeHitsV2S; else ++mergeHitsS2S; }*/ } } /*void HashGrid::PrintStatistics() const { const double mergeTotal = mergeHitsV2V + mergeHitsV2S + mergeHitsS2S; if (mergeTotal == 0.f) cout << "Volume2Volume = 0 Volume2Surface = 0 Volume2Volume = 0\n"; else cout << boost::format("Volume2Volume = %d (%.2f%%) Volume2Surface = %d (%.2f%%) Surface2Surface = %d (%.2f%%)") % mergeHitsV2V % (100.0 * mergeHitsV2V / mergeTotal) % mergeHitsV2S % (100.0 * mergeHitsV2S / mergeTotal) % mergeHitsS2S % (100.0 * mergeHitsS2S / mergeTotal) << "\n"; }*/
// This is free and unencumbered software released into the public domain. // For more information, please refer to <http://unlicense.org/> #include "span_analyzer_config_xml_handler.h" #include "wx/filename.h" #include "span_analyzer_app.h" SpanAnalyzerConfigXmlHandler::SpanAnalyzerConfigXmlHandler() { } SpanAnalyzerConfigXmlHandler::~SpanAnalyzerConfigXmlHandler() { } wxXmlNode* SpanAnalyzerConfigXmlHandler::CreateNode( const SpanAnalyzerConfig& config) { // variables used to create XML node wxXmlNode* node_root = nullptr; wxXmlNode* node_element = nullptr; std::string title; std::string content; // creates a node for the root node_root = new wxXmlNode(wxXML_ELEMENT_NODE, "span_analyzer_config"); node_root->AddAttribute("version", "1"); // adds child nodes for struct parameters // creates log level node title = "level_log"; if (config.level_log == wxLOG_Message) { content = "Normal"; } else if (config.level_log == wxLOG_Info) { content = "Verbose"; } else { content = ""; } node_element = CreateElementNodeWithContent(title, content); node_root->AddChild(node_element); // creates filepath-data node title = "filepath_data"; content = config.filepath_data; node_element = CreateElementNodeWithContent(title, content); node_root->AddChild(node_element); // creates size-frame node title = "size_frame"; content = ""; node_element = CreateElementNodeWithContent(title, content); wxString str; str = std::to_string(config.size_frame.GetWidth()); node_element->AddAttribute("x", str); str = std::to_string(config.size_frame.GetHeight()); node_element->AddAttribute("y", str); node_root->AddChild(node_element); // creates perspective node title = "perspective"; content = config.perspective; node_element = CreateElementNodeWithContent(title, content); node_root->AddChild(node_element); // creates units node title = "units"; if (config.units == units::UnitSystem::kMetric) { content = wxString("Metric"); } else if (config.units == units::UnitSystem::kImperial) { content = wxString("Imperial"); } node_element = CreateElementNodeWithContent(title, content); node_root->AddChild(node_element); // returns node return node_root; } bool SpanAnalyzerConfigXmlHandler::ParseNode(const wxXmlNode* root, const std::string& filepath, SpanAnalyzerConfig& config) { wxString message; // checks for valid root node if (root->GetName() != "span_analyzer_config") { message = FileAndLineNumber(filepath, root) + " Invalid root node. Aborting node parse."; wxLogError(message); return false; } // gets version attribute wxString version; if (root->GetAttribute("version", &version) == false) { message = FileAndLineNumber(filepath, root) + " Version attribute is missing. Aborting node parse."; wxLogError(message); return false; } // sends to proper parsing function if (version == "1") { return ParseNodeV1(root, filepath, config); } else { message = FileAndLineNumber(filepath, root) + " Invalid version number. Aborting node parse."; wxLogError(message); return false; } } bool SpanAnalyzerConfigXmlHandler::ParseNodeV1(const wxXmlNode* root, const std::string& filepath, SpanAnalyzerConfig& config) { bool status = true; wxString message; // evaluates each child node const wxXmlNode* node = root->GetChildren(); while (node != nullptr) { const wxString title = node->GetName(); const wxString content = ParseElementNodeWithContent(node); if (title == "filepath_data") { config.filepath_data = content; if (config.filepath_data.empty() == true) { message = FileAndLineNumber(filepath, node) + "Application data file isn't defined. Keeping default " "setting."; wxLogWarning(message); } } else if (title == "level_log") { if (content == "Normal") { config.level_log = wxLOG_Message; } else if (content == "Verbose") { config.level_log = wxLOG_Info; } else { message = FileAndLineNumber(filepath, node) + "Logging level isn't recognized. Keeping default setting."; wxLogWarning(message); } } else if (title == "size_frame") { std::string str; str = node->GetAttribute("x"); config.size_frame.SetWidth(std::stoi(str)); str = node->GetAttribute("y"); config.size_frame.SetHeight(std::stoi(str)); } else if (title == "perspective") { config.perspective = content; } else if (title == "units") { if (content == "Metric") { config.units = units::UnitSystem::kMetric; } else if (content == "Imperial") { config.units = units::UnitSystem::kImperial; } else { message = FileAndLineNumber(filepath, node) + "Unit system isn't recognized. Keeping default setting."; wxLogWarning(message); } } else { message = FileAndLineNumber(filepath, node) + "XML node isn't recognized. Skipping."; wxLogError(message); status = false; } node = node->GetNext(); } return status; } ConfigXmlHandler fix for blank data filepath. // This is free and unencumbered software released into the public domain. // For more information, please refer to <http://unlicense.org/> #include "span_analyzer_config_xml_handler.h" #include "wx/filename.h" #include "span_analyzer_app.h" SpanAnalyzerConfigXmlHandler::SpanAnalyzerConfigXmlHandler() { } SpanAnalyzerConfigXmlHandler::~SpanAnalyzerConfigXmlHandler() { } wxXmlNode* SpanAnalyzerConfigXmlHandler::CreateNode( const SpanAnalyzerConfig& config) { // variables used to create XML node wxXmlNode* node_root = nullptr; wxXmlNode* node_element = nullptr; std::string title; std::string content; // creates a node for the root node_root = new wxXmlNode(wxXML_ELEMENT_NODE, "span_analyzer_config"); node_root->AddAttribute("version", "1"); // adds child nodes for struct parameters // creates log level node title = "level_log"; if (config.level_log == wxLOG_Message) { content = "Normal"; } else if (config.level_log == wxLOG_Info) { content = "Verbose"; } else { content = ""; } node_element = CreateElementNodeWithContent(title, content); node_root->AddChild(node_element); // creates filepath-data node title = "filepath_data"; content = config.filepath_data; node_element = CreateElementNodeWithContent(title, content); node_root->AddChild(node_element); // creates size-frame node title = "size_frame"; content = ""; node_element = CreateElementNodeWithContent(title, content); wxString str; str = std::to_string(config.size_frame.GetWidth()); node_element->AddAttribute("x", str); str = std::to_string(config.size_frame.GetHeight()); node_element->AddAttribute("y", str); node_root->AddChild(node_element); // creates perspective node title = "perspective"; content = config.perspective; node_element = CreateElementNodeWithContent(title, content); node_root->AddChild(node_element); // creates units node title = "units"; if (config.units == units::UnitSystem::kMetric) { content = wxString("Metric"); } else if (config.units == units::UnitSystem::kImperial) { content = wxString("Imperial"); } node_element = CreateElementNodeWithContent(title, content); node_root->AddChild(node_element); // returns node return node_root; } bool SpanAnalyzerConfigXmlHandler::ParseNode(const wxXmlNode* root, const std::string& filepath, SpanAnalyzerConfig& config) { wxString message; // checks for valid root node if (root->GetName() != "span_analyzer_config") { message = FileAndLineNumber(filepath, root) + " Invalid root node. Aborting node parse."; wxLogError(message); return false; } // gets version attribute wxString version; if (root->GetAttribute("version", &version) == false) { message = FileAndLineNumber(filepath, root) + " Version attribute is missing. Aborting node parse."; wxLogError(message); return false; } // sends to proper parsing function if (version == "1") { return ParseNodeV1(root, filepath, config); } else { message = FileAndLineNumber(filepath, root) + " Invalid version number. Aborting node parse."; wxLogError(message); return false; } } bool SpanAnalyzerConfigXmlHandler::ParseNodeV1(const wxXmlNode* root, const std::string& filepath, SpanAnalyzerConfig& config) { bool status = true; wxString message; // evaluates each child node const wxXmlNode* node = root->GetChildren(); while (node != nullptr) { const wxString title = node->GetName(); const wxString content = ParseElementNodeWithContent(node); if (title == "filepath_data") { if (content.empty() == false) { config.filepath_data = content; } else { message = FileAndLineNumber(filepath, node) + "Application data file isn't defined. Keeping default " "setting."; wxLogWarning(message); } } else if (title == "level_log") { if (content == "Normal") { config.level_log = wxLOG_Message; } else if (content == "Verbose") { config.level_log = wxLOG_Info; } else { message = FileAndLineNumber(filepath, node) + "Logging level isn't recognized. Keeping default setting."; wxLogWarning(message); } } else if (title == "size_frame") { std::string str; str = node->GetAttribute("x"); config.size_frame.SetWidth(std::stoi(str)); str = node->GetAttribute("y"); config.size_frame.SetHeight(std::stoi(str)); } else if (title == "perspective") { config.perspective = content; } else if (title == "units") { if (content == "Metric") { config.units = units::UnitSystem::kMetric; } else if (content == "Imperial") { config.units = units::UnitSystem::kImperial; } else { message = FileAndLineNumber(filepath, node) + "Unit system isn't recognized. Keeping default setting."; wxLogWarning(message); } } else { message = FileAndLineNumber(filepath, node) + "XML node isn't recognized. Skipping."; wxLogError(message); status = false; } node = node->GetNext(); } return status; }
/************************************************************************* * * $RCSfile: xipage.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: kz $ $Date: 2004-07-30 16:20:08 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ // ============================================================================ #ifndef SC_XIPAGE_HXX #include "xipage.hxx" #endif #ifndef _SFXITEMSET_HXX #include <svtools/itemset.hxx> #endif #ifndef _SV_GRAPH_HXX #include <vcl/graph.hxx> #endif #ifndef _SV_BMPACC_HXX #include <vcl/bmpacc.hxx> #endif #ifndef SC_ITEMS_HXX #include "scitems.hxx" #endif #ifndef _SFXENUMITEM_HXX #include <svtools/eitem.hxx> #endif #ifndef _SFXINTITEM_HXX #include <svtools/intitem.hxx> #endif #ifndef _SVX_PAGEITEM_HXX #include <svx/pageitem.hxx> #endif #ifndef _SVX_SIZEITEM_HXX #include <svx/sizeitem.hxx> #endif #ifndef _SVX_LRSPITEM_HXX #include <svx/lrspitem.hxx> #endif #ifndef _SVX_ULSPITEM_HXX #include <svx/ulspitem.hxx> #endif #ifndef _SVX_BRSHITEM_HXX #include <svx/brshitem.hxx> #endif #ifndef SC_DOCUMENT_HXX #include "document.hxx" #endif #ifndef SC_STLSHEET_HXX #include "stlsheet.hxx" #endif #ifndef SC_SCATTR_HXX #include "attrib.hxx" #endif #ifndef SC_XIHELPER_HXX #include "xihelper.hxx" #endif #ifndef SC_XLTRACER_HXX #include "xltracer.hxx" #endif // Page settings ============================================================== XclImpPageSettings::XclImpPageSettings( const XclImpRoot& rRoot ) : XclImpRoot( rRoot ), mbValidPaper( false ) { } void XclImpPageSettings::ReadSetup( XclImpStream& rStrm ) { DBG_ASSERT_BIFF( GetBiff() >= xlBiff4 ); if( GetBiff() < xlBiff4 ) return; // BIFF4 - BIFF8 sal_uInt16 nFlags; rStrm >> maData.mnPaperSize >> maData.mnScaling >> maData.mnStartPage >> maData.mnFitToWidth >> maData.mnFitToHeight >> nFlags; mbValidPaper = maData.mbValid = !::get_flag( nFlags, EXC_SETUP_INVALID ); maData.mbPrintInRows = ::get_flag( nFlags, EXC_SETUP_INROWS ); maData.mbPortrait = ::get_flag( nFlags, EXC_SETUP_PORTRAIT ); maData.mbBlackWhite = ::get_flag( nFlags, EXC_SETUP_BLACKWHITE ); maData.mbManualStart = true; // new in BIFF5 - BIFF8 if( GetBiff() >= xlBiff5 ) { rStrm >> maData.mnHorPrintRes >> maData.mnVerPrintRes >> maData.mfHeaderMargin >> maData.mfFooterMargin >> maData.mnCopies; maData.mbDraftQuality = ::get_flag( nFlags, EXC_SETUP_DRAFT ); maData.mbPrintNotes = ::get_flag( nFlags, EXC_SETUP_PRINTNOTES ); maData.mbManualStart = ::get_flag( nFlags, EXC_SETUP_STARTPAGE ); } GetTracer().TracePrintFitToPages(maData.mnFitToWidth); } void XclImpPageSettings::ReadMargin( XclImpStream& rStrm ) { switch( rStrm.GetRecId() ) { case EXC_ID_LEFTMARGIN: rStrm >> maData.mfLeftMargin; break; case EXC_ID_RIGHTMARGIN: rStrm >> maData.mfRightMargin; break; case EXC_ID_TOPMARGIN: rStrm >> maData.mfTopMargin; break; case EXC_ID_BOTTOMMARGIN: rStrm >> maData.mfBottomMargin; break; default: DBG_ERRORFILE( "XclImpPageSettings::ReadMargin - unknown record" ); } } void XclImpPageSettings::ReadCenter( XclImpStream& rStrm ) { DBG_ASSERT_BIFF( GetBiff() >= xlBiff3 ); // read it anyway bool bCenter = (rStrm.ReaduInt16() != 0); switch( rStrm.GetRecId() ) { case EXC_ID_HCENTER: maData.mbHorCenter = bCenter; break; case EXC_ID_VCENTER: maData.mbVerCenter = bCenter; break; default: DBG_ERRORFILE( "XclImpPageSettings::ReadCenter - unknown record" ); } } void XclImpPageSettings::ReadHeaderFooter( XclImpStream& rStrm ) { String aString; if( rStrm.GetRecLeft() ) { if( GetBiff() < xlBiff8 ) rStrm.AppendByteString( aString, false ); else rStrm.AppendUniString( aString ); } switch( rStrm.GetRecId() ) { case EXC_ID_HEADER: maData.maHeader = aString; break; case EXC_ID_FOOTER: maData.maFooter = aString; break; default: DBG_ERRORFILE( "XclImpPageSettings::ReadHeaderFooter - unknown record" ); } } void XclImpPageSettings::ReadPageBreaks( XclImpStream& rStrm ) { ScfUInt16Vec* pVec = NULL; switch( rStrm.GetRecId() ) { case EXC_ID_HORPAGEBREAKS: pVec = &maData.maHorPageBreaks; break; case EXC_ID_VERPAGEBREAKS: pVec = &maData.maVerPageBreaks; break; default: DBG_ERRORFILE( "XclImpPageSettings::ReadPageBreaks - unknown record" ); } if( pVec ) { bool bIgnore = (GetBiff() >= xlBiff8); // ignore start/end columns or rows in BIFF8 sal_uInt16 nCount, nBreak; rStrm >> nCount; pVec->clear(); pVec->reserve( nCount ); while( nCount-- ) { rStrm >> nBreak; if( nBreak ) pVec->push_back( nBreak ); if( bIgnore ) rStrm.Ignore( 4 ); } } } void XclImpPageSettings::ReadPrintheaders( XclImpStream& rStrm ) { maData.mbPrintHeadings = (rStrm.ReaduInt16() != 0); } void XclImpPageSettings::ReadPrintgridlines( XclImpStream& rStrm ) { maData.mbPrintGrid = (rStrm.ReaduInt16() != 0); } void XclImpPageSettings::ReadBitmap( XclImpStream& rStrm ) { sal_uInt32 nID; sal_uInt16 nWidth, nHeight, nPlanes, nDepth; rStrm >> nID; rStrm.Ignore( 8 ); rStrm >> nWidth >> nHeight >> nPlanes >> nDepth; DBG_ASSERT( nID == EXC_BITMAP_UNKNOWNID, "XclImpPageSettings::ReadBitmap - wrong ID" ); DBG_ASSERT( nDepth == 24, "XclImpPageSettings::ReadBitmap - wrong depth" ); DBG_ASSERT( nPlanes == 1, "XclImpPageSettings::ReadBitmap - wrong plane count" ); if( rStrm.IsValid() && (nID == EXC_BITMAP_UNKNOWNID) && (nDepth == 24) && (nPlanes == 1) ) { sal_uInt32 nPadding = nWidth % 4; if( rStrm.GetRecLeft() == (nWidth * 3UL + nPadding) * nHeight ) { sal_Int32 nVclWidth = nWidth; sal_Int32 nVclHeight = nHeight; Bitmap aBmp( Size( nVclWidth, nVclHeight ), nDepth ); BitmapWriteAccess* pAccess = aBmp.AcquireWriteAccess(); if( pAccess ) { sal_uInt8 nBlue, nGreen, nRed; for( sal_Int32 nY = nVclHeight - 1; nY >= 0; --nY ) { for( sal_Int32 nX = 0; nX < nVclWidth; ++nX ) { rStrm >> nBlue >> nGreen >> nRed; pAccess->SetPixel( nY, nX, BitmapColor( nRed, nGreen, nBlue ) ); } rStrm.Ignore( nPadding ); } aBmp.ReleaseAccess( pAccess ); maData.mpBrushItem.reset( new SvxBrushItem( Graphic( aBmp ), GPOS_TILED ) ); } } else DBG_ERRORFILE( "XclImpPageSettings::ReadBitmap - record size invalid" ); } } void XclImpPageSettings::SetPaperSize( sal_uInt16 nXclPaperSize, bool bPortrait ) { maData.mnPaperSize = nXclPaperSize; maData.mbPortrait = bPortrait; mbValidPaper = true; } // ---------------------------------------------------------------------------- namespace { void lclPutMarginItem( SfxItemSet& rItemSet, sal_uInt16 nRecId, double fMarginInch ) { sal_uInt16 nMarginTwips = XclTools::GetTwipsFromInch( fMarginInch ); switch( nRecId ) { case EXC_ID_TOPMARGIN: case EXC_ID_BOTTOMMARGIN: { SvxULSpaceItem aItem( GETITEM( rItemSet, SvxULSpaceItem, ATTR_ULSPACE ) ); if( nRecId == EXC_ID_TOPMARGIN ) aItem.SetUpperValue( nMarginTwips ); else aItem.SetLowerValue( nMarginTwips ); rItemSet.Put( aItem ); } break; case EXC_ID_LEFTMARGIN: case EXC_ID_RIGHTMARGIN: { SvxLRSpaceItem aItem( GETITEM( rItemSet, SvxLRSpaceItem, ATTR_LRSPACE ) ); if( nRecId == EXC_ID_LEFTMARGIN ) aItem.SetLeftValue( nMarginTwips ); else aItem.SetRightValue( nMarginTwips ); rItemSet.Put( aItem ); } break; default: DBG_ERRORFILE( "XclImpPageSettings::SetMarginItem - unknown record id" ); } } } // namespace void XclImpPageSettings::CreatePageStyle() { ScDocument& rDoc = GetDoc(); SCTAB nScTab = GetCurrScTab(); // *** create page style sheet *** String aStyleName( RTL_CONSTASCII_USTRINGPARAM( "PageStyle_" ) ); String aTableName; if( GetDoc().GetName( nScTab, aTableName ) ) aStyleName.Append( aTableName ); else aStyleName.Append( String::CreateFromInt32( nScTab + 1 ) ); ScStyleSheet& rStyleSheet = ScfTools::MakePageStyleSheet( GetStyleSheetPool(), aStyleName, false ); SfxItemSet& rItemSet = rStyleSheet.GetItemSet(); // *** page settings *** ScfTools::PutItem( rItemSet, SfxBoolItem( ATTR_PAGE_TOPDOWN, !maData.mbPrintInRows ), true ); ScfTools::PutItem( rItemSet, SfxBoolItem( ATTR_PAGE_HORCENTER, maData.mbHorCenter ), true ); ScfTools::PutItem( rItemSet, SfxBoolItem( ATTR_PAGE_VERCENTER, maData.mbVerCenter ), true ); ScfTools::PutItem( rItemSet, SfxBoolItem( ATTR_PAGE_HEADERS, maData.mbPrintHeadings ), true ); ScfTools::PutItem( rItemSet, SfxBoolItem( ATTR_PAGE_GRID, maData.mbPrintGrid ), true ); ScfTools::PutItem( rItemSet, SfxBoolItem( ATTR_PAGE_NOTES, maData.mbPrintNotes ), true ); sal_uInt16 nStartPage = maData.mbManualStart ? maData.mnStartPage : 0; ScfTools::PutItem( rItemSet, SfxUInt16Item( ATTR_PAGE_FIRSTPAGENO, nStartPage ), true ); if( maData.mpBrushItem.get() ) rItemSet.Put( *maData.mpBrushItem ); if( mbValidPaper ) { SvxPageItem aPageItem( GETITEM( rItemSet, SvxPageItem, ATTR_PAGE ) ); aPageItem.SetLandscape( !maData.mbPortrait ); rItemSet.Put( aPageItem ); ScfTools::PutItem( rItemSet, SvxSizeItem( ATTR_PAGE_SIZE, maData.GetScPaperSize( GetPrinter() ) ), true ); } if( maData.mbFitToPages ) rItemSet.Put( ScPageScaleToItem( maData.mnFitToWidth, maData.mnFitToHeight ) ); else if( maData.mbValid ) rItemSet.Put( SfxUInt16Item( ATTR_PAGE_SCALE, maData.mnScaling ) ); // *** margin preparations *** double fLeftMargin = maData.mfLeftMargin; double fRightMargin = maData.mfRightMargin; double fTopMargin = maData.mfTopMargin; double fBottomMargin = maData.mfBottomMargin; // distances between header/footer and page area double fHeaderHeight = 0.0; double fHeaderDist = 0.0; double fFooterHeight = 0.0; double fFooterDist = 0.0; // in Calc, "header/footer left/right margin" is X distance between header/footer and page margin double fHdrLeftMargin = maData.mfHdrLeftMargin - maData.mfLeftMargin; double fHdrRightMargin = maData.mfHdrRightMargin - maData.mfRightMargin; double fFtrLeftMargin = maData.mfFtrLeftMargin - maData.mfLeftMargin; double fFtrRightMargin = maData.mfFtrRightMargin - maData.mfRightMargin; // *** header and footer *** XclImpHFConverter aHFConv( GetRoot() ); // header bool bHasHeader = (maData.maHeader.Len() != 0); SvxSetItem aHdrSetItem( GETITEM( rItemSet, SvxSetItem, ATTR_PAGE_HEADERSET ) ); SfxItemSet& rHdrItemSet = aHdrSetItem.GetItemSet(); rHdrItemSet.Put( SfxBoolItem( ATTR_PAGE_ON, bHasHeader ) ); if( bHasHeader ) { aHFConv.ParseString( maData.maHeader ); aHFConv.FillToItemSet( rItemSet, ATTR_PAGE_HEADERLEFT ); aHFConv.FillToItemSet( rItemSet, ATTR_PAGE_HEADERRIGHT ); // #i23296# In Calc, "top margin" is distance to header fTopMargin = maData.mfHeaderMargin; // Calc uses distance between header and sheet data area fHeaderHeight = XclTools::GetInchFromTwips( aHFConv.GetTotalHeight() ); fHeaderDist = maData.mfTopMargin - maData.mfHeaderMargin - fHeaderHeight; } if( fHeaderDist < 0.0 ) { /* #i23296# Header overlays sheet data: -> set fixed header height to get correct sheet data position. */ ScfTools::PutItem( rHdrItemSet, SfxBoolItem( ATTR_PAGE_DYNAMIC, false ), true ); // shrink header height long nHdrHeight = XclTools::GetTwipsFromInch( fHeaderHeight + fHeaderDist ); ScfTools::PutItem( rHdrItemSet, SvxSizeItem( ATTR_PAGE_SIZE, Size( 0, nHdrHeight ) ), true ); lclPutMarginItem( rHdrItemSet, EXC_ID_BOTTOMMARGIN, 0.0 ); } else { // use dynamic header height ScfTools::PutItem( rHdrItemSet, SfxBoolItem( ATTR_PAGE_DYNAMIC, true ), true ); lclPutMarginItem( rHdrItemSet, EXC_ID_BOTTOMMARGIN, fHeaderDist ); } lclPutMarginItem( rHdrItemSet, EXC_ID_LEFTMARGIN, fHdrLeftMargin ); lclPutMarginItem( rHdrItemSet, EXC_ID_RIGHTMARGIN, fHdrRightMargin ); rItemSet.Put( aHdrSetItem ); // footer bool bHasFooter = (maData.maFooter.Len() != 0); SvxSetItem aFtrSetItem( GETITEM( rItemSet, SvxSetItem, ATTR_PAGE_FOOTERSET ) ); SfxItemSet& rFtrItemSet = aFtrSetItem.GetItemSet(); rFtrItemSet.Put( SfxBoolItem( ATTR_PAGE_ON, bHasFooter ) ); if( bHasFooter ) { aHFConv.ParseString( maData.maFooter ); aHFConv.FillToItemSet( rItemSet, ATTR_PAGE_FOOTERLEFT ); aHFConv.FillToItemSet( rItemSet, ATTR_PAGE_FOOTERRIGHT ); // #i23296# In Calc, "bottom margin" is distance to footer fBottomMargin = maData.mfFooterMargin; // Calc uses distance between footer and sheet data area fFooterHeight = XclTools::GetInchFromTwips( aHFConv.GetTotalHeight() ); fFooterDist = maData.mfBottomMargin - maData.mfFooterMargin - fFooterHeight; } if( fFooterDist < 0.0 ) { /* #i23296# Footer overlays sheet data: -> set fixed footer height to get correct sheet data end position. */ ScfTools::PutItem( rFtrItemSet, SfxBoolItem( ATTR_PAGE_DYNAMIC, false ), true ); // shrink footer height long nFtrHeight = XclTools::GetTwipsFromInch( fFooterHeight + fFooterDist ); ScfTools::PutItem( rFtrItemSet, SvxSizeItem( ATTR_PAGE_SIZE, Size( 0, nFtrHeight ) ), true ); lclPutMarginItem( rFtrItemSet, EXC_ID_TOPMARGIN, 0.0 ); } else { // use dynamic footer height ScfTools::PutItem( rFtrItemSet, SfxBoolItem( ATTR_PAGE_DYNAMIC, true ), true ); lclPutMarginItem( rFtrItemSet, EXC_ID_TOPMARGIN, fFooterDist ); } lclPutMarginItem( rFtrItemSet, EXC_ID_LEFTMARGIN, fFtrLeftMargin ); lclPutMarginItem( rFtrItemSet, EXC_ID_RIGHTMARGIN, fFtrRightMargin ); rItemSet.Put( aFtrSetItem ); // *** set final margins *** lclPutMarginItem( rItemSet, EXC_ID_LEFTMARGIN, fLeftMargin ); lclPutMarginItem( rItemSet, EXC_ID_RIGHTMARGIN, fRightMargin ); lclPutMarginItem( rItemSet, EXC_ID_TOPMARGIN, fTopMargin ); lclPutMarginItem( rItemSet, EXC_ID_BOTTOMMARGIN, fBottomMargin ); // *** put style sheet into document *** rDoc.SetPageStyle( nScTab, rStyleSheet.GetName() ); // *** page breaks *** ScfUInt16Vec::const_iterator aIt, aEnd; for( aIt = maData.maHorPageBreaks.begin(), aEnd = maData.maHorPageBreaks.end(); (aIt != aEnd) && (*aIt <= MAXROW); ++aIt ) rDoc.SetRowFlags( static_cast<SCROW>(*aIt), nScTab, rDoc.GetRowFlags( static_cast<SCROW>(*aIt), nScTab ) | CR_MANUALBREAK ); for( aIt = maData.maVerPageBreaks.begin(), aEnd = maData.maVerPageBreaks.end(); (aIt != aEnd) && (*aIt <= MAXCOL); ++aIt ) rDoc.SetColFlags( static_cast<SCCOL>(*aIt), nScTab, rDoc.GetColFlags( static_cast<SCCOL>(*aIt), nScTab ) | CR_MANUALBREAK ); // set to defaults for next sheet maData.SetDefaults(); } // ============================================================================ INTEGRATION: CWS encryption (1.3.4); FILE MERGED 2004/07/14 10:19:07 dr 1.3.4.2: RESYNC: (1.3-1.5); FILE MERGED 2004/03/17 12:55:26 dr 1.3.4.1: #115980# preparations for decryption /************************************************************************* * * $RCSfile: xipage.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: obo $ $Date: 2004-08-11 09:01:52 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ // ============================================================================ #ifndef SC_XIPAGE_HXX #include "xipage.hxx" #endif #ifndef _SFXITEMSET_HXX #include <svtools/itemset.hxx> #endif #ifndef _SV_GRAPH_HXX #include <vcl/graph.hxx> #endif #ifndef _SV_BMPACC_HXX #include <vcl/bmpacc.hxx> #endif #ifndef SC_ITEMS_HXX #include "scitems.hxx" #endif #ifndef _SFXENUMITEM_HXX #include <svtools/eitem.hxx> #endif #ifndef _SFXINTITEM_HXX #include <svtools/intitem.hxx> #endif #ifndef _SVX_PAGEITEM_HXX #include <svx/pageitem.hxx> #endif #ifndef _SVX_SIZEITEM_HXX #include <svx/sizeitem.hxx> #endif #ifndef _SVX_LRSPITEM_HXX #include <svx/lrspitem.hxx> #endif #ifndef _SVX_ULSPITEM_HXX #include <svx/ulspitem.hxx> #endif #ifndef _SVX_BRSHITEM_HXX #include <svx/brshitem.hxx> #endif #ifndef SC_DOCUMENT_HXX #include "document.hxx" #endif #ifndef SC_STLSHEET_HXX #include "stlsheet.hxx" #endif #ifndef SC_SCATTR_HXX #include "attrib.hxx" #endif #ifndef SC_XIHELPER_HXX #include "xihelper.hxx" #endif #ifndef SC_XLTRACER_HXX #include "xltracer.hxx" #endif // Page settings ============================================================== XclImpPageSettings::XclImpPageSettings( const XclImpRoot& rRoot ) : XclImpRoot( rRoot ), mbValidPaper( false ) { } void XclImpPageSettings::ReadSetup( XclImpStream& rStrm ) { DBG_ASSERT_BIFF( GetBiff() >= xlBiff4 ); if( GetBiff() < xlBiff4 ) return; // BIFF4 - BIFF8 sal_uInt16 nFlags; rStrm >> maData.mnPaperSize >> maData.mnScaling >> maData.mnStartPage >> maData.mnFitToWidth >> maData.mnFitToHeight >> nFlags; mbValidPaper = maData.mbValid = !::get_flag( nFlags, EXC_SETUP_INVALID ); maData.mbPrintInRows = ::get_flag( nFlags, EXC_SETUP_INROWS ); maData.mbPortrait = ::get_flag( nFlags, EXC_SETUP_PORTRAIT ); maData.mbBlackWhite = ::get_flag( nFlags, EXC_SETUP_BLACKWHITE ); maData.mbManualStart = true; // new in BIFF5 - BIFF8 if( GetBiff() >= xlBiff5 ) { rStrm >> maData.mnHorPrintRes >> maData.mnVerPrintRes >> maData.mfHeaderMargin >> maData.mfFooterMargin >> maData.mnCopies; maData.mbDraftQuality = ::get_flag( nFlags, EXC_SETUP_DRAFT ); maData.mbPrintNotes = ::get_flag( nFlags, EXC_SETUP_PRINTNOTES ); maData.mbManualStart = ::get_flag( nFlags, EXC_SETUP_STARTPAGE ); } GetTracer().TracePrintFitToPages(maData.mnFitToWidth); } void XclImpPageSettings::ReadMargin( XclImpStream& rStrm ) { switch( rStrm.GetRecId() ) { case EXC_ID_LEFTMARGIN: rStrm >> maData.mfLeftMargin; break; case EXC_ID_RIGHTMARGIN: rStrm >> maData.mfRightMargin; break; case EXC_ID_TOPMARGIN: rStrm >> maData.mfTopMargin; break; case EXC_ID_BOTTOMMARGIN: rStrm >> maData.mfBottomMargin; break; default: DBG_ERRORFILE( "XclImpPageSettings::ReadMargin - unknown record" ); } } void XclImpPageSettings::ReadCenter( XclImpStream& rStrm ) { DBG_ASSERT_BIFF( GetBiff() >= xlBiff3 ); // read it anyway bool bCenter = (rStrm.ReaduInt16() != 0); switch( rStrm.GetRecId() ) { case EXC_ID_HCENTER: maData.mbHorCenter = bCenter; break; case EXC_ID_VCENTER: maData.mbVerCenter = bCenter; break; default: DBG_ERRORFILE( "XclImpPageSettings::ReadCenter - unknown record" ); } } void XclImpPageSettings::ReadHeaderFooter( XclImpStream& rStrm ) { String aString; if( rStrm.GetRecLeft() ) aString = (GetBiff() < xlBiff8) ? rStrm.ReadByteString( false ) : rStrm.ReadUniString(); switch( rStrm.GetRecId() ) { case EXC_ID_HEADER: maData.maHeader = aString; break; case EXC_ID_FOOTER: maData.maFooter = aString; break; default: DBG_ERRORFILE( "XclImpPageSettings::ReadHeaderFooter - unknown record" ); } } void XclImpPageSettings::ReadPageBreaks( XclImpStream& rStrm ) { ScfUInt16Vec* pVec = NULL; switch( rStrm.GetRecId() ) { case EXC_ID_HORPAGEBREAKS: pVec = &maData.maHorPageBreaks; break; case EXC_ID_VERPAGEBREAKS: pVec = &maData.maVerPageBreaks; break; default: DBG_ERRORFILE( "XclImpPageSettings::ReadPageBreaks - unknown record" ); } if( pVec ) { bool bIgnore = (GetBiff() >= xlBiff8); // ignore start/end columns or rows in BIFF8 sal_uInt16 nCount, nBreak; rStrm >> nCount; pVec->clear(); pVec->reserve( nCount ); while( nCount-- ) { rStrm >> nBreak; if( nBreak ) pVec->push_back( nBreak ); if( bIgnore ) rStrm.Ignore( 4 ); } } } void XclImpPageSettings::ReadPrintheaders( XclImpStream& rStrm ) { maData.mbPrintHeadings = (rStrm.ReaduInt16() != 0); } void XclImpPageSettings::ReadPrintgridlines( XclImpStream& rStrm ) { maData.mbPrintGrid = (rStrm.ReaduInt16() != 0); } void XclImpPageSettings::ReadBitmap( XclImpStream& rStrm ) { sal_uInt32 nID; sal_uInt16 nWidth, nHeight, nPlanes, nDepth; rStrm >> nID; rStrm.Ignore( 8 ); rStrm >> nWidth >> nHeight >> nPlanes >> nDepth; DBG_ASSERT( nID == EXC_BITMAP_UNKNOWNID, "XclImpPageSettings::ReadBitmap - wrong ID" ); DBG_ASSERT( nDepth == 24, "XclImpPageSettings::ReadBitmap - wrong depth" ); DBG_ASSERT( nPlanes == 1, "XclImpPageSettings::ReadBitmap - wrong plane count" ); if( rStrm.IsValid() && (nID == EXC_BITMAP_UNKNOWNID) && (nDepth == 24) && (nPlanes == 1) ) { sal_uInt32 nPadding = nWidth % 4; if( rStrm.GetRecLeft() == (nWidth * 3UL + nPadding) * nHeight ) { sal_Int32 nVclWidth = nWidth; sal_Int32 nVclHeight = nHeight; Bitmap aBmp( Size( nVclWidth, nVclHeight ), nDepth ); BitmapWriteAccess* pAccess = aBmp.AcquireWriteAccess(); if( pAccess ) { sal_uInt8 nBlue, nGreen, nRed; for( sal_Int32 nY = nVclHeight - 1; nY >= 0; --nY ) { for( sal_Int32 nX = 0; nX < nVclWidth; ++nX ) { rStrm >> nBlue >> nGreen >> nRed; pAccess->SetPixel( nY, nX, BitmapColor( nRed, nGreen, nBlue ) ); } rStrm.Ignore( nPadding ); } aBmp.ReleaseAccess( pAccess ); maData.mpBrushItem.reset( new SvxBrushItem( Graphic( aBmp ), GPOS_TILED ) ); } } else DBG_ERRORFILE( "XclImpPageSettings::ReadBitmap - record size invalid" ); } } void XclImpPageSettings::SetPaperSize( sal_uInt16 nXclPaperSize, bool bPortrait ) { maData.mnPaperSize = nXclPaperSize; maData.mbPortrait = bPortrait; mbValidPaper = true; } // ---------------------------------------------------------------------------- namespace { void lclPutMarginItem( SfxItemSet& rItemSet, sal_uInt16 nRecId, double fMarginInch ) { sal_uInt16 nMarginTwips = XclTools::GetTwipsFromInch( fMarginInch ); switch( nRecId ) { case EXC_ID_TOPMARGIN: case EXC_ID_BOTTOMMARGIN: { SvxULSpaceItem aItem( GETITEM( rItemSet, SvxULSpaceItem, ATTR_ULSPACE ) ); if( nRecId == EXC_ID_TOPMARGIN ) aItem.SetUpperValue( nMarginTwips ); else aItem.SetLowerValue( nMarginTwips ); rItemSet.Put( aItem ); } break; case EXC_ID_LEFTMARGIN: case EXC_ID_RIGHTMARGIN: { SvxLRSpaceItem aItem( GETITEM( rItemSet, SvxLRSpaceItem, ATTR_LRSPACE ) ); if( nRecId == EXC_ID_LEFTMARGIN ) aItem.SetLeftValue( nMarginTwips ); else aItem.SetRightValue( nMarginTwips ); rItemSet.Put( aItem ); } break; default: DBG_ERRORFILE( "XclImpPageSettings::SetMarginItem - unknown record id" ); } } } // namespace void XclImpPageSettings::CreatePageStyle() { ScDocument& rDoc = GetDoc(); SCTAB nScTab = GetCurrScTab(); // *** create page style sheet *** String aStyleName( RTL_CONSTASCII_USTRINGPARAM( "PageStyle_" ) ); String aTableName; if( GetDoc().GetName( nScTab, aTableName ) ) aStyleName.Append( aTableName ); else aStyleName.Append( String::CreateFromInt32( nScTab + 1 ) ); ScStyleSheet& rStyleSheet = ScfTools::MakePageStyleSheet( GetStyleSheetPool(), aStyleName, false ); SfxItemSet& rItemSet = rStyleSheet.GetItemSet(); // *** page settings *** ScfTools::PutItem( rItemSet, SfxBoolItem( ATTR_PAGE_TOPDOWN, !maData.mbPrintInRows ), true ); ScfTools::PutItem( rItemSet, SfxBoolItem( ATTR_PAGE_HORCENTER, maData.mbHorCenter ), true ); ScfTools::PutItem( rItemSet, SfxBoolItem( ATTR_PAGE_VERCENTER, maData.mbVerCenter ), true ); ScfTools::PutItem( rItemSet, SfxBoolItem( ATTR_PAGE_HEADERS, maData.mbPrintHeadings ), true ); ScfTools::PutItem( rItemSet, SfxBoolItem( ATTR_PAGE_GRID, maData.mbPrintGrid ), true ); ScfTools::PutItem( rItemSet, SfxBoolItem( ATTR_PAGE_NOTES, maData.mbPrintNotes ), true ); sal_uInt16 nStartPage = maData.mbManualStart ? maData.mnStartPage : 0; ScfTools::PutItem( rItemSet, SfxUInt16Item( ATTR_PAGE_FIRSTPAGENO, nStartPage ), true ); if( maData.mpBrushItem.get() ) rItemSet.Put( *maData.mpBrushItem ); if( mbValidPaper ) { SvxPageItem aPageItem( GETITEM( rItemSet, SvxPageItem, ATTR_PAGE ) ); aPageItem.SetLandscape( !maData.mbPortrait ); rItemSet.Put( aPageItem ); ScfTools::PutItem( rItemSet, SvxSizeItem( ATTR_PAGE_SIZE, maData.GetScPaperSize( GetPrinter() ) ), true ); } if( maData.mbFitToPages ) rItemSet.Put( ScPageScaleToItem( maData.mnFitToWidth, maData.mnFitToHeight ) ); else if( maData.mbValid ) rItemSet.Put( SfxUInt16Item( ATTR_PAGE_SCALE, maData.mnScaling ) ); // *** margin preparations *** double fLeftMargin = maData.mfLeftMargin; double fRightMargin = maData.mfRightMargin; double fTopMargin = maData.mfTopMargin; double fBottomMargin = maData.mfBottomMargin; // distances between header/footer and page area double fHeaderHeight = 0.0; double fHeaderDist = 0.0; double fFooterHeight = 0.0; double fFooterDist = 0.0; // in Calc, "header/footer left/right margin" is X distance between header/footer and page margin double fHdrLeftMargin = maData.mfHdrLeftMargin - maData.mfLeftMargin; double fHdrRightMargin = maData.mfHdrRightMargin - maData.mfRightMargin; double fFtrLeftMargin = maData.mfFtrLeftMargin - maData.mfLeftMargin; double fFtrRightMargin = maData.mfFtrRightMargin - maData.mfRightMargin; // *** header and footer *** XclImpHFConverter aHFConv( GetRoot() ); // header bool bHasHeader = (maData.maHeader.Len() != 0); SvxSetItem aHdrSetItem( GETITEM( rItemSet, SvxSetItem, ATTR_PAGE_HEADERSET ) ); SfxItemSet& rHdrItemSet = aHdrSetItem.GetItemSet(); rHdrItemSet.Put( SfxBoolItem( ATTR_PAGE_ON, bHasHeader ) ); if( bHasHeader ) { aHFConv.ParseString( maData.maHeader ); aHFConv.FillToItemSet( rItemSet, ATTR_PAGE_HEADERLEFT ); aHFConv.FillToItemSet( rItemSet, ATTR_PAGE_HEADERRIGHT ); // #i23296# In Calc, "top margin" is distance to header fTopMargin = maData.mfHeaderMargin; // Calc uses distance between header and sheet data area fHeaderHeight = XclTools::GetInchFromTwips( aHFConv.GetTotalHeight() ); fHeaderDist = maData.mfTopMargin - maData.mfHeaderMargin - fHeaderHeight; } if( fHeaderDist < 0.0 ) { /* #i23296# Header overlays sheet data: -> set fixed header height to get correct sheet data position. */ ScfTools::PutItem( rHdrItemSet, SfxBoolItem( ATTR_PAGE_DYNAMIC, false ), true ); // shrink header height long nHdrHeight = XclTools::GetTwipsFromInch( fHeaderHeight + fHeaderDist ); ScfTools::PutItem( rHdrItemSet, SvxSizeItem( ATTR_PAGE_SIZE, Size( 0, nHdrHeight ) ), true ); lclPutMarginItem( rHdrItemSet, EXC_ID_BOTTOMMARGIN, 0.0 ); } else { // use dynamic header height ScfTools::PutItem( rHdrItemSet, SfxBoolItem( ATTR_PAGE_DYNAMIC, true ), true ); lclPutMarginItem( rHdrItemSet, EXC_ID_BOTTOMMARGIN, fHeaderDist ); } lclPutMarginItem( rHdrItemSet, EXC_ID_LEFTMARGIN, fHdrLeftMargin ); lclPutMarginItem( rHdrItemSet, EXC_ID_RIGHTMARGIN, fHdrRightMargin ); rItemSet.Put( aHdrSetItem ); // footer bool bHasFooter = (maData.maFooter.Len() != 0); SvxSetItem aFtrSetItem( GETITEM( rItemSet, SvxSetItem, ATTR_PAGE_FOOTERSET ) ); SfxItemSet& rFtrItemSet = aFtrSetItem.GetItemSet(); rFtrItemSet.Put( SfxBoolItem( ATTR_PAGE_ON, bHasFooter ) ); if( bHasFooter ) { aHFConv.ParseString( maData.maFooter ); aHFConv.FillToItemSet( rItemSet, ATTR_PAGE_FOOTERLEFT ); aHFConv.FillToItemSet( rItemSet, ATTR_PAGE_FOOTERRIGHT ); // #i23296# In Calc, "bottom margin" is distance to footer fBottomMargin = maData.mfFooterMargin; // Calc uses distance between footer and sheet data area fFooterHeight = XclTools::GetInchFromTwips( aHFConv.GetTotalHeight() ); fFooterDist = maData.mfBottomMargin - maData.mfFooterMargin - fFooterHeight; } if( fFooterDist < 0.0 ) { /* #i23296# Footer overlays sheet data: -> set fixed footer height to get correct sheet data end position. */ ScfTools::PutItem( rFtrItemSet, SfxBoolItem( ATTR_PAGE_DYNAMIC, false ), true ); // shrink footer height long nFtrHeight = XclTools::GetTwipsFromInch( fFooterHeight + fFooterDist ); ScfTools::PutItem( rFtrItemSet, SvxSizeItem( ATTR_PAGE_SIZE, Size( 0, nFtrHeight ) ), true ); lclPutMarginItem( rFtrItemSet, EXC_ID_TOPMARGIN, 0.0 ); } else { // use dynamic footer height ScfTools::PutItem( rFtrItemSet, SfxBoolItem( ATTR_PAGE_DYNAMIC, true ), true ); lclPutMarginItem( rFtrItemSet, EXC_ID_TOPMARGIN, fFooterDist ); } lclPutMarginItem( rFtrItemSet, EXC_ID_LEFTMARGIN, fFtrLeftMargin ); lclPutMarginItem( rFtrItemSet, EXC_ID_RIGHTMARGIN, fFtrRightMargin ); rItemSet.Put( aFtrSetItem ); // *** set final margins *** lclPutMarginItem( rItemSet, EXC_ID_LEFTMARGIN, fLeftMargin ); lclPutMarginItem( rItemSet, EXC_ID_RIGHTMARGIN, fRightMargin ); lclPutMarginItem( rItemSet, EXC_ID_TOPMARGIN, fTopMargin ); lclPutMarginItem( rItemSet, EXC_ID_BOTTOMMARGIN, fBottomMargin ); // *** put style sheet into document *** rDoc.SetPageStyle( nScTab, rStyleSheet.GetName() ); // *** page breaks *** ScfUInt16Vec::const_iterator aIt, aEnd; for( aIt = maData.maHorPageBreaks.begin(), aEnd = maData.maHorPageBreaks.end(); (aIt != aEnd) && (*aIt <= MAXROW); ++aIt ) rDoc.SetRowFlags( static_cast<SCROW>(*aIt), nScTab, rDoc.GetRowFlags( static_cast<SCROW>(*aIt), nScTab ) | CR_MANUALBREAK ); for( aIt = maData.maVerPageBreaks.begin(), aEnd = maData.maVerPageBreaks.end(); (aIt != aEnd) && (*aIt <= MAXCOL); ++aIt ) rDoc.SetColFlags( static_cast<SCCOL>(*aIt), nScTab, rDoc.GetColFlags( static_cast<SCCOL>(*aIt), nScTab ) | CR_MANUALBREAK ); // set to defaults for next sheet maData.SetDefaults(); } // ============================================================================
/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (ivan.frade@nokia.com) ** ** This file is part of the QtSparql module (not yet part of the Qt Toolkit). ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial Usage ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** If you have questions regarding the use of this file, please contact ** Nokia at ivan.frade@nokia.com. ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qsparqlconnection.h" #include "qsparqlconnection_p.h" #include "qsparqlquery.h" #ifdef QT_SPARQL_VIRTUOSO #include "../drivers/virtuoso/qsparql_virtuoso_p.h" #endif #ifdef QT_SPARQL_TRACKER #include "../drivers/tracker/qsparql_tracker_p.h" #endif #ifdef QT_SPARQL_TRACKER_DIRECT #include "../drivers/tracker_direct/qsparql_tracker_direct_p.h" #endif #ifdef QT_SPARQL_ENDPOINT #include "../drivers/endpoint/qsparql_endpoint_p.h" #endif #include "qdebug.h" #include "qcoreapplication.h" #include "qsparqlresult.h" #include "qsparqlconnectionoptions.h" #include "qsparqldriver_p.h" #include "qsparqldriverplugin_p.h" #if WE_ARE_QT // QFactoryLoader is an internal part of Qt; we'll use it when where part of Qt // (or when Qt publishes it.) # include "qfactoryloader_p.h" #else # include "qdir.h" # include "qpluginloader.h" #endif #include "qsparqlnulldriver_p.h" #include <QtCore/qhash.h> #include <QtCore/quuid.h> #include <QtCore/qmutex.h> QT_BEGIN_NAMESPACE #if WE_ARE_QT #if !defined(QT_NO_LIBRARY) && !defined(QT_NO_SETTINGS) Q_GLOBAL_STATIC_WITH_ARGS(QFactoryLoader, loader, (QSparqlDriverFactoryInterface_iid, QLatin1String("/sparqldrivers"))) #endif #endif typedef QHash<QString, QSparqlDriverCreatorBase*> DriverDict; class QSparqlConnectionPrivate { public: QSparqlConnectionPrivate(QSparqlDriver *dr, const QString& name, const QSparqlConnectionOptions& opts): driver(dr), drvName(name), options(opts) { } ~QSparqlConnectionPrivate(); static DriverDict &driverDict(); static QSparqlDriver* findDriver(const QString& type); static QSparqlDriver* findDriverWithFactoryLoader(const QString& type); static void initKeys(); static QSparqlDriver* findDriverWithPluginLoader(const QString& type); static void registerConnectionCreator(const QString &type, QSparqlDriverCreatorBase* creator); static QSparqlConnectionPrivate* shared_null(); static QStringList allKeys; static QHash<QString, QSparqlDriverPlugin*> plugins; static QMutex pluginMutex; // protexts allKeys, plugins and driverDict QSparqlDriver* driver; QString drvName; QSparqlConnectionOptions options; }; QSparqlConnectionPrivate *QSparqlConnectionPrivate::shared_null() { static QSparqlNullDriver dr; static QSparqlConnectionPrivate n(&dr, QString(), QSparqlConnectionOptions()); return &n; } QSparqlConnectionPrivate::~QSparqlConnectionPrivate() { if (driver != shared_null()->driver) { delete driver; driver = shared_null()->driver; } } static bool qDriverDictInit = false; static void cleanDriverDict() { qDeleteAll(QSparqlConnectionPrivate::driverDict()); QSparqlConnectionPrivate::driverDict().clear(); qDriverDictInit = false; } DriverDict &QSparqlConnectionPrivate::driverDict() { static DriverDict dict; if (!qDriverDictInit) { qDriverDictInit = true; qAddPostRoutine(cleanDriverDict); } return dict; } /*! \internal Create the actual driver instance \a type. */ QSparqlDriver* QSparqlConnectionPrivate::findDriver(const QString &type) { QMutexLocker locker(&pluginMutex); // separately defined drivers (e.g., for tests) QSparqlDriver * driver = 0; DriverDict dict = QSparqlConnectionPrivate::driverDict(); for (DriverDict::const_iterator it = dict.constBegin(); it != dict.constEnd() && !driver; ++it) { if (type == it.key()) { driver = ((QSparqlDriverCreatorBase*)(*it))->createObject(); } } if (driver) return driver; // drivers built into the .so #ifdef QT_SPARQL_TRACKER if (type == QLatin1String("QTRACKER")) driver = new QTrackerDriver(); #endif #ifdef QT_SPARQL_TRACKER_DIRECT if (type == QLatin1String("QTRACKER_DIRECT")) driver = new QTrackerDirectDriver(); #endif #ifdef QT_SPARQL_ENDPOINT if (type == QLatin1String("QSPARQL_ENDPOINT")) driver = new EndpointDriver(); #endif #ifdef QT_SPARQL_VIRTUOSO if (type == QLatin1String("QVIRTUOSO")) driver = new QVirtuosoDriver(); #endif if (driver) return driver; // drivers built as plugins #if WE_ARE_QT return findDriverWithFactoryLoader(type); #else return findDriverWithPluginLoader(type); #endif } QSparqlDriver* QSparqlConnectionPrivate::findDriverWithFactoryLoader(const QString &type) { #if WE_ARE_QT #if !defined(QT_NO_LIBRARY) && !defined(QT_NO_SETTINGS) if (!driver && loader()) { if (QSparqlDriverFactoryInterface *factory = qobject_cast<QSparqlDriverFactoryInterface*>(loader()->instance(type))) driver = factory->create(type); } #endif // QT_NO_LIBRARY if (!driver) { qWarning("QSparqlConnection: %s driver not loaded", type.toLatin1().data()); qWarning("QSparqlConnection: available drivers: %s", QSparqlConnection::drivers().join(QLatin1String(" ")).toLatin1().data()); if (QCoreApplication::instance() == 0) qWarning("QSparqlConnectionPrivate: an instance of QCoreApplication is required for loading driver plugins"); driver = QSparqlConnectionPrivate::shared_null()->driver; } return driver; #else return 0; #endif // WE_ARE_QT } QStringList QSparqlConnectionPrivate::allKeys; QHash<QString, QSparqlDriverPlugin*> QSparqlConnectionPrivate::plugins; QMutex QSparqlConnectionPrivate::pluginMutex(QMutex::Recursive); void QSparqlConnectionPrivate::initKeys() { static bool keysRead = false; if (keysRead) return; int debugLevel = QString::fromLatin1(getenv("QT_DEBUG_PLUGINS")).toInt(); QStringList paths = QCoreApplication::libraryPaths(); foreach(const QString& path, paths) { QString realPath = path + QLatin1String("/sparqldrivers"); QStringList pluginNames = QDir(realPath).entryList(QDir::Files); for (int j = 0; j < pluginNames.count(); ++j) { QString fileName = QDir::cleanPath(realPath + QLatin1Char('/') + pluginNames.at(j)); if (debugLevel) { qDebug() << "QSparqlConnection looking at" << fileName; } QPluginLoader loader(fileName); QObject* instance = loader.instance(); QFactoryInterface *factory = qobject_cast<QFactoryInterface*>(instance); QSparqlDriverPlugin* driPlu = dynamic_cast<QSparqlDriverPlugin*>(factory); if (instance && factory && driPlu) { QStringList keys = factory->keys(); for (int k = 0; k < keys.size(); ++k) { // Don't override values in plugins; this prefers plugins // that are found first. E.g., // QCoreApplication::addLibraryPath() prepends a path to the // list of library paths, and this say custom plugins are // found first. if (!plugins.contains(keys[k])) plugins[keys[k]] = driPlu; } allKeys.append(keys); if (debugLevel) { qDebug() << "keys" << keys; } } else { if (debugLevel) { qDebug() << "not a plugin"; } } } } keysRead = true; return; } QSparqlDriver* QSparqlConnectionPrivate::findDriverWithPluginLoader(const QString &type) { #if WE_ARE_QT return 0; #else initKeys(); if (plugins.contains(type)) return plugins[type]->create(type); return QSparqlConnectionPrivate::shared_null()->driver; #endif } void qSparqlRegisterConnectionCreator(const QString& type, QSparqlDriverCreatorBase* creator) { QSparqlConnectionPrivate::registerConnectionCreator(type, creator); } void QSparqlConnectionPrivate::registerConnectionCreator(const QString& name, QSparqlDriverCreatorBase* creator) { delete QSparqlConnectionPrivate::driverDict().take(name); if (creator) QSparqlConnectionPrivate::driverDict().insert(name, creator); } /*! \class QSparqlConnection \brief The QSparqlConnection class provides an interface for accessing an RDF store. \inmodule QtSparql */ /*! Constructs and invalid QSparqlConnection. */ QSparqlConnection::QSparqlConnection(QObject* parent) : QObject(parent) { QSparqlDriver* driver = QSparqlConnectionPrivate::shared_null()->driver; d = new QSparqlConnectionPrivate(driver, QString(), QSparqlConnectionOptions()); } /*! Constructs a QSparqlConnection of the given \a type with the given \a options. The \a type is a string which identifies the driver. To get a list of available drivers, use drivers(). The accepted connection options depend on the selected driver. The drivers ignore unneeded connection options. */ QSparqlConnection::QSparqlConnection(const QString& type, const QSparqlConnectionOptions& options, QObject* parent) : QObject(parent) { QSparqlDriver* driver = QSparqlConnectionPrivate::findDriver(type); d = new QSparqlConnectionPrivate(driver, type, options); d->driver->open(d->options); } /*! Destroys the QSparqlConnection object and frees up any resources. Note that QSparqlResult objects that are returned from this class have this object set as their parents, which means that they will be deleted along with it if you don't call QObject::setParent() on them. */ QSparqlConnection::~QSparqlConnection() { QList<QSparqlResult*> children = findChildren<QSparqlResult *>(); foreach (QSparqlResult *result, children) { if (!result->isFinished()) qWarning() << "QSparqlConnection: Deleting active query:" << result->query(); } qDeleteAll(children); d->driver->close(); delete d; } /*! Executes a SPARQL query on the database and returns a pointer to a QSparqlResult object. The user is responsible for freeing it. If \a query is empty or if the this QSparqlConnection is not valid, exec() returns a QSparqlResult which is in the error state. It won't emit the finished() signal. \sa QSparqlQuery, QSparqlResult, QSparqlResult::hasError */ // TODO: isn't it quite bad that the user must check the error // state of the result? Or should the "error result" emit the // finished() signal when the main loop is entered the next time, // so that the user has a change to connect to it? QSparqlResult* QSparqlConnection::exec(const QSparqlQuery& query) { QSparqlResult * result; if (d->driver->isOpenError()) { qWarning("QSparqlConnection::exec: connection not open"); result = new QSparqlNullResult(); result->setLastError(d->driver->lastError()); } else if (!d->driver->isOpen()) { qWarning("QSparqlConnection::exec: connection not open"); result = new QSparqlNullResult(); result->setLastError(QSparqlError(QLatin1String("Connection not open"), QSparqlError::ConnectionError)); } else { QString queryText = query.preparedQueryText(); if (queryText.isEmpty()) { qWarning("QSparqlConnection::exec: empty query"); result = new QSparqlNullResult(); result->setLastError(QSparqlError(QLatin1String("Query is empty"), QSparqlError::ConnectionError)); } else { result = d->driver->exec(queryText, query.type()); } } result->setParent(this); return result; } /*! Returns the connection's driver name. */ QString QSparqlConnection::driverName() const { return d->drvName; } /*! \enum QSparqlConnection::Feature This enum contains a list of features a driver might support. Use hasFeature() to query whether a feature is supported or not. \value QuerySize Whether the database is capable of reporting the size of a query. Note that some databases do not support returning the size (i.e. number of rows returned) of a query, in which case QSparqlQuery::size() will return -1. \value DefaultGraph The store has a default graph which doesn't have to be specified. Some stores, like Virtuoso, don't have a default graph. \value AskQueries The driver supports ASK queries \value ConstructQueries The driver supports CONSTRUCT queries \value UpdateQueries The driver supports INSERT and UPDATE queries \sa hasFeature() */ /*! Returns true if the QSparqlConnection supports feature \a feature; otherwise returns false. */ bool QSparqlConnection::hasFeature(Feature feature) const { return d->driver->hasFeature(feature); } /*! Returns true if the QSparqlConnection has a valid driver, i.e., the name of the driver given in the constructor was valid. Example: \snippet doc/src/snippets/code/src_sparql_kernel_qsparqlconnection.cpp 8 */ bool QSparqlConnection::isValid() const { return d->driver && d->driver != d->shared_null()->driver; } /*! Adds a prefix/uri pair to the connection. Each SPARQL query made with the connection will have the prefixes prepended to it. */ void QSparqlConnection::addPrefix(const QString& prefix, const QUrl& uri) { d->driver->addPrefix(prefix, uri); } /*! Removes any prefix/uri pairs which have been added to the connection. */ void QSparqlConnection::clearPrefixes() { d->driver->clearPrefixes(); } /*! Creates a new Urn based Uri */ QUrl QSparqlConnection::createUrn() const { QByteArray uuid = QUuid::createUuid().toString().toLatin1(); QByteArray urn = "urn:uuid:" + uuid.mid(1, uuid.size() - 2); return QUrl::fromEncoded(urn); } /*! Creates a Urn for use in an insert query. The given name can be used to substitute the value into the query string. */ QSparqlBinding QSparqlConnection::createUrn(const QString& name) const { return QSparqlBinding(name, createUrn()); } /*! Returns the list of available drivers. The list contains driver names which can be passed to QSparqlConnection constructor. */ QStringList QSparqlConnection::drivers() { QMutexLocker locker(&(QSparqlConnectionPrivate::pluginMutex)); QStringList list; #ifdef QT_SPARQL_VIRTUOSO list << QLatin1String("QVIRTUOSO"); #endif #ifdef QT_SPARQL_TRACKER list << QLatin1String("QTRACKER"); #endif #ifdef QT_SPARQL_TRACKER_DIRECT list << QLatin1String("QTRACKER_DIRECT"); #endif #ifdef QT_SPARQL_ENDPOINT list << QLatin1String("QSPARQL_ENDPOINT"); #endif #if WE_ARE_QT #if !defined(QT_NO_LIBRARY) && !defined(QT_NO_SETTINGS) if (QFactoryLoader *fl = loader()) { QStringList keys = fl->keys(); for (QStringList::const_iterator i = keys.constBegin(); i != keys.constEnd(); ++i) { if (!list.contains(*i)) list << *i; } } #endif #else QSparqlConnectionPrivate::initKeys(); QStringList keys = QSparqlConnectionPrivate::allKeys; for (QStringList::const_iterator i = keys.constBegin(); i != keys.constEnd(); ++i) { if (!list.contains(*i)) list << *i; } #endif DriverDict dict = QSparqlConnectionPrivate::driverDict(); for (DriverDict::const_iterator i = dict.constBegin(); i != dict.constEnd(); ++i) { if (!list.contains(i.key())) list << i.key(); } return list; } #ifndef QT_NO_DEBUG_STREAM QDebug operator<<(QDebug dbg, const QSparqlConnection &d) { if (!d.isValid()) { dbg.nospace() << "QSparqlConnection(invalid)"; return dbg.space(); } dbg.nospace() << "QSparqlConnection(driver=\"" << d.driverName() << ")"; return dbg.space(); } #endif QT_END_NAMESPACE Adding docs about some gotchas. /**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (ivan.frade@nokia.com) ** ** This file is part of the QtSparql module (not yet part of the Qt Toolkit). ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial Usage ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** If you have questions regarding the use of this file, please contact ** Nokia at ivan.frade@nokia.com. ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qsparqlconnection.h" #include "qsparqlconnection_p.h" #include "qsparqlquery.h" #ifdef QT_SPARQL_VIRTUOSO #include "../drivers/virtuoso/qsparql_virtuoso_p.h" #endif #ifdef QT_SPARQL_TRACKER #include "../drivers/tracker/qsparql_tracker_p.h" #endif #ifdef QT_SPARQL_TRACKER_DIRECT #include "../drivers/tracker_direct/qsparql_tracker_direct_p.h" #endif #ifdef QT_SPARQL_ENDPOINT #include "../drivers/endpoint/qsparql_endpoint_p.h" #endif #include "qdebug.h" #include "qcoreapplication.h" #include "qsparqlresult.h" #include "qsparqlconnectionoptions.h" #include "qsparqldriver_p.h" #include "qsparqldriverplugin_p.h" #if WE_ARE_QT // QFactoryLoader is an internal part of Qt; we'll use it when where part of Qt // (or when Qt publishes it.) # include "qfactoryloader_p.h" #else # include "qdir.h" # include "qpluginloader.h" #endif #include "qsparqlnulldriver_p.h" #include <QtCore/qhash.h> #include <QtCore/quuid.h> #include <QtCore/qmutex.h> QT_BEGIN_NAMESPACE #if WE_ARE_QT #if !defined(QT_NO_LIBRARY) && !defined(QT_NO_SETTINGS) Q_GLOBAL_STATIC_WITH_ARGS(QFactoryLoader, loader, (QSparqlDriverFactoryInterface_iid, QLatin1String("/sparqldrivers"))) #endif #endif typedef QHash<QString, QSparqlDriverCreatorBase*> DriverDict; class QSparqlConnectionPrivate { public: QSparqlConnectionPrivate(QSparqlDriver *dr, const QString& name, const QSparqlConnectionOptions& opts): driver(dr), drvName(name), options(opts) { } ~QSparqlConnectionPrivate(); static DriverDict &driverDict(); static QSparqlDriver* findDriver(const QString& type); static QSparqlDriver* findDriverWithFactoryLoader(const QString& type); static void initKeys(); static QSparqlDriver* findDriverWithPluginLoader(const QString& type); static void registerConnectionCreator(const QString &type, QSparqlDriverCreatorBase* creator); static QSparqlConnectionPrivate* shared_null(); static QStringList allKeys; static QHash<QString, QSparqlDriverPlugin*> plugins; static QMutex pluginMutex; // protexts allKeys, plugins and driverDict QSparqlDriver* driver; QString drvName; QSparqlConnectionOptions options; }; QSparqlConnectionPrivate *QSparqlConnectionPrivate::shared_null() { static QSparqlNullDriver dr; static QSparqlConnectionPrivate n(&dr, QString(), QSparqlConnectionOptions()); return &n; } QSparqlConnectionPrivate::~QSparqlConnectionPrivate() { if (driver != shared_null()->driver) { delete driver; driver = shared_null()->driver; } } static bool qDriverDictInit = false; static void cleanDriverDict() { qDeleteAll(QSparqlConnectionPrivate::driverDict()); QSparqlConnectionPrivate::driverDict().clear(); qDriverDictInit = false; } DriverDict &QSparqlConnectionPrivate::driverDict() { static DriverDict dict; if (!qDriverDictInit) { qDriverDictInit = true; qAddPostRoutine(cleanDriverDict); } return dict; } /*! \internal Create the actual driver instance \a type. */ QSparqlDriver* QSparqlConnectionPrivate::findDriver(const QString &type) { QMutexLocker locker(&pluginMutex); // separately defined drivers (e.g., for tests) QSparqlDriver * driver = 0; DriverDict dict = QSparqlConnectionPrivate::driverDict(); for (DriverDict::const_iterator it = dict.constBegin(); it != dict.constEnd() && !driver; ++it) { if (type == it.key()) { driver = ((QSparqlDriverCreatorBase*)(*it))->createObject(); } } if (driver) return driver; // drivers built into the .so #ifdef QT_SPARQL_TRACKER if (type == QLatin1String("QTRACKER")) driver = new QTrackerDriver(); #endif #ifdef QT_SPARQL_TRACKER_DIRECT if (type == QLatin1String("QTRACKER_DIRECT")) driver = new QTrackerDirectDriver(); #endif #ifdef QT_SPARQL_ENDPOINT if (type == QLatin1String("QSPARQL_ENDPOINT")) driver = new EndpointDriver(); #endif #ifdef QT_SPARQL_VIRTUOSO if (type == QLatin1String("QVIRTUOSO")) driver = new QVirtuosoDriver(); #endif if (driver) return driver; // drivers built as plugins #if WE_ARE_QT return findDriverWithFactoryLoader(type); #else return findDriverWithPluginLoader(type); #endif } QSparqlDriver* QSparqlConnectionPrivate::findDriverWithFactoryLoader(const QString &type) { #if WE_ARE_QT #if !defined(QT_NO_LIBRARY) && !defined(QT_NO_SETTINGS) if (!driver && loader()) { if (QSparqlDriverFactoryInterface *factory = qobject_cast<QSparqlDriverFactoryInterface*>(loader()->instance(type))) driver = factory->create(type); } #endif // QT_NO_LIBRARY if (!driver) { qWarning("QSparqlConnection: %s driver not loaded", type.toLatin1().data()); qWarning("QSparqlConnection: available drivers: %s", QSparqlConnection::drivers().join(QLatin1String(" ")).toLatin1().data()); if (QCoreApplication::instance() == 0) qWarning("QSparqlConnectionPrivate: an instance of QCoreApplication is required for loading driver plugins"); driver = QSparqlConnectionPrivate::shared_null()->driver; } return driver; #else return 0; #endif // WE_ARE_QT } QStringList QSparqlConnectionPrivate::allKeys; QHash<QString, QSparqlDriverPlugin*> QSparqlConnectionPrivate::plugins; QMutex QSparqlConnectionPrivate::pluginMutex(QMutex::Recursive); void QSparqlConnectionPrivate::initKeys() { static bool keysRead = false; if (keysRead) return; int debugLevel = QString::fromLatin1(getenv("QT_DEBUG_PLUGINS")).toInt(); QStringList paths = QCoreApplication::libraryPaths(); foreach(const QString& path, paths) { QString realPath = path + QLatin1String("/sparqldrivers"); QStringList pluginNames = QDir(realPath).entryList(QDir::Files); for (int j = 0; j < pluginNames.count(); ++j) { QString fileName = QDir::cleanPath(realPath + QLatin1Char('/') + pluginNames.at(j)); if (debugLevel) { qDebug() << "QSparqlConnection looking at" << fileName; } QPluginLoader loader(fileName); QObject* instance = loader.instance(); QFactoryInterface *factory = qobject_cast<QFactoryInterface*>(instance); QSparqlDriverPlugin* driPlu = dynamic_cast<QSparqlDriverPlugin*>(factory); if (instance && factory && driPlu) { QStringList keys = factory->keys(); for (int k = 0; k < keys.size(); ++k) { // Don't override values in plugins; this prefers plugins // that are found first. E.g., // QCoreApplication::addLibraryPath() prepends a path to the // list of library paths, and this say custom plugins are // found first. if (!plugins.contains(keys[k])) plugins[keys[k]] = driPlu; } allKeys.append(keys); if (debugLevel) { qDebug() << "keys" << keys; } } else { if (debugLevel) { qDebug() << "not a plugin"; } } } } keysRead = true; return; } QSparqlDriver* QSparqlConnectionPrivate::findDriverWithPluginLoader(const QString &type) { #if WE_ARE_QT return 0; #else initKeys(); if (plugins.contains(type)) return plugins[type]->create(type); return QSparqlConnectionPrivate::shared_null()->driver; #endif } void qSparqlRegisterConnectionCreator(const QString& type, QSparqlDriverCreatorBase* creator) { QSparqlConnectionPrivate::registerConnectionCreator(type, creator); } void QSparqlConnectionPrivate::registerConnectionCreator(const QString& name, QSparqlDriverCreatorBase* creator) { delete QSparqlConnectionPrivate::driverDict().take(name); if (creator) QSparqlConnectionPrivate::driverDict().insert(name, creator); } /*! \class QSparqlConnection \brief The QSparqlConnection class provides an interface for accessing an RDF store. \inmodule QtSparql */ /*! Constructs and invalid QSparqlConnection. */ QSparqlConnection::QSparqlConnection(QObject* parent) : QObject(parent) { QSparqlDriver* driver = QSparqlConnectionPrivate::shared_null()->driver; d = new QSparqlConnectionPrivate(driver, QString(), QSparqlConnectionOptions()); } /*! Constructs a QSparqlConnection of the given \a type with the given \a options. The \a type is a string which identifies the driver. To get a list of available drivers, use drivers(). The accepted connection options depend on the selected driver. The drivers ignore unneeded connection options. */ QSparqlConnection::QSparqlConnection(const QString& type, const QSparqlConnectionOptions& options, QObject* parent) : QObject(parent) { QSparqlDriver* driver = QSparqlConnectionPrivate::findDriver(type); d = new QSparqlConnectionPrivate(driver, type, options); d->driver->open(d->options); } /*! Destroys the QSparqlConnection object and frees up any resources. Note that QSparqlResult objects that are returned from this class have this object set as their parents, which means that they will be deleted along with it if you don't call QObject::setParent() on them. */ QSparqlConnection::~QSparqlConnection() { QList<QSparqlResult*> children = findChildren<QSparqlResult *>(); foreach (QSparqlResult *result, children) { if (!result->isFinished()) qWarning() << "QSparqlConnection: Deleting active query:" << result->query(); } qDeleteAll(children); d->driver->close(); delete d; } /*! Executes a SPARQL query on the database and returns a pointer to a QSparqlResult object. The user is responsible for freeing it when it's no longer used (but not after the QSparqlConnection is deleted). The QSparqlResult object is also a child of the QSparqlConnection, so after the QSparqlConnection has been deleted, the QSparqlResult is no longer valid (and doesn't need to be freed). If \a query is empty or if the this QSparqlConnection is not valid, exec() returns a QSparqlResult which is in the error state. It won't emit the finished() signal. If this function fails with "connection not open" error, the most probable reason is that the required driver is not installed. \sa QSparqlQuery, QSparqlResult, QSparqlResult::hasError */ // TODO: isn't it quite bad that the user must check the error // state of the result? Or should the "error result" emit the // finished() signal when the main loop is entered the next time, // so that the user has a change to connect to it? QSparqlResult* QSparqlConnection::exec(const QSparqlQuery& query) { QSparqlResult * result; if (d->driver->isOpenError()) { qWarning("QSparqlConnection::exec: connection not open"); result = new QSparqlNullResult(); result->setLastError(d->driver->lastError()); } else if (!d->driver->isOpen()) { qWarning("QSparqlConnection::exec: connection not open"); result = new QSparqlNullResult(); result->setLastError(QSparqlError(QLatin1String("Connection not open"), QSparqlError::ConnectionError)); } else { QString queryText = query.preparedQueryText(); if (queryText.isEmpty()) { qWarning("QSparqlConnection::exec: empty query"); result = new QSparqlNullResult(); result->setLastError(QSparqlError(QLatin1String("Query is empty"), QSparqlError::ConnectionError)); } else { result = d->driver->exec(queryText, query.type()); } } result->setParent(this); return result; } /*! Returns the connection's driver name. */ QString QSparqlConnection::driverName() const { return d->drvName; } /*! \enum QSparqlConnection::Feature This enum contains a list of features a driver might support. Use hasFeature() to query whether a feature is supported or not. \value QuerySize Whether the database is capable of reporting the size of a query. Note that some databases do not support returning the size (i.e. number of rows returned) of a query, in which case QSparqlQuery::size() will return -1. \value DefaultGraph The store has a default graph which doesn't have to be specified. Some stores, like Virtuoso, don't have a default graph. \value AskQueries The driver supports ASK queries \value ConstructQueries The driver supports CONSTRUCT queries \value UpdateQueries The driver supports INSERT and UPDATE queries \sa hasFeature() */ /*! Returns true if the QSparqlConnection supports feature \a feature; otherwise returns false. */ bool QSparqlConnection::hasFeature(Feature feature) const { return d->driver->hasFeature(feature); } /*! Returns true if the QSparqlConnection has a valid driver, i.e., the name of the driver given in the constructor was valid. Example: \snippet doc/src/snippets/code/src_sparql_kernel_qsparqlconnection.cpp 8 */ bool QSparqlConnection::isValid() const { return d->driver && d->driver != d->shared_null()->driver; } /*! Adds a prefix/uri pair to the connection. Each SPARQL query made with the connection will have the prefixes prepended to it. */ void QSparqlConnection::addPrefix(const QString& prefix, const QUrl& uri) { d->driver->addPrefix(prefix, uri); } /*! Removes any prefix/uri pairs which have been added to the connection. */ void QSparqlConnection::clearPrefixes() { d->driver->clearPrefixes(); } /*! Creates a new Urn based Uri */ QUrl QSparqlConnection::createUrn() const { QByteArray uuid = QUuid::createUuid().toString().toLatin1(); QByteArray urn = "urn:uuid:" + uuid.mid(1, uuid.size() - 2); return QUrl::fromEncoded(urn); } /*! Creates a Urn for use in an insert query. The given name can be used to substitute the value into the query string. */ QSparqlBinding QSparqlConnection::createUrn(const QString& name) const { return QSparqlBinding(name, createUrn()); } /*! Returns the list of available drivers. The list contains driver names which can be passed to QSparqlConnection constructor. */ QStringList QSparqlConnection::drivers() { QMutexLocker locker(&(QSparqlConnectionPrivate::pluginMutex)); QStringList list; #ifdef QT_SPARQL_VIRTUOSO list << QLatin1String("QVIRTUOSO"); #endif #ifdef QT_SPARQL_TRACKER list << QLatin1String("QTRACKER"); #endif #ifdef QT_SPARQL_TRACKER_DIRECT list << QLatin1String("QTRACKER_DIRECT"); #endif #ifdef QT_SPARQL_ENDPOINT list << QLatin1String("QSPARQL_ENDPOINT"); #endif #if WE_ARE_QT #if !defined(QT_NO_LIBRARY) && !defined(QT_NO_SETTINGS) if (QFactoryLoader *fl = loader()) { QStringList keys = fl->keys(); for (QStringList::const_iterator i = keys.constBegin(); i != keys.constEnd(); ++i) { if (!list.contains(*i)) list << *i; } } #endif #else QSparqlConnectionPrivate::initKeys(); QStringList keys = QSparqlConnectionPrivate::allKeys; for (QStringList::const_iterator i = keys.constBegin(); i != keys.constEnd(); ++i) { if (!list.contains(*i)) list << *i; } #endif DriverDict dict = QSparqlConnectionPrivate::driverDict(); for (DriverDict::const_iterator i = dict.constBegin(); i != dict.constEnd(); ++i) { if (!list.contains(i.key())) list << i.key(); } return list; } #ifndef QT_NO_DEBUG_STREAM QDebug operator<<(QDebug dbg, const QSparqlConnection &d) { if (!d.isValid()) { dbg.nospace() << "QSparqlConnection(invalid)"; return dbg.space(); } dbg.nospace() << "QSparqlConnection(driver=\"" << d.driverName() << ")"; return dbg.space(); } #endif QT_END_NAMESPACE
/************************************************************************* * * $RCSfile: htmlexp.cxx,v $ * * $Revision: 1.23 $ * * last change: $Author: rt $ $Date: 2003-04-08 16:26:37 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifdef PCH #include "filt_pch.hxx" #endif #pragma hdrstop // INCLUDE --------------------------------------------------------------- #include "scitems.hxx" #include <svx/eeitem.hxx> #define ITEMID_FIELD EE_FEATURE_FIELD #define _SVSTDARR_STRINGSSORTDTOR #ifndef _RTL_TENCINFO_H //autogen wg. rtl_getBestMimeCharsetFromTextEncoding, rtl_getTextEncodingFromMimeCharset #include <rtl/tencinfo.h> #endif #include <svx/algitem.hxx> #include <svx/boxitem.hxx> #include <svx/brshitem.hxx> #include <svx/colritem.hxx> #include <svx/fhgtitem.hxx> #include <svx/fontitem.hxx> #include <svx/postitem.hxx> #include <svx/udlnitem.hxx> #include <svx/wghtitem.hxx> #include <svx/xoutbmp.hxx> #ifndef _MyEDITENG_HXX //autogen wg. EditEngine #include <svx/editeng.hxx> #endif #include <offmgr/app.hxx> #include <offmgr/htmlcfg.hxx> #include <sfx2/docfile.hxx> #include <sfx2/docinf.hxx> #include <sfx2/frmhtmlw.hxx> #include <sfx2/objsh.hxx> #include <svtools/stritem.hxx> #ifndef SVTOOLS_URIHELPER_HXX #include <svtools/urihelper.hxx> #endif #ifndef _SVSTDARR_USHORTS #define _SVSTDARR_USHORTS #endif #include <svtools/svstdarr.hxx> #include <svtools/zforlist.hxx> #include <svtools/htmlkywd.hxx> #include <svtools/htmlout.hxx> #include <svtools/parhtml.hxx> #include <vcl/outdev.hxx> #include <stdio.h> #if defined(GetNumberFormat) && SUPD<356 // xoutbmp.hxx -> svimbase.hxx -> sysdep.hxx -> windows.h -> // define GetNumberFormat GetNumberFormatA #undef GetNumberFormat #endif #include "htmlexp.hxx" #include "filter.hxx" #include "flttools.hxx" #include "global.hxx" #include "document.hxx" #include "scitems.hxx" #include "attrib.hxx" #include "patattr.hxx" #include "stlpool.hxx" #include "scresid.hxx" #include "cell.hxx" #include "cellform.hxx" #include "docoptio.hxx" #include "editutil.hxx" #define ITEMID_FIELD EE_FEATURE_FIELD #include <svx/flditem.hxx> #undef ITEMID_FIELD #ifndef INCLUDED_SVTOOLS_SYSLOCALE_HXX #include <svtools/syslocale.hxx> #endif // ohne sc.hrc: error C2679: binary '=' : no operator defined which takes a // right-hand operand of type 'const class String (__stdcall *)(class ScResId)' // bei // const String aStrTable( ScResId( SCSTR_TABLE ) ); aStrOut = aStrTable; // ?!??? #include "sc.hrc" #include "globstr.hrc" //======================================================================== const static sal_Char __FAR_DATA sMyBegComment[] = "<!-- "; const static sal_Char __FAR_DATA sMyEndComment[] = " -->"; const static sal_Char __FAR_DATA sFontFamily[] = "font-family:"; const static sal_Char __FAR_DATA sFontSize[] = "font-size:"; const USHORT __FAR_DATA ScHTMLExport::nDefaultFontSize[SC_HTML_FONTSIZES] = { HTMLFONTSZ1_DFLT, HTMLFONTSZ2_DFLT, HTMLFONTSZ3_DFLT, HTMLFONTSZ4_DFLT, HTMLFONTSZ5_DFLT, HTMLFONTSZ6_DFLT, HTMLFONTSZ7_DFLT }; USHORT ScHTMLExport::nFontSize[SC_HTML_FONTSIZES] = { 0 }; const char* __FAR_DATA ScHTMLExport::pFontSizeCss[SC_HTML_FONTSIZES] = { "xx-small", "x-small", "small", "medium", "large", "x-large", "xx-large" }; const USHORT ScHTMLExport::nCellSpacing = 0; const sal_Char __FAR_DATA ScHTMLExport::sIndentSource[nIndentMax+1] = "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t"; //======================================================================== // Makros fuer HTML-Export //======================================================================== #define OUT_PROLOGUE() (rStrm << sHTML30_Prologue << ScExportBase::sNewLine \ << ScExportBase::sNewLine) #define TAG_ON( tag ) HTMLOutFuncs::Out_AsciiTag( rStrm, tag ) #define TAG_OFF( tag ) HTMLOutFuncs::Out_AsciiTag( rStrm, tag, FALSE ) #define OUT_STR( str ) HTMLOutFuncs::Out_String( rStrm, str, eDestEnc, &aNonConvertibleChars ) #define OUT_STR_NO_CONV( str ) HTMLOutFuncs::Out_String( rStrm, str, eDestEnc ) #define OUT_LF() rStrm << ScExportBase::sNewLine << GetIndentStr() #define lcl_OUT_LF() rStrm << ScExportBase::sNewLine #define TAG_ON_LF( tag ) (TAG_ON( tag ) << ScExportBase::sNewLine << GetIndentStr()) #define TAG_OFF_LF( tag ) (TAG_OFF( tag ) << ScExportBase::sNewLine << GetIndentStr()) #define OUT_HR() TAG_ON_LF( sHTML_horzrule ) #define OUT_COMMENT( comment ) (rStrm << sMyBegComment, OUT_STR( comment ) \ << sMyEndComment << ScExportBase::sNewLine \ << GetIndentStr()) #define lcl_OUT_COMMENT( comment ) (rStrm << sMyBegComment, OUT_STR_NO_CONV( comment ) \ << sMyEndComment << ScExportBase::sNewLine) #define OUT_SP_CSTR_ASS( s ) rStrm << ' ' << s << '=' #define APPEND_SPACE( s ) s.AppendAscii(" ") extern BOOL bOderSo; #define GLOBSTR(id) ScGlobal::GetRscString( id ) //======================================================================== FltError ScExportHTML( SvStream& rStrm, ScDocument* pDoc, const ScRange& rRange, const CharSet eNach, BOOL bAll, const String& rStreamPath, String& rNonConvertibleChars ) { ScHTMLExport aEx( rStrm, pDoc, rRange, bAll, rStreamPath ); FltError nErr = aEx.Write(); rNonConvertibleChars = aEx.GetNonConvertibleChars(); return nErr; } void lcl_AddStamp( String& rStr, const SfxStamp& rStamp, const LocaleDataWrapper& rLoc ) { const DateTime& rDateTime = rStamp.GetTime(); String aStrDate = rLoc.getDate( rDateTime ); String aStrTime = rLoc.getTime( rDateTime ); rStr += GLOBSTR( STR_BY ); APPEND_SPACE( rStr ); if (rStamp.GetName().Len()) rStr += rStamp.GetName(); else rStr.AppendAscii( "???" ); APPEND_SPACE( rStr ); rStr += GLOBSTR( STR_ON ); APPEND_SPACE( rStr ); if (aStrDate.Len()) rStr += aStrDate; else rStr.AppendAscii( "???" ); rStr.AppendAscii( ", " ); if (aStrTime.Len()) rStr += aStrTime; else rStr.AppendAscii( "???" ); } void lcl_AppendHTMLColorTripel( ByteString& rStr, const Color& rColor ) { // <font COLOR="#00FF40">hallo</font> sal_Char buf[64]; sal_Char* p = buf; rStr += "\"#"; p += sprintf( p, "%02X", rColor.GetRed() ); // #100211# - checked p += sprintf( p, "%02X", rColor.GetGreen() ); // #100211# - checked p += sprintf( p, "%02X", rColor.GetBlue() ); // #100211# - checked rStr += buf; rStr += '\"'; } /*void lcl_TagOn( String& rResult, const String& rTag, const String* pStrOpt ) { rResult = '<'; rResult += rTag; if ( pStrOpt ) { rResult += ' '; rResult += *pStrOpt; } rResult += '>'; } */ /*void lcl_TagOff( String& rResult, const String& rTag ) { rResult = '<'; rResult += rTag; rResult += '>'; } */ void lcl_WriteTeamInfo( SvStream& rStrm, rtl_TextEncoding eDestEnc ) { if ( !bOderSo ) return; lcl_OUT_LF(); lcl_OUT_COMMENT( _STRINGCONST( "Sascha Ballach " ) ); lcl_OUT_COMMENT( _STRINGCONST( "Michael Daeumling (aka Bitsau) " ) ); lcl_OUT_COMMENT( _STRINGCONST( "Michael Hagen " ) ); lcl_OUT_COMMENT( _STRINGCONST( "Roland Jakobs " ) ); lcl_OUT_COMMENT( _STRINGCONST( "Andreas Krebs " ) ); lcl_OUT_COMMENT( _STRINGCONST( "John Marmion " ) ); lcl_OUT_COMMENT( _STRINGCONST( "Niklas Nebel " ) ); lcl_OUT_COMMENT( _STRINGCONST( "Jacques Nietsch " ) ); lcl_OUT_COMMENT( _STRINGCONST( "Marcus Olk " ) ); lcl_OUT_COMMENT( _STRINGCONST( "Eike Rathke " ) ); lcl_OUT_COMMENT( _STRINGCONST( "Daniel Rentz " ) ); lcl_OUT_COMMENT( _STRINGCONST( "Stephan Templin " ) ); lcl_OUT_COMMENT( _STRINGCONST( "Gunnar Timm " ) ); lcl_OUT_COMMENT( _STRINGCONST( "*** Man kann nicht ALLES haben! ***" ) ); lcl_OUT_LF(); } ////////////////////////////////////////////////////////////////////////////// ScHTMLExport::ScHTMLExport( SvStream& rStrmP, ScDocument* pDocP, const ScRange& rRangeP, BOOL bAllP, const String& rStreamPathP ) : ScExportBase( rStrmP, pDocP, rRangeP ), aStreamPath( rStreamPathP ), pAppWin( Application::GetDefaultDevice() ), pSrcArr( NULL ), pDestArr( NULL ), nUsedTables( 0 ), nIndent( 0 ), bAll( bAllP ), bTabHasGraphics( FALSE ), bCalcAsShown( pDocP->GetDocOptions().IsCalcAsShown() ), bTableDataHeight( TRUE ), bTableDataWidth( TRUE ) { strcpy( sIndent, sIndentSource ); // #100211# - checked sIndent[0] = 0; // set HTML configuration OfaHtmlOptions* pHtmlOptions = ((OfficeApplication*)SFX_APP())->GetHtmlOptions(); eDestEnc = (pDoc->IsClipOrUndo() ? RTL_TEXTENCODING_UTF8 : pHtmlOptions->GetTextEncoding()); bCopyLocalFileToINet = pHtmlOptions->IsSaveGraphicsLocal(); for ( USHORT j=0; j < SC_HTML_FONTSIZES; j++ ) { USHORT nSize = pHtmlOptions->GetFontSize( j ); // remember in Twips, like our SvxFontHeightItem if ( nSize ) nFontSize[j] = nSize * 20; else nFontSize[j] = nDefaultFontSize[j] * 20; } const USHORT nCount = pDoc->GetTableCount(); for ( USHORT nTab = 0; nTab < nCount; nTab++ ) { if ( !IsEmptyTable( nTab ) ) nUsedTables++; } // Content-Id fuer Mail-Export? SfxObjectShell* pDocSh = pDoc->GetDocumentShell(); if ( pDocSh ) { const SfxPoolItem* pItem = pDocSh->GetItem( SID_ORIGURL ); if( pItem ) { aCId = ((const SfxStringItem *)pItem)->GetValue(); DBG_ASSERT( aCId.Len(), "CID ohne Laenge!" ); } } } ScHTMLExport::~ScHTMLExport() { for ( ScHTMLGraphEntry* pE = aGraphList.First(); pE; pE = aGraphList.Next() ) delete pE; delete pSrcArr; delete pDestArr; } USHORT ScHTMLExport::GetFontSizeNumber( USHORT nHeight ) { USHORT nSize = 1; for ( USHORT j=SC_HTML_FONTSIZES-1; j>0; j-- ) { if( nHeight > (nFontSize[j] + nFontSize[j-1]) / 2 ) { // der naechstgelegene nSize = j+1; break; } } return nSize; } const char* ScHTMLExport::GetFontSizeCss( USHORT nHeight ) { USHORT nSize = GetFontSizeNumber( nHeight ); return pFontSizeCss[ nSize-1 ]; } USHORT ScHTMLExport::ToPixel( USHORT nVal ) { if( nVal ) { nVal = (USHORT)pAppWin->LogicToPixel( Size( nVal, nVal ), MapMode( MAP_TWIP ) ).Width(); if( !nVal ) // wo ein Twip ist sollte auch ein Pixel sein nVal = 1; } return nVal; } Size ScHTMLExport::MMToPixel( const Size& rSize ) { Size aSize( rSize ); aSize = pAppWin->LogicToPixel( rSize, MapMode( MAP_100TH_MM ) ); // wo etwas ist sollte auch ein Pixel sein if ( !aSize.Width() && rSize.Width() ) aSize.Width() = 1; if ( !aSize.Height() && rSize.Height() ) aSize.Height() = 1; return aSize; } ULONG ScHTMLExport::Write() { rStrm << '<' << sHTML_doctype << ' ' << sHTML_doctype32 << '>' << sNewLine << sNewLine; TAG_ON_LF( sHTML_html ); WriteHeader(); OUT_LF(); WriteBody(); OUT_LF(); TAG_OFF_LF( sHTML_html ); return rStrm.GetError(); } void ScHTMLExport::WriteHeader() { IncIndent(1); TAG_ON_LF( sHTML_head ); if ( pDoc->IsClipOrUndo() ) { // no real DocInfo available, but some META information like charset needed SfxFrameHTMLWriter::Out_DocInfo( rStrm, NULL, sIndent, eDestEnc, &aNonConvertibleChars ); } else { SfxDocumentInfo& rInfo = pDoc->GetDocumentShell()->GetDocInfo(); SfxFrameHTMLWriter::Out_DocInfo( rStrm, &rInfo, sIndent, eDestEnc, &aNonConvertibleChars ); OUT_LF(); //---------------------------------------------------------- if ( rInfo.GetPrinted().GetName().Len() ) { OUT_COMMENT( GLOBSTR( STR_DOC_INFO ) ); String aStrOut( GLOBSTR( STR_DOC_PRINTED ) ); aStrOut.AppendAscii( ": " ); lcl_AddStamp( aStrOut, rInfo.GetPrinted(), *ScGlobal::pLocaleData ); OUT_COMMENT( aStrOut ); } //---------------------------------------------------------- lcl_WriteTeamInfo( rStrm, eDestEnc ); } OUT_LF(); // CSS1 StyleSheet PageDefaults( bAll ? 0 : aRange.aStart.Tab() ); IncIndent(1); TAG_ON_LF( sHTML_style ); rStrm << sMyBegComment; OUT_LF(); rStrm << sHTML_body << "," << sHTML_division << "," << sHTML_table << "," << sHTML_thead << "," << sHTML_tbody << "," << sHTML_tfoot << "," << sHTML_tablerow << "," << sHTML_tableheader << "," << sHTML_tabledata << "," << sHTML_parabreak << " { " << sFontFamily; xub_StrLen nFonts = aHTMLStyle.aFontFamilyName.GetTokenCount( ';' ); if ( nFonts == 1 ) { rStrm << '\"'; OUT_STR( aHTMLStyle.aFontFamilyName ); rStrm << '\"'; } else { // Fontliste, VCL: Semikolon als Separator, // CSS1: Komma als Separator und jeder einzelne Fontname quoted const String& rList = aHTMLStyle.aFontFamilyName; for ( xub_StrLen j = 0, nPos = 0; j < nFonts; j++ ) { rStrm << '\"'; OUT_STR( rList.GetToken( 0, ';', nPos ) ); rStrm << '\"'; if ( j < nFonts-1 ) rStrm << ", "; } } rStrm << "; " << sFontSize << GetFontSizeCss( ( USHORT ) aHTMLStyle.nFontHeight ) << " }"; OUT_LF(); rStrm << sMyEndComment; IncIndent(-1); OUT_LF(); TAG_OFF_LF( sHTML_style ); IncIndent(-1); OUT_LF(); TAG_OFF_LF( sHTML_head ); } void ScHTMLExport::WriteOverview() { if ( nUsedTables > 1 ) { IncIndent(1); OUT_HR(); IncIndent(1); TAG_ON( sHTML_parabreak ); TAG_ON_LF( sHTML_center ); TAG_ON( sHTML_head1 ); OUT_STR( ScGlobal::GetRscString( STR_OVERVIEW ) ); TAG_OFF_LF( sHTML_head1 ); String aStr; const USHORT nCount = pDoc->GetTableCount(); for ( USHORT nTab = 0; nTab < nCount; nTab++ ) { if ( !IsEmptyTable( nTab ) ) { pDoc->GetName( nTab, aStr ); rStrm << "<A HREF=\"#table" << ByteString::CreateFromInt32( nTab ).GetBuffer() << "\">"; OUT_STR( aStr ); rStrm << "</A>"; TAG_ON_LF( sHTML_linebreak ); } } IncIndent(-1); OUT_LF(); IncIndent(-1); TAG_OFF( sHTML_center ); TAG_OFF_LF( sHTML_parabreak ); } } const SfxItemSet& ScHTMLExport::PageDefaults( USHORT nTab ) { SfxStyleSheetBasePool* pStylePool = pDoc->GetStyleSheetPool(); SfxStyleSheetBase* pStyleSheet = NULL; DBG_ASSERT( pStylePool, "StylePool not found! :-(" ); // remember defaults for compare in WriteCell if ( !aHTMLStyle.bInitialized ) { pStylePool->SetSearchMask( SFX_STYLE_FAMILY_PARA, SFXSTYLEBIT_ALL ); pStyleSheet = pStylePool->Find( ScGlobal::GetRscString(STR_STYLENAME_STANDARD), SFX_STYLE_FAMILY_PARA ); DBG_ASSERT( pStyleSheet, "ParaStyle not found! :-(" ); if (!pStyleSheet) pStyleSheet = pStylePool->First(); const SfxItemSet& rSetPara = pStyleSheet->GetItemSet(); aHTMLStyle.nDefaultScriptType = ScGlobal::GetDefaultScriptType(); aHTMLStyle.aFontFamilyName = ((const SvxFontItem&)(rSetPara.Get( ScGlobal::GetScriptedWhichID( aHTMLStyle.nDefaultScriptType, ATTR_FONT )))).GetFamilyName(); aHTMLStyle.nFontHeight = ((const SvxFontHeightItem&)(rSetPara.Get( ScGlobal::GetScriptedWhichID( aHTMLStyle.nDefaultScriptType, ATTR_FONT_HEIGHT )))).GetHeight(); aHTMLStyle.nFontSizeNumber = GetFontSizeNumber( aHTMLStyle.nFontHeight ); } // Page style sheet printer settings, e.g. for background graphics. // There's only one background graphic in HTML! pStylePool->SetSearchMask( SFX_STYLE_FAMILY_PAGE, SFXSTYLEBIT_ALL ); pStyleSheet = pStylePool->Find( pDoc->GetPageStyle( nTab ), SFX_STYLE_FAMILY_PAGE ); DBG_ASSERT( pStyleSheet, "PageStyle not found! :-(" ); if (!pStyleSheet) pStyleSheet = pStylePool->First(); const SfxItemSet& rSet = pStyleSheet->GetItemSet(); if ( !aHTMLStyle.bInitialized ) { const SvxBrushItem* pBrushItem = (const SvxBrushItem*)&rSet.Get( ATTR_BACKGROUND ); aHTMLStyle.aBackgroundColor = pBrushItem->GetColor(); aHTMLStyle.bInitialized = TRUE; } return rSet; } BOOL ScHTMLExport::HasBottomBorder( USHORT nRow, USHORT nTab, USHORT nStartCol, USHORT nEndCol ) { BOOL bHas = TRUE; for ( USHORT nCol=nStartCol; nCol<=nEndCol && bHas; nCol++ ) { SvxBoxItem* pBorder = (SvxBoxItem*) pDoc->GetAttr( nCol, nRow, nTab, ATTR_BORDER ); if ( !pBorder || !pBorder->GetBottom() ) { // vielleicht obere Border an Zelle darunter? if ( nRow < MAXROW ) { pBorder = (SvxBoxItem*) pDoc->GetAttr( nCol, nRow+1, nTab, ATTR_BORDER ); if ( !pBorder || !pBorder->GetTop() ) bHas = FALSE; } else bHas = FALSE; } } return bHas; } BOOL ScHTMLExport::HasLeftBorder( USHORT nCol, USHORT nTab, USHORT nStartRow, USHORT nEndRow ) { BOOL bHas = TRUE; for ( USHORT nRow=nStartRow; nRow<=nEndRow && bHas; nRow++ ) { SvxBoxItem* pBorder = (SvxBoxItem*) pDoc->GetAttr( nCol, nRow, nTab, ATTR_BORDER ); if ( !pBorder || !pBorder->GetLeft() ) { // vielleicht rechte Border an Zelle links daneben? if ( nCol > 0 ) { pBorder = (SvxBoxItem*) pDoc->GetAttr( nCol-1, nRow, nTab, ATTR_BORDER ); if ( !pBorder || !pBorder->GetRight() ) bHas = FALSE; } else bHas = FALSE; } } return bHas; } BOOL ScHTMLExport::HasTopBorder( USHORT nRow, USHORT nTab, USHORT nStartCol, USHORT nEndCol ) { BOOL bHas = TRUE; for ( USHORT nCol=nStartCol; nCol<=nEndCol && bHas; nCol++ ) { SvxBoxItem* pBorder = (SvxBoxItem*) pDoc->GetAttr( nCol, nRow, nTab, ATTR_BORDER ); if ( !pBorder || !pBorder->GetTop() ) { // vielleicht untere Border an Zelle darueber? if ( nRow > 0 ) { pBorder = (SvxBoxItem*) pDoc->GetAttr( nCol, nRow-1, nTab, ATTR_BORDER ); if ( !pBorder || !pBorder->GetBottom() ) bHas = FALSE; } else bHas = FALSE; } } return bHas; } BOOL ScHTMLExport::HasRightBorder( USHORT nCol, USHORT nTab, USHORT nStartRow, USHORT nEndRow ) { BOOL bHas = TRUE; for ( USHORT nRow=nStartRow; nRow<=nEndRow && bHas; nRow++ ) { SvxBoxItem* pBorder = (SvxBoxItem*) pDoc->GetAttr( nCol, nRow, nTab, ATTR_BORDER ); if ( !pBorder || !pBorder->GetRight() ) { // vielleicht linke Border an Zelle rechts daneben? if ( nCol < MAXCOL ) { pBorder = (SvxBoxItem*) pDoc->GetAttr( nCol+1, nRow, nTab, ATTR_BORDER ); if ( !pBorder || !pBorder->GetLeft() ) bHas = FALSE; } else bHas = FALSE; } } return bHas; } void ScHTMLExport::WriteBody() { const SfxItemSet& rSet = PageDefaults( bAll ? 0 : aRange.aStart.Tab() ); const SvxBrushItem* pBrushItem = (const SvxBrushItem*)&rSet.Get( ATTR_BACKGROUND ); // default Textfarbe schwarz rStrm << '<' << sHTML_body << ' ' << sHTML_O_text << "=\"#000000\""; if ( bAll && GPOS_NONE != pBrushItem->GetGraphicPos() ) { const String* pLink = pBrushItem->GetGraphicLink(); String aGrfNm; // embeddete Grafik -> via WriteGraphic schreiben if( !pLink ) { const Graphic* pGrf = pBrushItem->GetGraphic(); if( pGrf ) { // Grafik als (JPG-)File speichern aGrfNm = aStreamPath; USHORT nErr = XOutBitmap::WriteGraphic( *pGrf, aGrfNm, _STRINGCONST( "JPG" ), XOUTBMP_USE_NATIVE_IF_POSSIBLE ); if( !nErr ) // fehlerhaft, da ist nichts auszugeben { aGrfNm = URIHelper::SmartRelToAbs( aGrfNm ); if ( HasCId() ) MakeCIdURL( aGrfNm ); pLink = &aGrfNm; } } } else { aGrfNm = *pLink; if( bCopyLocalFileToINet || HasCId() ) { CopyLocalFileToINet( aGrfNm, aStreamPath ); if ( HasCId() ) MakeCIdURL( aGrfNm ); } else aGrfNm = URIHelper::SmartRelToAbs( aGrfNm ); pLink = &aGrfNm; } if( pLink ) { rStrm << ' ' << sHTML_O_background << "=\""; OUT_STR( INetURLObject::AbsToRel( *pLink ) ) << '\"'; } } if ( !aHTMLStyle.aBackgroundColor.GetTransparency() ) { // A transparent background color should always result in default // background of the browser. Also, HTMLOutFuncs::Out_Color() writes // black #000000 for COL_AUTO which is the same as white #ffffff with // transparency set to 0xff, our default background. OUT_SP_CSTR_ASS( sHTML_O_bgcolor ); HTMLOutFuncs::Out_Color( rStrm, aHTMLStyle.aBackgroundColor ); } rStrm << '>'; OUT_LF(); if ( bAll ) WriteOverview(); WriteTables(); TAG_OFF_LF( sHTML_body ); } void ScHTMLExport::WriteTables() { const USHORT nTabCount = pDoc->GetTableCount(); const String aStrTable( ScResId( SCSTR_TABLE ) ); String aStr; String aStrOut; USHORT nStartCol, nStartRow, nStartTab; USHORT nEndCol, nEndRow, nEndTab; USHORT nStartColFix, nStartRowFix, nEndColFix, nEndRowFix; ScDrawLayer* pDrawLayer = pDoc->GetDrawLayer(); if ( bAll ) { nStartTab = 0; nEndTab = nTabCount - 1; } else { nStartCol = nStartColFix = aRange.aStart.Col(); nStartRow = nStartRowFix = aRange.aStart.Row(); nStartTab = aRange.aStart.Tab(); nEndCol = nEndColFix = aRange.aEnd.Col(); nEndRow = nEndRowFix = aRange.aEnd.Row(); nEndTab = aRange.aEnd.Tab(); } USHORT nTableStrNum = 1; for ( USHORT nTab=nStartTab; nTab<=nEndTab; nTab++ ) { if ( !pDoc->IsVisible( nTab ) ) continue; // for if ( bAll ) { if ( !GetDataArea( nTab, nStartCol, nStartRow, nEndCol, nEndRow ) ) continue; // for if ( nUsedTables > 1 ) { aStrOut = aStrTable; aStrOut.AppendAscii( " " ); aStrOut += String::CreateFromInt32( nTableStrNum++ ); aStrOut.AppendAscii( ": " ); OUT_HR(); // Anker festlegen: rStrm << "<A NAME=\"table" << ByteString::CreateFromInt32( nTab ).GetBuffer() << "\">"; TAG_ON( sHTML_head1 ); OUT_STR( aStrOut ); TAG_ON( sHTML_emphasis ); pDoc->GetName( nTab, aStr ); OUT_STR( aStr ); TAG_OFF( sHTML_emphasis ); TAG_OFF( sHTML_head1 ); rStrm << "</A>"; OUT_LF(); } } else { nStartCol = nStartColFix; nStartRow = nStartRowFix; nEndCol = nEndColFix; nEndRow = nEndRowFix; if ( !TrimDataArea( nTab, nStartCol, nStartRow, nEndCol, nEndRow ) ) continue; // for } // <TABLE ...> ByteString aByteStrOut = sHTML_table; // aStrOut = sHTML_table; aByteStrOut += ' '; aByteStrOut += sHTML_frame; aByteStrOut += '='; USHORT nFrame = 0; if ( HasBottomBorder( nEndRow, nTab, nStartCol, nEndCol ) ) nFrame |= 2; if ( HasLeftBorder( nStartCol, nTab, nStartRow, nEndRow ) ) nFrame |= 4; if ( HasTopBorder( nStartRow, nTab, nStartCol, nEndCol ) ) nFrame |= 8; if ( HasRightBorder( nEndCol, nTab, nStartRow, nEndRow ) ) nFrame |= 16; if ( nFrame ) { // nicht alle Kombinationen sind in HTML moeglich // nur void, above, below, lhs, rhs, hsides, vsides, box const USHORT nAll = 2 | 4 | 8 | 16; USHORT nBit; for ( nBit=2; nBit<=16; nBit <<= 1 ) { if ( (nFrame | nBit) == nAll ) { // mindestens drei Seiten => vier aByteStrOut += sHTML_TF_box; nFrame = 0; break; } } if ( nFrame ) { // ein oder zwei Seiten for ( nBit=2; nBit<=16; nBit <<= 1 ) { if ( (nFrame & nBit) == nFrame ) { // eine Seite switch ( nBit ) { case 2: aByteStrOut += sHTML_TF_below; break; case 4: aByteStrOut += sHTML_TF_lhs; break; case 8: aByteStrOut += sHTML_TF_above; break; case 16: aByteStrOut += sHTML_TF_rhs; break; } nFrame = 0; break; } } if ( nFrame ) { // zwei Seiten // horizontale bevorzugt if ( nFrame & 8 ) { if ( nFrame & 2 ) aByteStrOut += sHTML_TF_hsides; else aByteStrOut += sHTML_TF_above; } else if ( nFrame & 2 ) aByteStrOut += sHTML_TF_below; else if ( nFrame & 4 ) { if ( nFrame & 16 ) aByteStrOut += sHTML_TF_vsides; else aByteStrOut += sHTML_TF_lhs; } else // if ( nFrame & 16 ) aByteStrOut += sHTML_TF_rhs; } } } else aByteStrOut += sHTML_TF_void; bTabHasGraphics = bTabAlignedLeft = FALSE; if ( bAll && pDrawLayer ) PrepareGraphics( pDrawLayer, nTab, nStartCol, nStartRow, nEndCol, nEndRow ); // mehr <TABLE ...> if ( bTabAlignedLeft ) (((aByteStrOut += ' ') += sHTML_O_align) += '=') += sHTML_AL_left; // ALIGN=LEFT allow text and graphics to flow around // CELLSPACING (((aByteStrOut += ' ' ) += sHTML_O_cellspacing ) += '=') += ByteString::CreateFromInt32( nCellSpacing ); // COLS=n USHORT nColCnt = 0; USHORT nCol; for ( nCol=nStartCol; nCol<=nEndCol; nCol++ ) { if ( !(pDoc->GetColFlags( nCol, nTab ) & CR_HIDDEN) ) ++nColCnt; } (((aByteStrOut += ' ') += sHTML_O_cols) += '=') += ByteString::CreateFromInt32( nColCnt ); // RULES=GROUPS (((aByteStrOut += ' ') += sHTML_O_rules) += '=') += sHTML_TR_groups; // Netscape und M$IE brauchen ein BORDER=n um ueberhaupt ein Rule zu zeichnen ((aByteStrOut += ' ') += sHTML_O_border) += "=1"; IncIndent(1); TAG_ON_LF( aByteStrOut.GetBuffer() ); // <COLGROUP> fuer RULES=GROUPS TAG_ON( sHTML_colgroup ); // <COL WIDTH=x> als Vorabinformation fuer lange Tabellen ByteString aByteStr = sHTML_col; aByteStr += ' '; aByteStr += sHTML_O_width; aByteStr += '='; for ( nCol=nStartCol; nCol<=nEndCol; nCol++ ) { if ( pDoc->GetColFlags( nCol, nTab ) & CR_HIDDEN ) continue; // for aByteStrOut = aByteStr; aByteStrOut += ByteString::CreateFromInt32( ToPixel( pDoc->GetColWidth( nCol, nTab ) ) ); TAG_ON( aByteStrOut.GetBuffer() ); if ( nCol < nEndCol && HasRightBorder( nCol, nTab, nStartRow, nEndRow ) ) { // neue ColGroup fuer RULES TAG_OFF_LF( sHTML_colgroup ); TAG_ON( sHTML_colgroup ); } } TAG_OFF_LF( sHTML_colgroup ); // <TBODY> fuer RULES=GROUPS IncIndent(1); TAG_ON_LF( sHTML_tbody ); // At least old (3.x, 4.x?) Netscape doesn't follow <TABLE COLS=n> and // <COL WIDTH=x> specified, but needs a width at every column. bTableDataWidth = TRUE; // widths in first row for ( USHORT nRow=nStartRow; nRow<=nEndRow; nRow++ ) { if ( pDoc->GetRowFlags( nRow, nTab ) & CR_HIDDEN ) continue; // for IncIndent(1); TAG_ON_LF( sHTML_tablerow ); bTableDataHeight = TRUE; // height at every first cell of each row for ( USHORT nCol=nStartCol; nCol<=nEndCol; nCol++ ) { if ( pDoc->GetColFlags( nCol, nTab ) & CR_HIDDEN ) continue; // for if ( nCol == nEndCol ) IncIndent(-1); WriteCell( nCol, nRow, nTab ); bTableDataHeight = FALSE; } bTableDataWidth = FALSE; // widths only in first row if ( nRow < nEndRow && HasBottomBorder( nRow, nTab, nStartCol, nEndCol ) ) { // neuer TBody fuer RULES IncIndent(-1); TAG_OFF_LF( sHTML_tablerow ); TAG_OFF_LF( sHTML_tbody ); IncIndent(1); TAG_ON_LF( sHTML_tbody ); } else { if ( nRow == nEndRow ) IncIndent(-1); TAG_OFF_LF( sHTML_tablerow ); } } IncIndent(-1); TAG_OFF_LF( sHTML_tbody ); IncIndent(-1); TAG_OFF_LF( sHTML_table ); if ( bTabHasGraphics ) { // der Rest, der nicht in Zellen ist for ( ScHTMLGraphEntry* pE = aGraphList.First(); pE; pE = aGraphList.Next() ) { if ( !pE->bWritten ) WriteGraphEntry( pE ); delete pE; } aGraphList.Clear(); if ( bTabAlignedLeft ) { // mit <BR CLEAR=LEFT> das <TABLE ALIGN=LEFT> wieder ausschalten aByteStrOut = sHTML_linebreak; (((aByteStrOut += ' ') += sHTML_O_clear) += '=') += sHTML_AL_left; TAG_ON_LF( aByteStrOut.GetBuffer() ); } } if ( bAll ) OUT_COMMENT( _STRINGCONST( "**************************************************************************" ) ); } } void ScHTMLExport::WriteCell( USHORT nCol, USHORT nRow, USHORT nTab ) { const ScPatternAttr* pAttr = pDoc->GetPattern( nCol, nRow, nTab ); const SfxItemSet* pCondItemSet = pDoc->GetCondResult( nCol, nRow, nTab ); const ScMergeFlagAttr& rMergeFlagAttr = (const ScMergeFlagAttr&) pAttr->GetItem( ATTR_MERGE_FLAG, pCondItemSet ); if ( rMergeFlagAttr.IsOverlapped() ) return ; ScAddress aPos( nCol, nRow, nTab ); ScHTMLGraphEntry* pGraphEntry = NULL; if ( bTabHasGraphics ) { for ( pGraphEntry = aGraphList.First(); pGraphEntry; pGraphEntry = aGraphList.Next() ) { if ( pGraphEntry->bInCell && pGraphEntry->aRange.In( aPos ) ) { if ( pGraphEntry->aRange.aStart == aPos ) break; // for else return ; // ist ein Col/RowSpan, Overlapped break; } } } ScBaseCell* pCell = pDoc->GetCell( aPos ); ULONG nFormat = pAttr->GetNumberFormat( pFormatter ); BOOL bValueData; BYTE nScriptType; if ( pCell ) { bValueData = pCell->HasValueData(); nScriptType = pDoc->GetScriptType( nCol, nRow, nTab, pCell ); } else { bValueData = FALSE; nScriptType = 0; } if ( nScriptType == 0 ) nScriptType = aHTMLStyle.nDefaultScriptType; ByteString aStrTD = sHTML_tabledata; String aStr; const sal_Char* pChar; USHORT nWidthPixel; USHORT nHeightPixel; const ScMergeAttr& rMergeAttr = (const ScMergeAttr&) pAttr->GetItem( ATTR_MERGE, pCondItemSet ); if ( pGraphEntry || rMergeAttr.IsMerged() ) { USHORT j, n, v; if ( pGraphEntry ) n = Max( USHORT(pGraphEntry->aRange.aEnd.Col() - nCol + 1), USHORT(rMergeAttr.GetColMerge()) ); else n = rMergeAttr.GetColMerge(); if ( n > 1 ) { (((aStrTD += ' ') += sHTML_O_colspan) += '=') += ByteString::CreateFromInt32( n ); n += nCol; for ( j=nCol, v=0; j<n; j++ ) v += pDoc->GetColWidth( j, nTab ); nWidthPixel = ToPixel( v ); } else nWidthPixel = ToPixel( pDoc->GetColWidth( nCol, nTab ) ); if ( pGraphEntry ) n = Max( USHORT(pGraphEntry->aRange.aEnd.Row() - nRow + 1), USHORT(rMergeAttr.GetRowMerge()) ); else n = rMergeAttr.GetRowMerge(); if ( n > 1 ) { (((aStrTD += ' ') += sHTML_O_rowspan) += '=') += ByteString::CreateFromInt32( n ); n += nRow; for ( j=nRow, v=0; j<n; j++ ) v += pDoc->GetRowHeight( j, nTab ); nHeightPixel = ToPixel( v ); } else nHeightPixel = ToPixel( pDoc->GetRowHeight( nRow, nTab ) ); } else { nWidthPixel = ToPixel( pDoc->GetColWidth( nCol, nTab ) ); nHeightPixel = ToPixel( pDoc->GetRowHeight( nRow, nTab ) ); } if ( bTableDataWidth ) (((aStrTD += ' ') += sHTML_O_width) += '=') += ByteString::CreateFromInt32( nWidthPixel ); if ( bTableDataHeight ) (((aStrTD += ' ') += sHTML_O_height) += '=') += ByteString::CreateFromInt32( nHeightPixel ); const SvxFontItem& rFontItem = (const SvxFontItem&) pAttr->GetItem( ScGlobal::GetScriptedWhichID( nScriptType, ATTR_FONT), pCondItemSet); const SvxFontHeightItem& rFontHeightItem = (const SvxFontHeightItem&) pAttr->GetItem( ScGlobal::GetScriptedWhichID( nScriptType, ATTR_FONT_HEIGHT), pCondItemSet); const SvxWeightItem& rWeightItem = (const SvxWeightItem&) pAttr->GetItem( ScGlobal::GetScriptedWhichID( nScriptType, ATTR_FONT_WEIGHT), pCondItemSet); const SvxPostureItem& rPostureItem = (const SvxPostureItem&) pAttr->GetItem( ScGlobal::GetScriptedWhichID( nScriptType, ATTR_FONT_POSTURE), pCondItemSet); const SvxUnderlineItem& rUnderlineItem = (const SvxUnderlineItem&) pAttr->GetItem( ATTR_FONT_UNDERLINE, pCondItemSet ); const SvxColorItem& rColorItem = (const SvxColorItem&) pAttr->GetItem( ATTR_FONT_COLOR, pCondItemSet ); const SvxHorJustifyItem& rHorJustifyItem = (const SvxHorJustifyItem&) pAttr->GetItem( ATTR_HOR_JUSTIFY, pCondItemSet ); const SvxVerJustifyItem& rVerJustifyItem = (const SvxVerJustifyItem&) pAttr->GetItem( ATTR_VER_JUSTIFY, pCondItemSet ); const SvxBrushItem& rBrushItem = (const SvxBrushItem&) pAttr->GetItem( ATTR_BACKGROUND, pCondItemSet ); Color aBgColor; if ( rBrushItem.GetColor().GetTransparency() == 255 ) aBgColor = aHTMLStyle.aBackgroundColor; // #55121# keine ungewollte Hintergrundfarbe else aBgColor = rBrushItem.GetColor(); BOOL bBold = ( WEIGHT_BOLD <= rWeightItem.GetWeight() ); BOOL bItalic = ( ITALIC_NONE != rPostureItem.GetPosture() ); BOOL bUnderline = ( UNDERLINE_NONE != rUnderlineItem.GetUnderline() ); BOOL bSetFontColor = ( COL_AUTO != rColorItem.GetValue().GetColor() ); // #97650# default is AUTO now #if 0 // keine StyleSheet-Fontangaben: hart fuer jede Zelle BOOL bSetFontName = TRUE; USHORT nSetFontSizeNumber = GetFontSizeNumber( (USHORT)rFontHeightItem.GetHeight() ); #else BOOL bSetFontName = ( aHTMLStyle.aFontFamilyName != rFontItem.GetFamilyName() ); USHORT nSetFontSizeNumber = 0; UINT32 nFontHeight = rFontHeightItem.GetHeight(); if ( nFontHeight != aHTMLStyle.nFontHeight ) { nSetFontSizeNumber = GetFontSizeNumber( (USHORT) nFontHeight ); if ( nSetFontSizeNumber == aHTMLStyle.nFontSizeNumber ) nSetFontSizeNumber = 0; // no difference, don't set } #endif BOOL bSetFont = (bSetFontColor || bSetFontName || nSetFontSizeNumber); //! TODO: we could entirely use CSS1 here instead, but that would exclude //! Netscape 3.0 and Netscape 4.x without JavaScript enabled. //! Do we want that? switch( rHorJustifyItem.GetValue() ) { case SVX_HOR_JUSTIFY_STANDARD: pChar = (bValueData ? sHTML_AL_right : sHTML_AL_left); break; case SVX_HOR_JUSTIFY_CENTER: pChar = sHTML_AL_center; break; case SVX_HOR_JUSTIFY_BLOCK: pChar = sHTML_AL_justify; break; case SVX_HOR_JUSTIFY_RIGHT: pChar = sHTML_AL_right; break; case SVX_HOR_JUSTIFY_LEFT: case SVX_HOR_JUSTIFY_REPEAT: default: pChar = sHTML_AL_left; break; } (((aStrTD += ' ') += sHTML_O_align) += '=') += pChar; switch( rVerJustifyItem.GetValue() ) { case SVX_VER_JUSTIFY_TOP: pChar = sHTML_VA_top; break; case SVX_VER_JUSTIFY_CENTER: pChar = sHTML_VA_middle; break; case SVX_VER_JUSTIFY_BOTTOM: pChar = sHTML_VA_bottom; break; case SVX_VER_JUSTIFY_STANDARD: default: pChar = NULL; } if ( pChar ) (((aStrTD += ' ') += sHTML_O_valign) += '=') += pChar; if ( aHTMLStyle.aBackgroundColor != aBgColor ) { ((aStrTD += ' ') += sHTML_O_bgcolor) += '='; lcl_AppendHTMLColorTripel( aStrTD, aBgColor ); } double fVal = 0.0; if ( bValueData ) { if ( pCell ) { switch ( pCell->GetCellType() ) { case CELLTYPE_VALUE: fVal = ((ScValueCell*)pCell)->GetValue(); if ( bCalcAsShown && fVal != 0.0 ) fVal = pDoc->RoundValueAsShown( fVal, nFormat ); break; case CELLTYPE_FORMULA: fVal = ((ScFormulaCell*)pCell)->GetValue(); if ( (nFormat % SV_COUNTRY_LANGUAGE_OFFSET) == 0 ) nFormat = ScGlobal::GetStandardFormat( fVal, *pFormatter, nFormat, ((ScFormulaCell*)pCell)->GetFormatType() ); break; default: DBG_ERRORFILE( "value data with unsupported cell type" ); } } } HTMLOutFuncs::CreateTableDataOptionsValNum( aStrTD, bValueData, fVal, nFormat, *pFormatter, eDestEnc, &aNonConvertibleChars ); TAG_ON( aStrTD.GetBuffer() ); if ( bBold ) TAG_ON( sHTML_bold ); if ( bItalic ) TAG_ON( sHTML_italic ); if ( bUnderline ) TAG_ON( sHTML_underline ); if ( bSetFont ) { ByteString aStr = sHTML_font; if ( bSetFontName ) { ((aStr += ' ') += sHTML_O_face) += "=\""; xub_StrLen nFonts = rFontItem.GetFamilyName().GetTokenCount( ';' ); if ( nFonts == 1 ) { ByteString aTmpStr; HTMLOutFuncs::ConvertStringToHTML( rFontItem.GetFamilyName(), aTmpStr, eDestEnc, &aNonConvertibleChars ); aStr += aTmpStr; } else { // Fontliste, VCL: Semikolon als Separator, HTML: Komma const String& rList = rFontItem.GetFamilyName(); for ( xub_StrLen j = 0, nPos = 0; j < nFonts; j++ ) { ByteString aTmpStr; HTMLOutFuncs::ConvertStringToHTML( rList.GetToken( 0, ';', nPos ), aTmpStr, eDestEnc, &aNonConvertibleChars ); aStr += aTmpStr; if ( j < nFonts-1 ) aStr += ','; } } aStr += '\"'; } if ( nSetFontSizeNumber ) { (((aStr += ' ') += sHTML_O_size) += '=') += ByteString::CreateFromInt32( nSetFontSizeNumber ); } if ( bSetFontColor ) { Color aColor = rColorItem.GetValue(); // always export automatic text color as black if ( aColor.GetColor() == COL_AUTO ) aColor.SetColor( COL_BLACK ); ((aStr += ' ') += sHTML_O_color) += '='; lcl_AppendHTMLColorTripel( aStr, aColor ); } TAG_ON( aStr.GetBuffer() ); } String aStrOut; BOOL bFieldText = FALSE; if ( pCell ) { // cell content Color* pColor; switch ( pCell->GetCellType() ) { case CELLTYPE_NOTE : // nothing break; case CELLTYPE_EDIT : bFieldText = WriteFieldText( (const ScEditCell*) pCell ); if ( bFieldText ) break; //! else: fallthru default: ScCellFormat::GetString( pCell, nFormat, aStrOut, &pColor, *pFormatter ); } } if ( !bFieldText ) { if ( !aStrOut.Len() ) TAG_ON( sHTML_linebreak ); // #42573# keine komplett leere Zelle else OUT_STR( aStrOut ); } if ( pGraphEntry ) WriteGraphEntry( pGraphEntry ); if ( bSetFont ) TAG_OFF( sHTML_font ); if ( bUnderline ) TAG_OFF( sHTML_underline ); if ( bItalic ) TAG_OFF( sHTML_italic ); if ( bBold ) TAG_OFF( sHTML_bold ); TAG_OFF_LF( sHTML_tabledata ); } BOOL ScHTMLExport::WriteFieldText( const ScEditCell* pCell ) { BOOL bFields = FALSE; const EditTextObject* pData; pCell->GetData( pData ); // text and anchor of URL fields, Doc-Engine is a ScFieldEditEngine EditEngine& rEngine = pDoc->GetEditEngine(); rEngine.SetText( *pData ); USHORT nParas = rEngine.GetParagraphCount(); if ( nParas ) { ESelection aSel( 0, 0, nParas-1, rEngine.GetTextLen( nParas-1 ) ); SfxItemSet aSet( rEngine.GetAttribs( aSel ) ); SfxItemState eFieldState = aSet.GetItemState( EE_FEATURE_FIELD, FALSE ); if ( eFieldState == SFX_ITEM_DONTCARE || eFieldState == SFX_ITEM_SET ) bFields = TRUE; } if ( bFields ) { BOOL bOldUpdateMode = rEngine.GetUpdateMode(); rEngine.SetUpdateMode( TRUE ); // no portions if not formatted for ( USHORT nPar=0; nPar < nParas; nPar++ ) { if ( nPar > 0 ) rStrm << ' '; // blank between paragraphs SvUShorts aPortions; rEngine.GetPortions( nPar, aPortions ); USHORT nCnt = aPortions.Count(); USHORT nStart = 0; for ( USHORT nPos = 0; nPos < nCnt; nPos++ ) { USHORT nEnd = aPortions.GetObject( nPos ); ESelection aSel( nPar, nStart, nPar, nEnd ); BOOL bUrl = FALSE; // fields are single characters if ( nEnd == nStart+1 ) { const SfxPoolItem* pItem; SfxItemSet aSet = rEngine.GetAttribs( aSel ); if ( aSet.GetItemState( EE_FEATURE_FIELD, FALSE, &pItem ) == SFX_ITEM_ON ) { const SvxFieldData* pField = ((const SvxFieldItem*)pItem)->GetField(); if ( pField && pField->ISA(SvxURLField) ) { bUrl = TRUE; const SvxURLField* pURLField = (const SvxURLField*)pField; // String aFieldText = rEngine.GetText( aSel ); rStrm << '<' << sHTML_anchor << ' ' << sHTML_O_href << "=\""; OUT_STR( pURLField->GetURL() ); rStrm << "\">"; OUT_STR( pURLField->GetRepresentation() ); rStrm << "</" << sHTML_anchor << '>'; } } } if ( !bUrl ) OUT_STR( rEngine.GetText( aSel ) ); nStart = nEnd; } } rEngine.SetUpdateMode( bOldUpdateMode ); } return bFields; } BOOL ScHTMLExport::CopyLocalFileToINet( String& rFileNm, const String& rTargetNm, BOOL bFileToFile ) { BOOL bRet = FALSE; INetURLObject aFileUrl, aTargetUrl; aFileUrl.SetSmartURL( rFileNm ); aTargetUrl.SetSmartURL( rTargetNm ); if( INET_PROT_FILE == aFileUrl.GetProtocol() && ( (bFileToFile && INET_PROT_FILE == aTargetUrl.GetProtocol()) || (!bFileToFile && INET_PROT_FILE != aTargetUrl.GetProtocol() && INET_PROT_FTP <= aTargetUrl.GetProtocol() && INET_PROT_NEWS >= aTargetUrl.GetProtocol()) ) ) { if( pSrcArr ) { // wurde die Datei schon verschoben USHORT nPos; if( pSrcArr->Seek_Entry( &rFileNm, &nPos )) { rFileNm = *(*pDestArr)[ nPos ]; return TRUE; } } else { pSrcArr = new SvStringsSortDtor( 4, 4 ); pDestArr = new SvStringsSortDtor( 4, 4 ); } String* pSrc = new String( rFileNm ); SvFileStream aTmp( aFileUrl.PathToFileName(), STREAM_READ ); String* pDest = new String( aTargetUrl.GetPartBeforeLastName() ); *pDest += aFileUrl.GetName(); if( bFileToFile ) { INetURLObject aCpyURL( *pDest ); SvFileStream aCpy( aCpyURL.PathToFileName(), STREAM_WRITE ); aCpy << aTmp; aCpy.Close(); bRet = SVSTREAM_OK == aCpy.GetError(); } else { SfxMedium aMedium( *pDest, STREAM_WRITE | STREAM_SHARE_DENYNONE, FALSE ); // temp. File anlegen // aMedium.DownLoad(); { SvFileStream aCpy( aMedium.GetPhysicalName(), STREAM_WRITE ); aCpy << aTmp; } // uebertragen aMedium.Close(); aMedium.Commit(); bRet = 0 == aMedium.GetError(); } if( bRet ) { pSrcArr->Insert( pSrc ); pDestArr->Insert( pDest ); rFileNm = *pDest; } else { delete pSrc; delete pDest; } } return bRet; } void ScHTMLExport::MakeCIdURL( String& rURL ) { if( !aCId.Len() ) return; INetURLObject aURLObj( rURL ); if( INET_PROT_FILE != aURLObj.GetProtocol() ) return; String aLastName( aURLObj.GetLastName() ); DBG_ASSERT( aLastName.Len(), "Dateiname ohne Laenge!" ); aLastName.ToLowerAscii(); rURL.AssignAscii( "cid:" ); rURL += aLastName; rURL.AppendAscii( "." ); rURL += aCId; } void ScHTMLExport::IncIndent( short nVal ) { sIndent[nIndent] = '\t'; nIndent += nVal; if ( nIndent < 0 ) nIndent = 0; else if ( nIndent > nIndentMax ) nIndent = nIndentMax; sIndent[nIndent] = 0; } INTEGRATION: CWS dialogdiet (1.23.186); FILE MERGED 2003/11/28 15:19:38 mba 1.23.186.1: #i22972#: FilterOptions moved to svtools /************************************************************************* * * $RCSfile: htmlexp.cxx,v $ * * $Revision: 1.24 $ * * last change: $Author: hr $ $Date: 2004-02-03 20:26:49 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifdef PCH #include "filt_pch.hxx" #endif #pragma hdrstop // INCLUDE --------------------------------------------------------------- #include "scitems.hxx" #include <svx/eeitem.hxx> #define ITEMID_FIELD EE_FEATURE_FIELD #define _SVSTDARR_STRINGSSORTDTOR #ifndef _RTL_TENCINFO_H //autogen wg. rtl_getBestMimeCharsetFromTextEncoding, rtl_getTextEncodingFromMimeCharset #include <rtl/tencinfo.h> #endif #include <vcl/svapp.hxx> #include <svx/algitem.hxx> #include <svx/boxitem.hxx> #include <svx/brshitem.hxx> #include <svx/colritem.hxx> #include <svx/fhgtitem.hxx> #include <svx/fontitem.hxx> #include <svx/postitem.hxx> #include <svx/udlnitem.hxx> #include <svx/wghtitem.hxx> #include <svx/xoutbmp.hxx> #ifndef _MyEDITENG_HXX //autogen wg. EditEngine #include <svx/editeng.hxx> #endif #include <svx/htmlcfg.hxx> #include <sfx2/docfile.hxx> #include <sfx2/docinf.hxx> #include <sfx2/frmhtmlw.hxx> #include <sfx2/objsh.hxx> #include <svtools/stritem.hxx> #ifndef SVTOOLS_URIHELPER_HXX #include <svtools/urihelper.hxx> #endif #ifndef _SVSTDARR_USHORTS #define _SVSTDARR_USHORTS #endif #include <svtools/svstdarr.hxx> #include <svtools/zforlist.hxx> #include <svtools/htmlkywd.hxx> #include <svtools/htmlout.hxx> #include <svtools/parhtml.hxx> #include <vcl/outdev.hxx> #include <stdio.h> #if defined(GetNumberFormat) && SUPD<356 // xoutbmp.hxx -> svimbase.hxx -> sysdep.hxx -> windows.h -> // define GetNumberFormat GetNumberFormatA #undef GetNumberFormat #endif #include "htmlexp.hxx" #include "filter.hxx" #include "flttools.hxx" #include "global.hxx" #include "document.hxx" #include "scitems.hxx" #include "attrib.hxx" #include "patattr.hxx" #include "stlpool.hxx" #include "scresid.hxx" #include "cell.hxx" #include "cellform.hxx" #include "docoptio.hxx" #include "editutil.hxx" #define ITEMID_FIELD EE_FEATURE_FIELD #include <svx/flditem.hxx> #undef ITEMID_FIELD #ifndef INCLUDED_SVTOOLS_SYSLOCALE_HXX #include <svtools/syslocale.hxx> #endif // ohne sc.hrc: error C2679: binary '=' : no operator defined which takes a // right-hand operand of type 'const class String (__stdcall *)(class ScResId)' // bei // const String aStrTable( ScResId( SCSTR_TABLE ) ); aStrOut = aStrTable; // ?!??? #include "sc.hrc" #include "globstr.hrc" //======================================================================== const static sal_Char __FAR_DATA sMyBegComment[] = "<!-- "; const static sal_Char __FAR_DATA sMyEndComment[] = " -->"; const static sal_Char __FAR_DATA sFontFamily[] = "font-family:"; const static sal_Char __FAR_DATA sFontSize[] = "font-size:"; const USHORT __FAR_DATA ScHTMLExport::nDefaultFontSize[SC_HTML_FONTSIZES] = { HTMLFONTSZ1_DFLT, HTMLFONTSZ2_DFLT, HTMLFONTSZ3_DFLT, HTMLFONTSZ4_DFLT, HTMLFONTSZ5_DFLT, HTMLFONTSZ6_DFLT, HTMLFONTSZ7_DFLT }; USHORT ScHTMLExport::nFontSize[SC_HTML_FONTSIZES] = { 0 }; const char* __FAR_DATA ScHTMLExport::pFontSizeCss[SC_HTML_FONTSIZES] = { "xx-small", "x-small", "small", "medium", "large", "x-large", "xx-large" }; const USHORT ScHTMLExport::nCellSpacing = 0; const sal_Char __FAR_DATA ScHTMLExport::sIndentSource[nIndentMax+1] = "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t"; //======================================================================== // Makros fuer HTML-Export //======================================================================== #define OUT_PROLOGUE() (rStrm << sHTML30_Prologue << ScExportBase::sNewLine \ << ScExportBase::sNewLine) #define TAG_ON( tag ) HTMLOutFuncs::Out_AsciiTag( rStrm, tag ) #define TAG_OFF( tag ) HTMLOutFuncs::Out_AsciiTag( rStrm, tag, FALSE ) #define OUT_STR( str ) HTMLOutFuncs::Out_String( rStrm, str, eDestEnc, &aNonConvertibleChars ) #define OUT_STR_NO_CONV( str ) HTMLOutFuncs::Out_String( rStrm, str, eDestEnc ) #define OUT_LF() rStrm << ScExportBase::sNewLine << GetIndentStr() #define lcl_OUT_LF() rStrm << ScExportBase::sNewLine #define TAG_ON_LF( tag ) (TAG_ON( tag ) << ScExportBase::sNewLine << GetIndentStr()) #define TAG_OFF_LF( tag ) (TAG_OFF( tag ) << ScExportBase::sNewLine << GetIndentStr()) #define OUT_HR() TAG_ON_LF( sHTML_horzrule ) #define OUT_COMMENT( comment ) (rStrm << sMyBegComment, OUT_STR( comment ) \ << sMyEndComment << ScExportBase::sNewLine \ << GetIndentStr()) #define lcl_OUT_COMMENT( comment ) (rStrm << sMyBegComment, OUT_STR_NO_CONV( comment ) \ << sMyEndComment << ScExportBase::sNewLine) #define OUT_SP_CSTR_ASS( s ) rStrm << ' ' << s << '=' #define APPEND_SPACE( s ) s.AppendAscii(" ") extern BOOL bOderSo; #define GLOBSTR(id) ScGlobal::GetRscString( id ) //======================================================================== FltError ScExportHTML( SvStream& rStrm, ScDocument* pDoc, const ScRange& rRange, const CharSet eNach, BOOL bAll, const String& rStreamPath, String& rNonConvertibleChars ) { ScHTMLExport aEx( rStrm, pDoc, rRange, bAll, rStreamPath ); FltError nErr = aEx.Write(); rNonConvertibleChars = aEx.GetNonConvertibleChars(); return nErr; } void lcl_AddStamp( String& rStr, const SfxStamp& rStamp, const LocaleDataWrapper& rLoc ) { const DateTime& rDateTime = rStamp.GetTime(); String aStrDate = rLoc.getDate( rDateTime ); String aStrTime = rLoc.getTime( rDateTime ); rStr += GLOBSTR( STR_BY ); APPEND_SPACE( rStr ); if (rStamp.GetName().Len()) rStr += rStamp.GetName(); else rStr.AppendAscii( "???" ); APPEND_SPACE( rStr ); rStr += GLOBSTR( STR_ON ); APPEND_SPACE( rStr ); if (aStrDate.Len()) rStr += aStrDate; else rStr.AppendAscii( "???" ); rStr.AppendAscii( ", " ); if (aStrTime.Len()) rStr += aStrTime; else rStr.AppendAscii( "???" ); } void lcl_AppendHTMLColorTripel( ByteString& rStr, const Color& rColor ) { // <font COLOR="#00FF40">hallo</font> sal_Char buf[64]; sal_Char* p = buf; rStr += "\"#"; p += sprintf( p, "%02X", rColor.GetRed() ); // #100211# - checked p += sprintf( p, "%02X", rColor.GetGreen() ); // #100211# - checked p += sprintf( p, "%02X", rColor.GetBlue() ); // #100211# - checked rStr += buf; rStr += '\"'; } /*void lcl_TagOn( String& rResult, const String& rTag, const String* pStrOpt ) { rResult = '<'; rResult += rTag; if ( pStrOpt ) { rResult += ' '; rResult += *pStrOpt; } rResult += '>'; } */ /*void lcl_TagOff( String& rResult, const String& rTag ) { rResult = '<'; rResult += rTag; rResult += '>'; } */ void lcl_WriteTeamInfo( SvStream& rStrm, rtl_TextEncoding eDestEnc ) { if ( !bOderSo ) return; lcl_OUT_LF(); lcl_OUT_COMMENT( _STRINGCONST( "Sascha Ballach " ) ); lcl_OUT_COMMENT( _STRINGCONST( "Michael Daeumling (aka Bitsau) " ) ); lcl_OUT_COMMENT( _STRINGCONST( "Michael Hagen " ) ); lcl_OUT_COMMENT( _STRINGCONST( "Roland Jakobs " ) ); lcl_OUT_COMMENT( _STRINGCONST( "Andreas Krebs " ) ); lcl_OUT_COMMENT( _STRINGCONST( "John Marmion " ) ); lcl_OUT_COMMENT( _STRINGCONST( "Niklas Nebel " ) ); lcl_OUT_COMMENT( _STRINGCONST( "Jacques Nietsch " ) ); lcl_OUT_COMMENT( _STRINGCONST( "Marcus Olk " ) ); lcl_OUT_COMMENT( _STRINGCONST( "Eike Rathke " ) ); lcl_OUT_COMMENT( _STRINGCONST( "Daniel Rentz " ) ); lcl_OUT_COMMENT( _STRINGCONST( "Stephan Templin " ) ); lcl_OUT_COMMENT( _STRINGCONST( "Gunnar Timm " ) ); lcl_OUT_COMMENT( _STRINGCONST( "*** Man kann nicht ALLES haben! ***" ) ); lcl_OUT_LF(); } ////////////////////////////////////////////////////////////////////////////// ScHTMLExport::ScHTMLExport( SvStream& rStrmP, ScDocument* pDocP, const ScRange& rRangeP, BOOL bAllP, const String& rStreamPathP ) : ScExportBase( rStrmP, pDocP, rRangeP ), aStreamPath( rStreamPathP ), pAppWin( Application::GetDefaultDevice() ), pSrcArr( NULL ), pDestArr( NULL ), nUsedTables( 0 ), nIndent( 0 ), bAll( bAllP ), bTabHasGraphics( FALSE ), bCalcAsShown( pDocP->GetDocOptions().IsCalcAsShown() ), bTableDataHeight( TRUE ), bTableDataWidth( TRUE ) { strcpy( sIndent, sIndentSource ); // #100211# - checked sIndent[0] = 0; // set HTML configuration SvxHtmlOptions* pHtmlOptions = SvxHtmlOptions::Get(); eDestEnc = (pDoc->IsClipOrUndo() ? RTL_TEXTENCODING_UTF8 : pHtmlOptions->GetTextEncoding()); bCopyLocalFileToINet = pHtmlOptions->IsSaveGraphicsLocal(); for ( USHORT j=0; j < SC_HTML_FONTSIZES; j++ ) { USHORT nSize = pHtmlOptions->GetFontSize( j ); // remember in Twips, like our SvxFontHeightItem if ( nSize ) nFontSize[j] = nSize * 20; else nFontSize[j] = nDefaultFontSize[j] * 20; } const USHORT nCount = pDoc->GetTableCount(); for ( USHORT nTab = 0; nTab < nCount; nTab++ ) { if ( !IsEmptyTable( nTab ) ) nUsedTables++; } // Content-Id fuer Mail-Export? SfxObjectShell* pDocSh = pDoc->GetDocumentShell(); if ( pDocSh ) { const SfxPoolItem* pItem = pDocSh->GetItem( SID_ORIGURL ); if( pItem ) { aCId = ((const SfxStringItem *)pItem)->GetValue(); DBG_ASSERT( aCId.Len(), "CID ohne Laenge!" ); } } } ScHTMLExport::~ScHTMLExport() { for ( ScHTMLGraphEntry* pE = aGraphList.First(); pE; pE = aGraphList.Next() ) delete pE; delete pSrcArr; delete pDestArr; } USHORT ScHTMLExport::GetFontSizeNumber( USHORT nHeight ) { USHORT nSize = 1; for ( USHORT j=SC_HTML_FONTSIZES-1; j>0; j-- ) { if( nHeight > (nFontSize[j] + nFontSize[j-1]) / 2 ) { // der naechstgelegene nSize = j+1; break; } } return nSize; } const char* ScHTMLExport::GetFontSizeCss( USHORT nHeight ) { USHORT nSize = GetFontSizeNumber( nHeight ); return pFontSizeCss[ nSize-1 ]; } USHORT ScHTMLExport::ToPixel( USHORT nVal ) { if( nVal ) { nVal = (USHORT)pAppWin->LogicToPixel( Size( nVal, nVal ), MapMode( MAP_TWIP ) ).Width(); if( !nVal ) // wo ein Twip ist sollte auch ein Pixel sein nVal = 1; } return nVal; } Size ScHTMLExport::MMToPixel( const Size& rSize ) { Size aSize( rSize ); aSize = pAppWin->LogicToPixel( rSize, MapMode( MAP_100TH_MM ) ); // wo etwas ist sollte auch ein Pixel sein if ( !aSize.Width() && rSize.Width() ) aSize.Width() = 1; if ( !aSize.Height() && rSize.Height() ) aSize.Height() = 1; return aSize; } ULONG ScHTMLExport::Write() { rStrm << '<' << sHTML_doctype << ' ' << sHTML_doctype32 << '>' << sNewLine << sNewLine; TAG_ON_LF( sHTML_html ); WriteHeader(); OUT_LF(); WriteBody(); OUT_LF(); TAG_OFF_LF( sHTML_html ); return rStrm.GetError(); } void ScHTMLExport::WriteHeader() { IncIndent(1); TAG_ON_LF( sHTML_head ); if ( pDoc->IsClipOrUndo() ) { // no real DocInfo available, but some META information like charset needed SfxFrameHTMLWriter::Out_DocInfo( rStrm, NULL, sIndent, eDestEnc, &aNonConvertibleChars ); } else { SfxDocumentInfo& rInfo = pDoc->GetDocumentShell()->GetDocInfo(); SfxFrameHTMLWriter::Out_DocInfo( rStrm, &rInfo, sIndent, eDestEnc, &aNonConvertibleChars ); OUT_LF(); //---------------------------------------------------------- if ( rInfo.GetPrinted().GetName().Len() ) { OUT_COMMENT( GLOBSTR( STR_DOC_INFO ) ); String aStrOut( GLOBSTR( STR_DOC_PRINTED ) ); aStrOut.AppendAscii( ": " ); lcl_AddStamp( aStrOut, rInfo.GetPrinted(), *ScGlobal::pLocaleData ); OUT_COMMENT( aStrOut ); } //---------------------------------------------------------- lcl_WriteTeamInfo( rStrm, eDestEnc ); } OUT_LF(); // CSS1 StyleSheet PageDefaults( bAll ? 0 : aRange.aStart.Tab() ); IncIndent(1); TAG_ON_LF( sHTML_style ); rStrm << sMyBegComment; OUT_LF(); rStrm << sHTML_body << "," << sHTML_division << "," << sHTML_table << "," << sHTML_thead << "," << sHTML_tbody << "," << sHTML_tfoot << "," << sHTML_tablerow << "," << sHTML_tableheader << "," << sHTML_tabledata << "," << sHTML_parabreak << " { " << sFontFamily; xub_StrLen nFonts = aHTMLStyle.aFontFamilyName.GetTokenCount( ';' ); if ( nFonts == 1 ) { rStrm << '\"'; OUT_STR( aHTMLStyle.aFontFamilyName ); rStrm << '\"'; } else { // Fontliste, VCL: Semikolon als Separator, // CSS1: Komma als Separator und jeder einzelne Fontname quoted const String& rList = aHTMLStyle.aFontFamilyName; for ( xub_StrLen j = 0, nPos = 0; j < nFonts; j++ ) { rStrm << '\"'; OUT_STR( rList.GetToken( 0, ';', nPos ) ); rStrm << '\"'; if ( j < nFonts-1 ) rStrm << ", "; } } rStrm << "; " << sFontSize << GetFontSizeCss( ( USHORT ) aHTMLStyle.nFontHeight ) << " }"; OUT_LF(); rStrm << sMyEndComment; IncIndent(-1); OUT_LF(); TAG_OFF_LF( sHTML_style ); IncIndent(-1); OUT_LF(); TAG_OFF_LF( sHTML_head ); } void ScHTMLExport::WriteOverview() { if ( nUsedTables > 1 ) { IncIndent(1); OUT_HR(); IncIndent(1); TAG_ON( sHTML_parabreak ); TAG_ON_LF( sHTML_center ); TAG_ON( sHTML_head1 ); OUT_STR( ScGlobal::GetRscString( STR_OVERVIEW ) ); TAG_OFF_LF( sHTML_head1 ); String aStr; const USHORT nCount = pDoc->GetTableCount(); for ( USHORT nTab = 0; nTab < nCount; nTab++ ) { if ( !IsEmptyTable( nTab ) ) { pDoc->GetName( nTab, aStr ); rStrm << "<A HREF=\"#table" << ByteString::CreateFromInt32( nTab ).GetBuffer() << "\">"; OUT_STR( aStr ); rStrm << "</A>"; TAG_ON_LF( sHTML_linebreak ); } } IncIndent(-1); OUT_LF(); IncIndent(-1); TAG_OFF( sHTML_center ); TAG_OFF_LF( sHTML_parabreak ); } } const SfxItemSet& ScHTMLExport::PageDefaults( USHORT nTab ) { SfxStyleSheetBasePool* pStylePool = pDoc->GetStyleSheetPool(); SfxStyleSheetBase* pStyleSheet = NULL; DBG_ASSERT( pStylePool, "StylePool not found! :-(" ); // remember defaults for compare in WriteCell if ( !aHTMLStyle.bInitialized ) { pStylePool->SetSearchMask( SFX_STYLE_FAMILY_PARA, SFXSTYLEBIT_ALL ); pStyleSheet = pStylePool->Find( ScGlobal::GetRscString(STR_STYLENAME_STANDARD), SFX_STYLE_FAMILY_PARA ); DBG_ASSERT( pStyleSheet, "ParaStyle not found! :-(" ); if (!pStyleSheet) pStyleSheet = pStylePool->First(); const SfxItemSet& rSetPara = pStyleSheet->GetItemSet(); aHTMLStyle.nDefaultScriptType = ScGlobal::GetDefaultScriptType(); aHTMLStyle.aFontFamilyName = ((const SvxFontItem&)(rSetPara.Get( ScGlobal::GetScriptedWhichID( aHTMLStyle.nDefaultScriptType, ATTR_FONT )))).GetFamilyName(); aHTMLStyle.nFontHeight = ((const SvxFontHeightItem&)(rSetPara.Get( ScGlobal::GetScriptedWhichID( aHTMLStyle.nDefaultScriptType, ATTR_FONT_HEIGHT )))).GetHeight(); aHTMLStyle.nFontSizeNumber = GetFontSizeNumber( aHTMLStyle.nFontHeight ); } // Page style sheet printer settings, e.g. for background graphics. // There's only one background graphic in HTML! pStylePool->SetSearchMask( SFX_STYLE_FAMILY_PAGE, SFXSTYLEBIT_ALL ); pStyleSheet = pStylePool->Find( pDoc->GetPageStyle( nTab ), SFX_STYLE_FAMILY_PAGE ); DBG_ASSERT( pStyleSheet, "PageStyle not found! :-(" ); if (!pStyleSheet) pStyleSheet = pStylePool->First(); const SfxItemSet& rSet = pStyleSheet->GetItemSet(); if ( !aHTMLStyle.bInitialized ) { const SvxBrushItem* pBrushItem = (const SvxBrushItem*)&rSet.Get( ATTR_BACKGROUND ); aHTMLStyle.aBackgroundColor = pBrushItem->GetColor(); aHTMLStyle.bInitialized = TRUE; } return rSet; } BOOL ScHTMLExport::HasBottomBorder( USHORT nRow, USHORT nTab, USHORT nStartCol, USHORT nEndCol ) { BOOL bHas = TRUE; for ( USHORT nCol=nStartCol; nCol<=nEndCol && bHas; nCol++ ) { SvxBoxItem* pBorder = (SvxBoxItem*) pDoc->GetAttr( nCol, nRow, nTab, ATTR_BORDER ); if ( !pBorder || !pBorder->GetBottom() ) { // vielleicht obere Border an Zelle darunter? if ( nRow < MAXROW ) { pBorder = (SvxBoxItem*) pDoc->GetAttr( nCol, nRow+1, nTab, ATTR_BORDER ); if ( !pBorder || !pBorder->GetTop() ) bHas = FALSE; } else bHas = FALSE; } } return bHas; } BOOL ScHTMLExport::HasLeftBorder( USHORT nCol, USHORT nTab, USHORT nStartRow, USHORT nEndRow ) { BOOL bHas = TRUE; for ( USHORT nRow=nStartRow; nRow<=nEndRow && bHas; nRow++ ) { SvxBoxItem* pBorder = (SvxBoxItem*) pDoc->GetAttr( nCol, nRow, nTab, ATTR_BORDER ); if ( !pBorder || !pBorder->GetLeft() ) { // vielleicht rechte Border an Zelle links daneben? if ( nCol > 0 ) { pBorder = (SvxBoxItem*) pDoc->GetAttr( nCol-1, nRow, nTab, ATTR_BORDER ); if ( !pBorder || !pBorder->GetRight() ) bHas = FALSE; } else bHas = FALSE; } } return bHas; } BOOL ScHTMLExport::HasTopBorder( USHORT nRow, USHORT nTab, USHORT nStartCol, USHORT nEndCol ) { BOOL bHas = TRUE; for ( USHORT nCol=nStartCol; nCol<=nEndCol && bHas; nCol++ ) { SvxBoxItem* pBorder = (SvxBoxItem*) pDoc->GetAttr( nCol, nRow, nTab, ATTR_BORDER ); if ( !pBorder || !pBorder->GetTop() ) { // vielleicht untere Border an Zelle darueber? if ( nRow > 0 ) { pBorder = (SvxBoxItem*) pDoc->GetAttr( nCol, nRow-1, nTab, ATTR_BORDER ); if ( !pBorder || !pBorder->GetBottom() ) bHas = FALSE; } else bHas = FALSE; } } return bHas; } BOOL ScHTMLExport::HasRightBorder( USHORT nCol, USHORT nTab, USHORT nStartRow, USHORT nEndRow ) { BOOL bHas = TRUE; for ( USHORT nRow=nStartRow; nRow<=nEndRow && bHas; nRow++ ) { SvxBoxItem* pBorder = (SvxBoxItem*) pDoc->GetAttr( nCol, nRow, nTab, ATTR_BORDER ); if ( !pBorder || !pBorder->GetRight() ) { // vielleicht linke Border an Zelle rechts daneben? if ( nCol < MAXCOL ) { pBorder = (SvxBoxItem*) pDoc->GetAttr( nCol+1, nRow, nTab, ATTR_BORDER ); if ( !pBorder || !pBorder->GetLeft() ) bHas = FALSE; } else bHas = FALSE; } } return bHas; } void ScHTMLExport::WriteBody() { const SfxItemSet& rSet = PageDefaults( bAll ? 0 : aRange.aStart.Tab() ); const SvxBrushItem* pBrushItem = (const SvxBrushItem*)&rSet.Get( ATTR_BACKGROUND ); // default Textfarbe schwarz rStrm << '<' << sHTML_body << ' ' << sHTML_O_text << "=\"#000000\""; if ( bAll && GPOS_NONE != pBrushItem->GetGraphicPos() ) { const String* pLink = pBrushItem->GetGraphicLink(); String aGrfNm; // embeddete Grafik -> via WriteGraphic schreiben if( !pLink ) { const Graphic* pGrf = pBrushItem->GetGraphic(); if( pGrf ) { // Grafik als (JPG-)File speichern aGrfNm = aStreamPath; USHORT nErr = XOutBitmap::WriteGraphic( *pGrf, aGrfNm, _STRINGCONST( "JPG" ), XOUTBMP_USE_NATIVE_IF_POSSIBLE ); if( !nErr ) // fehlerhaft, da ist nichts auszugeben { aGrfNm = URIHelper::SmartRelToAbs( aGrfNm ); if ( HasCId() ) MakeCIdURL( aGrfNm ); pLink = &aGrfNm; } } } else { aGrfNm = *pLink; if( bCopyLocalFileToINet || HasCId() ) { CopyLocalFileToINet( aGrfNm, aStreamPath ); if ( HasCId() ) MakeCIdURL( aGrfNm ); } else aGrfNm = URIHelper::SmartRelToAbs( aGrfNm ); pLink = &aGrfNm; } if( pLink ) { rStrm << ' ' << sHTML_O_background << "=\""; OUT_STR( INetURLObject::AbsToRel( *pLink ) ) << '\"'; } } if ( !aHTMLStyle.aBackgroundColor.GetTransparency() ) { // A transparent background color should always result in default // background of the browser. Also, HTMLOutFuncs::Out_Color() writes // black #000000 for COL_AUTO which is the same as white #ffffff with // transparency set to 0xff, our default background. OUT_SP_CSTR_ASS( sHTML_O_bgcolor ); HTMLOutFuncs::Out_Color( rStrm, aHTMLStyle.aBackgroundColor ); } rStrm << '>'; OUT_LF(); if ( bAll ) WriteOverview(); WriteTables(); TAG_OFF_LF( sHTML_body ); } void ScHTMLExport::WriteTables() { const USHORT nTabCount = pDoc->GetTableCount(); const String aStrTable( ScResId( SCSTR_TABLE ) ); String aStr; String aStrOut; USHORT nStartCol, nStartRow, nStartTab; USHORT nEndCol, nEndRow, nEndTab; USHORT nStartColFix, nStartRowFix, nEndColFix, nEndRowFix; ScDrawLayer* pDrawLayer = pDoc->GetDrawLayer(); if ( bAll ) { nStartTab = 0; nEndTab = nTabCount - 1; } else { nStartCol = nStartColFix = aRange.aStart.Col(); nStartRow = nStartRowFix = aRange.aStart.Row(); nStartTab = aRange.aStart.Tab(); nEndCol = nEndColFix = aRange.aEnd.Col(); nEndRow = nEndRowFix = aRange.aEnd.Row(); nEndTab = aRange.aEnd.Tab(); } USHORT nTableStrNum = 1; for ( USHORT nTab=nStartTab; nTab<=nEndTab; nTab++ ) { if ( !pDoc->IsVisible( nTab ) ) continue; // for if ( bAll ) { if ( !GetDataArea( nTab, nStartCol, nStartRow, nEndCol, nEndRow ) ) continue; // for if ( nUsedTables > 1 ) { aStrOut = aStrTable; aStrOut.AppendAscii( " " ); aStrOut += String::CreateFromInt32( nTableStrNum++ ); aStrOut.AppendAscii( ": " ); OUT_HR(); // Anker festlegen: rStrm << "<A NAME=\"table" << ByteString::CreateFromInt32( nTab ).GetBuffer() << "\">"; TAG_ON( sHTML_head1 ); OUT_STR( aStrOut ); TAG_ON( sHTML_emphasis ); pDoc->GetName( nTab, aStr ); OUT_STR( aStr ); TAG_OFF( sHTML_emphasis ); TAG_OFF( sHTML_head1 ); rStrm << "</A>"; OUT_LF(); } } else { nStartCol = nStartColFix; nStartRow = nStartRowFix; nEndCol = nEndColFix; nEndRow = nEndRowFix; if ( !TrimDataArea( nTab, nStartCol, nStartRow, nEndCol, nEndRow ) ) continue; // for } // <TABLE ...> ByteString aByteStrOut = sHTML_table; // aStrOut = sHTML_table; aByteStrOut += ' '; aByteStrOut += sHTML_frame; aByteStrOut += '='; USHORT nFrame = 0; if ( HasBottomBorder( nEndRow, nTab, nStartCol, nEndCol ) ) nFrame |= 2; if ( HasLeftBorder( nStartCol, nTab, nStartRow, nEndRow ) ) nFrame |= 4; if ( HasTopBorder( nStartRow, nTab, nStartCol, nEndCol ) ) nFrame |= 8; if ( HasRightBorder( nEndCol, nTab, nStartRow, nEndRow ) ) nFrame |= 16; if ( nFrame ) { // nicht alle Kombinationen sind in HTML moeglich // nur void, above, below, lhs, rhs, hsides, vsides, box const USHORT nAll = 2 | 4 | 8 | 16; USHORT nBit; for ( nBit=2; nBit<=16; nBit <<= 1 ) { if ( (nFrame | nBit) == nAll ) { // mindestens drei Seiten => vier aByteStrOut += sHTML_TF_box; nFrame = 0; break; } } if ( nFrame ) { // ein oder zwei Seiten for ( nBit=2; nBit<=16; nBit <<= 1 ) { if ( (nFrame & nBit) == nFrame ) { // eine Seite switch ( nBit ) { case 2: aByteStrOut += sHTML_TF_below; break; case 4: aByteStrOut += sHTML_TF_lhs; break; case 8: aByteStrOut += sHTML_TF_above; break; case 16: aByteStrOut += sHTML_TF_rhs; break; } nFrame = 0; break; } } if ( nFrame ) { // zwei Seiten // horizontale bevorzugt if ( nFrame & 8 ) { if ( nFrame & 2 ) aByteStrOut += sHTML_TF_hsides; else aByteStrOut += sHTML_TF_above; } else if ( nFrame & 2 ) aByteStrOut += sHTML_TF_below; else if ( nFrame & 4 ) { if ( nFrame & 16 ) aByteStrOut += sHTML_TF_vsides; else aByteStrOut += sHTML_TF_lhs; } else // if ( nFrame & 16 ) aByteStrOut += sHTML_TF_rhs; } } } else aByteStrOut += sHTML_TF_void; bTabHasGraphics = bTabAlignedLeft = FALSE; if ( bAll && pDrawLayer ) PrepareGraphics( pDrawLayer, nTab, nStartCol, nStartRow, nEndCol, nEndRow ); // mehr <TABLE ...> if ( bTabAlignedLeft ) (((aByteStrOut += ' ') += sHTML_O_align) += '=') += sHTML_AL_left; // ALIGN=LEFT allow text and graphics to flow around // CELLSPACING (((aByteStrOut += ' ' ) += sHTML_O_cellspacing ) += '=') += ByteString::CreateFromInt32( nCellSpacing ); // COLS=n USHORT nColCnt = 0; USHORT nCol; for ( nCol=nStartCol; nCol<=nEndCol; nCol++ ) { if ( !(pDoc->GetColFlags( nCol, nTab ) & CR_HIDDEN) ) ++nColCnt; } (((aByteStrOut += ' ') += sHTML_O_cols) += '=') += ByteString::CreateFromInt32( nColCnt ); // RULES=GROUPS (((aByteStrOut += ' ') += sHTML_O_rules) += '=') += sHTML_TR_groups; // Netscape und M$IE brauchen ein BORDER=n um ueberhaupt ein Rule zu zeichnen ((aByteStrOut += ' ') += sHTML_O_border) += "=1"; IncIndent(1); TAG_ON_LF( aByteStrOut.GetBuffer() ); // <COLGROUP> fuer RULES=GROUPS TAG_ON( sHTML_colgroup ); // <COL WIDTH=x> als Vorabinformation fuer lange Tabellen ByteString aByteStr = sHTML_col; aByteStr += ' '; aByteStr += sHTML_O_width; aByteStr += '='; for ( nCol=nStartCol; nCol<=nEndCol; nCol++ ) { if ( pDoc->GetColFlags( nCol, nTab ) & CR_HIDDEN ) continue; // for aByteStrOut = aByteStr; aByteStrOut += ByteString::CreateFromInt32( ToPixel( pDoc->GetColWidth( nCol, nTab ) ) ); TAG_ON( aByteStrOut.GetBuffer() ); if ( nCol < nEndCol && HasRightBorder( nCol, nTab, nStartRow, nEndRow ) ) { // neue ColGroup fuer RULES TAG_OFF_LF( sHTML_colgroup ); TAG_ON( sHTML_colgroup ); } } TAG_OFF_LF( sHTML_colgroup ); // <TBODY> fuer RULES=GROUPS IncIndent(1); TAG_ON_LF( sHTML_tbody ); // At least old (3.x, 4.x?) Netscape doesn't follow <TABLE COLS=n> and // <COL WIDTH=x> specified, but needs a width at every column. bTableDataWidth = TRUE; // widths in first row for ( USHORT nRow=nStartRow; nRow<=nEndRow; nRow++ ) { if ( pDoc->GetRowFlags( nRow, nTab ) & CR_HIDDEN ) continue; // for IncIndent(1); TAG_ON_LF( sHTML_tablerow ); bTableDataHeight = TRUE; // height at every first cell of each row for ( USHORT nCol=nStartCol; nCol<=nEndCol; nCol++ ) { if ( pDoc->GetColFlags( nCol, nTab ) & CR_HIDDEN ) continue; // for if ( nCol == nEndCol ) IncIndent(-1); WriteCell( nCol, nRow, nTab ); bTableDataHeight = FALSE; } bTableDataWidth = FALSE; // widths only in first row if ( nRow < nEndRow && HasBottomBorder( nRow, nTab, nStartCol, nEndCol ) ) { // neuer TBody fuer RULES IncIndent(-1); TAG_OFF_LF( sHTML_tablerow ); TAG_OFF_LF( sHTML_tbody ); IncIndent(1); TAG_ON_LF( sHTML_tbody ); } else { if ( nRow == nEndRow ) IncIndent(-1); TAG_OFF_LF( sHTML_tablerow ); } } IncIndent(-1); TAG_OFF_LF( sHTML_tbody ); IncIndent(-1); TAG_OFF_LF( sHTML_table ); if ( bTabHasGraphics ) { // der Rest, der nicht in Zellen ist for ( ScHTMLGraphEntry* pE = aGraphList.First(); pE; pE = aGraphList.Next() ) { if ( !pE->bWritten ) WriteGraphEntry( pE ); delete pE; } aGraphList.Clear(); if ( bTabAlignedLeft ) { // mit <BR CLEAR=LEFT> das <TABLE ALIGN=LEFT> wieder ausschalten aByteStrOut = sHTML_linebreak; (((aByteStrOut += ' ') += sHTML_O_clear) += '=') += sHTML_AL_left; TAG_ON_LF( aByteStrOut.GetBuffer() ); } } if ( bAll ) OUT_COMMENT( _STRINGCONST( "**************************************************************************" ) ); } } void ScHTMLExport::WriteCell( USHORT nCol, USHORT nRow, USHORT nTab ) { const ScPatternAttr* pAttr = pDoc->GetPattern( nCol, nRow, nTab ); const SfxItemSet* pCondItemSet = pDoc->GetCondResult( nCol, nRow, nTab ); const ScMergeFlagAttr& rMergeFlagAttr = (const ScMergeFlagAttr&) pAttr->GetItem( ATTR_MERGE_FLAG, pCondItemSet ); if ( rMergeFlagAttr.IsOverlapped() ) return ; ScAddress aPos( nCol, nRow, nTab ); ScHTMLGraphEntry* pGraphEntry = NULL; if ( bTabHasGraphics ) { for ( pGraphEntry = aGraphList.First(); pGraphEntry; pGraphEntry = aGraphList.Next() ) { if ( pGraphEntry->bInCell && pGraphEntry->aRange.In( aPos ) ) { if ( pGraphEntry->aRange.aStart == aPos ) break; // for else return ; // ist ein Col/RowSpan, Overlapped break; } } } ScBaseCell* pCell = pDoc->GetCell( aPos ); ULONG nFormat = pAttr->GetNumberFormat( pFormatter ); BOOL bValueData; BYTE nScriptType; if ( pCell ) { bValueData = pCell->HasValueData(); nScriptType = pDoc->GetScriptType( nCol, nRow, nTab, pCell ); } else { bValueData = FALSE; nScriptType = 0; } if ( nScriptType == 0 ) nScriptType = aHTMLStyle.nDefaultScriptType; ByteString aStrTD = sHTML_tabledata; String aStr; const sal_Char* pChar; USHORT nWidthPixel; USHORT nHeightPixel; const ScMergeAttr& rMergeAttr = (const ScMergeAttr&) pAttr->GetItem( ATTR_MERGE, pCondItemSet ); if ( pGraphEntry || rMergeAttr.IsMerged() ) { USHORT j, n, v; if ( pGraphEntry ) n = Max( USHORT(pGraphEntry->aRange.aEnd.Col() - nCol + 1), USHORT(rMergeAttr.GetColMerge()) ); else n = rMergeAttr.GetColMerge(); if ( n > 1 ) { (((aStrTD += ' ') += sHTML_O_colspan) += '=') += ByteString::CreateFromInt32( n ); n += nCol; for ( j=nCol, v=0; j<n; j++ ) v += pDoc->GetColWidth( j, nTab ); nWidthPixel = ToPixel( v ); } else nWidthPixel = ToPixel( pDoc->GetColWidth( nCol, nTab ) ); if ( pGraphEntry ) n = Max( USHORT(pGraphEntry->aRange.aEnd.Row() - nRow + 1), USHORT(rMergeAttr.GetRowMerge()) ); else n = rMergeAttr.GetRowMerge(); if ( n > 1 ) { (((aStrTD += ' ') += sHTML_O_rowspan) += '=') += ByteString::CreateFromInt32( n ); n += nRow; for ( j=nRow, v=0; j<n; j++ ) v += pDoc->GetRowHeight( j, nTab ); nHeightPixel = ToPixel( v ); } else nHeightPixel = ToPixel( pDoc->GetRowHeight( nRow, nTab ) ); } else { nWidthPixel = ToPixel( pDoc->GetColWidth( nCol, nTab ) ); nHeightPixel = ToPixel( pDoc->GetRowHeight( nRow, nTab ) ); } if ( bTableDataWidth ) (((aStrTD += ' ') += sHTML_O_width) += '=') += ByteString::CreateFromInt32( nWidthPixel ); if ( bTableDataHeight ) (((aStrTD += ' ') += sHTML_O_height) += '=') += ByteString::CreateFromInt32( nHeightPixel ); const SvxFontItem& rFontItem = (const SvxFontItem&) pAttr->GetItem( ScGlobal::GetScriptedWhichID( nScriptType, ATTR_FONT), pCondItemSet); const SvxFontHeightItem& rFontHeightItem = (const SvxFontHeightItem&) pAttr->GetItem( ScGlobal::GetScriptedWhichID( nScriptType, ATTR_FONT_HEIGHT), pCondItemSet); const SvxWeightItem& rWeightItem = (const SvxWeightItem&) pAttr->GetItem( ScGlobal::GetScriptedWhichID( nScriptType, ATTR_FONT_WEIGHT), pCondItemSet); const SvxPostureItem& rPostureItem = (const SvxPostureItem&) pAttr->GetItem( ScGlobal::GetScriptedWhichID( nScriptType, ATTR_FONT_POSTURE), pCondItemSet); const SvxUnderlineItem& rUnderlineItem = (const SvxUnderlineItem&) pAttr->GetItem( ATTR_FONT_UNDERLINE, pCondItemSet ); const SvxColorItem& rColorItem = (const SvxColorItem&) pAttr->GetItem( ATTR_FONT_COLOR, pCondItemSet ); const SvxHorJustifyItem& rHorJustifyItem = (const SvxHorJustifyItem&) pAttr->GetItem( ATTR_HOR_JUSTIFY, pCondItemSet ); const SvxVerJustifyItem& rVerJustifyItem = (const SvxVerJustifyItem&) pAttr->GetItem( ATTR_VER_JUSTIFY, pCondItemSet ); const SvxBrushItem& rBrushItem = (const SvxBrushItem&) pAttr->GetItem( ATTR_BACKGROUND, pCondItemSet ); Color aBgColor; if ( rBrushItem.GetColor().GetTransparency() == 255 ) aBgColor = aHTMLStyle.aBackgroundColor; // #55121# keine ungewollte Hintergrundfarbe else aBgColor = rBrushItem.GetColor(); BOOL bBold = ( WEIGHT_BOLD <= rWeightItem.GetWeight() ); BOOL bItalic = ( ITALIC_NONE != rPostureItem.GetPosture() ); BOOL bUnderline = ( UNDERLINE_NONE != rUnderlineItem.GetUnderline() ); BOOL bSetFontColor = ( COL_AUTO != rColorItem.GetValue().GetColor() ); // #97650# default is AUTO now #if 0 // keine StyleSheet-Fontangaben: hart fuer jede Zelle BOOL bSetFontName = TRUE; USHORT nSetFontSizeNumber = GetFontSizeNumber( (USHORT)rFontHeightItem.GetHeight() ); #else BOOL bSetFontName = ( aHTMLStyle.aFontFamilyName != rFontItem.GetFamilyName() ); USHORT nSetFontSizeNumber = 0; UINT32 nFontHeight = rFontHeightItem.GetHeight(); if ( nFontHeight != aHTMLStyle.nFontHeight ) { nSetFontSizeNumber = GetFontSizeNumber( (USHORT) nFontHeight ); if ( nSetFontSizeNumber == aHTMLStyle.nFontSizeNumber ) nSetFontSizeNumber = 0; // no difference, don't set } #endif BOOL bSetFont = (bSetFontColor || bSetFontName || nSetFontSizeNumber); //! TODO: we could entirely use CSS1 here instead, but that would exclude //! Netscape 3.0 and Netscape 4.x without JavaScript enabled. //! Do we want that? switch( rHorJustifyItem.GetValue() ) { case SVX_HOR_JUSTIFY_STANDARD: pChar = (bValueData ? sHTML_AL_right : sHTML_AL_left); break; case SVX_HOR_JUSTIFY_CENTER: pChar = sHTML_AL_center; break; case SVX_HOR_JUSTIFY_BLOCK: pChar = sHTML_AL_justify; break; case SVX_HOR_JUSTIFY_RIGHT: pChar = sHTML_AL_right; break; case SVX_HOR_JUSTIFY_LEFT: case SVX_HOR_JUSTIFY_REPEAT: default: pChar = sHTML_AL_left; break; } (((aStrTD += ' ') += sHTML_O_align) += '=') += pChar; switch( rVerJustifyItem.GetValue() ) { case SVX_VER_JUSTIFY_TOP: pChar = sHTML_VA_top; break; case SVX_VER_JUSTIFY_CENTER: pChar = sHTML_VA_middle; break; case SVX_VER_JUSTIFY_BOTTOM: pChar = sHTML_VA_bottom; break; case SVX_VER_JUSTIFY_STANDARD: default: pChar = NULL; } if ( pChar ) (((aStrTD += ' ') += sHTML_O_valign) += '=') += pChar; if ( aHTMLStyle.aBackgroundColor != aBgColor ) { ((aStrTD += ' ') += sHTML_O_bgcolor) += '='; lcl_AppendHTMLColorTripel( aStrTD, aBgColor ); } double fVal = 0.0; if ( bValueData ) { if ( pCell ) { switch ( pCell->GetCellType() ) { case CELLTYPE_VALUE: fVal = ((ScValueCell*)pCell)->GetValue(); if ( bCalcAsShown && fVal != 0.0 ) fVal = pDoc->RoundValueAsShown( fVal, nFormat ); break; case CELLTYPE_FORMULA: fVal = ((ScFormulaCell*)pCell)->GetValue(); if ( (nFormat % SV_COUNTRY_LANGUAGE_OFFSET) == 0 ) nFormat = ScGlobal::GetStandardFormat( fVal, *pFormatter, nFormat, ((ScFormulaCell*)pCell)->GetFormatType() ); break; default: DBG_ERRORFILE( "value data with unsupported cell type" ); } } } HTMLOutFuncs::CreateTableDataOptionsValNum( aStrTD, bValueData, fVal, nFormat, *pFormatter, eDestEnc, &aNonConvertibleChars ); TAG_ON( aStrTD.GetBuffer() ); if ( bBold ) TAG_ON( sHTML_bold ); if ( bItalic ) TAG_ON( sHTML_italic ); if ( bUnderline ) TAG_ON( sHTML_underline ); if ( bSetFont ) { ByteString aStr = sHTML_font; if ( bSetFontName ) { ((aStr += ' ') += sHTML_O_face) += "=\""; xub_StrLen nFonts = rFontItem.GetFamilyName().GetTokenCount( ';' ); if ( nFonts == 1 ) { ByteString aTmpStr; HTMLOutFuncs::ConvertStringToHTML( rFontItem.GetFamilyName(), aTmpStr, eDestEnc, &aNonConvertibleChars ); aStr += aTmpStr; } else { // Fontliste, VCL: Semikolon als Separator, HTML: Komma const String& rList = rFontItem.GetFamilyName(); for ( xub_StrLen j = 0, nPos = 0; j < nFonts; j++ ) { ByteString aTmpStr; HTMLOutFuncs::ConvertStringToHTML( rList.GetToken( 0, ';', nPos ), aTmpStr, eDestEnc, &aNonConvertibleChars ); aStr += aTmpStr; if ( j < nFonts-1 ) aStr += ','; } } aStr += '\"'; } if ( nSetFontSizeNumber ) { (((aStr += ' ') += sHTML_O_size) += '=') += ByteString::CreateFromInt32( nSetFontSizeNumber ); } if ( bSetFontColor ) { Color aColor = rColorItem.GetValue(); // always export automatic text color as black if ( aColor.GetColor() == COL_AUTO ) aColor.SetColor( COL_BLACK ); ((aStr += ' ') += sHTML_O_color) += '='; lcl_AppendHTMLColorTripel( aStr, aColor ); } TAG_ON( aStr.GetBuffer() ); } String aStrOut; BOOL bFieldText = FALSE; if ( pCell ) { // cell content Color* pColor; switch ( pCell->GetCellType() ) { case CELLTYPE_NOTE : // nothing break; case CELLTYPE_EDIT : bFieldText = WriteFieldText( (const ScEditCell*) pCell ); if ( bFieldText ) break; //! else: fallthru default: ScCellFormat::GetString( pCell, nFormat, aStrOut, &pColor, *pFormatter ); } } if ( !bFieldText ) { if ( !aStrOut.Len() ) TAG_ON( sHTML_linebreak ); // #42573# keine komplett leere Zelle else OUT_STR( aStrOut ); } if ( pGraphEntry ) WriteGraphEntry( pGraphEntry ); if ( bSetFont ) TAG_OFF( sHTML_font ); if ( bUnderline ) TAG_OFF( sHTML_underline ); if ( bItalic ) TAG_OFF( sHTML_italic ); if ( bBold ) TAG_OFF( sHTML_bold ); TAG_OFF_LF( sHTML_tabledata ); } BOOL ScHTMLExport::WriteFieldText( const ScEditCell* pCell ) { BOOL bFields = FALSE; const EditTextObject* pData; pCell->GetData( pData ); // text and anchor of URL fields, Doc-Engine is a ScFieldEditEngine EditEngine& rEngine = pDoc->GetEditEngine(); rEngine.SetText( *pData ); USHORT nParas = rEngine.GetParagraphCount(); if ( nParas ) { ESelection aSel( 0, 0, nParas-1, rEngine.GetTextLen( nParas-1 ) ); SfxItemSet aSet( rEngine.GetAttribs( aSel ) ); SfxItemState eFieldState = aSet.GetItemState( EE_FEATURE_FIELD, FALSE ); if ( eFieldState == SFX_ITEM_DONTCARE || eFieldState == SFX_ITEM_SET ) bFields = TRUE; } if ( bFields ) { BOOL bOldUpdateMode = rEngine.GetUpdateMode(); rEngine.SetUpdateMode( TRUE ); // no portions if not formatted for ( USHORT nPar=0; nPar < nParas; nPar++ ) { if ( nPar > 0 ) rStrm << ' '; // blank between paragraphs SvUShorts aPortions; rEngine.GetPortions( nPar, aPortions ); USHORT nCnt = aPortions.Count(); USHORT nStart = 0; for ( USHORT nPos = 0; nPos < nCnt; nPos++ ) { USHORT nEnd = aPortions.GetObject( nPos ); ESelection aSel( nPar, nStart, nPar, nEnd ); BOOL bUrl = FALSE; // fields are single characters if ( nEnd == nStart+1 ) { const SfxPoolItem* pItem; SfxItemSet aSet = rEngine.GetAttribs( aSel ); if ( aSet.GetItemState( EE_FEATURE_FIELD, FALSE, &pItem ) == SFX_ITEM_ON ) { const SvxFieldData* pField = ((const SvxFieldItem*)pItem)->GetField(); if ( pField && pField->ISA(SvxURLField) ) { bUrl = TRUE; const SvxURLField* pURLField = (const SvxURLField*)pField; // String aFieldText = rEngine.GetText( aSel ); rStrm << '<' << sHTML_anchor << ' ' << sHTML_O_href << "=\""; OUT_STR( pURLField->GetURL() ); rStrm << "\">"; OUT_STR( pURLField->GetRepresentation() ); rStrm << "</" << sHTML_anchor << '>'; } } } if ( !bUrl ) OUT_STR( rEngine.GetText( aSel ) ); nStart = nEnd; } } rEngine.SetUpdateMode( bOldUpdateMode ); } return bFields; } BOOL ScHTMLExport::CopyLocalFileToINet( String& rFileNm, const String& rTargetNm, BOOL bFileToFile ) { BOOL bRet = FALSE; INetURLObject aFileUrl, aTargetUrl; aFileUrl.SetSmartURL( rFileNm ); aTargetUrl.SetSmartURL( rTargetNm ); if( INET_PROT_FILE == aFileUrl.GetProtocol() && ( (bFileToFile && INET_PROT_FILE == aTargetUrl.GetProtocol()) || (!bFileToFile && INET_PROT_FILE != aTargetUrl.GetProtocol() && INET_PROT_FTP <= aTargetUrl.GetProtocol() && INET_PROT_NEWS >= aTargetUrl.GetProtocol()) ) ) { if( pSrcArr ) { // wurde die Datei schon verschoben USHORT nPos; if( pSrcArr->Seek_Entry( &rFileNm, &nPos )) { rFileNm = *(*pDestArr)[ nPos ]; return TRUE; } } else { pSrcArr = new SvStringsSortDtor( 4, 4 ); pDestArr = new SvStringsSortDtor( 4, 4 ); } String* pSrc = new String( rFileNm ); SvFileStream aTmp( aFileUrl.PathToFileName(), STREAM_READ ); String* pDest = new String( aTargetUrl.GetPartBeforeLastName() ); *pDest += aFileUrl.GetName(); if( bFileToFile ) { INetURLObject aCpyURL( *pDest ); SvFileStream aCpy( aCpyURL.PathToFileName(), STREAM_WRITE ); aCpy << aTmp; aCpy.Close(); bRet = SVSTREAM_OK == aCpy.GetError(); } else { SfxMedium aMedium( *pDest, STREAM_WRITE | STREAM_SHARE_DENYNONE, FALSE ); // temp. File anlegen // aMedium.DownLoad(); { SvFileStream aCpy( aMedium.GetPhysicalName(), STREAM_WRITE ); aCpy << aTmp; } // uebertragen aMedium.Close(); aMedium.Commit(); bRet = 0 == aMedium.GetError(); } if( bRet ) { pSrcArr->Insert( pSrc ); pDestArr->Insert( pDest ); rFileNm = *pDest; } else { delete pSrc; delete pDest; } } return bRet; } void ScHTMLExport::MakeCIdURL( String& rURL ) { if( !aCId.Len() ) return; INetURLObject aURLObj( rURL ); if( INET_PROT_FILE != aURLObj.GetProtocol() ) return; String aLastName( aURLObj.GetLastName() ); DBG_ASSERT( aLastName.Len(), "Dateiname ohne Laenge!" ); aLastName.ToLowerAscii(); rURL.AssignAscii( "cid:" ); rURL += aLastName; rURL.AppendAscii( "." ); rURL += aCId; } void ScHTMLExport::IncIndent( short nVal ) { sIndent[nIndent] = '\t'; nIndent += nVal; if ( nIndent < 0 ) nIndent = 0; else if ( nIndent > nIndentMax ) nIndent = nIndentMax; sIndent[nIndent] = 0; }
// For conditions of distribution and use, see copyright notice in license.txt #include "StableHeaders.h" #include "QtModule.h" #include "OgreRenderingModule.h" #include <QtUiTools> #include <QFile> #include <QHash> #include <QMessageBox> #include "LoginUI.h" namespace RexLogic { ///////////////////////////////////////// // Login CLASS ///////////////////////////////////////// Login::Login(Foundation::Framework *framework, RexLogicModule *rexLogicModule) : framework_(framework), rexLogicModule_(rexLogicModule) { InitUICanvas(); InitLoginUI(); InitLogoutUI(); } Login::~Login(void) { if (qtModule_.get() && canvas_login_.get() && canvas_logout_.get()) { qtModule_->DeleteCanvas(canvas_login_->GetID()); qtModule_->DeleteCanvas(canvas_logout_->GetID()); } } void Login::Show() { if (canvas_login_.get()) canvas_login_->Show(); } void Login::Hide() { if (canvas_login_.get()) canvas_login_->Hide(); } void Login::QuitApplication() { if (rexLogicModule_->GetServerConnection()->IsConnected()) rexLogicModule_->LogoutAndDeleteWorld(); framework_->Exit(); } void Login::Connected() { canvas_login_->Hide(); canvas_logout_->Show(); AdjustWindowSize(canvas_login_->GetRenderWindowSize()); if (qtModule_.get()) qtModule_->SetShowControlBar(true); } void Login::Disconnect() { if (qtModule_.get()) qtModule_->SetShowControlBar(false); if (rexLogicModule_->GetServerConnection()->IsConnected()) { rexLogicModule_->LogoutAndDeleteWorld(); canvas_logout_->Hide(); canvas_login_->Show(); AdjustWindowSize(canvas_logout_->GetRenderWindowSize()); } } void Login::InitUICanvas() { // Get QtModule and create canvas qtModule_ = framework_->GetModuleManager()->GetModule<QtUI::QtModule>(Foundation::Module::MT_Gui).lock(); if (!qtModule_.get()) return; canvas_login_ = qtModule_->CreateCanvas(QtUI::UICanvas::Internal).lock(); canvas_logout_ = qtModule_->CreateCanvas(QtUI::UICanvas::Internal).lock(); } void Login::InitLoginUI() { tabWidget_ = new QTabWidget(0); tabWidget_->addTab((QWidget*)new WebUI(tabWidget_, this, framework_, rexLogicModule_), QString("Web Login")); tabWidget_->addTab((QWidget*)new NaaliUI(tabWidget_, this, framework_, rexLogicModule_), QString("Traditional Login")); QSize rendererWindowSize = canvas_login_->GetRenderWindowSize(); tabWidget_->resize(rendererWindowSize.width(), rendererWindowSize.height()); canvas_login_->SetSize(rendererWindowSize.width(), rendererWindowSize.height()); canvas_login_->SetPosition(0, 0); canvas_login_->AddWidget(tabWidget_); canvas_login_->SetAlwaysOnTop(true); canvas_login_->SetStationary(true); canvas_login_->SetResizable(false); canvas_login_->Show(); QObject::connect(canvas_login_.get(), SIGNAL( RenderWindowSizeChanged(const QSize&) ), this, SLOT( AdjustWindowSize(const QSize&) )); } void Login::InitLogoutUI() { QUiLoader loader; QFile uiFile("./data/ui/inworld_controls.ui"); if ( uiFile.exists() ) { // Load ui to widget from file and get buttons QWidget *inworldControls = loader.load(&uiFile); inworldControls->resize(150, 25); logout_button_ = inworldControls->findChild<QPushButton *>("pushButton_Logout"); quit_button_ = inworldControls->findChild<QPushButton *>("pushButton_Quit"); uiFile.close(); // Create UICanvas QSize parentWindowSize = canvas_logout_->GetRenderWindowSize(); canvas_logout_->SetPosition(parentWindowSize.width()-95, 0); canvas_logout_->SetSize(95, 25); canvas_logout_->SetResizable(false); canvas_logout_->SetStationary(true); canvas_logout_->SetAlwaysOnTop(true); // Connect signals QObject::connect(canvas_logout_.get(), SIGNAL( RenderWindowSizeChanged(const QSize&) ), this, SLOT( AdjustWindowSize(const QSize&) )); QObject::connect(logout_button_, SIGNAL( clicked() ), this, SLOT( Disconnect() )); QObject::connect(quit_button_, SIGNAL( clicked() ), this, SLOT( QuitApplication() )); // Add widget to canvas and hide it as long as we are inworld canvas_logout_->AddWidget(inworldControls); canvas_logout_->Hide(); } } void Login::AdjustWindowSize(const QSize &newSize) { if ( !canvas_login_->IsHidden() ) { canvas_login_->SetSize(newSize.width(), newSize.height()); canvas_login_->SetPosition(0,0); canvas_login_->BringToTop(); canvas_login_->Redraw(); } if ( !canvas_logout_->IsHidden() ) { canvas_logout_->SetPosition(newSize.width()-95, 0); canvas_logout_->BringToTop(); canvas_logout_->Redraw(); } } ///////////////////////////////////////// // ABSTRACT AbstractLoginUI CLASS ///////////////////////////////////////// AbstractLoginUI::AbstractLoginUI(QWidget *parent, Login *controller, Foundation::Framework* framework, RexLogicModule *rexLogic) : QWidget(parent), controller_(controller), framework_(framework), rexLogicModule_(rexLogic), loginHandler_(0) { } void AbstractLoginUI::SetLayout() { this->setLayout(new QVBoxLayout()); this->layout()->setMargin(0); } void AbstractLoginUI::Show() { this->show(); } void AbstractLoginUI::Hide() { this->Hide(); } void AbstractLoginUI::LoginDone(bool success) { // Do something if needed, canvas hides/shows are already handled } ///////////////////////////////////////// // NaaliUI CLASS ///////////////////////////////////////// NaaliUI::NaaliUI(QWidget *parent, Login *controller, Foundation::Framework* framework, RexLogicModule *rexLogic) : AbstractLoginUI(parent, controller, framework, rexLogic) { SetLayout(); SetLoginHandler(); InitWidget(); ReadConfig(); ShowSelectedMode(); } NaaliUI::~NaaliUI() { delete loginHandler_; } void NaaliUI::SetLoginHandler() { loginHandler_ = new OpenSimLoginHandler(framework_, rexLogicModule_); QObject::connect(loginHandler_, SIGNAL( LoginDone(bool) ), this, SLOT( LoginDone(bool) )); } void NaaliUI::InitWidget() { QUiLoader loader; QFile uiFile("./data/ui/login_new.ui"); internalWidget_ = loader.load(&uiFile, this); uiFile.close(); radioButton_openSim_ = findChild<QRadioButton *>("radioButton_OpenSim"); radioButton_realXtend_ = findChild<QRadioButton *>("radioButton_realXtend"); pushButton_connect_ = findChild<QPushButton *>("pushButton_Connect"); pushButton_close_ = findChild<QPushButton *>("pushButton_Close"); label_authAddress_ = findChild<QLabel *>("label_AuthenticationServer"); lineEdit_authAddress_ = findChild<QLineEdit *>("lineEdit_AuthenticationAddress"); lineEdit_worldAddress_ = findChild<QLineEdit *>("lineEdit_WorldAddress"); lineEdit_username_ = findChild<QLineEdit *>("lineEdit_Username"); lineEdit_password_ = findChild<QLineEdit *>("lineEdit_Password"); QObject::connect(radioButton_openSim_, SIGNAL( clicked() ), this, SLOT( ShowSelectedMode() )); QObject::connect(radioButton_realXtend_, SIGNAL( clicked() ), this, SLOT( ShowSelectedMode() )); QObject::connect(pushButton_connect_, SIGNAL( clicked() ), this, SLOT( ParseInputAndConnect() )); QObject::connect(pushButton_close_, SIGNAL( clicked() ), controller_, SLOT( QuitApplication() )); QObject::connect(this, SIGNAL( ConnectOpenSim(QMap<QString, QString>) ), loginHandler_, SLOT( ProcessOpenSimLogin(QMap<QString, QString>) )); QObject::connect(this, SIGNAL( ConnectRealXtend(QMap<QString, QString>) ), loginHandler_, SLOT( ProcessRealXtendLogin(QMap<QString, QString>) )); this->layout()->addWidget(internalWidget_); } void NaaliUI::ReadConfig() { // Recover the connection settings that were used in previous login // from the xml configuration file. QString value, configKey; QString configGroup("Login"); configKey = QString("username"); opensim_username_ = QString(framework_->GetDefaultConfigPtr()->GetSetting<std::string>(configGroup.toStdString(), configKey.toStdString()).c_str()); lineEdit_username_->setText(opensim_username_); configKey = QString("auth_name"); realXtend_username_ = QString(framework_->GetDefaultConfigPtr()->GetSetting<std::string>(configGroup.toStdString(), configKey.toStdString()).c_str()); configKey = QString("rex_server"); realXtend_server_ = QString(framework_->GetDefaultConfigPtr()->GetSetting<std::string>(configGroup.toStdString(), configKey.toStdString()).c_str()); configKey = QString("server"); value = QString(framework_->GetDefaultConfigPtr()->GetSetting<std::string>(configGroup.toStdString(), configKey.toStdString()).c_str()); lineEdit_worldAddress_->setText(value); opensim_server_ = value; configKey = QString("auth_server"); value = QString(framework_->GetDefaultConfigPtr()->GetSetting<std::string>(configGroup.toStdString(), configKey.toStdString()).c_str()); lineEdit_authAddress_->setText(value); realXtend_authserver_ = value; } void NaaliUI::ShowSelectedMode() { bool hide = false; if (radioButton_openSim_->isChecked() == true) { hide = false; if (lineEdit_username_->text() == realXtend_username_) lineEdit_username_->setText(opensim_username_); if (lineEdit_worldAddress_->text() == realXtend_server_) lineEdit_worldAddress_->setText(opensim_server_); } else if (radioButton_realXtend_->isChecked() == true) { hide = true; if (lineEdit_username_->text() == opensim_username_) lineEdit_username_->setText(realXtend_username_); if (lineEdit_worldAddress_->text() == opensim_server_) lineEdit_worldAddress_->setText(realXtend_server_); } label_authAddress_->setVisible(hide); lineEdit_authAddress_->setVisible(hide); lineEdit_password_->clear(); } void NaaliUI::ParseInputAndConnect() { if ( !lineEdit_worldAddress_->text().isEmpty() && !lineEdit_username_->text().isEmpty() && !lineEdit_password_->text().isEmpty() ) { QMap<QString, QString> map; map["WorldAddress"] = lineEdit_worldAddress_->text(); map["Username"] = lineEdit_username_->text(); map["Password"] = lineEdit_password_->text(); if (radioButton_openSim_->isChecked() == true) { emit( ConnectOpenSim(map) ); } else if (radioButton_realXtend_->isChecked() == true && !lineEdit_authAddress_->text().isEmpty() ) { map["AuthenticationAddress"] = lineEdit_authAddress_->text(); emit( ConnectRealXtend(map) ); } } } ///////////////////////////////////////// // WebUI CLASS ///////////////////////////////////////// WebUI::WebUI(QWidget *parent, Login *controller, Foundation::Framework *framework, RexLogicModule *rexLogic) : AbstractLoginUI(parent, controller, framework, rexLogic) { SetLayout(); SetLoginHandler(); InitWidget(); } WebUI::~WebUI() { delete loginHandler_; } void WebUI::SetLoginHandler() { loginHandler_ = new TaigaLoginHandler(framework_, rexLogicModule_); QObject::connect(loginHandler_, SIGNAL( LoginDone(bool) ), this, SLOT( LoginDone(bool) )); } void WebUI::InitWidget() { QFile confFile("./data/default_login.ini"); if (!confFile.open(QIODevice::ReadOnly | QIODevice::Text)) return; QString url(confFile.readLine()); confFile.close(); webLogin_ = new RexWebLogin(this, url); QObject::connect(webLogin_, SIGNAL( WebLoginInfoRecieved(QWebFrame *) ), loginHandler_, SLOT( ProcessWebLogin(QWebFrame *) )); this->layout()->addWidget(webLogin_); } } Removed not needed OgreRenderingModule include git-svn-id: 65dd0ccd495961f396d5302e5521154b071f0302@1761 5b2332b8-efa3-11de-8684-7d64432d61a3 // For conditions of distribution and use, see copyright notice in license.txt #include "StableHeaders.h" #include "QtModule.h" #include "RexLogicModule.h" #include <QtUiTools> #include <QFile> #include <QHash> #include <QMessageBox> #include "LoginUI.h" namespace RexLogic { ///////////////////////////////////////// // Login CLASS ///////////////////////////////////////// Login::Login(Foundation::Framework *framework, RexLogicModule *rexLogicModule) : framework_(framework), rexLogicModule_(rexLogicModule) { InitUICanvas(); InitLoginUI(); InitLogoutUI(); } Login::~Login(void) { if (qtModule_.get() && canvas_login_.get() && canvas_logout_.get()) { qtModule_->DeleteCanvas(canvas_login_->GetID()); qtModule_->DeleteCanvas(canvas_logout_->GetID()); } } void Login::Show() { if (canvas_login_.get()) canvas_login_->Show(); } void Login::Hide() { if (canvas_login_.get()) canvas_login_->Hide(); } void Login::QuitApplication() { if (rexLogicModule_->GetServerConnection()->IsConnected()) rexLogicModule_->LogoutAndDeleteWorld(); framework_->Exit(); } void Login::Connected() { canvas_login_->Hide(); canvas_logout_->Show(); AdjustWindowSize(canvas_login_->GetRenderWindowSize()); if (qtModule_.get()) qtModule_->SetShowControlBar(true); } void Login::Disconnect() { if (qtModule_.get()) qtModule_->SetShowControlBar(false); if (rexLogicModule_->GetServerConnection()->IsConnected()) { rexLogicModule_->LogoutAndDeleteWorld(); canvas_logout_->Hide(); canvas_login_->Show(); AdjustWindowSize(canvas_logout_->GetRenderWindowSize()); } } void Login::InitUICanvas() { // Get QtModule and create canvas qtModule_ = framework_->GetModuleManager()->GetModule<QtUI::QtModule>(Foundation::Module::MT_Gui).lock(); if (!qtModule_.get()) return; canvas_login_ = qtModule_->CreateCanvas(QtUI::UICanvas::Internal).lock(); canvas_logout_ = qtModule_->CreateCanvas(QtUI::UICanvas::Internal).lock(); } void Login::InitLoginUI() { tabWidget_ = new QTabWidget(0); tabWidget_->addTab((QWidget*)new WebUI(tabWidget_, this, framework_, rexLogicModule_), QString("Web Login")); tabWidget_->addTab((QWidget*)new NaaliUI(tabWidget_, this, framework_, rexLogicModule_), QString("Traditional Login")); QSize rendererWindowSize = canvas_login_->GetRenderWindowSize(); tabWidget_->resize(rendererWindowSize.width(), rendererWindowSize.height()); canvas_login_->SetSize(rendererWindowSize.width(), rendererWindowSize.height()); canvas_login_->SetPosition(0, 0); canvas_login_->AddWidget(tabWidget_); canvas_login_->SetAlwaysOnTop(true); canvas_login_->SetStationary(true); canvas_login_->SetResizable(false); canvas_login_->Show(); QObject::connect(canvas_login_.get(), SIGNAL( RenderWindowSizeChanged(const QSize&) ), this, SLOT( AdjustWindowSize(const QSize&) )); } void Login::InitLogoutUI() { QUiLoader loader; QFile uiFile("./data/ui/inworld_controls.ui"); if ( uiFile.exists() ) { // Load ui to widget from file and get buttons QWidget *inworldControls = loader.load(&uiFile); inworldControls->resize(150, 25); logout_button_ = inworldControls->findChild<QPushButton *>("pushButton_Logout"); quit_button_ = inworldControls->findChild<QPushButton *>("pushButton_Quit"); uiFile.close(); // Create UICanvas QSize parentWindowSize = canvas_logout_->GetRenderWindowSize(); canvas_logout_->SetPosition(parentWindowSize.width()-95, 0); canvas_logout_->SetSize(95, 25); canvas_logout_->SetResizable(false); canvas_logout_->SetStationary(true); canvas_logout_->SetAlwaysOnTop(true); // Connect signals QObject::connect(canvas_logout_.get(), SIGNAL( RenderWindowSizeChanged(const QSize&) ), this, SLOT( AdjustWindowSize(const QSize&) )); QObject::connect(logout_button_, SIGNAL( clicked() ), this, SLOT( Disconnect() )); QObject::connect(quit_button_, SIGNAL( clicked() ), this, SLOT( QuitApplication() )); // Add widget to canvas and hide it as long as we are inworld canvas_logout_->AddWidget(inworldControls); canvas_logout_->Hide(); } } void Login::AdjustWindowSize(const QSize &newSize) { if ( !canvas_login_->IsHidden() ) { canvas_login_->SetSize(newSize.width(), newSize.height()); canvas_login_->SetPosition(0,0); canvas_login_->BringToTop(); canvas_login_->Redraw(); } if ( !canvas_logout_->IsHidden() ) { canvas_logout_->SetPosition(newSize.width()-95, 0); canvas_logout_->BringToTop(); canvas_logout_->Redraw(); } } ///////////////////////////////////////// // ABSTRACT AbstractLoginUI CLASS ///////////////////////////////////////// AbstractLoginUI::AbstractLoginUI(QWidget *parent, Login *controller, Foundation::Framework* framework, RexLogicModule *rexLogic) : QWidget(parent), controller_(controller), framework_(framework), rexLogicModule_(rexLogic), loginHandler_(0) { } void AbstractLoginUI::SetLayout() { this->setLayout(new QVBoxLayout()); this->layout()->setMargin(0); } void AbstractLoginUI::Show() { this->show(); } void AbstractLoginUI::Hide() { this->Hide(); } void AbstractLoginUI::LoginDone(bool success) { // Do something if needed, canvas hides/shows are already handled } ///////////////////////////////////////// // NaaliUI CLASS ///////////////////////////////////////// NaaliUI::NaaliUI(QWidget *parent, Login *controller, Foundation::Framework* framework, RexLogicModule *rexLogic) : AbstractLoginUI(parent, controller, framework, rexLogic) { SetLayout(); SetLoginHandler(); InitWidget(); ReadConfig(); ShowSelectedMode(); } NaaliUI::~NaaliUI() { delete loginHandler_; } void NaaliUI::SetLoginHandler() { loginHandler_ = new OpenSimLoginHandler(framework_, rexLogicModule_); QObject::connect(loginHandler_, SIGNAL( LoginDone(bool) ), this, SLOT( LoginDone(bool) )); } void NaaliUI::InitWidget() { QUiLoader loader; QFile uiFile("./data/ui/login_new.ui"); internalWidget_ = loader.load(&uiFile, this); uiFile.close(); radioButton_openSim_ = findChild<QRadioButton *>("radioButton_OpenSim"); radioButton_realXtend_ = findChild<QRadioButton *>("radioButton_realXtend"); pushButton_connect_ = findChild<QPushButton *>("pushButton_Connect"); pushButton_close_ = findChild<QPushButton *>("pushButton_Close"); label_authAddress_ = findChild<QLabel *>("label_AuthenticationServer"); lineEdit_authAddress_ = findChild<QLineEdit *>("lineEdit_AuthenticationAddress"); lineEdit_worldAddress_ = findChild<QLineEdit *>("lineEdit_WorldAddress"); lineEdit_username_ = findChild<QLineEdit *>("lineEdit_Username"); lineEdit_password_ = findChild<QLineEdit *>("lineEdit_Password"); QObject::connect(radioButton_openSim_, SIGNAL( clicked() ), this, SLOT( ShowSelectedMode() )); QObject::connect(radioButton_realXtend_, SIGNAL( clicked() ), this, SLOT( ShowSelectedMode() )); QObject::connect(pushButton_connect_, SIGNAL( clicked() ), this, SLOT( ParseInputAndConnect() )); QObject::connect(pushButton_close_, SIGNAL( clicked() ), controller_, SLOT( QuitApplication() )); QObject::connect(this, SIGNAL( ConnectOpenSim(QMap<QString, QString>) ), loginHandler_, SLOT( ProcessOpenSimLogin(QMap<QString, QString>) )); QObject::connect(this, SIGNAL( ConnectRealXtend(QMap<QString, QString>) ), loginHandler_, SLOT( ProcessRealXtendLogin(QMap<QString, QString>) )); this->layout()->addWidget(internalWidget_); } void NaaliUI::ReadConfig() { // Recover the connection settings that were used in previous login // from the xml configuration file. QString value, configKey; QString configGroup("Login"); configKey = QString("username"); opensim_username_ = QString(framework_->GetDefaultConfigPtr()->GetSetting<std::string>(configGroup.toStdString(), configKey.toStdString()).c_str()); lineEdit_username_->setText(opensim_username_); configKey = QString("auth_name"); realXtend_username_ = QString(framework_->GetDefaultConfigPtr()->GetSetting<std::string>(configGroup.toStdString(), configKey.toStdString()).c_str()); configKey = QString("rex_server"); realXtend_server_ = QString(framework_->GetDefaultConfigPtr()->GetSetting<std::string>(configGroup.toStdString(), configKey.toStdString()).c_str()); configKey = QString("server"); value = QString(framework_->GetDefaultConfigPtr()->GetSetting<std::string>(configGroup.toStdString(), configKey.toStdString()).c_str()); lineEdit_worldAddress_->setText(value); opensim_server_ = value; configKey = QString("auth_server"); value = QString(framework_->GetDefaultConfigPtr()->GetSetting<std::string>(configGroup.toStdString(), configKey.toStdString()).c_str()); lineEdit_authAddress_->setText(value); realXtend_authserver_ = value; } void NaaliUI::ShowSelectedMode() { bool hide = false; if (radioButton_openSim_->isChecked() == true) { hide = false; if (lineEdit_username_->text() == realXtend_username_) lineEdit_username_->setText(opensim_username_); if (lineEdit_worldAddress_->text() == realXtend_server_) lineEdit_worldAddress_->setText(opensim_server_); } else if (radioButton_realXtend_->isChecked() == true) { hide = true; if (lineEdit_username_->text() == opensim_username_) lineEdit_username_->setText(realXtend_username_); if (lineEdit_worldAddress_->text() == opensim_server_) lineEdit_worldAddress_->setText(realXtend_server_); } label_authAddress_->setVisible(hide); lineEdit_authAddress_->setVisible(hide); lineEdit_password_->clear(); } void NaaliUI::ParseInputAndConnect() { if ( !lineEdit_worldAddress_->text().isEmpty() && !lineEdit_username_->text().isEmpty() && !lineEdit_password_->text().isEmpty() ) { QMap<QString, QString> map; map["WorldAddress"] = lineEdit_worldAddress_->text(); map["Username"] = lineEdit_username_->text(); map["Password"] = lineEdit_password_->text(); if (radioButton_openSim_->isChecked() == true) { emit( ConnectOpenSim(map) ); } else if (radioButton_realXtend_->isChecked() == true && !lineEdit_authAddress_->text().isEmpty() ) { map["AuthenticationAddress"] = lineEdit_authAddress_->text(); emit( ConnectRealXtend(map) ); } } } ///////////////////////////////////////// // WebUI CLASS ///////////////////////////////////////// WebUI::WebUI(QWidget *parent, Login *controller, Foundation::Framework *framework, RexLogicModule *rexLogic) : AbstractLoginUI(parent, controller, framework, rexLogic) { SetLayout(); SetLoginHandler(); InitWidget(); } WebUI::~WebUI() { delete loginHandler_; } void WebUI::SetLoginHandler() { loginHandler_ = new TaigaLoginHandler(framework_, rexLogicModule_); QObject::connect(loginHandler_, SIGNAL( LoginDone(bool) ), this, SLOT( LoginDone(bool) )); } void WebUI::InitWidget() { QFile confFile("./data/default_login.ini"); if (!confFile.open(QIODevice::ReadOnly | QIODevice::Text)) return; QString url(confFile.readLine()); confFile.close(); webLogin_ = new RexWebLogin(this, url); QObject::connect(webLogin_, SIGNAL( WebLoginInfoRecieved(QWebFrame *) ), loginHandler_, SLOT( ProcessWebLogin(QWebFrame *) )); this->layout()->addWidget(webLogin_); } }
/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ //MITK #include "mitkTestingMacros.h" #include "mitkRenderingTestHelper.h" //VTK #include <vtkRegressionTestImage.h> #include <mitkTransferFunctionProperty.h> #include <mitkTransferFunction.h> int mitkImageVtkMapper2DTransferFunctionTest(int argc, char* argv[]) { // load all arguments into a datastorage, take last argument as reference rendering // setup a renderwindow of fixed size X*Y // render the datastorage // compare rendering to reference image MITK_TEST_BEGIN("mitkImageVtkMapper2DTransferFunctionTest") // enough parameters? if ( argc < 2 ) { MITK_TEST_OUTPUT( << "Usage: " << std::string(*argv) << " [file1 file2 ...] outputfile" ) MITK_TEST_OUTPUT( << "Will render a central axial slice of all given files into outputfile" ) exit( EXIT_SUCCESS ); } mitkRenderingTestHelper renderingHelper(640, 480, argc, argv); //define an arbitrary colortransferfunction vtkSmartPointer<vtkColorTransferFunction> colorTransferFunction = vtkSmartPointer<vtkColorTransferFunction>::New(); colorTransferFunction->SetColorSpaceToRGB(); colorTransferFunction->AddRGBPoint(0.0, 1, 0, 0); //black = red colorTransferFunction->AddRGBPoint(127.5, 0, 1, 0); //grey = green colorTransferFunction->AddRGBPoint(255.0, 0, 0, 1); //white = blue mitk::TransferFunction::Pointer transferFucntion = mitk::TransferFunction::New(); transferFucntion->SetColorTransferFunction( colorTransferFunction ); //set the property for the image renderingHelper.SetImageProperty("Image Rendering.Transfer Function", mitk::TransferFunctionProperty::New(transferFucntion)); renderingHelper.Render(); //use this to generate a reference screenshot or save the file: bool generateReferenceScreenshot = false; if(generateReferenceScreenshot) { renderingHelper.SaveAsPNG("/home/kilgus/Pictures/RenderingTestData/output.png"); } //### Usage of vtkRegressionTestImage: //vtkRegressionTestImage( vtkRenderWindow ) //Set a vtkRenderWindow containing the desired scene. //vtkRegressionTestImage automatically searches in argc and argv[] //for a path a valid image with -V. If the test failed with the //first image (foo.png) check if there are images of the form //foo_N.png (where N=1,2,3...) and compare against them. renderingHelper.PrepareRender(); int retVal = vtkRegressionTestImage( renderingHelper.GetVtkRenderWindow() ); //retVal meanings: (see VTK/Rendering/vtkTesting.h) //0 = test failed //1 = test passed //2 = test not run //3 = something with vtkInteraction MITK_TEST_CONDITION( retVal == 1, "VTK test result positive" ); MITK_TEST_END(); } COMP: doubling tolerance threshold for issues on windows. /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ //MITK #include "mitkTestingMacros.h" #include "mitkRenderingTestHelper.h" //VTK #include <vtkRegressionTestImage.h> #include <mitkTransferFunctionProperty.h> #include <mitkTransferFunction.h> int mitkImageVtkMapper2DTransferFunctionTest(int argc, char* argv[]) { // load all arguments into a datastorage, take last argument as reference rendering // setup a renderwindow of fixed size X*Y // render the datastorage // compare rendering to reference image MITK_TEST_BEGIN("mitkImageVtkMapper2DTransferFunctionTest") // enough parameters? if ( argc < 2 ) { MITK_TEST_OUTPUT( << "Usage: " << std::string(*argv) << " [file1 file2 ...] outputfile" ) MITK_TEST_OUTPUT( << "Will render a central axial slice of all given files into outputfile" ) exit( EXIT_SUCCESS ); } mitkRenderingTestHelper renderingHelper(640, 480, argc, argv); //define an arbitrary colortransferfunction vtkSmartPointer<vtkColorTransferFunction> colorTransferFunction = vtkSmartPointer<vtkColorTransferFunction>::New(); colorTransferFunction->SetColorSpaceToRGB(); colorTransferFunction->AddRGBPoint(0.0, 1, 0, 0); //black = red colorTransferFunction->AddRGBPoint(127.5, 0, 1, 0); //grey = green colorTransferFunction->AddRGBPoint(255.0, 0, 0, 1); //white = blue mitk::TransferFunction::Pointer transferFucntion = mitk::TransferFunction::New(); transferFucntion->SetColorTransferFunction( colorTransferFunction ); //set the property for the image renderingHelper.SetImageProperty("Image Rendering.Transfer Function", mitk::TransferFunctionProperty::New(transferFucntion)); renderingHelper.Render(); //use this to generate a reference screenshot or save the file: bool generateReferenceScreenshot = false; if(generateReferenceScreenshot) { renderingHelper.SaveAsPNG("/home/kilgus/Pictures/RenderingTestData/output.png"); } renderingHelper.PrepareRender(); //### Usage of vtkRegressionTestImage: //vtkRegressionTestImage( vtkRenderWindow ) //Set a vtkRenderWindow containing the desired scene. //vtkRegressionTestImage automatically searches in argc and argv[] //for a path a valid image with -V. If the test failed with the //first image (foo.png) check if there are images of the form //foo_N.png (where N=1,2,3...) and compare against them. //Default tolerance for rendering tests is 10 (set by VTK). //For this case, small artifacts in Windows occur and boundaries of the fonts, //thus we double the default tolerance threshold and set it to 20. int retVal = vtkTesting::Test(argc, argv, renderingHelper.GetVtkRenderWindow(), 20 ); //retVal meanings: (see VTK/Rendering/vtkTesting.h) //0 = test failed //1 = test passed //2 = test not run //3 = something with vtkInteraction MITK_TEST_CONDITION( retVal == 1, "VTK test result positive" ); MITK_TEST_END(); }
/* -------------------------------------------------------------------------- * * OpenSim: Coordinate.cpp * * -------------------------------------------------------------------------- * * The OpenSim API is a toolkit for musculoskeletal modeling and simulation. * * See http://opensim.stanford.edu and the NOTICE file for more information. * * OpenSim is developed at Stanford University and supported by the US * * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA * * through the Warrior Web program. * * * * Author(s): Ajay Seth, Michael A. Sherman, Ayman Habib * * Contributor(s): Frank C. Anderson, Jeffrey A. Reinbolt * * * * Licensed under the Apache License, Version 2.0 (the "License"); you may * * not use this file except in compliance with the License. You may obtain a * * copy of the License at http://www.apache.org/licenses/LICENSE-2.0. * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * * -------------------------------------------------------------------------- */ //============================================================================= // INCLUDES //============================================================================= #include "Coordinate.h" #include "CoordinateCouplerConstraint.h" #include <OpenSim/Common/IO.h> #include <OpenSim/Common/Function.h> #include <OpenSim/Simulation/Model/Model.h> #include <OpenSim/Simulation/SimbodyEngine/Joint.h> #include <memory> //============================================================================= // STATICS //============================================================================= using namespace std; using namespace SimTK; using namespace OpenSim; /** @cond **/ // hide from Doxygen /** * A Constant Function whose value is modifiable. */ class ModifiableConstant : public SimTK::Function_<SimTK::Real>{ public: ModifiableConstant(const SimTK::Real& value, int argumentSize) : value(value), argumentSize(argumentSize) { } ModifiableConstant* clone() const override { return new ModifiableConstant(this->value, this->argumentSize); } SimTK::Real calcValue(const SimTK::Vector& x) const override { assert(x.size() == argumentSize); return value; } SimTK::Real calcDerivative(const std::vector<int>& derivComponents, const SimTK::Vector& x) const { return calcDerivative(SimTK::ArrayViewConst_<int>(derivComponents),x); } SimTK::Real calcDerivative(const SimTK::Array_<int>& derivComponents, const SimTK::Vector& x) const override { return 0; } int getArgumentSize() const override { return argumentSize; } int getMaxDerivativeOrder() const override { return std::numeric_limits<int>::max(); } void setValue(SimTK::Real newValue){ value = newValue; } private: const int argumentSize; SimTK::Real value; }; /** @endcond **/ //============================================================================= // CONSTRUCTOR(S) AND DESTRUCTOR //============================================================================= //_____________________________________________________________________________ /** * Default constructor. */ Coordinate::Coordinate() { constructInfrastructure(); } //_____________________________________________________________________________ /** * Constructor. */ Coordinate::Coordinate(const std::string &aName, MotionType aMotionType, double defaultValue, double aRangeMin, double aRangeMax) : Coordinate() { setName(aName); setMotionType(aMotionType); setDefaultValue(defaultValue); setRangeMin(aRangeMin); setRangeMax(aRangeMax); } //_____________________________________________________________________________ /** * Connect properties to local pointers. */ void Coordinate::constructProperties(void) { setAuthors("Ajay Seth, Ayman Habib, Michael Sherman"); //The motion type of a Coordinate is determined by its parent Joint constructProperty_motion_type("set_by_joint"); constructProperty_default_value(0.0); constructProperty_default_speed_value(0.0); Array<double> defaultRange(-10.0, 2); //twp values in range defaultRange[1] = 10.0; // second value in range is 10.0 constructProperty_range(defaultRange); constructProperty_clamped(false); constructProperty_locked(false); constructProperty_prescribed_function(); constructProperty_prescribed(false); constructProperty_is_free_to_satisfy_constraints(false); } //_____________________________________________________________________________ /* * Perform some set up functions that happen after the * object has been deserialized or copied. * */ void Coordinate::extendFinalizeFromProperties() { Super::extendFinalizeFromProperties(); string prefix = "Coordinate("+getName()+")::extendFinalizeFromProperties: "; // Make sure the default value is within the range when clamped if (get_clamped()){ // Make sure the range is min to max. SimTK_ERRCHK_ALWAYS(get_range(0) <= get_range(1), prefix.c_str(), "Maximum coordinate range less than minimum."); double dv = get_default_value(); SimTK_ERRCHK2_ALWAYS(dv > (get_range(0) - SimTK::SqrtEps), prefix.c_str(), "Default coordinate value is less than range minimum.\n" "Default value = %d < min = %d.", dv, get_range(0)); SimTK_ERRCHK2_ALWAYS(dv < (get_range(1) + SimTK::SqrtEps), prefix.c_str(), "Default coordinate value is greater than range maximum.\n" "Default value = %d > max = %d.", dv, get_range(1)); } _lockedWarningGiven=false; _speedName = getName() + "/speed"; } void Coordinate::extendAddToSystem(SimTK::MultibodySystem& system) const { Super::extendAddToSystem(system); // Make this modifiable temporarily so we can record information needed // to later access our pieces of the SimTK::MultibodySystem. That info is // const after the system has been built. Coordinate* mutableThis = const_cast<Coordinate *>(this); // Define the locked value for the constraint as a function. // The PrescribedMotion will take ownership, but we'll keep a reference // pointer here to allow for later modification. std::unique_ptr<ModifiableConstant> funcOwner(new ModifiableConstant(get_default_value(), 1)); mutableThis->_lockFunction = funcOwner.get(); // The underlying SimTK constraint SimTK::Constraint::PrescribedMotion lock(system.updMatterSubsystem(), funcOwner.release(), // give up ownership _bodyIndex, SimTK::MobilizerQIndex(_mobilizerQIndex)); // Save the index so we can access the SimTK::Constraint later mutableThis->_lockedConstraintIndex = lock.getConstraintIndex(); if(!getProperty_prescribed_function().empty()){ //create prescribed motion constraint automatically SimTK::Constraint::PrescribedMotion prescribe( _model->updMatterSubsystem(), get_prescribed_function().createSimTKFunction(), _bodyIndex, SimTK::MobilizerQIndex(_mobilizerQIndex)); mutableThis->_prescribedConstraintIndex = prescribe.getConstraintIndex(); } else{ // even if prescribed is set to true, if there is no prescribed // function defined, then it cannot be prescribed. mutableThis->upd_prescribed() = false; } //TODO add clamping addModelingOption("is_clamped", 1); SimTK::SubsystemIndex sbsix = getModel().getMatterSubsystem().getMySubsystemIndex(); //Expose coordinate state variable CoordinateStateVariable* csv = new CoordinateStateVariable("value", *this, sbsix, _mobilizerQIndex ); addStateVariable(csv); //Expose coordinate's speed state variable SpeedStateVariable* ssv = new SpeedStateVariable("speed", *this, sbsix, _mobilizerQIndex); addStateVariable(ssv); } void Coordinate::extendRealizeInstance(const SimTK::State& state) const { const MobilizedBody& mb = getModel().getMatterSubsystem().getMobilizedBody(_bodyIndex); int uix = state.getUStart() + mb.getFirstUIndex(state) + _mobilizerQIndex; /* Set the YIndex on the StateVariable */ } void Coordinate::extendInitStateFromProperties(State& s) const { // Cannot enforce the constraint, since state of constraints may still be undefined const MobilizedBody& mb=_model->getMatterSubsystem().getMobilizedBody(_bodyIndex); int nq=mb.getNumQ(s); if (_mobilizerQIndex>=nq){ //Something is wrong/inconsistent with model definition. Abort throw(Exception("Coordinate: "+getName()+" is not consistent with owner Joint. Aborting.")); } _model->getMatterSubsystem().getMobilizedBody(_bodyIndex) .setOneQ(s,_mobilizerQIndex,get_default_value()); _model->getMatterSubsystem().getMobilizedBody(_bodyIndex) .setOneU(s,_mobilizerQIndex,get_default_speed_value()); setIsPrescribed(s, get_prescribed()); setClamped(s, get_clamped()); // Locking takes precedence if all joint constraints are ON setLocked(s, get_locked()); } void Coordinate::extendSetPropertiesFromState(const SimTK::State& state) { upd_default_value() = _model->getMatterSubsystem().getMobilizedBody(_bodyIndex).getOneQ(state,_mobilizerQIndex); upd_default_speed_value() = _model->getMatterSubsystem().getMobilizedBody(_bodyIndex).getOneU(state,_mobilizerQIndex); upd_prescribed() = isPrescribed(state); upd_clamped() = getClamped(state); upd_locked() = getLocked(state); } //============================================================================= // GET AND SET //============================================================================= //----------------------------------------------------------------------------- // JOINT //----------------------------------------------------------------------------- //_____________________________________________________________________________ /** * Set the joint to which this coordinate belongs. * * @param aowningJoint Joint to which this coordinate belongs. */ void Coordinate::setJoint(const Joint& aOwningJoint) { _joint = &aOwningJoint; } //_____________________________________________________________________________ /** * Get the joint to which this coordinate belongs. * * @return Joint to which this coordinate belongs. */ const Joint& Coordinate::getJoint() const { return(_joint.getRef()); } //----------------------------------------------------------------------------- // VALUE //----------------------------------------------------------------------------- //done_____________________________________________________________________________ /** * Get the value. * * @return The current value of the coordinate. */ double Coordinate::getValue(const SimTK::State& s) const { return _model->getMatterSubsystem().getMobilizedBody(_bodyIndex).getOneQ(s,_mobilizerQIndex); } //done_____________________________________________________________________________ /** * Set the value. * * @param aValue value to change to. */ void Coordinate::setValue(SimTK::State& s, double aValue , bool enforceConstraints) const { // If the coordinate is clamped, pull aValue into range. if (getClamped(s)) { if (aValue < get_range(0)) aValue = get_range(0); else if (aValue > get_range(1)) aValue = get_range(1); } // If the coordinate is locked and aValue is not the current value, print an error. // Otherwise, set the value to aValue. if (getLocked(s)) { if (aValue != getValue(s) && !_lockedWarningGiven){ cout<<"Coordinate.setValue: WARN- coordinate "<<getName()<<" is locked. Unable to change its value." << endl; _lockedWarningGiven=true; } } else { _model->updMatterSubsystem().getMobilizedBody(_bodyIndex).setOneQ(s,_mobilizerQIndex,aValue); } // The Q that was set might not satisfy constraints, so if enforceConstraints then call model assemble. // You want to do this even if the coordinate is locked and its value hasn't changed, because this may be // the last setValue() call in a string of them (e.g., to set a model pose), in which case you only try to // enforce constraints during the last call. if (enforceConstraints) { if (_model->getConstraintSet().getSize()>0 || isConstrained(s)){ // if this coordinate is set up to be dependent on other coordinates // its value should be dictated by the other coordinates and not its present value double weight = isDependent(s) ? 0.0 : 10; // assemble model so that states satisfy ALL constraints _model->assemble(s, this, weight); } else _model->getMultibodySystem().realize(s, Stage::Position ); } } double Coordinate::getSpeedValue(const SimTK::State& s) const { return _model->getMatterSubsystem().getMobilizedBody(_bodyIndex).getOneU(s,_mobilizerQIndex); } void Coordinate::setSpeedValue(SimTK::State& s, double aValue) const { _model->updMatterSubsystem().getMobilizedBody(_bodyIndex).setOneU(s,_mobilizerQIndex,aValue); } const std::string& Coordinate::getSpeedName() const { return _speedName; } double Coordinate::getAccelerationValue(const SimTK::State& s) const { return getModel().getMatterSubsystem().getMobilizedBody(_bodyIndex).getOneUDot(s, _mobilizerQIndex); } //_____________________________________________________________________________ /** * Set the range min and max. * * @param aRange range min and man to change to. * @return Whether or not the range was changed. */ void Coordinate::setRange(double aRange[2]) { if (aRange[1] >= aRange[0]) { upd_range(0) = aRange[0]; upd_range(1) = aRange[1]; } else throw Exception("Coordinate::setRange, range is invalid, " "min range value exceeds max."); } //_____________________________________________________________________________ /** * Set the range min. * * @param aRange range min to change to. * @return Whether or not the range min was changed. */ void Coordinate::setRangeMin(double aMin) { upd_range(0) = aMin; } //_____________________________________________________________________________ /** * Set the range max. * * @param aRange range max to change to. * @return Whether or not the range max was changed. */ void Coordinate::setRangeMax(double aMax) { upd_range(1) = aMax; } //_____________________________________________________________________________ /** * Set coordinate's motion type. * */ void Coordinate::setMotionType(MotionType motionType) { if (_motionType == motionType) { return; } _motionType = motionType; //Also update the motionTypeName so that it is serialized with the model switch(motionType){ case(Rotational) : //upd_motion_type() = "rotational"; break; case(Translational) : //upd_motion_type() = "translational"; break; case(Coupled) : //upd_motion_type() = "coupled"; break; default : throw(Exception("Coordinate: Attempting to specify an undefined motion type.")); } } //_____________________________________________________________________________ /** * Set the default value. * * @param aDefaultValue new default value to change to. */ void Coordinate::setDefaultValue(double aDefaultValue) { upd_default_value() = aDefaultValue; } //_____________________________________________________________________________ /** * Get the prescribed motion function. * * @return const reference to the prescribed motion function. */ const OpenSim::Function& Coordinate::getPrescribedFunction() const { return get_prescribed_function(); } //_____________________________________________________________________________ /** * Set the prescribed motion function. */ void Coordinate::setPrescribedFunction(const OpenSim::Function& function) { //Optional property so clear out previous function value if any updProperty_prescribed_function().clear(); updProperty_prescribed_function().adoptAndAppendValue(function.clone()); } //_____________________________________________________________________________ /** * Determine if the coordinate is dependent on other coordinates or not, * by checking to see whether there is a CoordinateCouplerConstraint relating * it to another coordinate. If so return true, false otherwise. * TODO: note that this will fail to detect any other kind of constraint that * might couple coordinates together. */ bool Coordinate::isDependent(const SimTK::State& s) const { if(get_is_free_to_satisfy_constraints()) return true; for(int i=0; i<_model->getConstraintSet().getSize(); i++){ Constraint& constraint = _model->getConstraintSet().get(i); CoordinateCouplerConstraint* couplerp = dynamic_cast<CoordinateCouplerConstraint*>(&constraint); if(couplerp) { if (couplerp->getDependentCoordinateName() == getName()) return !couplerp->isDisabled(s); } } return false; } //_____________________________________________________________________________ /** * Determine if the coordinate is constrained or not. * Specifically, is locked, prescribed, or completely dependent on other coordinates? * If so return true, false otherwise. */ bool Coordinate::isConstrained(const SimTK::State& s) const { return (getLocked(s) || isPrescribed(s) || isDependent(s)); } //----------------------------------------------------------------------------- // LOCK //----------------------------------------------------------------------------- //_____________________________________________________________________________ /** * Set whether or not this coordinate is locked. * A prescribed constraint is used to lock the joint at the dynamics level. * If lock is applied after clamping or prescribed motion it takes precedence. * * @param aLocked If true the joint is locked; if false the joint is unlocked. */ void Coordinate::setLocked(SimTK::State& s, bool aLocked) const { // Do nothing if the same, but make sure _locked is also up-to-date if(aLocked == getLocked(s)){ return; } _lockedWarningGiven=false; // reset flag in case needed later SimTK::Constraint *lock = NULL; // Get constraint if(_lockedConstraintIndex.isValid()){ lock = &_model->updMultibodySystem().updMatterSubsystem().updConstraint(_lockedConstraintIndex); } else{ string msg = "Lock constraint for coordinate could not be found."; throw Exception(msg,__FILE__,__LINE__); } // Now enable if locked otherwise disable if(aLocked){ // Update the locked value of the constraint before locking _lockFunction->setValue(getValue(s)); lock->enable(s); //Cannot be locked and have prescribed motion and/or clamping setIsPrescribed(s, false); } else { lock->disable(s); } } /** * Get whether or not this coordinate is locked. * Calls the underlying constraint at the dynamics level. * * @return true if the coordinate is locked and false if unlocked. */ bool Coordinate::getLocked(const SimTK::State& s) const { if(_lockedConstraintIndex.isValid()){ bool disabled = _model->updMultibodySystem().updMatterSubsystem().getConstraint(_lockedConstraintIndex).isDisabled(s); return !disabled; } else{ return get_locked(); } } //----------------------------------------------------------------------------- // PRESCRIBED MOTION //----------------------------------------------------------------------------- //_____________________________________________________________________________ /** * Set whether or not this coordinate is being prescribed. * A prescribed constraint is used specify motion at the dynamics level. * If isPrescribed is set after clamping or locking it takes precedence- * and clamped and locked are false. * * @param isPrescribed If true the coordinate is prescribed; if false not prescribed. */ void Coordinate::setIsPrescribed(SimTK::State& s, bool isPrescribed) const { // Do nothing if the same if(isPrescribed == this->isPrescribed(s) ) return; // The underlying SimTK constraint SimTK::Constraint *prescribe = NULL; // Get constraint if(_prescribedConstraintIndex.isValid()){ //get constraint prescribe = &_model->updMultibodySystem().updMatterSubsystem().updConstraint(_prescribedConstraintIndex); } else{ string msg = "Prescribed motion for coordinate not found."; throw Exception(msg,__FILE__,__LINE__); } // Now enable if prescribed motion constraint otherwise disable if(isPrescribed){ prescribe->enable(s); setLocked(s, false); } else prescribe->disable(s); } bool Coordinate::isPrescribed(const SimTK::State& s) const { if(_prescribedConstraintIndex.isValid()){ bool disabled = _model->updMultibodySystem().updMatterSubsystem().getConstraint(_prescribedConstraintIndex).isDisabled(s); return !disabled; } else{ return get_prescribed(); } } //----------------------------------------------------------------------------- // CLAMP //----------------------------------------------------------------------------- //_____________________________________________________________________________ bool Coordinate::getClamped(const SimTK::State& s) const { return getModelingOption(s, "is_clamped") > 0; } void Coordinate::setClamped(SimTK::State& s, bool aLocked) const { setModelingOption(s, "is_clamped", (int)aLocked); } //----------------------------------------------------------------------------- // Coordinate::CoordinateStateVariable //----------------------------------------------------------------------------- double Coordinate::CoordinateStateVariable:: getValue(const SimTK::State& state) const { return ((Coordinate *)&getOwner())->getValue(state); } void Coordinate::CoordinateStateVariable:: setValue(SimTK::State& state, double value) const { ((Coordinate *)&getOwner())->setValue(state, value); } double Coordinate::CoordinateStateVariable:: getDerivative(const SimTK::State& state) const { //TODO: update to get qdot value from the mobilized body return ((Coordinate *)&getOwner())->getSpeedValue(state); } void Coordinate::CoordinateStateVariable:: setDerivative(const SimTK::State& state, double deriv) const { string msg = "CoordinateStateVariable::setDerivative() - ERROR \n"; msg += "Coordinate derivative (qdot) is computed by the Multibody system."; throw Exception(msg); } //----------------------------------------------------------------------------- // Coordinate::SpeedStateVariable //----------------------------------------------------------------------------- double Coordinate::SpeedStateVariable:: getValue(const SimTK::State& state) const { //TODO: update to get qdot value from the mobilized body return ((Coordinate *)&getOwner())->getSpeedValue(state); } void Coordinate::SpeedStateVariable:: setValue(SimTK::State& state, double deriv) const { //TODO: update to set qdot value from the mobilized body ((Coordinate *)&getOwner())->setSpeedValue(state, deriv); } double Coordinate::SpeedStateVariable:: getDerivative(const SimTK::State& state) const { const Coordinate& owner = *((Coordinate *)&getOwner()); const MobilizedBody& mb = owner.getModel().getMatterSubsystem() .getMobilizedBody(owner.getBodyIndex()); return mb.getUDotAsVector(state)[owner.getMobilizerQIndex()]; } void Coordinate::SpeedStateVariable:: setDerivative(const SimTK::State& state, double deriv) const { string msg = "SpeedStateVariable::setDerivative() - ERROR \n"; msg += "Generalized speed derivative (udot) can only be set by the Multibody system."; throw Exception(msg); } Initialization order. Unused variable. /* -------------------------------------------------------------------------- * * OpenSim: Coordinate.cpp * * -------------------------------------------------------------------------- * * The OpenSim API is a toolkit for musculoskeletal modeling and simulation. * * See http://opensim.stanford.edu and the NOTICE file for more information. * * OpenSim is developed at Stanford University and supported by the US * * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA * * through the Warrior Web program. * * * * Author(s): Ajay Seth, Michael A. Sherman, Ayman Habib * * Contributor(s): Frank C. Anderson, Jeffrey A. Reinbolt * * * * Licensed under the Apache License, Version 2.0 (the "License"); you may * * not use this file except in compliance with the License. You may obtain a * * copy of the License at http://www.apache.org/licenses/LICENSE-2.0. * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * * -------------------------------------------------------------------------- */ //============================================================================= // INCLUDES //============================================================================= #include "Coordinate.h" #include "CoordinateCouplerConstraint.h" #include <OpenSim/Common/IO.h> #include <OpenSim/Common/Function.h> #include <OpenSim/Simulation/Model/Model.h> #include <OpenSim/Simulation/SimbodyEngine/Joint.h> #include <memory> //============================================================================= // STATICS //============================================================================= using namespace std; using namespace SimTK; using namespace OpenSim; /** @cond **/ // hide from Doxygen /** * A Constant Function whose value is modifiable. */ class ModifiableConstant : public SimTK::Function_<SimTK::Real>{ public: ModifiableConstant(const SimTK::Real& value, int argumentSize) : argumentSize(argumentSize), value(value) { } ModifiableConstant* clone() const override { return new ModifiableConstant(this->value, this->argumentSize); } SimTK::Real calcValue(const SimTK::Vector& x) const override { assert(x.size() == argumentSize); return value; } SimTK::Real calcDerivative(const std::vector<int>& derivComponents, const SimTK::Vector& x) const { return calcDerivative(SimTK::ArrayViewConst_<int>(derivComponents),x); } SimTK::Real calcDerivative(const SimTK::Array_<int>& derivComponents, const SimTK::Vector& x) const override { return 0; } int getArgumentSize() const override { return argumentSize; } int getMaxDerivativeOrder() const override { return std::numeric_limits<int>::max(); } void setValue(SimTK::Real newValue){ value = newValue; } private: const int argumentSize; SimTK::Real value; }; /** @endcond **/ //============================================================================= // CONSTRUCTOR(S) AND DESTRUCTOR //============================================================================= //_____________________________________________________________________________ /** * Default constructor. */ Coordinate::Coordinate() { constructInfrastructure(); } //_____________________________________________________________________________ /** * Constructor. */ Coordinate::Coordinate(const std::string &aName, MotionType aMotionType, double defaultValue, double aRangeMin, double aRangeMax) : Coordinate() { setName(aName); setMotionType(aMotionType); setDefaultValue(defaultValue); setRangeMin(aRangeMin); setRangeMax(aRangeMax); } //_____________________________________________________________________________ /** * Connect properties to local pointers. */ void Coordinate::constructProperties(void) { setAuthors("Ajay Seth, Ayman Habib, Michael Sherman"); //The motion type of a Coordinate is determined by its parent Joint constructProperty_motion_type("set_by_joint"); constructProperty_default_value(0.0); constructProperty_default_speed_value(0.0); Array<double> defaultRange(-10.0, 2); //twp values in range defaultRange[1] = 10.0; // second value in range is 10.0 constructProperty_range(defaultRange); constructProperty_clamped(false); constructProperty_locked(false); constructProperty_prescribed_function(); constructProperty_prescribed(false); constructProperty_is_free_to_satisfy_constraints(false); } //_____________________________________________________________________________ /* * Perform some set up functions that happen after the * object has been deserialized or copied. * */ void Coordinate::extendFinalizeFromProperties() { Super::extendFinalizeFromProperties(); string prefix = "Coordinate("+getName()+")::extendFinalizeFromProperties: "; // Make sure the default value is within the range when clamped if (get_clamped()){ // Make sure the range is min to max. SimTK_ERRCHK_ALWAYS(get_range(0) <= get_range(1), prefix.c_str(), "Maximum coordinate range less than minimum."); double dv = get_default_value(); SimTK_ERRCHK2_ALWAYS(dv > (get_range(0) - SimTK::SqrtEps), prefix.c_str(), "Default coordinate value is less than range minimum.\n" "Default value = %d < min = %d.", dv, get_range(0)); SimTK_ERRCHK2_ALWAYS(dv < (get_range(1) + SimTK::SqrtEps), prefix.c_str(), "Default coordinate value is greater than range maximum.\n" "Default value = %d > max = %d.", dv, get_range(1)); } _lockedWarningGiven=false; _speedName = getName() + "/speed"; } void Coordinate::extendAddToSystem(SimTK::MultibodySystem& system) const { Super::extendAddToSystem(system); // Make this modifiable temporarily so we can record information needed // to later access our pieces of the SimTK::MultibodySystem. That info is // const after the system has been built. Coordinate* mutableThis = const_cast<Coordinate *>(this); // Define the locked value for the constraint as a function. // The PrescribedMotion will take ownership, but we'll keep a reference // pointer here to allow for later modification. std::unique_ptr<ModifiableConstant> funcOwner(new ModifiableConstant(get_default_value(), 1)); mutableThis->_lockFunction = funcOwner.get(); // The underlying SimTK constraint SimTK::Constraint::PrescribedMotion lock(system.updMatterSubsystem(), funcOwner.release(), // give up ownership _bodyIndex, SimTK::MobilizerQIndex(_mobilizerQIndex)); // Save the index so we can access the SimTK::Constraint later mutableThis->_lockedConstraintIndex = lock.getConstraintIndex(); if(!getProperty_prescribed_function().empty()){ //create prescribed motion constraint automatically SimTK::Constraint::PrescribedMotion prescribe( _model->updMatterSubsystem(), get_prescribed_function().createSimTKFunction(), _bodyIndex, SimTK::MobilizerQIndex(_mobilizerQIndex)); mutableThis->_prescribedConstraintIndex = prescribe.getConstraintIndex(); } else{ // even if prescribed is set to true, if there is no prescribed // function defined, then it cannot be prescribed. mutableThis->upd_prescribed() = false; } //TODO add clamping addModelingOption("is_clamped", 1); SimTK::SubsystemIndex sbsix = getModel().getMatterSubsystem().getMySubsystemIndex(); //Expose coordinate state variable CoordinateStateVariable* csv = new CoordinateStateVariable("value", *this, sbsix, _mobilizerQIndex ); addStateVariable(csv); //Expose coordinate's speed state variable SpeedStateVariable* ssv = new SpeedStateVariable("speed", *this, sbsix, _mobilizerQIndex); addStateVariable(ssv); } void Coordinate::extendRealizeInstance(const SimTK::State& state) const { //const MobilizedBody& mb // = getModel().getMatterSubsystem().getMobilizedBody(_bodyIndex); //int uix = state.getUStart() + mb.getFirstUIndex(state) + _mobilizerQIndex; /* Set the YIndex on the StateVariable */ } void Coordinate::extendInitStateFromProperties(State& s) const { // Cannot enforce the constraint, since state of constraints may still be undefined const MobilizedBody& mb=_model->getMatterSubsystem().getMobilizedBody(_bodyIndex); int nq=mb.getNumQ(s); if (_mobilizerQIndex>=nq){ //Something is wrong/inconsistent with model definition. Abort throw(Exception("Coordinate: "+getName()+" is not consistent with owner Joint. Aborting.")); } _model->getMatterSubsystem().getMobilizedBody(_bodyIndex) .setOneQ(s,_mobilizerQIndex,get_default_value()); _model->getMatterSubsystem().getMobilizedBody(_bodyIndex) .setOneU(s,_mobilizerQIndex,get_default_speed_value()); setIsPrescribed(s, get_prescribed()); setClamped(s, get_clamped()); // Locking takes precedence if all joint constraints are ON setLocked(s, get_locked()); } void Coordinate::extendSetPropertiesFromState(const SimTK::State& state) { upd_default_value() = _model->getMatterSubsystem().getMobilizedBody(_bodyIndex).getOneQ(state,_mobilizerQIndex); upd_default_speed_value() = _model->getMatterSubsystem().getMobilizedBody(_bodyIndex).getOneU(state,_mobilizerQIndex); upd_prescribed() = isPrescribed(state); upd_clamped() = getClamped(state); upd_locked() = getLocked(state); } //============================================================================= // GET AND SET //============================================================================= //----------------------------------------------------------------------------- // JOINT //----------------------------------------------------------------------------- //_____________________________________________________________________________ /** * Set the joint to which this coordinate belongs. * * @param aowningJoint Joint to which this coordinate belongs. */ void Coordinate::setJoint(const Joint& aOwningJoint) { _joint = &aOwningJoint; } //_____________________________________________________________________________ /** * Get the joint to which this coordinate belongs. * * @return Joint to which this coordinate belongs. */ const Joint& Coordinate::getJoint() const { return(_joint.getRef()); } //----------------------------------------------------------------------------- // VALUE //----------------------------------------------------------------------------- //done_____________________________________________________________________________ /** * Get the value. * * @return The current value of the coordinate. */ double Coordinate::getValue(const SimTK::State& s) const { return _model->getMatterSubsystem().getMobilizedBody(_bodyIndex).getOneQ(s,_mobilizerQIndex); } //done_____________________________________________________________________________ /** * Set the value. * * @param aValue value to change to. */ void Coordinate::setValue(SimTK::State& s, double aValue , bool enforceConstraints) const { // If the coordinate is clamped, pull aValue into range. if (getClamped(s)) { if (aValue < get_range(0)) aValue = get_range(0); else if (aValue > get_range(1)) aValue = get_range(1); } // If the coordinate is locked and aValue is not the current value, print an error. // Otherwise, set the value to aValue. if (getLocked(s)) { if (aValue != getValue(s) && !_lockedWarningGiven){ cout<<"Coordinate.setValue: WARN- coordinate "<<getName()<<" is locked. Unable to change its value." << endl; _lockedWarningGiven=true; } } else { _model->updMatterSubsystem().getMobilizedBody(_bodyIndex).setOneQ(s,_mobilizerQIndex,aValue); } // The Q that was set might not satisfy constraints, so if enforceConstraints then call model assemble. // You want to do this even if the coordinate is locked and its value hasn't changed, because this may be // the last setValue() call in a string of them (e.g., to set a model pose), in which case you only try to // enforce constraints during the last call. if (enforceConstraints) { if (_model->getConstraintSet().getSize()>0 || isConstrained(s)){ // if this coordinate is set up to be dependent on other coordinates // its value should be dictated by the other coordinates and not its present value double weight = isDependent(s) ? 0.0 : 10; // assemble model so that states satisfy ALL constraints _model->assemble(s, this, weight); } else _model->getMultibodySystem().realize(s, Stage::Position ); } } double Coordinate::getSpeedValue(const SimTK::State& s) const { return _model->getMatterSubsystem().getMobilizedBody(_bodyIndex).getOneU(s,_mobilizerQIndex); } void Coordinate::setSpeedValue(SimTK::State& s, double aValue) const { _model->updMatterSubsystem().getMobilizedBody(_bodyIndex).setOneU(s,_mobilizerQIndex,aValue); } const std::string& Coordinate::getSpeedName() const { return _speedName; } double Coordinate::getAccelerationValue(const SimTK::State& s) const { return getModel().getMatterSubsystem().getMobilizedBody(_bodyIndex).getOneUDot(s, _mobilizerQIndex); } //_____________________________________________________________________________ /** * Set the range min and max. * * @param aRange range min and man to change to. * @return Whether or not the range was changed. */ void Coordinate::setRange(double aRange[2]) { if (aRange[1] >= aRange[0]) { upd_range(0) = aRange[0]; upd_range(1) = aRange[1]; } else throw Exception("Coordinate::setRange, range is invalid, " "min range value exceeds max."); } //_____________________________________________________________________________ /** * Set the range min. * * @param aRange range min to change to. * @return Whether or not the range min was changed. */ void Coordinate::setRangeMin(double aMin) { upd_range(0) = aMin; } //_____________________________________________________________________________ /** * Set the range max. * * @param aRange range max to change to. * @return Whether or not the range max was changed. */ void Coordinate::setRangeMax(double aMax) { upd_range(1) = aMax; } //_____________________________________________________________________________ /** * Set coordinate's motion type. * */ void Coordinate::setMotionType(MotionType motionType) { if (_motionType == motionType) { return; } _motionType = motionType; //Also update the motionTypeName so that it is serialized with the model switch(motionType){ case(Rotational) : //upd_motion_type() = "rotational"; break; case(Translational) : //upd_motion_type() = "translational"; break; case(Coupled) : //upd_motion_type() = "coupled"; break; default : throw(Exception("Coordinate: Attempting to specify an undefined motion type.")); } } //_____________________________________________________________________________ /** * Set the default value. * * @param aDefaultValue new default value to change to. */ void Coordinate::setDefaultValue(double aDefaultValue) { upd_default_value() = aDefaultValue; } //_____________________________________________________________________________ /** * Get the prescribed motion function. * * @return const reference to the prescribed motion function. */ const OpenSim::Function& Coordinate::getPrescribedFunction() const { return get_prescribed_function(); } //_____________________________________________________________________________ /** * Set the prescribed motion function. */ void Coordinate::setPrescribedFunction(const OpenSim::Function& function) { //Optional property so clear out previous function value if any updProperty_prescribed_function().clear(); updProperty_prescribed_function().adoptAndAppendValue(function.clone()); } //_____________________________________________________________________________ /** * Determine if the coordinate is dependent on other coordinates or not, * by checking to see whether there is a CoordinateCouplerConstraint relating * it to another coordinate. If so return true, false otherwise. * TODO: note that this will fail to detect any other kind of constraint that * might couple coordinates together. */ bool Coordinate::isDependent(const SimTK::State& s) const { if(get_is_free_to_satisfy_constraints()) return true; for(int i=0; i<_model->getConstraintSet().getSize(); i++){ Constraint& constraint = _model->getConstraintSet().get(i); CoordinateCouplerConstraint* couplerp = dynamic_cast<CoordinateCouplerConstraint*>(&constraint); if(couplerp) { if (couplerp->getDependentCoordinateName() == getName()) return !couplerp->isDisabled(s); } } return false; } //_____________________________________________________________________________ /** * Determine if the coordinate is constrained or not. * Specifically, is locked, prescribed, or completely dependent on other coordinates? * If so return true, false otherwise. */ bool Coordinate::isConstrained(const SimTK::State& s) const { return (getLocked(s) || isPrescribed(s) || isDependent(s)); } //----------------------------------------------------------------------------- // LOCK //----------------------------------------------------------------------------- //_____________________________________________________________________________ /** * Set whether or not this coordinate is locked. * A prescribed constraint is used to lock the joint at the dynamics level. * If lock is applied after clamping or prescribed motion it takes precedence. * * @param aLocked If true the joint is locked; if false the joint is unlocked. */ void Coordinate::setLocked(SimTK::State& s, bool aLocked) const { // Do nothing if the same, but make sure _locked is also up-to-date if(aLocked == getLocked(s)){ return; } _lockedWarningGiven=false; // reset flag in case needed later SimTK::Constraint *lock = NULL; // Get constraint if(_lockedConstraintIndex.isValid()){ lock = &_model->updMultibodySystem().updMatterSubsystem().updConstraint(_lockedConstraintIndex); } else{ string msg = "Lock constraint for coordinate could not be found."; throw Exception(msg,__FILE__,__LINE__); } // Now enable if locked otherwise disable if(aLocked){ // Update the locked value of the constraint before locking _lockFunction->setValue(getValue(s)); lock->enable(s); //Cannot be locked and have prescribed motion and/or clamping setIsPrescribed(s, false); } else { lock->disable(s); } } /** * Get whether or not this coordinate is locked. * Calls the underlying constraint at the dynamics level. * * @return true if the coordinate is locked and false if unlocked. */ bool Coordinate::getLocked(const SimTK::State& s) const { if(_lockedConstraintIndex.isValid()){ bool disabled = _model->updMultibodySystem().updMatterSubsystem().getConstraint(_lockedConstraintIndex).isDisabled(s); return !disabled; } else{ return get_locked(); } } //----------------------------------------------------------------------------- // PRESCRIBED MOTION //----------------------------------------------------------------------------- //_____________________________________________________________________________ /** * Set whether or not this coordinate is being prescribed. * A prescribed constraint is used specify motion at the dynamics level. * If isPrescribed is set after clamping or locking it takes precedence- * and clamped and locked are false. * * @param isPrescribed If true the coordinate is prescribed; if false not prescribed. */ void Coordinate::setIsPrescribed(SimTK::State& s, bool isPrescribed) const { // Do nothing if the same if(isPrescribed == this->isPrescribed(s) ) return; // The underlying SimTK constraint SimTK::Constraint *prescribe = NULL; // Get constraint if(_prescribedConstraintIndex.isValid()){ //get constraint prescribe = &_model->updMultibodySystem().updMatterSubsystem().updConstraint(_prescribedConstraintIndex); } else{ string msg = "Prescribed motion for coordinate not found."; throw Exception(msg,__FILE__,__LINE__); } // Now enable if prescribed motion constraint otherwise disable if(isPrescribed){ prescribe->enable(s); setLocked(s, false); } else prescribe->disable(s); } bool Coordinate::isPrescribed(const SimTK::State& s) const { if(_prescribedConstraintIndex.isValid()){ bool disabled = _model->updMultibodySystem().updMatterSubsystem().getConstraint(_prescribedConstraintIndex).isDisabled(s); return !disabled; } else{ return get_prescribed(); } } //----------------------------------------------------------------------------- // CLAMP //----------------------------------------------------------------------------- //_____________________________________________________________________________ bool Coordinate::getClamped(const SimTK::State& s) const { return getModelingOption(s, "is_clamped") > 0; } void Coordinate::setClamped(SimTK::State& s, bool aLocked) const { setModelingOption(s, "is_clamped", (int)aLocked); } //----------------------------------------------------------------------------- // Coordinate::CoordinateStateVariable //----------------------------------------------------------------------------- double Coordinate::CoordinateStateVariable:: getValue(const SimTK::State& state) const { return ((Coordinate *)&getOwner())->getValue(state); } void Coordinate::CoordinateStateVariable:: setValue(SimTK::State& state, double value) const { ((Coordinate *)&getOwner())->setValue(state, value); } double Coordinate::CoordinateStateVariable:: getDerivative(const SimTK::State& state) const { //TODO: update to get qdot value from the mobilized body return ((Coordinate *)&getOwner())->getSpeedValue(state); } void Coordinate::CoordinateStateVariable:: setDerivative(const SimTK::State& state, double deriv) const { string msg = "CoordinateStateVariable::setDerivative() - ERROR \n"; msg += "Coordinate derivative (qdot) is computed by the Multibody system."; throw Exception(msg); } //----------------------------------------------------------------------------- // Coordinate::SpeedStateVariable //----------------------------------------------------------------------------- double Coordinate::SpeedStateVariable:: getValue(const SimTK::State& state) const { //TODO: update to get qdot value from the mobilized body return ((Coordinate *)&getOwner())->getSpeedValue(state); } void Coordinate::SpeedStateVariable:: setValue(SimTK::State& state, double deriv) const { //TODO: update to set qdot value from the mobilized body ((Coordinate *)&getOwner())->setSpeedValue(state, deriv); } double Coordinate::SpeedStateVariable:: getDerivative(const SimTK::State& state) const { const Coordinate& owner = *((Coordinate *)&getOwner()); const MobilizedBody& mb = owner.getModel().getMatterSubsystem() .getMobilizedBody(owner.getBodyIndex()); return mb.getUDotAsVector(state)[owner.getMobilizerQIndex()]; } void Coordinate::SpeedStateVariable:: setDerivative(const SimTK::State& state, double deriv) const { string msg = "SpeedStateVariable::setDerivative() - ERROR \n"; msg += "Generalized speed derivative (udot) can only be set by the Multibody system."; throw Exception(msg); }
/************************************************************************* * * $RCSfile: excrecds.hxx,v $ * * $Revision: 1.31 $ * * last change: $Author: hr $ $Date: 2003-03-26 18:05:00 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _EXCRECDS_HXX #define _EXCRECDS_HXX #ifndef _SOLAR_H #include <tools/solar.h> #endif #ifndef _ZFORLIST_HXX #include <svtools/zforlist.hxx> #endif #ifndef _STRING_HXX #include <tools/string.hxx> #endif #ifndef _SV_FONTTYPE_HXX //autogen #include <vcl/fonttype.hxx> #endif #ifndef _TOOLS_COLOR_HXX #include <tools/color.hxx> #endif #include <vector> #ifndef SC_OUTLINETAB_HXX #include "olinetab.hxx" #endif #ifndef SC_FILTER_HXX #include "filter.hxx" #endif #ifndef SC_RANGELST_HXX #include "rangelst.hxx" #endif #ifndef SC_XEHELPER_HXX #include "xehelper.hxx" #endif #ifndef SC_XESTYLE_HXX #include "xestyle.hxx" #endif #ifndef _ROOT_HXX #include "root.hxx" #endif #ifndef _FLTTOOLS_HXX #include "flttools.hxx" #endif #ifndef _EXCDEFS_HXX #include "excdefs.hxx" #endif #ifndef SC_CELL_HXX #include "cell.hxx" #endif //------------------------------------------------------------------ Forwards - class SvxBorderLine; class SvStream; class XclExpStream; class Font; class List; class ScPatternAttr; class ScTokenArray; class ScRangeData; class ScDBData; class ScEditCell; class SfxItemSet; class EditTextObject; class ScPageHFItem; class ScProgress; class ExcTable; class UsedAttrList; class ExcArray; class ExcArrays; class ExcShrdFmla; class ExcUPN; //----------------------------------------------------------- class ExcRecord - class ExcRecord : public XclExpRecord { public: virtual void Save( XclExpStream& rStrm ); virtual UINT16 GetNum() const = 0; virtual ULONG GetLen() const = 0; protected: virtual void SaveCont( XclExpStream& rStrm ); private: /** Writes the body of the record. */ virtual void WriteBody( XclExpStream& rStrm ); }; //--------------------------------------------------------- class ExcEmptyRec - class ExcEmptyRec : public ExcRecord { private: protected: public: virtual void Save( XclExpStream& rStrm ); virtual UINT16 GetNum() const; virtual ULONG GetLen() const; }; //------------------------------------------------------- class ExcRecordList - class ExcRecordList : protected List, public ExcEmptyRec { private: protected: public: virtual ~ExcRecordList(); List::Count; inline ExcRecord* First( void ) { return ( ExcRecord* ) List::First(); } inline ExcRecord* Next( void ) { return ( ExcRecord* ) List::Next(); } inline void Append( ExcRecord* pNew ) { if( pNew ) List::Insert( pNew, LIST_APPEND ); } inline const ExcRecord* Get( UINT32 nNum ) const { return ( ExcRecord* ) List::GetObject( nNum ); } virtual void Save( XclExpStream& rStrm ); }; //--------------------------------------------------------- class ExcDummyRec - class ExcDummyRec : public ExcRecord { protected: public: virtual void Save( XclExpStream& rStrm ); virtual UINT16 GetNum() const; virtual const BYTE* GetData() const = 0; // byte data must contain header and body }; //------------------------------------------------------- class ExcBoolRecord - // stores BOOL as 16bit val ( 0x0000 | 0x0001 ) class ExcBoolRecord : public ExcRecord { private: virtual void SaveCont( XclExpStream& rStrm ); protected: BOOL bVal; inline ExcBoolRecord() : bVal( FALSE ) {} public: inline ExcBoolRecord( const BOOL bDefault ) : bVal( bDefault ) {} ExcBoolRecord( SfxItemSet*, USHORT nWhich, BOOL bDefault ); virtual ULONG GetLen( void ) const; }; //--------------------------------------------------------- class ExcBof_Base - class ExcBof_Base : public ExcRecord { private: protected: UINT16 nDocType; UINT16 nVers; UINT16 nRupBuild; UINT16 nRupYear; public: ExcBof_Base( void ); }; //-------------------------------------------------------------- class ExcBof - // Header Record fuer WORKSHEETS class ExcBof : public ExcBof_Base { private: virtual void SaveCont( XclExpStream& rStrm ); public: ExcBof( void ); virtual UINT16 GetNum( void ) const; virtual ULONG GetLen( void ) const; }; //------------------------------------------------------------- class ExcBofW - // Header Record fuer WORKBOOKS class ExcBofW : public ExcBof_Base { private: virtual void SaveCont( XclExpStream& rStrm ); public: ExcBofW( void ); virtual UINT16 GetNum( void ) const; virtual ULONG GetLen( void ) const; }; //-------------------------------------------------------------- class ExcEof - class ExcEof : public ExcRecord { private: public: virtual UINT16 GetNum( void ) const; virtual ULONG GetLen( void ) const; }; //----------------------------------------------------- class ExcFngroupcount - class ExcFngroupcount : public ExcRecord { private: virtual void SaveCont( XclExpStream& rStrm ); public: virtual UINT16 GetNum( void ) const; virtual ULONG GetLen( void ) const; }; //--------------------------------------------------------- class ExcDummy_00 - // INTERFACEHDR to FNGROUPCOUNT (see excrecds.cxx) class ExcDummy_00 : public ExcDummyRec { private: static const BYTE pMyData[]; static const ULONG nMyLen; public: virtual ULONG GetLen( void ) const; virtual const BYTE* GetData( void ) const; }; // EXC_ID_WINDOWPROTECTION class XclExpWindowProtection : public XclExpBoolRecord { public: XclExpWindowProtection(bool bValue); }; // EXC_ID_PROTECT Document Protection class XclExpDocProtection : public XclExpBoolRecord { public: XclExpDocProtection(bool bValue); }; //-------------------------------------------------------- class ExcDummy_04x - // PASSWORD to BOOKBOOL (see excrecds.cxx), no 1904 class ExcDummy_040 : public ExcDummyRec { private: static const BYTE pMyData[]; static const ULONG nMyLen; public: virtual ULONG GetLen( void ) const; virtual const BYTE* GetData( void ) const; }; class ExcDummy_041 : public ExcDummyRec { private: static const BYTE pMyData[]; static const ULONG nMyLen; public: virtual ULONG GetLen( void ) const; virtual const BYTE* GetData( void ) const; }; //------------------------------------------------------------- class Exc1904 - class Exc1904 : public ExcBoolRecord { public: Exc1904( ScDocument& rDoc ); virtual UINT16 GetNum( void ) const; }; //------------------------------------------------------ class ExcBundlesheet - class ExcBundlesheetBase : public ExcRecord { protected: ULONG nStrPos; ULONG nOwnPos; // Position NACH # und Len UINT16 nGrbit; ExcBundlesheetBase(); public: ExcBundlesheetBase( RootData& rRootData, UINT16 nTab ); inline void SetStreamPos( ULONG nNewStrPos ) { nStrPos = nNewStrPos; } void UpdateStreamPos( XclExpStream& rStrm ); virtual UINT16 GetNum() const; }; class ExcBundlesheet : public ExcBundlesheetBase { private: ByteString aName; virtual void SaveCont( XclExpStream& rStrm ); public: ExcBundlesheet( RootData& rRootData, UINT16 nTab ); virtual ULONG GetLen() const; }; //--------------------------------------------------------- class ExcDummy_02 - // sheet dummies: CALCMODE to SETUP class ExcDummy_02a : public ExcDummyRec { private: static const BYTE pMyData[]; static const ULONG nMyLen; public: virtual ULONG GetLen( void ) const; virtual const BYTE* GetData( void ) const; }; //--------------------------------------------------------- class ExcDummy_02 - // sheet dummies: CALCMODE to SETUP class ExcDummy_02b : public ExcDummyRec { private: static const BYTE pMyData[]; static const ULONG nMyLen; public: virtual ULONG GetLen( void ) const; virtual const BYTE* GetData( void ) const; }; //--------------------------------------------------------- class ExcDummy_02 - // sheet dummies: CALCMODE to SETUP class ExcDummy_02c : public ExcDummyRec { private: static const BYTE pMyData[]; static const ULONG nMyLen; public: virtual ULONG GetLen( void ) const; virtual const BYTE* GetData( void ) const; }; //------------------------------------------------------------- class ExcNote - class ExcNote : public ExcEmptyRec { private: ByteString* pText; ScAddress aPos; UINT16 nTextLen; public: ExcNote( const ScAddress, const String& rText, RootData& ); virtual ~ExcNote(); virtual void Save( XclExpStream& rStrm ); }; //------------------------------------------------------------- class ExcCell - class ExcCell : public ExcRecord { protected: ScAddress aPos; UINT16 nXF; static UINT32 nCellCount; // zaehlt DOPPELT: im Ctor und SaveCont static ScProgress* pPrgrsBar; #ifdef DBG_UTIL friend class ExcDocument; static INT32 _nRefCount; #endif ExcCell( const ScAddress rPos, const ScPatternAttr* pAttr, RootData& rRootData, const ULONG nAltNumForm = NUMBERFORMAT_ENTRY_NOT_FOUND ); virtual void SaveCont( XclExpStream& rStrm ); virtual void SaveDiff( XclExpStream& rStrm ); virtual ULONG GetDiffLen() const = 0; public: virtual ~ExcCell(); inline void SetXF( UINT16 nNew ) { nXF = nNew; } virtual UINT16 GetXF() const; inline static void ResetCellCount() { nCellCount = 0; } inline static void IncCellCount() { nCellCount++; } inline static UINT32 GetCellCount() { return nCellCount; } inline static void SetPrgrsBar( ScProgress& rNewBar ); inline static void ClearPrgrsBar() { pPrgrsBar = NULL; } virtual ULONG GetLen() const; }; inline void ExcCell::SetPrgrsBar( ScProgress& rNewBar ) { ResetCellCount(); // logisch... oder? pPrgrsBar = &rNewBar; } //----------------------------------------------------------- class ExcNumber - class ExcNumber : public ExcCell { private: double fVal; virtual void SaveDiff( XclExpStream& rStrm ); // instead of SaveCont() virtual ULONG GetDiffLen( void ) const; public: ExcNumber( const ScAddress, const ScPatternAttr*, RootData& rRootData, const double& rVal ); virtual UINT16 GetNum( void ) const; }; //---------------------------------------------------------- class ExcBoolerr - class ExcBoolerr : public ExcCell { private: UINT8 nVal; UINT8 bError; virtual void SaveDiff( XclExpStream& rStrm ); // instead of SaveCont() virtual ULONG GetDiffLen( void ) const; public: ExcBoolerr( const ScAddress, const ScPatternAttr*, RootData& rRootData, UINT8 nVal, BOOL bIsError ); virtual UINT16 GetNum( void ) const; }; //---------------------------------------------------------- class ExcRKMulRK - class ExcRKMulRK : private List, public ExcCell { private: struct ExcRKMulRKEntry { UINT32 nVal; UINT16 nXF; }; inline ExcRKMulRKEntry* _First() { return (ExcRKMulRKEntry*) List::First(); } inline ExcRKMulRKEntry* _Next() { return (ExcRKMulRKEntry*) List::Next(); } inline ExcRKMulRKEntry* _Get( ULONG nIndex ) const { return (ExcRKMulRKEntry*) List::GetObject( nIndex ); } protected: virtual void SaveCont( XclExpStream& rStrm ); virtual ULONG GetDiffLen( void ) const; public: ExcRKMulRK( const ScAddress, const ScPatternAttr*, RootData& rRootData, const INT32 nVal ); virtual ~ExcRKMulRK(); // returns new RK or NULL if an old RK was extendable ExcRKMulRK* Extend( const ScAddress rPos, const ScPatternAttr *pAttr, RootData& rRootData, const INT32 nVal ); virtual UINT16 GetXF() const; virtual UINT16 GetNum( void ) const; inline BOOL IsRK( void ) const { return List::Count() == 1; } inline BOOL IsMulRK( void ) const { return List::Count() > 1; } }; //------------------------------------------------------------ class ExcLabel - class ExcLabel : public ExcCell { private: ByteString aText; UINT16 nTextLen; virtual void SaveDiff( XclExpStream& rStrm ); // instead of SaveCont() virtual ULONG GetDiffLen( void ) const; public: ExcLabel( const ScAddress, const ScPatternAttr*, RootData& rRootData, const String& rText ); virtual ~ExcLabel(); virtual UINT16 GetNum( void ) const; }; //---------------------------------------------------------- class ExcRichStr // helper class for ExcRString and ExcLabel8/XclExpRichString class ExcRichStr { private: ScfUInt16List aForms; // Form und Pos nacheinander BiffTyp eBiff; public: ExcRichStr( ExcCell& rExcCell, String& rText, const ScPatternAttr* pAttr, const ScEditCell& rEdCell, RootData& rRoot, xub_StrLen nMaxChars ); inline ExcRichStr( const ExcRichStr& rCopy ) : aForms( rCopy.aForms ), eBiff( rCopy.eBiff ) {} ~ExcRichStr(); inline UINT16 GetFormCount() const; // number of bytes to be saved inline ULONG GetByteCount() const; // write list of forms void Write( XclExpStream& rStrm ); }; inline UINT16 ExcRichStr::GetFormCount() const { return (UINT16) Min( aForms.Count() / 2, (eBiff < Biff8 ? ULONG(0xFF) : ULONG(0xFFFF)) ); } inline ULONG ExcRichStr::GetByteCount() const { return (eBiff < Biff8 ? 2 : 4) * GetFormCount(); } //---------------------------------------------------------- class ExcRString - class ExcRString : public ExcCell, ExcRoot { private: String aText; ExcRichStr* pRichStr; UINT16 nTextLen; virtual void SaveDiff( XclExpStream& rStrm ); // instead of SaveCont() virtual ULONG GetDiffLen( void ) const; public: ExcRString( const ScAddress aPos, const ScPatternAttr* pAttr, RootData& rRootData, const ScEditCell& rEdCell ); virtual ~ExcRString(); virtual UINT16 GetNum( void ) const; }; /*----------------------------------------------------------------------*/ class ExcFmlaResultStr : public XclExpRecord { private: XclExpString maResultText; public: ExcFmlaResultStr(const XclExpString &aFmlaText); virtual ~ExcFmlaResultStr(); private: virtual void WriteBody( XclExpStream& rStrm ); }; //---------------------------------------------------------- class ExcFormula - class ExcFormula : public ExcCell { private: sal_Char* pData; UINT16 nFormLen; BOOL bShrdFmla; ScFormulaCell* pFCell; virtual void SaveDiff( XclExpStream& rStrm ); // instead of SaveCont() virtual ULONG GetDiffLen( void ) const; public: ExcFormula( const ScAddress rPos, const ScPatternAttr *pAttr, RootData& rRootData, const ULONG nAltNumForm, const ScTokenArray& rCode, ExcArray** ppArray = NULL, ScMatrixMode eMM = MM_NONE, ExcShrdFmla** ppShrdFmla = NULL, ExcArrays* pShrdFmlas = NULL, ScFormulaCell* pFCell = NULL, ExcFmlaResultStr **pFormulaResult = NULL); ~ExcFormula(); inline const ScAddress& GetPosition() const { return aPos; } // from ExcCell void SetTableOp( USHORT nCol, USHORT nRow ); // for TableOp export virtual UINT16 GetNum( void ) const; static BYTE ScErrorCodeToExc(UINT16 nErrorCode); }; //---------------------------------------------------- class ExcBlankMulblank - class ExcBlankMulblank : public ExcCell, private ScfUInt32List { protected: ULONG nRecLen; UINT16 nLastCol; BOOL bMulBlank; BOOL bDummy; // not saved, 'cause row contains formatting info inline UINT16 GetXF( UINT32 nEntry ) const { return (UINT16) nEntry; } inline UINT16 GetCount( UINT32 nEntry ) const { return (UINT16)(nEntry >> 16); } inline void Append( UINT16 nXF, UINT16 nCount ); void AddEntries( const ScAddress rPos, const ScPatternAttr* pAttr, RootData& rRootData, UINT16 nCount, ExcTable& rExcTab ); virtual void SaveDiff( XclExpStream& rStrm ); // instead of SaveCont() virtual ULONG GetDiffLen( void ) const; public: ExcBlankMulblank( const ScAddress rPos, const ScPatternAttr* pFirstAttr, RootData& rRootData, UINT16 nFirstCount, ExcTable& rExcTab ); void Add( const ScAddress rPos, const ScPatternAttr* pAttr, RootData& rRootData, UINT16 nAddCount, ExcTable& rExcTab ); inline UINT16 GetLastCol() const { return nLastCol; } virtual UINT16 GetXF() const; // returns last used XF virtual UINT16 GetNum() const; virtual void Save( XclExpStream& ); // for dummy case }; inline void ExcBlankMulblank::Append( UINT16 nXF, UINT16 nCount ) { ScfUInt32List::Append( (UINT32) nXF + (((UINT32) nCount) << 16) ); } //---------------------------------------------------- class ExcNameListEntry - class ExcNameListEntry : public ExcRecord { protected: UINT8* pData; UINT16 nFormLen; UINT16 nTabNum; // Excel index, 1-based, 0==none UINT8 nBuiltInKey; BOOL bDummy; void DeleteData(); void SetCode( const ExcUPN& rUPN ); // default: save builtin key virtual void SaveCont( XclExpStream& rStrm ); public: ExcNameListEntry(); ExcNameListEntry( RootData& rRootData, UINT16 nScTab, UINT8 nKey ); virtual ~ExcNameListEntry(); inline UINT16 GetTabIndex() const { return nTabNum; } inline UINT8 GetBuiltInKey() const { return nBuiltInKey; } inline BOOL IsDummy() const { return bDummy; } virtual UINT16 GetNum() const; virtual ULONG GetLen() const; }; //------------------------------------------------------------- class ExcName - class ExcName : public ExcNameListEntry, public ExcRoot { private: String aName; BiffTyp eBiff; BOOL bHidden; BOOL bBuiltIn; void Init( BOOL bHid = FALSE, BOOL bBIn = FALSE ); void BuildFormula( const ScRange& rRange ); void SetName( const String& rRangeName ); void SetUniqueName( const String& rRangeName ); BOOL SetBuiltInName( const String& rName, UINT8 nKey ); BOOL IsBuiltInAFName( const String& rName, UINT8 nKey ); virtual void SaveCont( XclExpStream& rStrm ); public: ExcName( RootData& rRootData, ScRangeData* pRange ); ExcName( RootData& rRootData, ScDBData* pArea ); ExcName( RootData& rRootData, const ScRange& rRange, const String& rName ); ExcName( RootData& rRootData, const ScRange& rRange, UINT8 nKey, BOOL bHid = FALSE ); inline const String& GetName() const { return aName; } virtual ULONG GetLen() const; }; // ---- class XclBuildInName ----------------------------------------- class XclBuildInName : public ExcNameListEntry { private: ScRangeList aRL; protected: inline void Append( const ScRange& rNew ) { aRL.Append( rNew ); } void CreateFormula( RootData& rRootData ); public: XclBuildInName( RootData& rRootData, UINT16 nScTab, UINT8 nKey ); }; // ---- class XclPrintRange, class XclTitleRange --------------------- class XclPrintRange : public XclBuildInName { public: XclPrintRange( RootData& rRootData, UINT16 nScTab ); }; class XclPrintTitles : public XclBuildInName { public: XclPrintTitles( RootData& rRootData, UINT16 nScTab ); }; //--------------------------------------------------------- class ExcNameList - class ExcNameList : public ExcEmptyRec, private List { private: ULONG nFirstPrintRangeIx; ULONG nFirstPrintTitleIx; ULONG nFirstOtherNameIx; ::std::vector< sal_uInt32 > maNextInsVec; /// List positions for next insertion for each sheet. inline ExcNameListEntry* _First() { return (ExcNameListEntry*) List::First(); } inline ExcNameListEntry* _Next() { return (ExcNameListEntry*) List::Next(); } inline ExcNameListEntry* _Get( ULONG nIndex ) const { return (ExcNameListEntry*) List::GetObject( nIndex ); } UINT16 Append( ExcNameListEntry* pName ); public: ExcNameList( RootData& rRootData ); virtual ~ExcNameList(); UINT16 GetBuiltInIx( const ExcNameListEntry* pName ); /** Inserts a named range in table name sort order. */ void InsertSorted( RootData& rRootData, ExcNameListEntry* pName, sal_uInt16 nScTab ); virtual void Save( XclExpStream& rStrm ); }; //------------------------------------------------------- class ExcDimensions - class ExcDimensions : public ExcRecord { private: UINT16 nRwMic; UINT16 nRwMac; UINT16 nColMic; UINT16 nColMac; BiffTyp eBiff; virtual void SaveCont( XclExpStream& rStrm ); public: ExcDimensions( BiffTyp ); ExcDimensions( UINT16 nFirstCol, UINT16 nFirstRow, UINT16 nLastCol, UINT16 nLastRow, BiffTyp ); void SetLimits( UINT16 nFirstCol, UINT16 nFirstRow, UINT16 nLastCol, UINT16 nLastRow ); virtual UINT16 GetNum( void ) const; virtual ULONG GetLen( void ) const; }; //--------------------------------------------------------- class ExcEOutline - class ExcEOutline { private: ScOutlineArray* pOLArray; UINT16 nCurrExcLevel; BOOL bIsColl; UINT16 nEnd[ SC_OL_MAXDEPTH ]; BOOL bHidden[ SC_OL_MAXDEPTH ]; protected: public: ExcEOutline( ScOutlineArray* pArray ); void Update( UINT16 nNum ); inline BOOL IsCollapsed() const { return bIsColl; } inline UINT16 GetLevel() const { return Min( nCurrExcLevel, (UINT16) EXC_OUTLINE_MAX ); } }; //------------------------------------------------------------ class ExcEGuts - class ExcEGuts : public ExcRecord { private: UINT16 nRowLevel; UINT16 nColLevel; virtual void SaveCont( XclExpStream& rStrm ); protected: public: ExcEGuts( ScOutlineArray* pCol, ScOutlineArray* pRow ); virtual UINT16 GetNum() const; virtual ULONG GetLen() const; }; //-------------------------------------------------------------- class ExcRow - class ExcRow : public ExcRecord { private: friend class DefRowXFs; ExcTable& rExcTab; UINT16 nNum; UINT16 nFirstCol; UINT16 nLastCol; UINT16 nHeight; UINT16 nOptions; UINT16 nXF; BOOL bDefHeight; void SetRange( UINT16 nFCol, UINT16 nLCol ); void SetHeight( UINT16 nNewHeight, BOOL bUser ); virtual void SaveCont( XclExpStream& rStrm ); protected: public: ExcRow( UINT16 nNum, UINT16 nTab, UINT16 nFCol, UINT16 nLCol, UINT16 nXF, ScDocument& rDoc, ExcEOutline& rOutline, ExcTable& rExcTab ); inline BOOL IsDefault(); virtual UINT16 GetNum() const; virtual ULONG GetLen() const; }; inline BOOL ExcRow::IsDefault() { return (TRUEBOOL( nHeight & EXC_ROW_FLAGDEFHEIGHT ) && !nOptions); } //--------------------------------------------------------- class ExcRowBlock - class ExcRowBlock : public ExcEmptyRec { private: ExcRow** ppRows; // 32 rows per block UINT16 nNext; protected: public: ExcRowBlock(); virtual ~ExcRowBlock(); // returns new block or NULL if last block not full ExcRowBlock* Append( ExcRow* pNewRow ); void SetDefXFs( DefRowXFs& rDefRowXFs ); virtual void Save( XclExpStream& rStrm ); }; //------------------------------------------------------ class ExcDefcolwidth - class ExcDefcolwidth : public ExcRecord { private: UINT16 nWidth; virtual void SaveCont( XclExpStream& rStrm ); public: ExcDefcolwidth( UINT16 nDefColWidth ); virtual UINT16 GetNum( void ) const; virtual ULONG GetLen( void ) const; }; //---------------------------------------------------------- class ExcColinfo - class ExcColinfo : public ExcRecord { private: UINT16 nFirstCol; UINT16 nLastCol; UINT16 nColWidth; UINT16 nXF; UINT16 nOptions; virtual void SaveCont( XclExpStream& rStrm ); public: ExcColinfo( UINT16 nCol, UINT16 nTab, UINT16 nXF, RootData&, ExcEOutline& rOutline ); // if expandable, delete rpExp and set to NULL void Expand( ExcColinfo*& rpExp ); virtual UINT16 GetNum( void ) const; virtual ULONG GetLen( void ) const; }; //------------------------------------------------------ class ExcExterncount - class ExcExterncount : public ExcRecord, ExcRoot { private: BOOL bTable; virtual void SaveCont( XclExpStream& rStrm ); public: ExcExterncount( RootData*, const BOOL bTable ); virtual UINT16 GetNum( void ) const; virtual ULONG GetLen( void ) const; }; //------------------------------------------------------ class ExcExternsheet - class ExcExternsheet : public ExcRecord, public ExcRoot { private: String aTabName; virtual void SaveCont( XclExpStream& rStrm ); public: ExcExternsheet( RootData* pRD, const UINT16 nTabNum ); virtual UINT16 GetNum( void ) const; virtual ULONG GetLen( void ) const; }; //-------------------------------------------------- class ExcExternsheetList - class ExcExternsheetList : public ExcEmptyRec, protected List { private: inline ExcExternsheet* _First() { return (ExcExternsheet*) List::First(); } inline ExcExternsheet* _Next() { return (ExcExternsheet*) List::Next(); } protected: public: virtual ~ExcExternsheetList(); inline void Add( ExcExternsheet* pNew ) { List::Insert( pNew, LIST_APPEND ); } virtual void Save( XclExpStream& rStrm ); }; //-------------------------------------------------------- class ExcExternDup - class ExcExternDup : public ExcEmptyRec { private: ExcExterncount& rExtCnt; ExcExternsheetList& rExtSheetList; protected: public: ExcExternDup( ExcExterncount&, ExcExternsheetList& ); ExcExternDup( const ExcExternDup& ); virtual void Save( XclExpStream& rStrm ); }; //---------------------------------------------------------- class ExcWindow2 - class ExcWindow2 : public ExcRecord { private: UINT16 nTable; virtual void SaveCont( XclExpStream& rStrm ); public: ExcWindow2( UINT16 nTable ); inline UINT16 GetTable() const { return nTable; } virtual UINT16 GetNum( void ) const; virtual ULONG GetLen( void ) const; }; //-------------------------------------------------------- class ExcSelection - class ExcSelection : public ExcRecord { private: UINT16 nCol; UINT16 nRow; UINT8 nPane; virtual void SaveCont( XclExpStream& rStrm ); public: inline ExcSelection( UINT16 _nCol, UINT16 _nRow, UINT8 _nPane ) : nCol( _nCol ), nRow( _nRow ), nPane( _nPane ) {} virtual UINT16 GetNum( void ) const; virtual ULONG GetLen( void ) const; }; // XclExpWsbool =============================================================== class XclExpWsbool : public XclExpUInt16Record { public: XclExpWsbool( RootData& rRootData ); }; //------------------------------------------------------------ class ExcSetup - class ExcSetup : public ExcRecord { private: UINT16 nPaperSize; UINT16 nScale; UINT16 nPageStart; sal_uInt16 nFitToPages; UINT16 nGrbit; sal_uInt16 nHeaderMargin; sal_uInt16 nFooterMargin; virtual void SaveCont( XclExpStream& rStrm ); public: ExcSetup( RootData* ); virtual UINT16 GetNum( void ) const; virtual ULONG GetLen( void ) const; }; // Header/Footer ============================================================== /** Base class for header/footer contents. Constructs the complete format string based on the given which IDs. */ class XclExpHeaderFooter : public XclExpRecord, public ExcRoot { private: String maFormatString; /// The content of the header/footer. bool mbUnicode; /// true = write Unicode string. public: /** @param nHFSetWhichId The which ID of the SetItem of the header/footer. @param nHFTextWhichId The which ID od the text contents of the header/footer. */ XclExpHeaderFooter( sal_uInt16 nRecId, RootData& rRootData, sal_uInt16 nHFSetWhichId, sal_uInt16 nHFTextWhichId ); /** Writes the record, if the text is not empty. */ virtual void Save( XclExpStream& rStrm ); private: /** Constructs the contents of the complete header/footer. */ static void GetFormatString( String& rString, RootData& rRootData, sal_uInt16 nWhich ); /** Writes the string (Byte or Unicode, depending on mbUnicode). */ virtual void WriteBody( XclExpStream& rStrm ); }; /** Contains the header text of a sheet. */ class XclExpHeader : public XclExpHeaderFooter { public: XclExpHeader( RootData& rRootData ); }; /** Contains the footer text of a sheet. */ class XclExpFooter : public XclExpHeaderFooter { public: XclExpFooter( RootData& rRootData ); }; // ============================================================================ //----------------------------------------------------- class ExcPrintheaders - class ExcPrintheaders : public ExcBoolRecord { private: public: ExcPrintheaders( SfxItemSet* ); virtual UINT16 GetNum( void ) const; }; //--------------------------------------------------- class ExcPrintGridlines - class ExcPrintGridlines : public ExcBoolRecord { private: public: ExcPrintGridlines( SfxItemSet* ); virtual UINT16 GetNum( void ) const; }; //---------------------------------------------------------- class ExcHcenter - class ExcHcenter : public ExcBoolRecord { private: public: ExcHcenter( SfxItemSet* ); virtual UINT16 GetNum( void ) const; }; //---------------------------------------------------------- class ExcVcenter - class ExcVcenter : public ExcBoolRecord { private: public: ExcVcenter( SfxItemSet* ); virtual UINT16 GetNum( void ) const; }; //---------------------------------------------------------------- AutoFilter - // classes: ExcFilterMode, ExcAutoFilterInfo, ExcFilterCondition, // ExcAutoFilter, ExcAutoFilterRecs class ExcFilterMode : public ExcRecord { public: virtual UINT16 GetNum() const; virtual ULONG GetLen() const; }; class ExcAutoFilterInfo : public ExcRecord { private: UINT16 nCount; virtual void SaveCont( XclExpStream& rStrm ); protected: public: inline ExcAutoFilterInfo( UINT16 nC ) { nCount = nC; } virtual ~ExcAutoFilterInfo(); virtual UINT16 GetNum() const; virtual ULONG GetLen() const; }; class ExcFilterCondition { private: UINT8 nType; UINT8 nOper; double fVal; XclExpUniString* pText; protected: public: ExcFilterCondition(); ~ExcFilterCondition(); inline BOOL IsEmpty() const { return (nType == EXC_AFTYPE_NOTUSED); } inline BOOL HasEqual() const { return (nOper == EXC_AFOPER_EQUAL); } ULONG GetTextBytes() const; void SetCondition( UINT8 nTp, UINT8 nOp, double fV, String* pT ); void Save( XclExpStream& rStrm ); void SaveText( XclExpStream& rStrm ); }; class ExcAutoFilter : public ExcRecord { private: UINT16 nCol; UINT16 nFlags; ExcFilterCondition aCond[ 2 ]; BOOL AddCondition( ScQueryConnect eConn, UINT8 nType, UINT8 nOp, double fVal, String* pText, BOOL bSimple = FALSE ); virtual void SaveCont( XclExpStream& rStrm ); protected: public: ExcAutoFilter( UINT16 nC ); inline UINT16 GetCol() const { return nCol; } inline BOOL HasCondition() const { return !aCond[ 0 ].IsEmpty(); } inline BOOL HasTop10() const { return TRUEBOOL( nFlags & EXC_AFFLAG_TOP10 ); } BOOL AddEntry( RootData& rRoot, const ScQueryEntry& rEntry ); virtual UINT16 GetNum() const; virtual ULONG GetLen() const; }; class ExcAutoFilterRecs : private List, public ExcEmptyRec { private: ExcFilterMode* pFilterMode; ExcAutoFilterInfo* pFilterInfo; inline ExcAutoFilter* _First() { return (ExcAutoFilter*) List::First(); } inline ExcAutoFilter* _Next() { return (ExcAutoFilter*) List::Next(); } ExcAutoFilter* GetByCol( UINT16 nCol ); // always 0-based BOOL IsFiltered( UINT16 nCol ); void DeleteList(); inline void Append( ExcAutoFilter* pFilter ) { List::Insert( pFilter, LIST_APPEND ); } void AddObjRecs( RootData& rRoot, const ScAddress& rPos, UINT16 nCols ); protected: public: ExcAutoFilterRecs( RootData& rRoot, UINT16 nTab ); virtual ~ExcAutoFilterRecs(); virtual void Save( XclExpStream& rStrm ); }; // ---------------------------------------------------------------------------- /** Stores the margin value of one border of the page. */ class XclExpMargin : public XclExpDoubleRecord { public: /** @param nMargin The margin value in twips. @param eSide The page border identifier. */ XclExpMargin( sal_Int32 nMargin, XclMarginType eSide ); }; // Manual page breaks ========================================================= /** Stores an array of manual page breaks for columns or rows. */ class XclExpPagebreaks : public XclExpRecord { protected: ScfUInt16List maPagebreaks; /// Array of manual page breaks. public: XclExpPagebreaks( RootData& rRootData, sal_uInt16 nScTab, XclPBOrientation eOrient ); /** Writes the record, if the list is not empty. */ virtual void Save( XclExpStream& rStrm ); private: /** Writes the page break list. */ virtual void WriteBody( XclExpStream& rStrm ); }; // ---------------------------------------------------------------------------- /** Stores an array of manual page breaks for columns or rows (BIFF8). */ class XclExpPagebreaks8 : public XclExpPagebreaks { private: sal_uInt16 mnRangeMax; /// Index of last row/column. public: XclExpPagebreaks8( RootData& rRootData, sal_uInt16 nScTab, XclPBOrientation eOrient ); private: /** Writes the page break list. */ virtual void WriteBody( XclExpStream& rStrm ); }; // ============================================================================ //------------------------ class ExcArray, class ExcArrays, class ExcShrdFmla - class ExcArray : public ExcRecord { protected: UINT32 nID; UINT16 nFirstRow; UINT16 nLastRow; UINT8 nFirstCol; UINT8 nLastCol; sal_Char* pData; UINT16 nFormLen; void SetColRow( UINT8 nCol, UINT16 nRow, UINT32 nID = 0xFFFFFFFF ); virtual void SaveCont( XclExpStream& rStrm ); ExcArray( const sal_Char* pData, UINT16 nLen, UINT8 nCol, UINT16 nRow ); public: ExcArray( const ExcUPN&, UINT8 nCol, UINT16 nRow ); ExcArray( UINT8 nCol, UINT16 nRow, UINT32 nID ); virtual ~ExcArray(); virtual UINT16 GetNum() const; virtual ULONG GetLen() const; BOOL AppendBy( const ExcArray& rExt ); // TRUE, if rEXt is touching given range and extend range BOOL AppendBy( UINT8 nStartCol, UINT16 nStartRow, UINT8 nEndCol, UINT16 nEndRow ); }; class ExcArrays : protected List { private: protected: public: ExcArrays( void ); virtual ~ExcArrays(); BOOL Insert( ExcArray* pPossibleNewArrayFormula ); // insert only, if not already in array // only ref in list, so if return is TRUE, do not delete _before_ using // Insert() the _last_ time! BOOL Extend( UINT8 nStartCol, UINT16 nStartRow, UINT8 nEndCol, UINT16 nEndRow ); // extend existing range, when start is base inline void Append( ExcArray* ); }; inline void ExcArrays::Append( ExcArray* p ) { List::Insert( p, LIST_APPEND ); } class ExcShrdFmla : public ExcArray { private: // ScRange aPos; // sal_Char* pData; // UINT16 nLen; virtual void SaveCont( XclExpStream& rStrm ); public: ExcShrdFmla( const sal_Char* pData, UINT16 nLen, const ScRange& rPos ); virtual ~ExcShrdFmla(); virtual UINT16 GetNum() const; virtual ULONG GetLen() const; }; //--------------------------- class XclExpTableOp, class XclExpTableOpManager - // multiple operations aka table operations (record TABLE) // a multiple operations record // stores pointers to all affected formula records class XclExpTableOp : private List, public ExcRecord { private: USHORT nFirstCol; USHORT nLastCol; USHORT nNextCol; // next column of next row USHORT nFirstRow; USHORT nLastRow; USHORT nMode; USHORT nColInpCol; USHORT nColInpRow; USHORT nRowInpCol; USHORT nRowInpRow; BOOL bIsValid; inline ExcFormula* _First() { return (ExcFormula*) List::First(); } inline ExcFormula* _Next() { return (ExcFormula*) List::Next(); } inline void Append( ExcFormula* pFmla ) { List::Insert( pFmla, LIST_APPEND ); } virtual void SaveCont( XclExpStream& rStrm ); public: XclExpTableOp( ExcFormula& rFormula, const ScAddress& rColFirstPos, const ScAddress& rRowFirstPos, USHORT nNewMode ); virtual ~XclExpTableOp(); BOOL IsAppendable( const ScAddress& rPos ); BOOL CheckPosition( const ScAddress& rPos, const ScAddress& rFmlaPos, const ScAddress& rColFirstPos, const ScAddress& rColRelPos, const ScAddress& rRowFirstPos, const ScAddress& rRowRelPos, BOOL bMode2 ); static BOOL CheckFirstPosition( const ScAddress& rPos, const ScAddress& rFmlaPos, const ScAddress& rColFirstPos, const ScAddress& rColRelPos, const ScAddress& rRowFirstPos, const ScAddress& rRowRelPos, BOOL bMode2, USHORT& rnMode ); // insert pointer to Formula rec and update range data void InsertCell( ExcFormula& rFormula ); // change #NA error values of formula recs to TableOp values if in table op range void UpdateCells(); virtual void Save( XclExpStream& rStrm ); virtual UINT16 GetNum() const; virtual ULONG GetLen() const; }; // stores pointers to ExcTableOp records - insert cells to existing or new ExcTableOp class XclExpTableOpManager : private List { private: inline XclExpTableOp* _First() { return (XclExpTableOp*) List::First(); } inline XclExpTableOp* _Next() { return (XclExpTableOp*) List::Next(); } public: inline XclExpTableOpManager() : List() {} virtual ~XclExpTableOpManager(); // create & return new TableOp record or insert to an existing XclExpTableOp* InsertCell( const ScTokenArray* pTokenArray, ExcFormula& rFormula ); // change #NA error values of formula recs to TableOp values void UpdateCells(); }; #endif INTEGRATION: CWS calc06 (1.27.2.3.10); FILE MERGED 2003/03/31 15:22:24 sab 1.27.2.3.10.2: #107688#; cwsresync 2003/03/28 15:29:03 dr 1.27.2.3.10.1: #107688# sort/reduce XF list on export /************************************************************************* * * $RCSfile: excrecds.hxx,v $ * * $Revision: 1.32 $ * * last change: $Author: rt $ $Date: 2003-04-08 16:27:26 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _EXCRECDS_HXX #define _EXCRECDS_HXX #ifndef _SOLAR_H #include <tools/solar.h> #endif #ifndef _ZFORLIST_HXX #include <svtools/zforlist.hxx> #endif #ifndef _STRING_HXX #include <tools/string.hxx> #endif #ifndef _SV_FONTTYPE_HXX //autogen #include <vcl/fonttype.hxx> #endif #ifndef _TOOLS_COLOR_HXX #include <tools/color.hxx> #endif #include <vector> #ifndef SC_OUTLINETAB_HXX #include "olinetab.hxx" #endif #ifndef SC_FILTER_HXX #include "filter.hxx" #endif #ifndef SC_RANGELST_HXX #include "rangelst.hxx" #endif #ifndef SC_XEHELPER_HXX #include "xehelper.hxx" #endif #ifndef SC_XESTYLE_HXX #include "xestyle.hxx" #endif #ifndef _ROOT_HXX #include "root.hxx" #endif #ifndef _FLTTOOLS_HXX #include "flttools.hxx" #endif #ifndef _EXCDEFS_HXX #include "excdefs.hxx" #endif #ifndef SC_CELL_HXX #include "cell.hxx" #endif //------------------------------------------------------------------ Forwards - class SvxBorderLine; class SvStream; class XclExpStream; class Font; class List; class ScPatternAttr; class ScTokenArray; class ScRangeData; class ScDBData; class ScEditCell; class SfxItemSet; class EditTextObject; class ScPageHFItem; class ScProgress; class ExcTable; class UsedAttrList; class ExcArray; class ExcArrays; class ExcShrdFmla; class ExcUPN; //----------------------------------------------------------- class ExcRecord - class ExcRecord : public XclExpRecord { public: virtual void Save( XclExpStream& rStrm ); virtual UINT16 GetNum() const = 0; virtual ULONG GetLen() const = 0; protected: virtual void SaveCont( XclExpStream& rStrm ); private: /** Writes the body of the record. */ virtual void WriteBody( XclExpStream& rStrm ); }; //--------------------------------------------------------- class ExcEmptyRec - class ExcEmptyRec : public ExcRecord { private: protected: public: virtual void Save( XclExpStream& rStrm ); virtual UINT16 GetNum() const; virtual ULONG GetLen() const; }; //------------------------------------------------------- class ExcRecordList - class ExcRecordList : protected List, public ExcEmptyRec { private: protected: public: virtual ~ExcRecordList(); List::Count; inline ExcRecord* First( void ) { return ( ExcRecord* ) List::First(); } inline ExcRecord* Next( void ) { return ( ExcRecord* ) List::Next(); } inline void Append( ExcRecord* pNew ) { if( pNew ) List::Insert( pNew, LIST_APPEND ); } inline const ExcRecord* Get( UINT32 nNum ) const { return ( ExcRecord* ) List::GetObject( nNum ); } virtual void Save( XclExpStream& rStrm ); }; //--------------------------------------------------------- class ExcDummyRec - class ExcDummyRec : public ExcRecord { protected: public: virtual void Save( XclExpStream& rStrm ); virtual UINT16 GetNum() const; virtual const BYTE* GetData() const = 0; // byte data must contain header and body }; //------------------------------------------------------- class ExcBoolRecord - // stores BOOL as 16bit val ( 0x0000 | 0x0001 ) class ExcBoolRecord : public ExcRecord { private: virtual void SaveCont( XclExpStream& rStrm ); protected: BOOL bVal; inline ExcBoolRecord() : bVal( FALSE ) {} public: inline ExcBoolRecord( const BOOL bDefault ) : bVal( bDefault ) {} ExcBoolRecord( SfxItemSet*, USHORT nWhich, BOOL bDefault ); virtual ULONG GetLen( void ) const; }; //--------------------------------------------------------- class ExcBof_Base - class ExcBof_Base : public ExcRecord { private: protected: UINT16 nDocType; UINT16 nVers; UINT16 nRupBuild; UINT16 nRupYear; public: ExcBof_Base( void ); }; //-------------------------------------------------------------- class ExcBof - // Header Record fuer WORKSHEETS class ExcBof : public ExcBof_Base { private: virtual void SaveCont( XclExpStream& rStrm ); public: ExcBof( void ); virtual UINT16 GetNum( void ) const; virtual ULONG GetLen( void ) const; }; //------------------------------------------------------------- class ExcBofW - // Header Record fuer WORKBOOKS class ExcBofW : public ExcBof_Base { private: virtual void SaveCont( XclExpStream& rStrm ); public: ExcBofW( void ); virtual UINT16 GetNum( void ) const; virtual ULONG GetLen( void ) const; }; //-------------------------------------------------------------- class ExcEof - class ExcEof : public ExcRecord { private: public: virtual UINT16 GetNum( void ) const; virtual ULONG GetLen( void ) const; }; //----------------------------------------------------- class ExcFngroupcount - class ExcFngroupcount : public ExcRecord { private: virtual void SaveCont( XclExpStream& rStrm ); public: virtual UINT16 GetNum( void ) const; virtual ULONG GetLen( void ) const; }; //--------------------------------------------------------- class ExcDummy_00 - // INTERFACEHDR to FNGROUPCOUNT (see excrecds.cxx) class ExcDummy_00 : public ExcDummyRec { private: static const BYTE pMyData[]; static const ULONG nMyLen; public: virtual ULONG GetLen( void ) const; virtual const BYTE* GetData( void ) const; }; // EXC_ID_WINDOWPROTECTION class XclExpWindowProtection : public XclExpBoolRecord { public: XclExpWindowProtection(bool bValue); }; // EXC_ID_PROTECT Document Protection class XclExpDocProtection : public XclExpBoolRecord { public: XclExpDocProtection(bool bValue); }; //-------------------------------------------------------- class ExcDummy_04x - // PASSWORD to BOOKBOOL (see excrecds.cxx), no 1904 class ExcDummy_040 : public ExcDummyRec { private: static const BYTE pMyData[]; static const ULONG nMyLen; public: virtual ULONG GetLen( void ) const; virtual const BYTE* GetData( void ) const; }; class ExcDummy_041 : public ExcDummyRec { private: static const BYTE pMyData[]; static const ULONG nMyLen; public: virtual ULONG GetLen( void ) const; virtual const BYTE* GetData( void ) const; }; //------------------------------------------------------------- class Exc1904 - class Exc1904 : public ExcBoolRecord { public: Exc1904( ScDocument& rDoc ); virtual UINT16 GetNum( void ) const; }; //------------------------------------------------------ class ExcBundlesheet - class ExcBundlesheetBase : public ExcRecord { protected: ULONG nStrPos; ULONG nOwnPos; // Position NACH # und Len UINT16 nGrbit; ExcBundlesheetBase(); public: ExcBundlesheetBase( RootData& rRootData, UINT16 nTab ); inline void SetStreamPos( ULONG nNewStrPos ) { nStrPos = nNewStrPos; } void UpdateStreamPos( XclExpStream& rStrm ); virtual UINT16 GetNum() const; }; class ExcBundlesheet : public ExcBundlesheetBase { private: ByteString aName; virtual void SaveCont( XclExpStream& rStrm ); public: ExcBundlesheet( RootData& rRootData, UINT16 nTab ); virtual ULONG GetLen() const; }; //--------------------------------------------------------- class ExcDummy_02 - // sheet dummies: CALCMODE to SETUP class ExcDummy_02a : public ExcDummyRec { private: static const BYTE pMyData[]; static const ULONG nMyLen; public: virtual ULONG GetLen( void ) const; virtual const BYTE* GetData( void ) const; }; //--------------------------------------------------------- class ExcDummy_02 - // sheet dummies: CALCMODE to SETUP class ExcDummy_02b : public ExcDummyRec { private: static const BYTE pMyData[]; static const ULONG nMyLen; public: virtual ULONG GetLen( void ) const; virtual const BYTE* GetData( void ) const; }; //--------------------------------------------------------- class ExcDummy_02 - // sheet dummies: CALCMODE to SETUP class ExcDummy_02c : public ExcDummyRec { private: static const BYTE pMyData[]; static const ULONG nMyLen; public: virtual ULONG GetLen( void ) const; virtual const BYTE* GetData( void ) const; }; //------------------------------------------------------------- class ExcNote - class ExcNote : public ExcEmptyRec { private: ByteString* pText; ScAddress aPos; UINT16 nTextLen; public: ExcNote( const ScAddress, const String& rText, RootData& ); virtual ~ExcNote(); virtual void Save( XclExpStream& rStrm ); }; //------------------------------------------------------------- class ExcCell - class ExcCell : public ExcRecord { protected: ScAddress aPos; sal_uInt32 mnXFId; static UINT32 nCellCount; // zaehlt DOPPELT: im Ctor und SaveCont static ScProgress* pPrgrsBar; #ifdef DBG_UTIL friend class ExcDocument; static INT32 _nRefCount; #endif ExcCell( const ScAddress rPos, const ScPatternAttr* pAttr, RootData& rRootData, const ULONG nAltNumForm = NUMBERFORMAT_ENTRY_NOT_FOUND ); virtual void SaveCont( XclExpStream& rStrm ); virtual void SaveDiff( XclExpStream& rStrm ); virtual ULONG GetDiffLen() const = 0; public: virtual ~ExcCell(); inline void SetXFId( sal_uInt32 nXFId ) { mnXFId = nXFId; } virtual sal_uInt32 GetXFId() const; inline static void ResetCellCount() { nCellCount = 0; } inline static void IncCellCount() { nCellCount++; } inline static UINT32 GetCellCount() { return nCellCount; } inline static void SetPrgrsBar( ScProgress& rNewBar ); inline static void ClearPrgrsBar() { pPrgrsBar = NULL; } virtual ULONG GetLen() const; }; inline void ExcCell::SetPrgrsBar( ScProgress& rNewBar ) { ResetCellCount(); // logisch... oder? pPrgrsBar = &rNewBar; } //----------------------------------------------------------- class ExcNumber - class ExcNumber : public ExcCell { private: double fVal; virtual void SaveDiff( XclExpStream& rStrm ); // instead of SaveCont() virtual ULONG GetDiffLen( void ) const; public: ExcNumber( const ScAddress, const ScPatternAttr*, RootData& rRootData, const double& rVal ); virtual UINT16 GetNum( void ) const; }; //---------------------------------------------------------- class ExcBoolerr - class ExcBoolerr : public ExcCell { private: UINT8 nVal; UINT8 bError; virtual void SaveDiff( XclExpStream& rStrm ); // instead of SaveCont() virtual ULONG GetDiffLen( void ) const; public: ExcBoolerr( const ScAddress, const ScPatternAttr*, RootData& rRootData, UINT8 nVal, BOOL bIsError ); virtual UINT16 GetNum( void ) const; }; //---------------------------------------------------------- class ExcRKMulRK - class ExcRKMulRK : public ExcCell { private: struct ExcRKMulRKEntry { sal_Int32 mnValue; sal_uInt32 mnXFId; }; typedef ScfDelList< ExcRKMulRKEntry > ExcRKMulRKEntryList; ExcRKMulRKEntryList maEntryList; protected: virtual void SaveCont( XclExpStream& rStrm ); virtual ULONG GetDiffLen( void ) const; public: ExcRKMulRK( const ScAddress, const ScPatternAttr*, RootData& rRootData, sal_Int32 nValue ); // returns new RK or NULL if an old RK was extendable ExcRKMulRK* Extend( const ScAddress rPos, const ScPatternAttr *pAttr, RootData& rRootData, sal_Int32 nValue ); virtual sal_uInt32 GetXFId() const; virtual UINT16 GetNum( void ) const; inline BOOL IsRK( void ) const { return maEntryList.Count() == 1; } inline BOOL IsMulRK( void ) const { return maEntryList.Count() > 1; } }; //------------------------------------------------------------ class ExcLabel - class ExcLabel : public ExcCell { private: ByteString aText; UINT16 nTextLen; virtual void SaveDiff( XclExpStream& rStrm ); // instead of SaveCont() virtual ULONG GetDiffLen( void ) const; public: ExcLabel( const ScAddress, const ScPatternAttr*, RootData& rRootData, const String& rText ); virtual ~ExcLabel(); virtual UINT16 GetNum( void ) const; }; //---------------------------------------------------------- class ExcRichStr // helper class for ExcRString and ExcLabel8/XclExpRichString class ExcRichStr { private: ScfUInt16List aForms; // Form und Pos nacheinander BiffTyp eBiff; public: ExcRichStr( ExcCell& rExcCell, String& rText, const ScPatternAttr* pAttr, const ScEditCell& rEdCell, RootData& rRoot, xub_StrLen nMaxChars ); inline ExcRichStr( const ExcRichStr& rCopy ) : aForms( rCopy.aForms ), eBiff( rCopy.eBiff ) {} ~ExcRichStr(); inline UINT16 GetFormCount() const; // number of bytes to be saved inline ULONG GetByteCount() const; // write list of forms void Write( XclExpStream& rStrm ); }; inline UINT16 ExcRichStr::GetFormCount() const { return (UINT16) Min( aForms.Count() / 2, (eBiff < Biff8 ? ULONG(0xFF) : ULONG(0xFFFF)) ); } inline ULONG ExcRichStr::GetByteCount() const { return (eBiff < Biff8 ? 2 : 4) * GetFormCount(); } //---------------------------------------------------------- class ExcRString - class ExcRString : public ExcCell, ExcRoot { private: String aText; ExcRichStr* pRichStr; UINT16 nTextLen; virtual void SaveDiff( XclExpStream& rStrm ); // instead of SaveCont() virtual ULONG GetDiffLen( void ) const; public: ExcRString( const ScAddress aPos, const ScPatternAttr* pAttr, RootData& rRootData, const ScEditCell& rEdCell ); virtual ~ExcRString(); virtual UINT16 GetNum( void ) const; }; /*----------------------------------------------------------------------*/ class ExcFmlaResultStr : public XclExpRecord { private: XclExpString maResultText; public: ExcFmlaResultStr(const XclExpString &aFmlaText); virtual ~ExcFmlaResultStr(); private: virtual void WriteBody( XclExpStream& rStrm ); }; //---------------------------------------------------------- class ExcFormula - class ExcFormula : public ExcCell { private: sal_Char* pData; UINT16 nFormLen; BOOL bShrdFmla; ScFormulaCell* pFCell; virtual void SaveDiff( XclExpStream& rStrm ); // instead of SaveCont() virtual ULONG GetDiffLen( void ) const; public: ExcFormula( const ScAddress rPos, const ScPatternAttr *pAttr, RootData& rRootData, const ULONG nAltNumForm, const ScTokenArray& rCode, ExcArray** ppArray = NULL, ScMatrixMode eMM = MM_NONE, ExcShrdFmla** ppShrdFmla = NULL, ExcArrays* pShrdFmlas = NULL, ScFormulaCell* pFCell = NULL, ExcFmlaResultStr **pFormulaResult = NULL); ~ExcFormula(); inline const ScAddress& GetPosition() const { return aPos; } // from ExcCell void SetTableOp( USHORT nCol, USHORT nRow ); // for TableOp export virtual UINT16 GetNum( void ) const; static BYTE ScErrorCodeToExc(UINT16 nErrorCode); }; //---------------------------------------------------- class ExcBlankMulblank - class ExcBlankMulblank : public ExcCell { protected: struct XclExpBlankCell { sal_uInt32 mnXFId; sal_uInt16 mnCount; inline explicit XclExpBlankCell() : mnXFId( 0 ), mnCount( 0 ) {} inline explicit XclExpBlankCell( sal_uInt32 nXFId, sal_uInt16 nCount ) : mnXFId( nXFId ), mnCount( nCount ) {} }; typedef ::std::vector< XclExpBlankCell > XclExpBlankCellVec; XclExpBlankCellVec maCellList; ULONG nRecLen; UINT16 nLastCol; BOOL bMulBlank; BOOL bDummy; // not saved, 'cause row contains formatting info inline sal_uInt32 GetXFId( UINT32 nEntry ) const { return (UINT16) nEntry; } inline UINT16 GetCount( UINT32 nEntry ) const { return (UINT16)(nEntry >> 16); } inline void Append( sal_uInt32 nXFId, sal_uInt16 nCount ); void AddEntries( const ScAddress rPos, const ScPatternAttr* pAttr, RootData& rRootData, UINT16 nCount, ExcTable& rExcTab ); virtual void SaveDiff( XclExpStream& rStrm ); // instead of SaveCont() virtual ULONG GetDiffLen( void ) const; public: ExcBlankMulblank( const ScAddress rPos, const ScPatternAttr* pFirstAttr, RootData& rRootData, UINT16 nFirstCount, ExcTable& rExcTab ); void Add( const ScAddress rPos, const ScPatternAttr* pAttr, RootData& rRootData, UINT16 nAddCount, ExcTable& rExcTab ); inline UINT16 GetLastCol() const { return nLastCol; } virtual sal_uInt32 GetXFId() const; // returns last used XF virtual UINT16 GetNum() const; virtual void Save( XclExpStream& ); // for dummy case }; inline void ExcBlankMulblank::Append( sal_uInt32 nXFId, sal_uInt16 nCount ) { maCellList.push_back( XclExpBlankCell( nXFId, nCount ) ); } //---------------------------------------------------- class ExcNameListEntry - class ExcNameListEntry : public ExcRecord { protected: UINT8* pData; UINT16 nFormLen; UINT16 nTabNum; // Excel index, 1-based, 0==none UINT8 nBuiltInKey; BOOL bDummy; void DeleteData(); void SetCode( const ExcUPN& rUPN ); // default: save builtin key virtual void SaveCont( XclExpStream& rStrm ); public: ExcNameListEntry(); ExcNameListEntry( RootData& rRootData, UINT16 nScTab, UINT8 nKey ); virtual ~ExcNameListEntry(); inline UINT16 GetTabIndex() const { return nTabNum; } inline UINT8 GetBuiltInKey() const { return nBuiltInKey; } inline BOOL IsDummy() const { return bDummy; } virtual UINT16 GetNum() const; virtual ULONG GetLen() const; }; //------------------------------------------------------------- class ExcName - class ExcName : public ExcNameListEntry, public ExcRoot { private: String aName; BiffTyp eBiff; BOOL bHidden; BOOL bBuiltIn; void Init( BOOL bHid = FALSE, BOOL bBIn = FALSE ); void BuildFormula( const ScRange& rRange ); void SetName( const String& rRangeName ); void SetUniqueName( const String& rRangeName ); BOOL SetBuiltInName( const String& rName, UINT8 nKey ); BOOL IsBuiltInAFName( const String& rName, UINT8 nKey ); virtual void SaveCont( XclExpStream& rStrm ); public: ExcName( RootData& rRootData, ScRangeData* pRange ); ExcName( RootData& rRootData, ScDBData* pArea ); ExcName( RootData& rRootData, const ScRange& rRange, const String& rName ); ExcName( RootData& rRootData, const ScRange& rRange, UINT8 nKey, BOOL bHid = FALSE ); inline const String& GetName() const { return aName; } virtual ULONG GetLen() const; }; // ---- class XclBuildInName ----------------------------------------- class XclBuildInName : public ExcNameListEntry { private: ScRangeList aRL; protected: inline void Append( const ScRange& rNew ) { aRL.Append( rNew ); } void CreateFormula( RootData& rRootData ); public: XclBuildInName( RootData& rRootData, UINT16 nScTab, UINT8 nKey ); }; // ---- class XclPrintRange, class XclTitleRange --------------------- class XclPrintRange : public XclBuildInName { public: XclPrintRange( RootData& rRootData, UINT16 nScTab ); }; class XclPrintTitles : public XclBuildInName { public: XclPrintTitles( RootData& rRootData, UINT16 nScTab ); }; //--------------------------------------------------------- class ExcNameList - class ExcNameList : public ExcEmptyRec, private List { private: ULONG nFirstPrintRangeIx; ULONG nFirstPrintTitleIx; ULONG nFirstOtherNameIx; ::std::vector< sal_uInt32 > maNextInsVec; /// List positions for next insertion for each sheet. inline ExcNameListEntry* _First() { return (ExcNameListEntry*) List::First(); } inline ExcNameListEntry* _Next() { return (ExcNameListEntry*) List::Next(); } inline ExcNameListEntry* _Get( ULONG nIndex ) const { return (ExcNameListEntry*) List::GetObject( nIndex ); } UINT16 Append( ExcNameListEntry* pName ); public: ExcNameList( RootData& rRootData ); virtual ~ExcNameList(); UINT16 GetBuiltInIx( const ExcNameListEntry* pName ); /** Inserts a named range in table name sort order. */ void InsertSorted( RootData& rRootData, ExcNameListEntry* pName, sal_uInt16 nScTab ); virtual void Save( XclExpStream& rStrm ); }; //------------------------------------------------------- class ExcDimensions - class ExcDimensions : public ExcRecord { private: UINT16 nRwMic; UINT16 nRwMac; UINT16 nColMic; UINT16 nColMac; BiffTyp eBiff; virtual void SaveCont( XclExpStream& rStrm ); public: ExcDimensions( BiffTyp ); ExcDimensions( UINT16 nFirstCol, UINT16 nFirstRow, UINT16 nLastCol, UINT16 nLastRow, BiffTyp ); void SetLimits( UINT16 nFirstCol, UINT16 nFirstRow, UINT16 nLastCol, UINT16 nLastRow ); virtual UINT16 GetNum( void ) const; virtual ULONG GetLen( void ) const; }; //--------------------------------------------------------- class ExcEOutline - class ExcEOutline { private: ScOutlineArray* pOLArray; UINT16 nCurrExcLevel; BOOL bIsColl; UINT16 nEnd[ SC_OL_MAXDEPTH ]; BOOL bHidden[ SC_OL_MAXDEPTH ]; protected: public: ExcEOutline( ScOutlineArray* pArray ); void Update( UINT16 nNum ); inline BOOL IsCollapsed() const { return bIsColl; } inline UINT16 GetLevel() const { return Min( nCurrExcLevel, (UINT16) EXC_OUTLINE_MAX ); } }; //------------------------------------------------------------ class ExcEGuts - class ExcEGuts : public ExcRecord { private: UINT16 nRowLevel; UINT16 nColLevel; virtual void SaveCont( XclExpStream& rStrm ); protected: public: ExcEGuts( ScOutlineArray* pCol, ScOutlineArray* pRow ); virtual UINT16 GetNum() const; virtual ULONG GetLen() const; }; //-------------------------------------------------------------- class ExcRow - class ExcRow : public ExcRecord { private: friend class DefRowXFs; ExcTable& rExcTab; UINT16 nNum; UINT16 nFirstCol; UINT16 nLastCol; UINT16 nHeight; UINT16 nOptions; sal_uInt32 mnXFId; BOOL bDefHeight; void SetRange( UINT16 nFCol, UINT16 nLCol ); void SetHeight( UINT16 nNewHeight, BOOL bUser ); virtual void SaveCont( XclExpStream& rStrm ); protected: public: ExcRow( UINT16 nNum, UINT16 nTab, UINT16 nFCol, UINT16 nLCol, sal_uInt32 nXFId, ScDocument& rDoc, ExcEOutline& rOutline, ExcTable& rExcTab ); inline BOOL IsDefault(); virtual UINT16 GetNum() const; virtual ULONG GetLen() const; }; inline BOOL ExcRow::IsDefault() { return (TRUEBOOL( nHeight & EXC_ROW_FLAGDEFHEIGHT ) && !nOptions); } //--------------------------------------------------------- class ExcRowBlock - class ExcRowBlock : public ExcEmptyRec { private: ExcRow** ppRows; // 32 rows per block UINT16 nNext; protected: public: ExcRowBlock(); virtual ~ExcRowBlock(); // returns new block or NULL if last block not full ExcRowBlock* Append( ExcRow* pNewRow ); void SetDefXFs( DefRowXFs& rDefRowXFs ); virtual void Save( XclExpStream& rStrm ); }; //------------------------------------------------------ class ExcDefcolwidth - class ExcDefcolwidth : public ExcRecord { private: UINT16 nWidth; virtual void SaveCont( XclExpStream& rStrm ); public: ExcDefcolwidth( UINT16 nDefColWidth ); virtual UINT16 GetNum( void ) const; virtual ULONG GetLen( void ) const; }; //---------------------------------------------------------- class ExcColinfo - class ExcColinfo : public ExcRecord { private: sal_uInt32 mnXFId; UINT16 nFirstCol; UINT16 nLastCol; UINT16 nColWidth; UINT16 nOptions; virtual void SaveCont( XclExpStream& rStrm ); public: ExcColinfo( UINT16 nCol, UINT16 nTab, sal_uInt32 nXFId, RootData&, ExcEOutline& rOutline ); // if expandable, delete rpExp and set to NULL void Expand( ExcColinfo*& rpExp ); virtual UINT16 GetNum( void ) const; virtual ULONG GetLen( void ) const; }; //------------------------------------------------------ class ExcExterncount - class ExcExterncount : public ExcRecord, ExcRoot { private: BOOL bTable; virtual void SaveCont( XclExpStream& rStrm ); public: ExcExterncount( RootData*, const BOOL bTable ); virtual UINT16 GetNum( void ) const; virtual ULONG GetLen( void ) const; }; //------------------------------------------------------ class ExcExternsheet - class ExcExternsheet : public ExcRecord, public ExcRoot { private: String aTabName; virtual void SaveCont( XclExpStream& rStrm ); public: ExcExternsheet( RootData* pRD, const UINT16 nTabNum ); virtual UINT16 GetNum( void ) const; virtual ULONG GetLen( void ) const; }; //-------------------------------------------------- class ExcExternsheetList - class ExcExternsheetList : public ExcEmptyRec, protected List { private: inline ExcExternsheet* _First() { return (ExcExternsheet*) List::First(); } inline ExcExternsheet* _Next() { return (ExcExternsheet*) List::Next(); } protected: public: virtual ~ExcExternsheetList(); inline void Add( ExcExternsheet* pNew ) { List::Insert( pNew, LIST_APPEND ); } virtual void Save( XclExpStream& rStrm ); }; //-------------------------------------------------------- class ExcExternDup - class ExcExternDup : public ExcEmptyRec { private: ExcExterncount& rExtCnt; ExcExternsheetList& rExtSheetList; protected: public: ExcExternDup( ExcExterncount&, ExcExternsheetList& ); ExcExternDup( const ExcExternDup& ); virtual void Save( XclExpStream& rStrm ); }; //---------------------------------------------------------- class ExcWindow2 - class ExcWindow2 : public ExcRecord { private: UINT16 nTable; virtual void SaveCont( XclExpStream& rStrm ); public: ExcWindow2( UINT16 nTable ); inline UINT16 GetTable() const { return nTable; } virtual UINT16 GetNum( void ) const; virtual ULONG GetLen( void ) const; }; //-------------------------------------------------------- class ExcSelection - class ExcSelection : public ExcRecord { private: UINT16 nCol; UINT16 nRow; UINT8 nPane; virtual void SaveCont( XclExpStream& rStrm ); public: inline ExcSelection( UINT16 _nCol, UINT16 _nRow, UINT8 _nPane ) : nCol( _nCol ), nRow( _nRow ), nPane( _nPane ) {} virtual UINT16 GetNum( void ) const; virtual ULONG GetLen( void ) const; }; // XclExpWsbool =============================================================== class XclExpWsbool : public XclExpUInt16Record { public: XclExpWsbool( RootData& rRootData ); }; //------------------------------------------------------------ class ExcSetup - class ExcSetup : public ExcRecord { private: UINT16 nPaperSize; UINT16 nScale; UINT16 nPageStart; sal_uInt16 nFitToPages; UINT16 nGrbit; sal_uInt16 nHeaderMargin; sal_uInt16 nFooterMargin; virtual void SaveCont( XclExpStream& rStrm ); public: ExcSetup( RootData* ); virtual UINT16 GetNum( void ) const; virtual ULONG GetLen( void ) const; }; // Header/Footer ============================================================== /** Base class for header/footer contents. Constructs the complete format string based on the given which IDs. */ class XclExpHeaderFooter : public XclExpRecord, public ExcRoot { private: String maFormatString; /// The content of the header/footer. bool mbUnicode; /// true = write Unicode string. public: /** @param nHFSetWhichId The which ID of the SetItem of the header/footer. @param nHFTextWhichId The which ID od the text contents of the header/footer. */ XclExpHeaderFooter( sal_uInt16 nRecId, RootData& rRootData, sal_uInt16 nHFSetWhichId, sal_uInt16 nHFTextWhichId ); /** Writes the record, if the text is not empty. */ virtual void Save( XclExpStream& rStrm ); private: /** Constructs the contents of the complete header/footer. */ static void GetFormatString( String& rString, RootData& rRootData, sal_uInt16 nWhich ); /** Writes the string (Byte or Unicode, depending on mbUnicode). */ virtual void WriteBody( XclExpStream& rStrm ); }; /** Contains the header text of a sheet. */ class XclExpHeader : public XclExpHeaderFooter { public: XclExpHeader( RootData& rRootData ); }; /** Contains the footer text of a sheet. */ class XclExpFooter : public XclExpHeaderFooter { public: XclExpFooter( RootData& rRootData ); }; // ============================================================================ //----------------------------------------------------- class ExcPrintheaders - class ExcPrintheaders : public ExcBoolRecord { private: public: ExcPrintheaders( SfxItemSet* ); virtual UINT16 GetNum( void ) const; }; //--------------------------------------------------- class ExcPrintGridlines - class ExcPrintGridlines : public ExcBoolRecord { private: public: ExcPrintGridlines( SfxItemSet* ); virtual UINT16 GetNum( void ) const; }; //---------------------------------------------------------- class ExcHcenter - class ExcHcenter : public ExcBoolRecord { private: public: ExcHcenter( SfxItemSet* ); virtual UINT16 GetNum( void ) const; }; //---------------------------------------------------------- class ExcVcenter - class ExcVcenter : public ExcBoolRecord { private: public: ExcVcenter( SfxItemSet* ); virtual UINT16 GetNum( void ) const; }; //---------------------------------------------------------------- AutoFilter - // classes: ExcFilterMode, ExcAutoFilterInfo, ExcFilterCondition, // ExcAutoFilter, ExcAutoFilterRecs class ExcFilterMode : public ExcRecord { public: virtual UINT16 GetNum() const; virtual ULONG GetLen() const; }; class ExcAutoFilterInfo : public ExcRecord { private: UINT16 nCount; virtual void SaveCont( XclExpStream& rStrm ); protected: public: inline ExcAutoFilterInfo( UINT16 nC ) { nCount = nC; } virtual ~ExcAutoFilterInfo(); virtual UINT16 GetNum() const; virtual ULONG GetLen() const; }; class ExcFilterCondition { private: UINT8 nType; UINT8 nOper; double fVal; XclExpUniString* pText; protected: public: ExcFilterCondition(); ~ExcFilterCondition(); inline BOOL IsEmpty() const { return (nType == EXC_AFTYPE_NOTUSED); } inline BOOL HasEqual() const { return (nOper == EXC_AFOPER_EQUAL); } ULONG GetTextBytes() const; void SetCondition( UINT8 nTp, UINT8 nOp, double fV, String* pT ); void Save( XclExpStream& rStrm ); void SaveText( XclExpStream& rStrm ); }; class ExcAutoFilter : public ExcRecord { private: UINT16 nCol; UINT16 nFlags; ExcFilterCondition aCond[ 2 ]; BOOL AddCondition( ScQueryConnect eConn, UINT8 nType, UINT8 nOp, double fVal, String* pText, BOOL bSimple = FALSE ); virtual void SaveCont( XclExpStream& rStrm ); protected: public: ExcAutoFilter( UINT16 nC ); inline UINT16 GetCol() const { return nCol; } inline BOOL HasCondition() const { return !aCond[ 0 ].IsEmpty(); } inline BOOL HasTop10() const { return TRUEBOOL( nFlags & EXC_AFFLAG_TOP10 ); } BOOL AddEntry( RootData& rRoot, const ScQueryEntry& rEntry ); virtual UINT16 GetNum() const; virtual ULONG GetLen() const; }; class ExcAutoFilterRecs : private List, public ExcEmptyRec { private: ExcFilterMode* pFilterMode; ExcAutoFilterInfo* pFilterInfo; inline ExcAutoFilter* _First() { return (ExcAutoFilter*) List::First(); } inline ExcAutoFilter* _Next() { return (ExcAutoFilter*) List::Next(); } ExcAutoFilter* GetByCol( UINT16 nCol ); // always 0-based BOOL IsFiltered( UINT16 nCol ); void DeleteList(); inline void Append( ExcAutoFilter* pFilter ) { List::Insert( pFilter, LIST_APPEND ); } void AddObjRecs( RootData& rRoot, const ScAddress& rPos, UINT16 nCols ); protected: public: ExcAutoFilterRecs( RootData& rRoot, UINT16 nTab ); virtual ~ExcAutoFilterRecs(); virtual void Save( XclExpStream& rStrm ); }; // ---------------------------------------------------------------------------- /** Stores the margin value of one border of the page. */ class XclExpMargin : public XclExpDoubleRecord { public: /** @param nMargin The margin value in twips. @param eSide The page border identifier. */ XclExpMargin( sal_Int32 nMargin, XclMarginType eSide ); }; // Manual page breaks ========================================================= /** Stores an array of manual page breaks for columns or rows. */ class XclExpPagebreaks : public XclExpRecord { protected: ScfUInt16List maPagebreaks; /// Array of manual page breaks. public: XclExpPagebreaks( RootData& rRootData, sal_uInt16 nScTab, XclPBOrientation eOrient ); /** Writes the record, if the list is not empty. */ virtual void Save( XclExpStream& rStrm ); private: /** Writes the page break list. */ virtual void WriteBody( XclExpStream& rStrm ); }; // ---------------------------------------------------------------------------- /** Stores an array of manual page breaks for columns or rows (BIFF8). */ class XclExpPagebreaks8 : public XclExpPagebreaks { private: sal_uInt16 mnRangeMax; /// Index of last row/column. public: XclExpPagebreaks8( RootData& rRootData, sal_uInt16 nScTab, XclPBOrientation eOrient ); private: /** Writes the page break list. */ virtual void WriteBody( XclExpStream& rStrm ); }; // ============================================================================ //------------------------ class ExcArray, class ExcArrays, class ExcShrdFmla - class ExcArray : public ExcRecord { protected: UINT32 nID; UINT16 nFirstRow; UINT16 nLastRow; UINT8 nFirstCol; UINT8 nLastCol; sal_Char* pData; UINT16 nFormLen; void SetColRow( UINT8 nCol, UINT16 nRow, UINT32 nID = 0xFFFFFFFF ); virtual void SaveCont( XclExpStream& rStrm ); ExcArray( const sal_Char* pData, UINT16 nLen, UINT8 nCol, UINT16 nRow ); public: ExcArray( const ExcUPN&, UINT8 nCol, UINT16 nRow ); ExcArray( UINT8 nCol, UINT16 nRow, UINT32 nID ); virtual ~ExcArray(); virtual UINT16 GetNum() const; virtual ULONG GetLen() const; BOOL AppendBy( const ExcArray& rExt ); // TRUE, if rEXt is touching given range and extend range BOOL AppendBy( UINT8 nStartCol, UINT16 nStartRow, UINT8 nEndCol, UINT16 nEndRow ); }; class ExcArrays : protected List { private: protected: public: ExcArrays( void ); virtual ~ExcArrays(); BOOL Insert( ExcArray* pPossibleNewArrayFormula ); // insert only, if not already in array // only ref in list, so if return is TRUE, do not delete _before_ using // Insert() the _last_ time! BOOL Extend( UINT8 nStartCol, UINT16 nStartRow, UINT8 nEndCol, UINT16 nEndRow ); // extend existing range, when start is base inline void Append( ExcArray* ); }; inline void ExcArrays::Append( ExcArray* p ) { List::Insert( p, LIST_APPEND ); } class ExcShrdFmla : public ExcArray { private: // ScRange aPos; // sal_Char* pData; // UINT16 nLen; virtual void SaveCont( XclExpStream& rStrm ); public: ExcShrdFmla( const sal_Char* pData, UINT16 nLen, const ScRange& rPos ); virtual ~ExcShrdFmla(); virtual UINT16 GetNum() const; virtual ULONG GetLen() const; }; //--------------------------- class XclExpTableOp, class XclExpTableOpManager - // multiple operations aka table operations (record TABLE) // a multiple operations record // stores pointers to all affected formula records class XclExpTableOp : private List, public ExcRecord { private: USHORT nFirstCol; USHORT nLastCol; USHORT nNextCol; // next column of next row USHORT nFirstRow; USHORT nLastRow; USHORT nMode; USHORT nColInpCol; USHORT nColInpRow; USHORT nRowInpCol; USHORT nRowInpRow; BOOL bIsValid; inline ExcFormula* _First() { return (ExcFormula*) List::First(); } inline ExcFormula* _Next() { return (ExcFormula*) List::Next(); } inline void Append( ExcFormula* pFmla ) { List::Insert( pFmla, LIST_APPEND ); } virtual void SaveCont( XclExpStream& rStrm ); public: XclExpTableOp( ExcFormula& rFormula, const ScAddress& rColFirstPos, const ScAddress& rRowFirstPos, USHORT nNewMode ); virtual ~XclExpTableOp(); BOOL IsAppendable( const ScAddress& rPos ); BOOL CheckPosition( const ScAddress& rPos, const ScAddress& rFmlaPos, const ScAddress& rColFirstPos, const ScAddress& rColRelPos, const ScAddress& rRowFirstPos, const ScAddress& rRowRelPos, BOOL bMode2 ); static BOOL CheckFirstPosition( const ScAddress& rPos, const ScAddress& rFmlaPos, const ScAddress& rColFirstPos, const ScAddress& rColRelPos, const ScAddress& rRowFirstPos, const ScAddress& rRowRelPos, BOOL bMode2, USHORT& rnMode ); // insert pointer to Formula rec and update range data void InsertCell( ExcFormula& rFormula ); // change #NA error values of formula recs to TableOp values if in table op range void UpdateCells(); virtual void Save( XclExpStream& rStrm ); virtual UINT16 GetNum() const; virtual ULONG GetLen() const; }; // stores pointers to ExcTableOp records - insert cells to existing or new ExcTableOp class XclExpTableOpManager : private List { private: inline XclExpTableOp* _First() { return (XclExpTableOp*) List::First(); } inline XclExpTableOp* _Next() { return (XclExpTableOp*) List::Next(); } public: inline XclExpTableOpManager() : List() {} virtual ~XclExpTableOpManager(); // create & return new TableOp record or insert to an existing XclExpTableOp* InsertCell( const ScTokenArray* pTokenArray, ExcFormula& rFormula ); // change #NA error values of formula recs to TableOp values void UpdateCells(); }; #endif
#include <algorithm> #include <cassert> #include <cmath> #include <limits> #include <thread> #include "SoftwareRenderer.h" #include "../Math/Constants.h" #include "../Media/Color.h" #include "../Utilities/Debug.h" #include "../Utilities/Platform.h" #include "../World/VoxelData.h" #include "../World/VoxelDataType.h" #include "../World/VoxelGrid.h" SoftwareRenderer::OcclusionData::OcclusionData(int yMin, int yMax) { this->yMin = yMin; this->yMax = yMax; } SoftwareRenderer::OcclusionData::OcclusionData() : OcclusionData(0, 0) { } void SoftwareRenderer::OcclusionData::clipRange(int *yStart, int *yEnd) const { // To do. /*const bool occluded = (*yEnd <= this->yMin) || (*yStart >= this->yMax); if (occluded) { // The drawing range is completely hidden. *yStart = *yEnd; } else { // To do: need to handle more cases (yStart == yEnd, outside of screen, etc.). // Clip the drawing range. *yStart = std::max(*yStart, this->yMin); *yEnd = std::min(*yEnd, this->yMax); }*/ } void SoftwareRenderer::OcclusionData::update(int yStart, int yEnd) { // To do. // Slightly different than clipRange() because values just needs to be adjacent // rather than overlap. /*const bool canIncreaseMin = yStart <= this->yMin; const bool canDecreaseMax = yEnd >= this->yMax; // To do: need to handle more cases (yStart == yEnd, outside of screen, etc.). // Determine how to update the occlusion ranges. if (canIncreaseMin && canDecreaseMax) { // The drawing range touches the top and bottom occlusion values, so the // entire column is occluded. this->yMin = this->yMax; } else if (canIncreaseMin) { this->yMin = std::min(yEnd, this->yMax); } else if (canDecreaseMax) { this->yMax = std::max(yStart, this->yMin); }*/ } SoftwareRenderer::ShadingInfo::ShadingInfo(const Double3 &horizonSkyColor, const Double3 &zenithSkyColor, const Double3 &sunColor, const Double3 &sunDirection, double ambient, double fogDistance) : horizonSkyColor(horizonSkyColor), zenithSkyColor(zenithSkyColor), sunColor(sunColor), sunDirection(sunDirection) { this->ambient = ambient; this->fogDistance = fogDistance; } SoftwareRenderer::FrameView::FrameView(uint32_t *colorBuffer, double *depthBuffer, int width, int height) { this->colorBuffer = colorBuffer; this->depthBuffer = depthBuffer; this->width = width; this->height = height; } const double SoftwareRenderer::NEAR_PLANE = 0.0001; const double SoftwareRenderer::FAR_PLANE = 1000.0; SoftwareRenderer::SoftwareRenderer(int width, int height) { // Initialize 2D frame buffer. const int pixelCount = width * height; this->depthBuffer = std::vector<double>(pixelCount, std::numeric_limits<double>::infinity()); // Initialize occlusion columns. this->occlusion = std::vector<OcclusionData>(width, OcclusionData(0, height)); this->width = width; this->height = height; // Obtain the number of threads to use. this->renderThreadCount = Platform::getThreadCount(); // Fog distance is zero by default. this->fogDistance = 0.0; } SoftwareRenderer::~SoftwareRenderer() { } void SoftwareRenderer::addFlat(int id, const Double3 &position, double width, double height, int textureID) { // Verify that the ID is not already in use. DebugAssert(this->flats.find(id) == this->flats.end(), "Flat ID \"" + std::to_string(id) + "\" already taken."); SoftwareRenderer::Flat flat; flat.position = position; flat.width = width; flat.height = height; flat.textureID = textureID; flat.flipped = false; // The initial value doesn't matter; it's updated frequently. // Add the flat (sprite, door, store sign, etc.). this->flats.insert(std::make_pair(id, flat)); } void SoftwareRenderer::addLight(int id, const Double3 &point, const Double3 &color, double intensity) { DebugNotImplemented(); } int SoftwareRenderer::addTexture(const uint32_t *texels, int width, int height) { const int texelCount = width * height; SoftwareTexture texture; texture.texels = std::vector<Double4>(texelCount); texture.emissionTexels = std::vector<double>(texelCount); std::fill(texture.emissionTexels.begin(), texture.emissionTexels.end(), 0.0); texture.width = width; texture.height = height; // Convert ARGB color from integer to double-precision format for speed. // This does waste an extreme amount of memory (32 bytes per pixel!), but // it's not a big deal for Arena's textures (mostly 64x64, so eight textures // would be a megabyte). Double4 *textureTexels = texture.texels.data(); for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { const int index = x + (y * width); textureTexels[index] = Double4::fromARGB(texels[index]); // If it's a white texel, it's used with night lights (i.e., yellow at night). const Double4 &texel = textureTexels[index]; const bool isWhite = (texel.x == 1.0) && (texel.y == 1.0) && (texel.z == 1.0); if (isWhite) { texture.lightTexels.push_back(Int2(x, y)); } } } this->textures.push_back(std::move(texture)); return static_cast<int>(this->textures.size() - 1); } void SoftwareRenderer::updateFlat(int id, const Double3 *position, const double *width, const double *height, const int *textureID, const bool *flipped) { const auto flatIter = this->flats.find(id); DebugAssert(flatIter != this->flats.end(), "Cannot update a non-existent flat (" + std::to_string(id) + ")."); SoftwareRenderer::Flat &flat = flatIter->second; // Check which values requested updating and update them. if (position != nullptr) { flat.position = *position; } if (width != nullptr) { flat.width = *width; } if (height != nullptr) { flat.height = *height; } if (textureID != nullptr) { flat.textureID = *textureID; } if (flipped != nullptr) { flat.flipped = *flipped; } } void SoftwareRenderer::updateLight(int id, const Double3 *point, const Double3 *color, const double *intensity) { DebugNotImplemented(); } void SoftwareRenderer::setFogDistance(double fogDistance) { this->fogDistance = fogDistance; } void SoftwareRenderer::setSkyPalette(const uint32_t *colors, int count) { this->skyPalette = std::vector<Double3>(count); for (size_t i = 0; i < this->skyPalette.size(); i++) { this->skyPalette[i] = Double3::fromRGB(colors[i]); } } void SoftwareRenderer::setNightLightsActive(bool active) { // To do: activate lights (don't worry about textures). // Change voxel texels based on whether it's night. const Double4 texelColor = Double4::fromARGB( (active ? Color(255, 166, 0) : Color::Black).toARGB()); const double texelEmission = active ? 1.0 : 0.0; for (auto &texture : this->textures) { std::vector<Double4> &texels = texture.texels; std::vector<double> &emissionTexels = texture.emissionTexels; for (const auto &lightTexels : texture.lightTexels) { const int index = lightTexels.x + (lightTexels.y * texture.width); texels.at(index) = texelColor; emissionTexels.at(index) = texelEmission; } } } void SoftwareRenderer::removeFlat(int id) { // Make sure the flat exists before removing it. const auto flatIter = this->flats.find(id); DebugAssert(flatIter != this->flats.end(), "Cannot remove a non-existent flat (" + std::to_string(id) + ")."); this->flats.erase(flatIter); } void SoftwareRenderer::removeLight(int id) { DebugNotImplemented(); } void SoftwareRenderer::removeAllTextures() { this->textures.clear(); } void SoftwareRenderer::resize(int width, int height) { const int pixelCount = width * height; this->depthBuffer.resize(pixelCount); std::fill(this->depthBuffer.begin(), this->depthBuffer.end(), std::numeric_limits<double>::infinity()); this->occlusion.resize(width); std::fill(this->occlusion.begin(), this->occlusion.end(), OcclusionData(0, height)); this->width = width; this->height = height; } void SoftwareRenderer::updateVisibleFlats(const Double2 &eye, const Double2 &direction, const Matrix4d &transform, double yShear, double aspect, double zoom) { assert(direction.isNormalized()); this->visibleFlats.clear(); // Each flat shares the same axes. The forward direction always faces opposite to // the camera direction. const Double3 flatForward = Double3(-direction.x, 0.0, -direction.y).normalized(); const Double3 flatUp = Double3::UnitY; const Double3 flatRight = flatForward.cross(flatUp).normalized(); // This is the visible flat determination algorithm. It goes through all flats and sees // which ones would be at least partially visible in the view frustum. for (const auto &pair : this->flats) { const Flat &flat = pair.second; // Scaled axes based on flat dimensions. const Double3 flatRightScaled = flatRight * (flat.width * 0.50); const Double3 flatUpScaled = flatUp * flat.height; // Calculate each corner of the flat in world space. Flat::Frame flatFrame; flatFrame.bottomStart = flat.position + flatRightScaled; flatFrame.bottomEnd = flat.position - flatRightScaled; flatFrame.topStart = flatFrame.bottomStart + flatUpScaled; flatFrame.topEnd = flatFrame.bottomEnd + flatUpScaled; // If the flat is somewhere in front of the camera, do further checks. const Double2 flatPosition2D(flat.position.x, flat.position.z); const Double2 flatEyeDiff = (flatPosition2D - eye).normalized(); const bool inFrontOfCamera = direction.dot(flatEyeDiff) > 0.0; if (inFrontOfCamera) { // Now project two of the flat's opposing corner points into camera space. // The Z value is used with flat sorting (not rendering), and the X and Y values // are used to find where the flat is on-screen. Double4 projStart = transform * Double4(flatFrame.topStart, 1.0); Double4 projEnd = transform * Double4(flatFrame.bottomEnd, 1.0); // Normalize coordinates. projStart = projStart / projStart.w; projEnd = projEnd / projEnd.w; // Assign each screen value to the flat frame data. flatFrame.startX = 0.50 + (projStart.x * 0.50); flatFrame.endX = 0.50 + (projEnd.x * 0.50); flatFrame.startY = (0.50 + yShear) - (projStart.y * 0.50); flatFrame.endY = (0.50 + yShear) - (projEnd.y * 0.50); flatFrame.z = projStart.z; // Check that the Z value is within the clipping planes. const bool inPlanes = (flatFrame.z >= SoftwareRenderer::NEAR_PLANE) && (flatFrame.z <= SoftwareRenderer::FAR_PLANE); if (inPlanes) { // Add the flat data to the draw list. this->visibleFlats.push_back(std::make_pair(&flat, std::move(flatFrame))); } } } // Sort the visible flats farthest to nearest (relevant for transparencies). std::sort(this->visibleFlats.begin(), this->visibleFlats.end(), [](const std::pair<const Flat*, Flat::Frame> &a, const std::pair<const Flat*, Flat::Frame> &b) { return a.second.z > b.second.z; }); } /*Double3 SoftwareRenderer::castRay(const Double3 &direction, const VoxelGrid &voxelGrid) const { // This is an extension of Lode Vandevenne's DDA algorithm from 2D to 3D. // Technically, it could be considered a "3D-DDA" algorithm. It will eventually // have some additional features so all of Arena's geometry can be represented. // To do: // - Figure out proper DDA lengths for variable-height voxels, and why using // voxelHeight squared instead of 1.0 in deltaDist.y looks weird (sideDist.y?). // - Cuboids within voxels (bridges, beds, shelves) with variable Y offset and size. // - Sprites (SpriteGrid? Sprite data, and list of sprite IDs per voxel). // - Transparent textures (check texel alpha in DDA loop). // - Sky (if hitID == 0). // - Shading (shadows from the sun, point lights). // Some floating point behavior assumptions: // -> (value / 0.0) == infinity // -> (value / infinity) == 0.0 // -> (int)(-0.8) == 0 // -> (int)floor(-0.8) == -1 // -> (int)ceil(-0.8) == 0 const Double3 dirSquared( direction.x * direction.x, direction.y * direction.y, direction.z * direction.z); // Height (Y size) of each voxel in the voxel grid. Some levels in Arena have // "tall" voxels, so the voxel height must be a variable. const double voxelHeight = voxelGrid.getVoxelHeight(); // A custom variable that represents the Y "floor" of the current voxel. const double eyeYRelativeFloor = std::floor(this->eye.y / voxelHeight) * voxelHeight; // Calculate delta distances along each axis. These determine how far // the ray has to go until the next X, Y, or Z side is hit, respectively. const Double3 deltaDist( std::sqrt(1.0 + (dirSquared.y / dirSquared.x) + (dirSquared.z / dirSquared.x)), std::sqrt(1.0 + (dirSquared.x / dirSquared.y) + (dirSquared.z / dirSquared.y)), std::sqrt(1.0 + (dirSquared.x / dirSquared.z) + (dirSquared.y / dirSquared.z))); // Booleans for whether a ray component is non-negative. Used with step directions // and texture coordinates. const bool nonNegativeDirX = direction.x >= 0.0; const bool nonNegativeDirY = direction.y >= 0.0; const bool nonNegativeDirZ = direction.z >= 0.0; // Calculate step directions and initial side distances. Int3 step; Double3 sideDist; if (nonNegativeDirX) { step.x = 1; sideDist.x = (this->startCellReal.x + 1.0 - this->eye.x) * deltaDist.x; } else { step.x = -1; sideDist.x = (this->eye.x - this->startCellReal.x) * deltaDist.x; } if (nonNegativeDirY) { step.y = 1; sideDist.y = (eyeYRelativeFloor + voxelHeight - this->eye.y) * deltaDist.y; } else { step.y = -1; sideDist.y = (this->eye.y - eyeYRelativeFloor) * deltaDist.y; } if (nonNegativeDirZ) { step.z = 1; sideDist.z = (this->startCellReal.z + 1.0 - this->eye.z) * deltaDist.z; } else { step.z = -1; sideDist.z = (this->eye.z - this->startCellReal.z) * deltaDist.z; } // Make a copy of the initial side distances. They are used for the special case // of the ray ending in the same voxel it started in. const Double3 initialSideDist = sideDist; // Make a copy of the step magnitudes, converted to doubles. const Double3 stepReal( static_cast<double>(step.x), static_cast<double>(step.y), static_cast<double>(step.z)); // Get initial voxel coordinates. Int3 cell = this->startCell; // ID of a hit voxel. Zero (air) by default. char hitID = 0; // Axis of a hit voxel's side. X by default. enum class Axis { X, Y, Z }; Axis axis = Axis::X; // Distance squared (in voxels) that the ray has stepped. Square roots are // too slow to use in the DDA loop, so this is used instead. // - When using variable-sized voxels, this may be calculated differently. double cellDistSquared = 0.0; // Offset values for which corner of a voxel to compare the distance // squared against. The correct corner to use is important when culling // shapes at max view distance. const Double3 startCellWithOffset( this->startCellReal.x + ((1.0 + stepReal.x) / 2.0), eyeYRelativeFloor + (((1.0 + stepReal.y) / 2.0) * voxelHeight), this->startCellReal.z + ((1.0 + stepReal.z) / 2.0)); const Double3 cellOffset( (1.0 - stepReal.x) / 2.0, ((1.0 - stepReal.y) / 2.0) * voxelHeight, (1.0 - stepReal.z) / 2.0); // Get dimensions of the voxel grid. const int gridWidth = voxelGrid.getWidth(); const int gridHeight = voxelGrid.getHeight(); const int gridDepth = voxelGrid.getDepth(); // Check world bounds on the start voxel. Bounds are partially recalculated // for axes that the DDA loop is stepping through. bool voxelIsValid = (cell.x >= 0) && (cell.y >= 0) && (cell.z >= 0) && (cell.x < gridWidth) && (cell.y < gridHeight) && (cell.z < gridDepth); // Step through the voxel grid while the current coordinate is valid and // the total voxel distance stepped is less than the view distance. // (Note that the "voxel distance" is not the same as "actual" distance.) const char *voxels = voxelGrid.getVoxels(); while (voxelIsValid && (cellDistSquared < this->viewDistSquared)) { // Get the index of the current voxel in the voxel grid. const int gridIndex = cell.x + (cell.y * gridWidth) + (cell.z * gridWidth * gridHeight); // Check if the current voxel is solid. const char voxelID = voxels[gridIndex]; if (voxelID > 0) { hitID = voxelID; break; } if ((sideDist.x < sideDist.y) && (sideDist.x < sideDist.z)) { sideDist.x += deltaDist.x; cell.x += step.x; axis = Axis::X; voxelIsValid &= (cell.x >= 0) && (cell.x < gridWidth); } else if (sideDist.y < sideDist.z) { sideDist.y += deltaDist.y; cell.y += step.y; axis = Axis::Y; voxelIsValid &= (cell.y >= 0) && (cell.y < gridHeight); } else { sideDist.z += deltaDist.z; cell.z += step.z; axis = Axis::Z; voxelIsValid &= (cell.z >= 0) && (cell.z < gridDepth); } // Refresh how far the current cell is from the start cell, squared. // The "offsets" move each point to the correct corner for each voxel // so that the stepping stops correctly at max view distance. const Double3 cellDiff( (static_cast<double>(cell.x) + cellOffset.x) - startCellWithOffset.x, (static_cast<double>(cell.y) + cellOffset.y) - startCellWithOffset.y, (static_cast<double>(cell.z) + cellOffset.z) - startCellWithOffset.z); cellDistSquared = (cellDiff.x * cellDiff.x) + (cellDiff.y * cellDiff.y) + (cellDiff.z * cellDiff.z); } // Boolean for whether the ray ended in the same voxel it started in. const bool stoppedInFirstVoxel = cell == this->startCell; // Get the distance from the camera to the hit point. It is a special case // if the ray stopped in the first voxel. double distance; if (stoppedInFirstVoxel) { if ((initialSideDist.x < initialSideDist.y) && (initialSideDist.x < initialSideDist.z)) { distance = initialSideDist.x; axis = Axis::X; } else if (initialSideDist.y < initialSideDist.z) { distance = initialSideDist.y; axis = Axis::Y; } else { distance = initialSideDist.z; axis = Axis::Z; } } else { const size_t axisIndex = static_cast<size_t>(axis); // Assign to distance based on which axis was hit. if (axis == Axis::X) { distance = (static_cast<double>(cell.x) - this->eye.x + ((1.0 - stepReal.x) / 2.0)) / direction.x; } else if (axis == Axis::Y) { distance = ((static_cast<double>(cell.y) * voxelHeight) - this->eye.y + (((1.0 - stepReal.y) / 2.0) * voxelHeight)) / direction.y; } else { distance = (static_cast<double>(cell.z) - this->eye.z + ((1.0 - stepReal.z) / 2.0)) / direction.z; } } // If there was a hit, get the shaded color. if (hitID > 0) { // Intersection point on the voxel. const Double3 hitPoint = this->eye + (direction * distance); // Boolean for whether the hit point is on the back of a voxel face. const bool backFace = stoppedInFirstVoxel; // Texture coordinates. U and V are affected by which side is hit (near, far), // and whether the hit point is on the front or back of the voxel face. // - Note, for edge cases where {u,v}Val == 1.0, the texture coordinate is // out of bounds by one pixel, so instead of 1.0, something like 0.9999999 // should be used instead. std::nextafter(1.0, -INFINITY)? double u, v; if (axis == Axis::X) { const double uVal = hitPoint.z - std::floor(hitPoint.z); u = (nonNegativeDirX ^ backFace) ? uVal : (1.0 - uVal); //v = 1.0 - (hitPoint.y - std::floor(hitPoint.y)); v = 1.0 - (std::fmod(hitPoint.y, voxelHeight) / voxelHeight); } else if (axis == Axis::Y) { const double vVal = hitPoint.x - std::floor(hitPoint.x); u = hitPoint.z - std::floor(hitPoint.z); v = (nonNegativeDirY ^ backFace) ? vVal : (1.0 - vVal); } else { const double uVal = hitPoint.x - std::floor(hitPoint.x); u = (nonNegativeDirZ ^ backFace) ? (1.0 - uVal) : uVal; //v = 1.0 - (hitPoint.y - std::floor(hitPoint.y)); v = 1.0 - (std::fmod(hitPoint.y, voxelHeight) / voxelHeight); } // -- temp -- // Display bad texture coordinates as magenta. If any of these is true, it // means something above is wrong. if ((u < 0.0) || (u >= 1.0) || (v < 0.0) || (v >= 1.0)) { return Double3(1.0, 0.0, 1.0); } // -- end temp -- // Get the voxel data associated with the ID. Subtract 1 because the first // entry is at index 0 but the lowest hitID is 1. const VoxelData &voxelData = voxelGrid.getVoxelData(hitID - 1); // Get the texture depending on which face was hit. const TextureData &texture = (axis == Axis::Y) ? this->textures[voxelData.floorAndCeilingID] : this->textures[voxelData.sideID]; // Calculate position in texture. const int textureX = static_cast<int>(u * texture.width); const int textureY = static_cast<int>(v * texture.height); // Get the texel color at the hit point. // - Later, the alpha component can be used for transparency and ignoring // intersections (in the DDA loop). const Double4 &texel = texture.pixels[textureX + (textureY * texture.width)]; // Convert the texel to a 3-component color. const Double3 color(texel.x, texel.y, texel.z); // Linearly interpolate with some depth. const double depth = std::min(distance, this->viewDistance) / this->viewDistance; return color.lerp(this->fogColor, depth); } else { // No intersection. Return sky color. return this->fogColor; } }*/ Double3 SoftwareRenderer::getFogColor(double daytimePercent) const { // Get the real index (not the integer index), so the color can be interpolated // between two samples. const double realIndex = static_cast<double>(this->skyPalette.size()) * daytimePercent; const size_t index = static_cast<size_t>(realIndex); const size_t nextIndex = (index + 1) % this->skyPalette.size(); const Double3 &color = this->skyPalette[index]; const Double3 &nextColor = this->skyPalette[nextIndex]; const double percent = realIndex - std::floor(realIndex); return color.lerp(nextColor, percent); } Double3 SoftwareRenderer::getSunDirection(double daytimePercent) const { // The sun rises in the east (+Z) and sets in the west (-Z). const double radians = daytimePercent * (2.0 * Constants::Pi); return Double3(0.0, -std::cos(radians), std::sin(radians)).normalized(); } Double3 SoftwareRenderer::getNormal(VoxelData::Facing facing) { // Decide what the normal is, based on the facing. It can only be on the X or Z axis // because floors and ceilings are drawn separately from walls, and their // normals are trivial. if (facing == VoxelData::Facing::PositiveX) { return Double3::UnitX; } else if (facing == VoxelData::Facing::NegativeX) { return -Double3::UnitX; } else if (facing == VoxelData::Facing::PositiveZ) { return Double3::UnitZ; } else { return -Double3::UnitZ; } } double SoftwareRenderer::getProjectedY(const Double3 &point, const Matrix4d &transform, double yShear) { // Just do 3D projection for the Y and W coordinates instead of a whole // matrix * vector4 multiplication to keep from doing some unnecessary work. double projectedY, projectedW; transform.ywMultiply(point, projectedY, projectedW); // Convert the projected Y to normalized coordinates. projectedY /= projectedW; // Calculate the Y position relative to the center row of the screen, and offset it by // the Y-shear. Multiply by 0.5 for the correct aspect ratio. return (0.50 + yShear) - (projectedY * 0.50); } int SoftwareRenderer::getLowerBoundedPixel(double projected, int frameDim) { return std::min(std::max(0, static_cast<int>(std::ceil(projected - 0.50))), frameDim); } int SoftwareRenderer::getUpperBoundedPixel(double projected, int frameDim) { return std::min(std::max(0, static_cast<int>(std::floor(projected + 0.50))), frameDim); } bool SoftwareRenderer::findDiag1Intersection(int voxelX, int voxelZ, const Double2 &nearPoint, const Double2 &farPoint, RayHit &hit) { // Start, middle, and end points of the diagonal line segment relative to the grid. const Double2 diagStart( static_cast<double>(voxelX), static_cast<double>(voxelZ)); const Double2 diagMiddle( static_cast<double>(voxelX) + 0.50, static_cast<double>(voxelZ) + 0.50); const Double2 diagEnd( static_cast<double>(voxelX) + Constants::JustBelowOne, static_cast<double>(voxelZ) + Constants::JustBelowOne); // Normals for the left and right faces of the wall, facing up-left and down-right // respectively (magic number is sqrt(2) / 2). const Double3 leftNormal(0.7071068, 0.0, -0.7071068); const Double3 rightNormal(-0.7071068, 0.0, 0.7071068); // An intersection occurs if the near point and far point are on different sides // of the diagonal line, or if the near point lies on the diagonal line. No need // to normalize the (localPoint - diagMiddle) vector because it's just checking // if it's greater than zero. const Double2 leftNormal2D(leftNormal.x, leftNormal.z); const bool nearOnLeft = leftNormal2D.dot(nearPoint - diagMiddle) >= 0.0; const bool farOnLeft = leftNormal2D.dot(farPoint - diagMiddle) >= 0.0; const bool intersectionOccurred = (nearOnLeft && !farOnLeft) || (!nearOnLeft && farOnLeft); // Only set the output data if an intersection occurred. if (intersectionOccurred) { // Change in X and change in Z of the incoming ray across the voxel. const double dx = farPoint.x - nearPoint.x; const double dz = farPoint.y - nearPoint.y; // The hit coordinate is a 0->1 value representing where the diagonal was hit. const double hitCoordinate = [&nearPoint, &diagStart, dx, dz]() { // Special cases: when the slope is horizontal or vertical. This method treats // the X axis as the vertical axis and the Z axis as the horizontal axis. const double isHorizontal = std::abs(dx) < Constants::Epsilon; const double isVertical = std::abs(dz) < Constants::Epsilon; if (isHorizontal) { // The X axis intercept is the intersection coordinate. return nearPoint.x - diagStart.x; } else if (isVertical) { // The Z axis intercept is the intersection coordinate. return nearPoint.y - diagStart.y; } else { // Slope of the diagonal line (trivial, x = z). const double diagSlope = 1.0; // Vertical axis intercept of the diagonal line. const double diagXIntercept = diagStart.x - diagStart.y; // Slope of the incoming ray. const double raySlope = dx / dz; // Get the vertical axis intercept of the incoming ray. const double rayXIntercept = nearPoint.x - (raySlope * nearPoint.y); // General line intersection calculation. return ((rayXIntercept - diagXIntercept) / (diagSlope - raySlope)) - diagStart.y; } }(); // Set the hit data. hit.u = std::max(std::min(hitCoordinate, Constants::JustBelowOne), 0.0); hit.point = Double2( static_cast<double>(voxelX) + hit.u, static_cast<double>(voxelZ) + hit.u); hit.innerZ = (hit.point - nearPoint).length(); hit.normal = nearOnLeft ? leftNormal : rightNormal; return true; } else { // No intersection. return false; } } bool SoftwareRenderer::findDiag2Intersection(int voxelX, int voxelZ, const Double2 &nearPoint, const Double2 &farPoint, RayHit &hit) { // Mostly a copy of findDiag1Intersection(), though with a couple different values // for the diagonal (end points, slope, etc.). // Start, middle, and end points of the diagonal line segment relative to the grid. const Double2 diagStart( static_cast<double>(voxelX) + Constants::JustBelowOne, static_cast<double>(voxelZ)); const Double2 diagMiddle( static_cast<double>(voxelX) + 0.50, static_cast<double>(voxelZ) + 0.50); const Double2 diagEnd( static_cast<double>(voxelX), static_cast<double>(voxelZ) + Constants::JustBelowOne); // Normals for the left and right faces of the wall, facing up-right and down-left // respectively (magic number is sqrt(2) / 2). const Double3 leftNormal(0.7071068, 0.0, 0.7071068); const Double3 rightNormal(-0.7071068, 0.0, -0.7071068); // An intersection occurs if the near point and far point are on different sides // of the diagonal line, or if the near point lies on the diagonal line. No need // to normalize the (localPoint - diagMiddle) vector because it's just checking // if it's greater than zero. const Double2 leftNormal2D(leftNormal.x, leftNormal.z); const bool nearOnLeft = leftNormal2D.dot(nearPoint - diagMiddle) >= 0.0; const bool farOnLeft = leftNormal2D.dot(farPoint - diagMiddle) >= 0.0; const bool intersectionOccurred = (nearOnLeft && !farOnLeft) || (!nearOnLeft && farOnLeft); // Only set the output data if an intersection occurred. if (intersectionOccurred) { // Change in X and change in Z of the incoming ray across the voxel. const double dx = farPoint.x - nearPoint.x; const double dz = farPoint.y - nearPoint.y; // The hit coordinate is a 0->1 value representing where the diagonal was hit. const double hitCoordinate = [&nearPoint, &diagStart, dx, dz]() { // Special cases: when the slope is horizontal or vertical. This method treats // the X axis as the vertical axis and the Z axis as the horizontal axis. const double isHorizontal = std::abs(dx) < Constants::Epsilon; const double isVertical = std::abs(dz) < Constants::Epsilon; if (isHorizontal) { // The X axis intercept is the compliment of the intersection coordinate. return Constants::JustBelowOne - (nearPoint.x - diagStart.x); } else if (isVertical) { // The Z axis intercept is the compliment of the intersection coordinate. return Constants::JustBelowOne - (nearPoint.y - diagStart.y); } else { // Slope of the diagonal line (trivial, x = -z). const double diagSlope = -1.0; // Vertical axis intercept of the diagonal line. const double diagXIntercept = diagStart.x + diagStart.y; // Slope of the incoming ray. const double raySlope = dx / dz; // Get the vertical axis intercept of the incoming ray. const double rayXIntercept = nearPoint.x - (raySlope * nearPoint.y); // General line intersection calculation. return ((rayXIntercept - diagXIntercept) / (diagSlope - raySlope)) - diagStart.y; } }(); // Set the hit data. hit.u = std::max(std::min(hitCoordinate, Constants::JustBelowOne), 0.0); hit.point = Double2( static_cast<double>(voxelX) + (Constants::JustBelowOne - hit.u), static_cast<double>(voxelZ) + hit.u); hit.innerZ = (hit.point - nearPoint).length(); hit.normal = nearOnLeft ? leftNormal : rightNormal; return true; } else { // No intersection. return false; } } bool SoftwareRenderer::findEdgeIntersection(int voxelX, int voxelZ, VoxelData::Facing facing, const Double2 &nearPoint, const Double2 &farPoint, RayHit &hit) { // To do. return false; } bool SoftwareRenderer::findDoorIntersection(int voxelX, int voxelZ, VoxelData::DoorData::Type doorType, const Double2 &nearPoint, const Double2 &farPoint, RayHit &hit) { // To do. return false; } void SoftwareRenderer::diagProjection(double voxelYReal, double voxelHeight, const Double2 &point, const Matrix4d &transform, double yShear, int frameHeight, double heightReal, double &diagTopScreenY, double &diagBottomScreenY, int &diagStart, int &diagEnd) { // Points in world space for the top and bottom of the diagonal wall slice. const Double3 diagTop(point.x, voxelYReal + voxelHeight, point.y); const Double3 diagBottom(point.x, voxelYReal, point.y); // Projected Y coordinates on-screen. diagTopScreenY = SoftwareRenderer::getProjectedY( diagTop, transform, yShear) * heightReal; diagBottomScreenY = SoftwareRenderer::getProjectedY( diagBottom, transform, yShear) * heightReal; // Y drawing range on-screen. diagStart = std::min(std::max(0, static_cast<int>(std::ceil(diagTopScreenY - 0.50))), frameHeight); diagEnd = std::min(std::max(0, static_cast<int>(std::floor(diagBottomScreenY + 0.50))), frameHeight); } void SoftwareRenderer::drawPixels(int x, int yStart, int yEnd, double projectedYStart, double projectedYEnd, double depth, double u, double vStart, double vEnd, const Double3 &normal, const SoftwareTexture &texture, const ShadingInfo &shadingInfo, OcclusionData &occlusion, const FrameView &frame) { // Horizontal offset in texture. const int textureX = static_cast<int>(u * static_cast<double>(texture.width)); // Linearly interpolated fog. const Double3 &fogColor = shadingInfo.horizonSkyColor; const double fogPercent = std::min(depth / shadingInfo.fogDistance, 1.0); // Contribution from the sun. const double lightNormalDot = std::max(0.0, shadingInfo.sunDirection.dot(normal)); const Double3 sunComponent = (shadingInfo.sunColor * lightNormalDot).clamped( 0.0, 1.0 - shadingInfo.ambient); // Shading on the texture. // - To do: contribution from lights. const Double3 shading( shadingInfo.ambient + sunComponent.x, shadingInfo.ambient + sunComponent.y, shadingInfo.ambient + sunComponent.z); // Clip the Y start and end coordinates as needed, and refresh the occlusion buffer. occlusion.clipRange(&yStart, &yEnd); occlusion.update(yStart, yEnd); // Draw the column to the output buffer. for (int y = yStart; y < yEnd; y++) { const int index = x + (y * frame.width); // Check depth of the pixel before rendering. // - To do: implement occlusion culling and back-to-front transparent rendering so // this depth check isn't needed. if (depth <= (frame.depthBuffer[index] - Constants::Epsilon)) { // Percent stepped from beginning to end on the column. const double yPercent = ((static_cast<double>(y) + 0.50) - projectedYStart) / (projectedYEnd - projectedYStart); // Vertical texture coordinate. const double v = vStart + ((vEnd - vStart) * yPercent); // Y position in texture. const int textureY = static_cast<int>(v * static_cast<double>(texture.height)); // Alpha is ignored in this loop, so transparent texels will appear black. const int textureIndex = textureX + (textureY * texture.width); const Double4 &texel = texture.texels[textureIndex]; const double emission = texture.emissionTexels[textureIndex]; // Texture color with shading. const double shadingMax = 1.0; double colorR = texel.x * std::min(shading.x + emission, shadingMax); double colorG = texel.y * std::min(shading.y + emission, shadingMax); double colorB = texel.z * std::min(shading.z + emission, shadingMax); // Linearly interpolate with fog. colorR += (fogColor.x - colorR) * fogPercent; colorG += (fogColor.y - colorG) * fogPercent; colorB += (fogColor.z - colorB) * fogPercent; // Clamp maximum (don't worry about negative values). const double high = 1.0; colorR = (colorR > high) ? high : colorR; colorG = (colorG > high) ? high : colorG; colorB = (colorB > high) ? high : colorB; // Convert floats to integers. const uint32_t colorRGB = static_cast<uint32_t>( ((static_cast<uint8_t>(colorR * 255.0)) << 16) | ((static_cast<uint8_t>(colorG * 255.0)) << 8) | ((static_cast<uint8_t>(colorB * 255.0)))); frame.colorBuffer[index] = colorRGB; frame.depthBuffer[index] = depth; } } } void SoftwareRenderer::drawPerspectivePixels(int x, int yStart, int yEnd, double projectedYStart, double projectedYEnd, const Double2 &startPoint, const Double2 &endPoint, double depthStart, double depthEnd, const Double3 &normal, const SoftwareTexture &texture, const ShadingInfo &shadingInfo, OcclusionData &occlusion, const FrameView &frame) { // Fog color to interpolate with. const Double3 &fogColor = shadingInfo.horizonSkyColor; // Contribution from the sun. const double lightNormalDot = std::max(0.0, shadingInfo.sunDirection.dot(normal)); const Double3 sunComponent = (shadingInfo.sunColor * lightNormalDot).clamped( 0.0, 1.0 - shadingInfo.ambient); // Shading on the texture. // - To do: contribution from lights. const Double3 shading( shadingInfo.ambient + sunComponent.x, shadingInfo.ambient + sunComponent.y, shadingInfo.ambient + sunComponent.z); // Values for perspective-correct interpolation. const double depthStartRecip = 1.0 / depthStart; const double depthEndRecip = 1.0 / depthEnd; const Double2 startPointDiv = startPoint * depthStartRecip; const Double2 endPointDiv = endPoint * depthEndRecip; const Double2 pointDivDiff( endPointDiv.x - startPointDiv.x, endPointDiv.y - startPointDiv.y); // Clip the Y start and end coordinates as needed, and refresh the occlusion buffer. occlusion.clipRange(&yStart, &yEnd); occlusion.update(yStart, yEnd); // Draw the column to the output buffer. for (int y = yStart; y < yEnd; y++) { const int index = x + (y * frame.width); // Percent stepped from beginning to end on the column. const double yPercent = ((static_cast<double>(y) + 0.50) - projectedYStart) / (projectedYEnd - projectedYStart); // Interpolate between the near and far depth. const double depth = 1.0 / (depthStartRecip + ((depthEndRecip - depthStartRecip) * yPercent)); // Check depth of the pixel before rendering. // - To do: implement occlusion culling and back-to-front transparent rendering so // this depth check isn't needed. if (depth <= frame.depthBuffer[index]) { // Linearly interpolated fog. const double fogPercent = std::min(depth / shadingInfo.fogDistance, 1.0); // Interpolate between start and end points. const double currentPointX = (startPointDiv.x + (pointDivDiff.x * yPercent)) * depth; const double currentPointY = (startPointDiv.y + (pointDivDiff.y * yPercent)) * depth; // Texture coordinates. const double u = std::max(std::min(Constants::JustBelowOne, Constants::JustBelowOne - (currentPointX - std::floor(currentPointX))), 0.0); const double v = std::max(std::min(Constants::JustBelowOne, Constants::JustBelowOne - (currentPointY - std::floor(currentPointY))), 0.0); // Offsets in texture. const int textureX = static_cast<int>(u * static_cast<double>(texture.width)); const int textureY = static_cast<int>(v * static_cast<double>(texture.height)); // Alpha is ignored in this loop, so transparent texels will appear black. const int textureIndex = textureX + (textureY * texture.width); const Double4 &texel = texture.texels[textureIndex]; const double emission = texture.emissionTexels[textureIndex]; // Texture color with shading. const double shadingMax = 1.0; double colorR = texel.x * std::min(shading.x + emission, shadingMax); double colorG = texel.y * std::min(shading.y + emission, shadingMax); double colorB = texel.z * std::min(shading.z + emission, shadingMax); // Linearly interpolate with fog. colorR += (fogColor.x - colorR) * fogPercent; colorG += (fogColor.y - colorG) * fogPercent; colorB += (fogColor.z - colorB) * fogPercent; // Clamp maximum (don't worry about negative values). const double high = 1.0; colorR = (colorR > high) ? high : colorR; colorG = (colorG > high) ? high : colorG; colorB = (colorB > high) ? high : colorB; // Convert floats to integers. const uint32_t colorRGB = static_cast<uint32_t>( ((static_cast<uint8_t>(colorR * 255.0)) << 16) | ((static_cast<uint8_t>(colorG * 255.0)) << 8) | ((static_cast<uint8_t>(colorB * 255.0)))); frame.colorBuffer[index] = colorRGB; frame.depthBuffer[index] = depth; } } } void SoftwareRenderer::drawTransparentPixels(int x, int yStart, int yEnd, double projectedYStart, double projectedYEnd, double depth, double u, double vStart, double vEnd, const Double3 &normal, const SoftwareTexture &texture, const ShadingInfo &shadingInfo, const OcclusionData &occlusion, const FrameView &frame) { // Horizontal offset in texture. const int textureX = static_cast<int>(u * static_cast<double>(texture.width)); // Linearly interpolated fog. const Double3 &fogColor = shadingInfo.horizonSkyColor; const double fogPercent = std::min(depth / shadingInfo.fogDistance, 1.0); // Contribution from the sun. const double lightNormalDot = std::max(0.0, shadingInfo.sunDirection.dot(normal)); const Double3 sunComponent = (shadingInfo.sunColor * lightNormalDot).clamped( 0.0, 1.0 - shadingInfo.ambient); // Shading on the texture. // - To do: contribution from lights. const Double3 shading( shadingInfo.ambient + sunComponent.x, shadingInfo.ambient + sunComponent.y, shadingInfo.ambient + sunComponent.z); // Clip the Y start and end coordinates as needed, but do not refresh the occlusion buffer, // because transparent ranges do not occlude as simply as opaque ranges. occlusion.clipRange(&yStart, &yEnd); // Draw the column to the output buffer. for (int y = yStart; y < yEnd; y++) { const int index = x + (y * frame.width); // Check depth of the pixel before rendering. if (depth <= (frame.depthBuffer[index] - Constants::Epsilon)) { // Percent stepped from beginning to end on the column. const double yPercent = ((static_cast<double>(y) + 0.50) - projectedYStart) / (projectedYEnd - projectedYStart); // Vertical texture coordinate. const double v = vStart + ((vEnd - vStart) * yPercent); // Y position in texture. const int textureY = static_cast<int>(v * static_cast<double>(texture.height)); // Alpha is checked in this loop, and transparent texels are not drawn. const int textureIndex = textureX + (textureY * texture.width); const Double4 &texel = texture.texels[textureIndex]; const double emission = texture.emissionTexels[textureIndex]; if (texel.w > 0.0) { // Texture color with shading. const double shadingMax = 1.0; double colorR = texel.x * std::min(shading.x + emission, shadingMax); double colorG = texel.y * std::min(shading.y + emission, shadingMax); double colorB = texel.z * std::min(shading.z + emission, shadingMax); // Linearly interpolate with fog. colorR += (fogColor.x - colorR) * fogPercent; colorG += (fogColor.y - colorG) * fogPercent; colorB += (fogColor.z - colorB) * fogPercent; // Clamp maximum (don't worry about negative values). const double high = 1.0; colorR = (colorR > high) ? high : colorR; colorG = (colorG > high) ? high : colorG; colorB = (colorB > high) ? high : colorB; // Convert floats to integers. const uint32_t colorRGB = static_cast<uint32_t>( ((static_cast<uint8_t>(colorR * 255.0)) << 16) | ((static_cast<uint8_t>(colorG * 255.0)) << 8) | ((static_cast<uint8_t>(colorB * 255.0)))); frame.colorBuffer[index] = colorRGB; frame.depthBuffer[index] = depth; } } } } void SoftwareRenderer::drawInitialVoxelColumn(int x, int voxelX, int voxelZ, double playerY, VoxelData::Facing facing, const Double2 &nearPoint, const Double2 &farPoint, double nearZ, double farZ, const Matrix4d &transform, double yShear, const ShadingInfo &shadingInfo, double ceilingHeight, const VoxelGrid &voxelGrid, const std::vector<SoftwareTexture> &textures, OcclusionData &occlusion, const FrameView &frame) { // This method handles some special cases such as drawing the back-faces of wall sides. // When clamping Y values for drawing ranges, subtract 0.5 from starts and add 0.5 to // ends before converting to integers because the drawing methods sample at the center // of pixels. The clamping function depends on which side of the range is being clamped; // either way, the drawing range should be contained within the projected range at the // sub-pixel level. This ensures that the vertical texture coordinate is always within 0->1. const double heightReal = static_cast<double>(frame.height); // Y position at the base of the player's voxel. const double playerYFloor = std::floor(playerY); // Voxel Y of the player. const int playerVoxelY = static_cast<int>(playerYFloor); const double wallU = [&farPoint, facing]() { const double uVal = [&farPoint, facing]() { if (facing == VoxelData::Facing::PositiveX) { return farPoint.y - std::floor(farPoint.y); } else if (facing == VoxelData::Facing::NegativeX) { return Constants::JustBelowOne - (farPoint.y - std::floor(farPoint.y)); } else if (facing == VoxelData::Facing::PositiveZ) { return Constants::JustBelowOne - (farPoint.x - std::floor(farPoint.x)); } else { return farPoint.x - std::floor(farPoint.x); } }(); return std::max(std::min(uVal, Constants::JustBelowOne), 0.0); }(); // Normal of the wall for the incoming ray, potentially shared between multiple voxels in // this voxel column. const Double3 wallNormal = -SoftwareRenderer::getNormal(facing); auto drawInitialVoxel = [x, voxelX, voxelZ, playerY, playerYFloor, &wallNormal, &nearPoint, &farPoint, nearZ, farZ, wallU, &transform, yShear, &shadingInfo, ceilingHeight, &voxelGrid, &textures, &occlusion, &frame, heightReal]() { const int voxelY = static_cast<int>(playerYFloor); const char voxelID = voxelGrid.getVoxels()[voxelX + (voxelY * voxelGrid.getWidth()) + (voxelZ * voxelGrid.getWidth() * voxelGrid.getHeight())]; const VoxelData &voxelData = voxelGrid.getVoxelData(voxelID); // Height of the voxel depends on whether it's the main floor. const double voxelHeight = (voxelY == 1) ? ceilingHeight : 1.0; if (voxelData.dataType == VoxelDataType::Wall) { // Draw inner ceiling, wall, and floor. const VoxelData::WallData &wallData = voxelData.wall; const Double3 farCeilingPoint( farPoint.x, playerYFloor + voxelHeight, farPoint.y); const Double3 nearCeilingPoint( nearPoint.x, farCeilingPoint.y, nearPoint.y); const Double3 farFloorPoint( farPoint.x, playerYFloor, farPoint.y); const Double3 nearFloorPoint( nearPoint.x, farFloorPoint.y, nearPoint.y); const double farCeilingScreenY = SoftwareRenderer::getProjectedY( farCeilingPoint, transform, yShear) * heightReal; const double nearCeilingScreenY = SoftwareRenderer::getProjectedY( nearCeilingPoint, transform, yShear) * heightReal; const double farFloorScreenY = SoftwareRenderer::getProjectedY( farFloorPoint, transform, yShear) * heightReal; const double nearFloorScreenY = SoftwareRenderer::getProjectedY( nearFloorPoint, transform, yShear) * heightReal; const int ceilingStart = SoftwareRenderer::getLowerBoundedPixel( nearCeilingScreenY, frame.height); const int ceilingEnd = SoftwareRenderer::getUpperBoundedPixel( farCeilingScreenY, frame.height); const int wallStart = ceilingEnd; const int wallEnd = SoftwareRenderer::getUpperBoundedPixel( farFloorScreenY, frame.height); const int floorStart = wallEnd; const int floorEnd = SoftwareRenderer::getUpperBoundedPixel( nearFloorScreenY, frame.height); // Ceiling. SoftwareRenderer::drawPerspectivePixels(x, ceilingStart, ceilingEnd, nearCeilingScreenY, farCeilingScreenY, nearPoint, farPoint, nearZ, farZ, -Double3::UnitY, textures.at(wallData.ceilingID - 1), shadingInfo, occlusion, frame); // Side. SoftwareRenderer::drawPixels(x, wallStart, wallEnd, farCeilingScreenY, farFloorScreenY, farZ, wallU, 0.0, Constants::JustBelowOne, wallNormal, textures.at(wallData.sideID - 1), shadingInfo, occlusion, frame); // Floor. SoftwareRenderer::drawPerspectivePixels(x, floorStart, floorEnd, farFloorScreenY, nearFloorScreenY, farPoint, nearPoint, farZ, nearZ, Double3::UnitY, textures.at(wallData.floorID - 1), shadingInfo, occlusion, frame); } else if (voxelData.dataType == VoxelDataType::Floor) { // Do nothing. Floors can only be seen from above. } else if (voxelData.dataType == VoxelDataType::Ceiling) { // Do nothing. Ceilings can only be seen from below. } else if (voxelData.dataType == VoxelDataType::Raised) { const VoxelData::RaisedData &raisedData = voxelData.raised; const Double3 nearCeilingPoint( nearPoint.x, playerYFloor + ((raisedData.yOffset + raisedData.ySize) * voxelHeight), nearPoint.y); const Double3 nearFloorPoint( nearPoint.x, playerYFloor + (raisedData.yOffset * voxelHeight), nearPoint.y); // Draw order depends on the player's Y position relative to the platform. if (playerY > nearCeilingPoint.y) { // Above platform. const Double3 farCeilingPoint( farPoint.x, nearCeilingPoint.y, farPoint.y); const double farCeilingScreenY = SoftwareRenderer::getProjectedY( farCeilingPoint, transform, yShear) * heightReal; const double nearCeilingScreenY = SoftwareRenderer::getProjectedY( nearCeilingPoint, transform, yShear) * heightReal; const int ceilingStart = SoftwareRenderer::getLowerBoundedPixel( farCeilingScreenY, frame.height); const int ceilingEnd = SoftwareRenderer::getUpperBoundedPixel( nearCeilingScreenY, frame.height); // Ceiling. SoftwareRenderer::drawPerspectivePixels(x, ceilingStart, ceilingEnd, farCeilingScreenY, nearCeilingScreenY, farPoint, nearPoint, farZ, nearZ, Double3::UnitY, textures.at(raisedData.ceilingID - 1), shadingInfo, occlusion, frame); } else if (playerY < nearFloorPoint.y) { // Below platform. const Double3 farFloorPoint( farPoint.x, nearFloorPoint.y, farPoint.y); const double nearFloorScreenY = SoftwareRenderer::getProjectedY( nearFloorPoint, transform, yShear) * heightReal; const double farFloorScreenY = SoftwareRenderer::getProjectedY( farFloorPoint, transform, yShear) * heightReal; const int floorStart = SoftwareRenderer::getLowerBoundedPixel( nearFloorScreenY, frame.height); const int floorEnd = SoftwareRenderer::getUpperBoundedPixel( farFloorScreenY, frame.height); // Floor. SoftwareRenderer::drawPerspectivePixels(x, floorStart, floorEnd, nearFloorScreenY, farFloorScreenY, nearPoint, farPoint, nearZ, farZ, -Double3::UnitY, textures.at(raisedData.floorID - 1), shadingInfo, occlusion, frame); } else { // Between top and bottom. const Double3 farCeilingPoint( farPoint.x, nearCeilingPoint.y, farPoint.y); const Double3 farFloorPoint( farPoint.x, nearFloorPoint.y, farPoint.y); const double farCeilingScreenY = SoftwareRenderer::getProjectedY( farCeilingPoint, transform, yShear) * heightReal; const double nearCeilingScreenY = SoftwareRenderer::getProjectedY( nearCeilingPoint, transform, yShear) * heightReal; const double farFloorScreenY = SoftwareRenderer::getProjectedY( farFloorPoint, transform, yShear) * heightReal; const double nearFloorScreenY = SoftwareRenderer::getProjectedY( nearFloorPoint, transform, yShear) * heightReal; const int ceilingStart = SoftwareRenderer::getLowerBoundedPixel( nearCeilingScreenY, frame.height); const int ceilingEnd = SoftwareRenderer::getUpperBoundedPixel( farCeilingScreenY, frame.height); const int wallStart = ceilingEnd; const int wallEnd = SoftwareRenderer::getUpperBoundedPixel( farFloorScreenY, frame.height); const int floorStart = wallEnd; const int floorEnd = SoftwareRenderer::getUpperBoundedPixel( nearFloorScreenY, frame.height); // Ceiling. SoftwareRenderer::drawPerspectivePixels(x, ceilingStart, ceilingEnd, nearCeilingScreenY, farCeilingScreenY, nearPoint, farPoint, nearZ, farZ, -Double3::UnitY, textures.at(raisedData.ceilingID - 1), shadingInfo, occlusion, frame); // Side. SoftwareRenderer::drawTransparentPixels(x, wallStart, wallEnd, farCeilingScreenY, farFloorScreenY, farZ, wallU, raisedData.vTop, raisedData.vBottom, wallNormal, textures.at(raisedData.sideID - 1), shadingInfo, occlusion, frame); // Floor. SoftwareRenderer::drawPerspectivePixels(x, floorStart, floorEnd, farFloorScreenY, nearFloorScreenY, farPoint, nearPoint, farZ, nearZ, Double3::UnitY, textures.at(raisedData.floorID - 1), shadingInfo, occlusion, frame); } } else if (voxelData.dataType == VoxelDataType::Diagonal) { const VoxelData::DiagonalData &diagData = voxelData.diagonal; // Find intersection. RayHit hit; const bool success = diagData.type1 ? SoftwareRenderer::findDiag1Intersection(voxelX, voxelZ, nearPoint, farPoint, hit) : SoftwareRenderer::findDiag2Intersection(voxelX, voxelZ, nearPoint, farPoint, hit); if (success) { double diagTopScreenY, diagBottomScreenY; int diagStart, diagEnd; SoftwareRenderer::diagProjection(playerYFloor, voxelHeight, hit.point, transform, yShear, frame.height, heightReal, diagTopScreenY, diagBottomScreenY, diagStart, diagEnd); SoftwareRenderer::drawPixels(x, diagStart, diagEnd, diagTopScreenY, diagBottomScreenY, nearZ + hit.innerZ, hit.u, 0.0, Constants::JustBelowOne, hit.normal, textures.at(diagData.id - 1), shadingInfo, occlusion, frame); } } else if (voxelData.dataType == VoxelDataType::TransparentWall) { // Do nothing. Transparent walls have no back-faces. } else if (voxelData.dataType == VoxelDataType::Edge) { const VoxelData::EdgeData &edgeData = voxelData.edge; // Find intersection. RayHit hit; const bool success = SoftwareRenderer::findEdgeIntersection( voxelX, voxelZ, edgeData.facing, nearPoint, farPoint, hit); if (success) { const Double3 edgeTopPoint( hit.point.x, playerYFloor + voxelHeight, hit.point.y); const Double3 edgeBottomPoint( hit.point.x, playerYFloor, hit.point.y); const double edgeTopScreenY = SoftwareRenderer::getProjectedY( edgeTopPoint, transform, yShear) * heightReal; const double edgeBottomScreenY = SoftwareRenderer::getProjectedY( edgeBottomPoint, transform, yShear) * heightReal; const int edgeStart = SoftwareRenderer::getLowerBoundedPixel( edgeTopScreenY, frame.height); const int edgeEnd = SoftwareRenderer::getUpperBoundedPixel( edgeBottomScreenY, frame.height); SoftwareRenderer::drawTransparentPixels(x, edgeStart, edgeEnd, edgeTopScreenY, edgeBottomScreenY, nearZ + hit.innerZ, hit.u, 0.0, Constants::JustBelowOne, hit.normal, textures.at(edgeData.id - 1), shadingInfo, occlusion, frame); } } else if (voxelData.dataType == VoxelDataType::Chasm) { // Render front and back-faces. const VoxelData::ChasmData &chasmData = voxelData.chasm; // To do. } else if (voxelData.dataType == VoxelDataType::Door) { // To do: find intersection via SoftwareRenderer::findDoorIntersection(). // Render nothing for now. } }; auto drawInitialVoxelBelow = [x, voxelX, voxelZ, playerY, &wallNormal, &nearPoint, &farPoint, nearZ, farZ, wallU, &transform, yShear, &shadingInfo, ceilingHeight, &voxelGrid, &textures, &occlusion, &frame, heightReal](int voxelY) { const char voxelID = voxelGrid.getVoxels()[voxelX + (voxelY * voxelGrid.getWidth()) + (voxelZ * voxelGrid.getWidth() * voxelGrid.getHeight())]; const VoxelData &voxelData = voxelGrid.getVoxelData(voxelID); const double voxelYReal = static_cast<double>(voxelY); // Height of the voxel depends on whether it's the main floor. const double voxelHeight = (voxelY == 1) ? ceilingHeight : 1.0; if (voxelData.dataType == VoxelDataType::Wall) { const VoxelData::WallData &wallData = voxelData.wall; const Double3 farCeilingPoint( farPoint.x, voxelYReal + voxelHeight, farPoint.y); const Double3 nearCeilingPoint( nearPoint.x, farCeilingPoint.y, nearPoint.y); const double farCeilingScreenY = SoftwareRenderer::getProjectedY( farCeilingPoint, transform, yShear) * heightReal; const double nearCeilingScreenY = SoftwareRenderer::getProjectedY( nearCeilingPoint, transform, yShear) * heightReal; const int ceilingStart = SoftwareRenderer::getLowerBoundedPixel( farCeilingScreenY, frame.height); const int ceilingEnd = SoftwareRenderer::getUpperBoundedPixel( nearCeilingScreenY, frame.height); // Ceiling. SoftwareRenderer::drawPerspectivePixels(x, ceilingStart, ceilingEnd, farCeilingScreenY, nearCeilingScreenY, farPoint, nearPoint, farZ, nearZ, Double3::UnitY, textures.at(wallData.ceilingID - 1), shadingInfo, occlusion, frame); } else if (voxelData.dataType == VoxelDataType::Floor) { // Draw top of floor voxel. const VoxelData::FloorData &floorData = voxelData.floor; const Double3 farCeilingPoint( farPoint.x, voxelYReal + voxelHeight, farPoint.y); const Double3 nearCeilingPoint( nearPoint.x, farCeilingPoint.y, nearPoint.y); const double farCeilingScreenY = SoftwareRenderer::getProjectedY( farCeilingPoint, transform, yShear) * heightReal; const double nearCeilingScreenY = SoftwareRenderer::getProjectedY( nearCeilingPoint, transform, yShear) * heightReal; const int ceilingStart = SoftwareRenderer::getLowerBoundedPixel( farCeilingScreenY, frame.height); const int ceilingEnd = SoftwareRenderer::getUpperBoundedPixel( nearCeilingScreenY, frame.height); // Ceiling. SoftwareRenderer::drawPerspectivePixels(x, ceilingStart, ceilingEnd, farCeilingScreenY, nearCeilingScreenY, farPoint, nearPoint, farZ, nearZ, Double3::UnitY, textures.at(floorData.id), shadingInfo, occlusion, frame); } else if (voxelData.dataType == VoxelDataType::Ceiling) { // Do nothing. Ceilings can only be seen from below. } else if (voxelData.dataType == VoxelDataType::Raised) { const VoxelData::RaisedData &raisedData = voxelData.raised; const Double3 nearCeilingPoint( nearPoint.x, voxelYReal + ((raisedData.yOffset + raisedData.ySize) * voxelHeight), nearPoint.y); const Double3 nearFloorPoint( nearPoint.x, voxelYReal + (raisedData.yOffset * voxelHeight), nearPoint.y); // Draw order depends on the player's Y position relative to the platform. if (playerY > nearCeilingPoint.y) { // Above platform. const Double3 farCeilingPoint( farPoint.x, nearCeilingPoint.y, farPoint.y); const double farCeilingScreenY = SoftwareRenderer::getProjectedY( farCeilingPoint, transform, yShear) * heightReal; const double nearCeilingScreenY = SoftwareRenderer::getProjectedY( nearCeilingPoint, transform, yShear) * heightReal; const int ceilingStart = SoftwareRenderer::getLowerBoundedPixel( farCeilingScreenY, frame.height); const int ceilingEnd = SoftwareRenderer::getUpperBoundedPixel( nearCeilingScreenY, frame.height); // Ceiling. SoftwareRenderer::drawPerspectivePixels(x, ceilingStart, ceilingEnd, farCeilingScreenY, nearCeilingScreenY, farPoint, nearPoint, farZ, nearZ, Double3::UnitY, textures.at(raisedData.ceilingID - 1), shadingInfo, occlusion, frame); } else if (playerY < nearFloorPoint.y) { // Below platform. const Double3 farFloorPoint( farPoint.x, nearFloorPoint.y, farPoint.y); const double nearFloorScreenY = SoftwareRenderer::getProjectedY( nearFloorPoint, transform, yShear) * heightReal; const double farFloorScreenY = SoftwareRenderer::getProjectedY( farFloorPoint, transform, yShear) * heightReal; const int floorStart = SoftwareRenderer::getLowerBoundedPixel( nearFloorScreenY, frame.height); const int floorEnd = SoftwareRenderer::getUpperBoundedPixel( farFloorScreenY, frame.height); // Floor. SoftwareRenderer::drawPerspectivePixels(x, floorStart, floorEnd, nearFloorScreenY, farFloorScreenY, nearPoint, farPoint, nearZ, farZ, -Double3::UnitY, textures.at(raisedData.floorID - 1), shadingInfo, occlusion, frame); } else { // Between top and bottom. const Double3 farCeilingPoint( farPoint.x, nearCeilingPoint.y, farPoint.y); const Double3 farFloorPoint( farPoint.x, nearFloorPoint.y, farPoint.y); const double farCeilingScreenY = SoftwareRenderer::getProjectedY( farCeilingPoint, transform, yShear) * heightReal; const double nearCeilingScreenY = SoftwareRenderer::getProjectedY( nearCeilingPoint, transform, yShear) * heightReal; const double farFloorScreenY = SoftwareRenderer::getProjectedY( farFloorPoint, transform, yShear) * heightReal; const double nearFloorScreenY = SoftwareRenderer::getProjectedY( nearFloorPoint, transform, yShear) * heightReal; const int ceilingStart = SoftwareRenderer::getLowerBoundedPixel( nearCeilingScreenY, frame.height); const int ceilingEnd = SoftwareRenderer::getUpperBoundedPixel( farCeilingScreenY, frame.height); const int wallStart = ceilingEnd; const int wallEnd = SoftwareRenderer::getUpperBoundedPixel( farFloorScreenY, frame.height); const int floorStart = wallEnd; const int floorEnd = SoftwareRenderer::getUpperBoundedPixel( nearFloorScreenY, frame.height); // Ceiling. SoftwareRenderer::drawPerspectivePixels(x, ceilingStart, ceilingEnd, nearCeilingScreenY, farCeilingScreenY, nearPoint, farPoint, nearZ, farZ, -Double3::UnitY, textures.at(raisedData.ceilingID - 1), shadingInfo, occlusion, frame); // Side. SoftwareRenderer::drawTransparentPixels(x, wallStart, wallEnd, farCeilingScreenY, farFloorScreenY, farZ, wallU, raisedData.vTop, raisedData.vBottom, wallNormal, textures.at(raisedData.sideID - 1), shadingInfo, occlusion, frame); // Floor. SoftwareRenderer::drawPerspectivePixels(x, floorStart, floorEnd, farFloorScreenY, nearFloorScreenY, farPoint, nearPoint, farZ, nearZ, Double3::UnitY, textures.at(raisedData.floorID - 1), shadingInfo, occlusion, frame); } } else if (voxelData.dataType == VoxelDataType::Diagonal) { const VoxelData::DiagonalData &diagData = voxelData.diagonal; // Find intersection. RayHit hit; const bool success = diagData.type1 ? SoftwareRenderer::findDiag1Intersection(voxelX, voxelZ, nearPoint, farPoint, hit) : SoftwareRenderer::findDiag2Intersection(voxelX, voxelZ, nearPoint, farPoint, hit); if (success) { double diagTopScreenY, diagBottomScreenY; int diagStart, diagEnd; SoftwareRenderer::diagProjection(voxelYReal, voxelHeight, hit.point, transform, yShear, frame.height, heightReal, diagTopScreenY, diagBottomScreenY, diagStart, diagEnd); SoftwareRenderer::drawPixels(x, diagStart, diagEnd, diagTopScreenY, diagBottomScreenY, nearZ + hit.innerZ, hit.u, 0.0, Constants::JustBelowOne, hit.normal, textures.at(diagData.id - 1), shadingInfo, occlusion, frame); } } else if (voxelData.dataType == VoxelDataType::TransparentWall) { // Do nothing. Transparent walls have no back-faces. } else if (voxelData.dataType == VoxelDataType::Edge) { const VoxelData::EdgeData &edgeData = voxelData.edge; // Find intersection. RayHit hit; const bool success = SoftwareRenderer::findEdgeIntersection( voxelX, voxelZ, edgeData.facing, nearPoint, farPoint, hit); if (success) { const Double3 edgeTopPoint( hit.point.x, voxelYReal + voxelHeight, hit.point.y); const Double3 edgeBottomPoint( hit.point.x, voxelYReal, hit.point.y); const double edgeTopScreenY = SoftwareRenderer::getProjectedY( edgeTopPoint, transform, yShear) * heightReal; const double edgeBottomScreenY = SoftwareRenderer::getProjectedY( edgeBottomPoint, transform, yShear) * heightReal; const int edgeStart = SoftwareRenderer::getLowerBoundedPixel( edgeTopScreenY, frame.height); const int edgeEnd = SoftwareRenderer::getUpperBoundedPixel( edgeBottomScreenY, frame.height); SoftwareRenderer::drawTransparentPixels(x, edgeStart, edgeEnd, edgeTopScreenY, edgeBottomScreenY, nearZ + hit.innerZ, hit.u, 0.0, Constants::JustBelowOne, hit.normal, textures.at(edgeData.id - 1), shadingInfo, occlusion, frame); } } else if (voxelData.dataType == VoxelDataType::Chasm) { // Render front and back-faces. const VoxelData::ChasmData &chasmData = voxelData.chasm; // To do. } else if (voxelData.dataType == VoxelDataType::Door) { // To do: find intersection via SoftwareRenderer::findDoorIntersection(). // Render nothing for now. } }; auto drawInitialVoxelAbove = [x, voxelX, voxelZ, playerY, &wallNormal, &nearPoint, &farPoint, nearZ, farZ, wallU, &transform, yShear, &shadingInfo, ceilingHeight, &voxelGrid, &textures, &occlusion, &frame, heightReal](int voxelY) { const char voxelID = voxelGrid.getVoxels()[voxelX + (voxelY * voxelGrid.getWidth()) + (voxelZ * voxelGrid.getWidth() * voxelGrid.getHeight())]; const VoxelData &voxelData = voxelGrid.getVoxelData(voxelID); const double voxelYReal = static_cast<double>(voxelY); // Height of the voxel depends on whether it's the main floor. const double voxelHeight = (voxelY == 1) ? ceilingHeight : 1.0; if (voxelData.dataType == VoxelDataType::Wall) { const VoxelData::WallData &wallData = voxelData.wall; const Double3 nearFloorPoint( nearPoint.x, voxelYReal, nearPoint.y); const Double3 farFloorPoint( farPoint.x, nearFloorPoint.y, farPoint.y); const double nearFloorScreenY = SoftwareRenderer::getProjectedY( nearFloorPoint, transform, yShear) * heightReal; const double farFloorScreenY = SoftwareRenderer::getProjectedY( farFloorPoint, transform, yShear) * heightReal; const int floorStart = SoftwareRenderer::getLowerBoundedPixel( nearFloorScreenY, frame.height); const int floorEnd = SoftwareRenderer::getUpperBoundedPixel( farFloorScreenY, frame.height); // Floor. SoftwareRenderer::drawPerspectivePixels(x, floorStart, floorEnd, nearFloorScreenY, farFloorScreenY, nearPoint, farPoint, nearZ, farZ, -Double3::UnitY, textures.at(wallData.floorID - 1), shadingInfo, occlusion, frame); } else if (voxelData.dataType == VoxelDataType::Floor) { // Do nothing. Floors can only be seen from above. } else if (voxelData.dataType == VoxelDataType::Ceiling) { // Draw bottom of ceiling voxel. const VoxelData::CeilingData &ceilingData = voxelData.ceiling; const Double3 nearFloorPoint( nearPoint.x, 1.0 + ceilingHeight, nearPoint.y); const Double3 farFloorPoint( farPoint.x, nearFloorPoint.y, farPoint.y); const double nearFloorScreenY = SoftwareRenderer::getProjectedY( nearFloorPoint, transform, yShear) * heightReal; const double farFloorScreenY = SoftwareRenderer::getProjectedY( farFloorPoint, transform, yShear) * heightReal; const int floorStart = SoftwareRenderer::getLowerBoundedPixel( nearFloorScreenY, frame.height); const int floorEnd = SoftwareRenderer::getUpperBoundedPixel( farFloorScreenY, frame.height); SoftwareRenderer::drawPerspectivePixels(x, floorStart, floorEnd, nearFloorScreenY, farFloorScreenY, nearPoint, farPoint, nearZ, farZ, -Double3::UnitY, textures.at(ceilingData.id), shadingInfo, occlusion, frame); } else if (voxelData.dataType == VoxelDataType::Raised) { const VoxelData::RaisedData &raisedData = voxelData.raised; const Double3 nearCeilingPoint( nearPoint.x, voxelYReal + ((raisedData.yOffset + raisedData.ySize) * voxelHeight), nearPoint.y); const Double3 nearFloorPoint( nearPoint.x, voxelYReal + (raisedData.yOffset * voxelHeight), nearPoint.y); // Draw order depends on the player's Y position relative to the platform. if (playerY > nearCeilingPoint.y) { // Above platform. const Double3 farCeilingPoint( farPoint.x, nearCeilingPoint.y, farPoint.y); const double farCeilingScreenY = SoftwareRenderer::getProjectedY( farCeilingPoint, transform, yShear) * heightReal; const double nearCeilingScreenY = SoftwareRenderer::getProjectedY( nearCeilingPoint, transform, yShear) * heightReal; const int ceilingStart = SoftwareRenderer::getLowerBoundedPixel( farCeilingScreenY, frame.height); const int ceilingEnd = SoftwareRenderer::getUpperBoundedPixel( nearCeilingScreenY, frame.height); // Ceiling. SoftwareRenderer::drawPerspectivePixels(x, ceilingStart, ceilingEnd, farCeilingScreenY, nearCeilingScreenY, farPoint, nearPoint, farZ, nearZ, Double3::UnitY, textures.at(raisedData.ceilingID - 1), shadingInfo, occlusion, frame); } else if (playerY < nearFloorPoint.y) { // Below platform. const Double3 farFloorPoint( farPoint.x, nearFloorPoint.y, farPoint.y); const double nearFloorScreenY = SoftwareRenderer::getProjectedY( nearFloorPoint, transform, yShear) * heightReal; const double farFloorScreenY = SoftwareRenderer::getProjectedY( farFloorPoint, transform, yShear) * heightReal; const int floorStart = SoftwareRenderer::getLowerBoundedPixel( nearFloorScreenY, frame.height); const int floorEnd = SoftwareRenderer::getUpperBoundedPixel( farFloorScreenY, frame.height); // Floor. SoftwareRenderer::drawPerspectivePixels(x, floorStart, floorEnd, nearFloorScreenY, farFloorScreenY, nearPoint, farPoint, nearZ, farZ, -Double3::UnitY, textures.at(raisedData.floorID - 1), shadingInfo, occlusion, frame); } else { // Between top and bottom. const Double3 farCeilingPoint( farPoint.x, nearCeilingPoint.y, farPoint.y); const Double3 farFloorPoint( farPoint.x, nearFloorPoint.y, farPoint.y); const double farCeilingScreenY = SoftwareRenderer::getProjectedY( farCeilingPoint, transform, yShear) * heightReal; const double nearCeilingScreenY = SoftwareRenderer::getProjectedY( nearCeilingPoint, transform, yShear) * heightReal; const double farFloorScreenY = SoftwareRenderer::getProjectedY( farFloorPoint, transform, yShear) * heightReal; const double nearFloorScreenY = SoftwareRenderer::getProjectedY( nearFloorPoint, transform, yShear) * heightReal; const int ceilingStart = SoftwareRenderer::getLowerBoundedPixel( nearCeilingScreenY, frame.height); const int ceilingEnd = SoftwareRenderer::getUpperBoundedPixel( farCeilingScreenY, frame.height); const int wallStart = ceilingEnd; const int wallEnd = SoftwareRenderer::getUpperBoundedPixel( farFloorScreenY, frame.height); const int floorStart = wallEnd; const int floorEnd = SoftwareRenderer::getUpperBoundedPixel( nearFloorScreenY, frame.height); // Ceiling. SoftwareRenderer::drawPerspectivePixels(x, ceilingStart, ceilingEnd, nearCeilingScreenY, farCeilingScreenY, nearPoint, farPoint, nearZ, farZ, -Double3::UnitY, textures.at(raisedData.ceilingID - 1), shadingInfo, occlusion, frame); // Side. SoftwareRenderer::drawTransparentPixels(x, wallStart, wallEnd, farCeilingScreenY, farFloorScreenY, farZ, wallU, raisedData.vTop, raisedData.vBottom, wallNormal, textures.at(raisedData.sideID - 1), shadingInfo, occlusion, frame); // Floor. SoftwareRenderer::drawPerspectivePixels(x, floorStart, floorEnd, farFloorScreenY, nearFloorScreenY, farPoint, nearPoint, farZ, nearZ, Double3::UnitY, textures.at(raisedData.floorID - 1), shadingInfo, occlusion, frame); } } else if (voxelData.dataType == VoxelDataType::Diagonal) { const VoxelData::DiagonalData &diagData = voxelData.diagonal; // Find intersection. RayHit hit; const bool success = diagData.type1 ? SoftwareRenderer::findDiag1Intersection(voxelX, voxelZ, nearPoint, farPoint, hit) : SoftwareRenderer::findDiag2Intersection(voxelX, voxelZ, nearPoint, farPoint, hit); if (success) { double diagTopScreenY, diagBottomScreenY; int diagStart, diagEnd; SoftwareRenderer::diagProjection(voxelYReal, voxelHeight, hit.point, transform, yShear, frame.height, heightReal, diagTopScreenY, diagBottomScreenY, diagStart, diagEnd); SoftwareRenderer::drawPixels(x, diagStart, diagEnd, diagTopScreenY, diagBottomScreenY, nearZ + hit.innerZ, hit.u, 0.0, Constants::JustBelowOne, hit.normal, textures.at(diagData.id - 1), shadingInfo, occlusion, frame); } } else if (voxelData.dataType == VoxelDataType::TransparentWall) { // Do nothing. Transparent walls have no back-faces. } else if (voxelData.dataType == VoxelDataType::Edge) { const VoxelData::EdgeData &edgeData = voxelData.edge; // Find intersection. RayHit hit; const bool success = SoftwareRenderer::findEdgeIntersection( voxelX, voxelZ, edgeData.facing, nearPoint, farPoint, hit); if (success) { const Double3 edgeTopPoint( hit.point.x, voxelYReal + voxelHeight, hit.point.y); const Double3 edgeBottomPoint( hit.point.x, voxelYReal, hit.point.y); const double edgeTopScreenY = SoftwareRenderer::getProjectedY( edgeTopPoint, transform, yShear) * heightReal; const double edgeBottomScreenY = SoftwareRenderer::getProjectedY( edgeBottomPoint, transform, yShear) * heightReal; const int edgeStart = SoftwareRenderer::getLowerBoundedPixel( edgeTopScreenY, frame.height); const int edgeEnd = SoftwareRenderer::getUpperBoundedPixel( edgeBottomScreenY, frame.height); SoftwareRenderer::drawTransparentPixels(x, edgeStart, edgeEnd, edgeTopScreenY, edgeBottomScreenY, nearZ + hit.innerZ, hit.u, 0.0, Constants::JustBelowOne, hit.normal, textures.at(edgeData.id - 1), shadingInfo, occlusion, frame); } } else if (voxelData.dataType == VoxelDataType::Chasm) { // Render front and back-faces. const VoxelData::ChasmData &chasmData = voxelData.chasm; // To do. } else if (voxelData.dataType == VoxelDataType::Door) { // To do: find intersection via SoftwareRenderer::findDoorIntersection(). // Render nothing for now. } }; // Draw the player's current voxel first. drawInitialVoxel(); // Draw voxels below the player's voxel. for (int voxelY = (playerVoxelY - 1); voxelY >= 0; voxelY--) { drawInitialVoxelBelow(voxelY); } // Draw voxels above the player's voxel. for (int voxelY = (playerVoxelY + 1); voxelY < voxelGrid.getHeight(); voxelY++) { drawInitialVoxelAbove(voxelY); } } void SoftwareRenderer::drawVoxelColumn(int x, int voxelX, int voxelZ, double playerY, VoxelData::Facing facing, const Double2 &nearPoint, const Double2 &farPoint, double nearZ, double farZ, const Matrix4d &transform, double yShear, const ShadingInfo &shadingInfo, double ceilingHeight, const VoxelGrid &voxelGrid, const std::vector<SoftwareTexture> &textures, OcclusionData &occlusion, const FrameView &frame) { // Much of the code here is duplicated from the initial voxel column drawing method, but // there are a couple differences, like the horizontal texture coordinate being flipped, // and the drawing orders being slightly modified. The reason for having so much code is // so we cover all the different ray casting cases efficiently. It would slow down this // method if it had an "initialColumn" boolean that was false 90% of the time. // When clamping Y values for drawing ranges, subtract 0.5 from starts and add 0.5 to // ends before converting to integers because the drawing methods sample at the center // of pixels. The clamping function depends on which side of the range is being clamped; // either way, the drawing range should be contained within the projected range at the // sub-pixel level. This ensures that the vertical texture coordinate is always within 0->1. const double heightReal = static_cast<double>(frame.height); // Y position at the base of the player's voxel. const double playerYFloor = std::floor(playerY); // Voxel Y of the player. const int playerVoxelY = static_cast<int>(playerYFloor); // Horizontal texture coordinate for the wall, potentially shared between multiple voxels // in this voxel column. const double wallU = [&nearPoint, facing]() { const double uVal = [&nearPoint, facing]() { if (facing == VoxelData::Facing::PositiveX) { return Constants::JustBelowOne - (nearPoint.y - std::floor(nearPoint.y)); } else if (facing == VoxelData::Facing::NegativeX) { return nearPoint.y - std::floor(nearPoint.y); } else if (facing == VoxelData::Facing::PositiveZ) { return nearPoint.x - std::floor(nearPoint.x); } else { return Constants::JustBelowOne - (nearPoint.x - std::floor(nearPoint.x)); } }(); return std::max(std::min(uVal, Constants::JustBelowOne), 0.0); }(); // Normal of the wall for the incoming ray, potentially shared between multiple voxels in // this voxel column. const Double3 wallNormal = SoftwareRenderer::getNormal(facing); auto drawVoxel = [x, voxelX, voxelZ, playerY, playerYFloor, &wallNormal, &nearPoint, &farPoint, nearZ, farZ, wallU, &transform, yShear, &shadingInfo, ceilingHeight, &voxelGrid, &textures, &occlusion, &frame, heightReal]() { const int voxelY = static_cast<int>(playerYFloor); const char voxelID = voxelGrid.getVoxels()[voxelX + (voxelY * voxelGrid.getWidth()) + (voxelZ * voxelGrid.getWidth() * voxelGrid.getHeight())]; const VoxelData &voxelData = voxelGrid.getVoxelData(voxelID); // Height of the voxel depends on whether it's the main floor. const double voxelHeight = (voxelY == 1) ? ceilingHeight : 1.0; if (voxelData.dataType == VoxelDataType::Wall) { // Draw side. const VoxelData::WallData &wallData = voxelData.wall; const Double3 nearCeilingPoint( nearPoint.x, playerYFloor + voxelHeight, nearPoint.y); const Double3 nearFloorPoint( nearPoint.x, playerYFloor, nearPoint.y); const double nearCeilingScreenY = SoftwareRenderer::getProjectedY( nearCeilingPoint, transform, yShear) * heightReal; const double nearFloorScreenY = SoftwareRenderer::getProjectedY( nearFloorPoint, transform, yShear) * heightReal; const int wallStart = SoftwareRenderer::getLowerBoundedPixel( nearCeilingScreenY, frame.height); const int wallEnd = SoftwareRenderer::getUpperBoundedPixel( nearFloorScreenY, frame.height); SoftwareRenderer::drawPixels(x, wallStart, wallEnd, nearCeilingScreenY, nearFloorScreenY, nearZ, wallU, 0.0, Constants::JustBelowOne, wallNormal, textures.at(wallData.sideID - 1), shadingInfo, occlusion, frame); } else if (voxelData.dataType == VoxelDataType::Floor) { // Do nothing. Floors can only be seen from above. } else if (voxelData.dataType == VoxelDataType::Ceiling) { // Do nothing. Ceilings can only be seen from below. } else if (voxelData.dataType == VoxelDataType::Raised) { const VoxelData::RaisedData &raisedData = voxelData.raised; const Double3 nearCeilingPoint( nearPoint.x, playerYFloor + ((raisedData.yOffset + raisedData.ySize) * voxelHeight), nearPoint.y); const Double3 nearFloorPoint( nearPoint.x, playerYFloor + (raisedData.yOffset * voxelHeight), nearPoint.y); const double nearCeilingScreenY = SoftwareRenderer::getProjectedY( nearCeilingPoint, transform, yShear) * heightReal; const double nearFloorScreenY = SoftwareRenderer::getProjectedY( nearFloorPoint, transform, yShear) * heightReal; const int wallStart = SoftwareRenderer::getLowerBoundedPixel( nearCeilingScreenY, frame.height); const int wallEnd = SoftwareRenderer::getUpperBoundedPixel( nearFloorScreenY, frame.height); // Draw order depends on the player's Y position relative to the platform. if (playerY > nearCeilingPoint.y) { // Above platform. const Double3 farCeilingPoint( farPoint.x, nearCeilingPoint.y, farPoint.y); const double farCeilingScreenY = SoftwareRenderer::getProjectedY( farCeilingPoint, transform, yShear) * heightReal; const int ceilingStart = SoftwareRenderer::getLowerBoundedPixel( farCeilingScreenY, frame.height); const int ceilingEnd = wallStart; // Ceiling. SoftwareRenderer::drawPerspectivePixels(x, ceilingStart, ceilingEnd, farCeilingScreenY, nearCeilingScreenY, farPoint, nearPoint, farZ, nearZ, Double3::UnitY, textures.at(raisedData.ceilingID - 1), shadingInfo, occlusion, frame); // Side. SoftwareRenderer::drawTransparentPixels(x, wallStart, wallEnd, nearCeilingScreenY, nearFloorScreenY, nearZ, wallU, raisedData.vTop, raisedData.vBottom, wallNormal, textures.at(raisedData.sideID - 1), shadingInfo, occlusion, frame); } else if (playerY < nearFloorPoint.y) { // Below platform. const Double3 farFloorPoint( farPoint.x, nearFloorPoint.y, farPoint.y); const double farFloorScreenY = SoftwareRenderer::getProjectedY( farFloorPoint, transform, yShear) * heightReal; const int floorStart = wallEnd; const int floorEnd = SoftwareRenderer::getUpperBoundedPixel( farFloorScreenY, frame.height); // Side. SoftwareRenderer::drawTransparentPixels(x, wallStart, wallEnd, nearCeilingScreenY, nearFloorScreenY, nearZ, wallU, raisedData.vTop, raisedData.vBottom, wallNormal, textures.at(raisedData.sideID - 1), shadingInfo, occlusion, frame); // Floor. SoftwareRenderer::drawPerspectivePixels(x, floorStart, floorEnd, nearFloorScreenY, farFloorScreenY, nearPoint, farPoint, nearZ, farZ, -Double3::UnitY, textures.at(raisedData.floorID - 1), shadingInfo, occlusion, frame); } else { // Between top and bottom. SoftwareRenderer::drawTransparentPixels(x, wallStart, wallEnd, nearCeilingScreenY, nearFloorScreenY, nearZ, wallU, raisedData.vTop, raisedData.vBottom, wallNormal, textures.at(raisedData.sideID - 1), shadingInfo, occlusion, frame); } } else if (voxelData.dataType == VoxelDataType::Diagonal) { const VoxelData::DiagonalData &diagData = voxelData.diagonal; // Find intersection. RayHit hit; const bool success = diagData.type1 ? SoftwareRenderer::findDiag1Intersection(voxelX, voxelZ, nearPoint, farPoint, hit) : SoftwareRenderer::findDiag2Intersection(voxelX, voxelZ, nearPoint, farPoint, hit); if (success) { double diagTopScreenY, diagBottomScreenY; int diagStart, diagEnd; SoftwareRenderer::diagProjection(playerYFloor, voxelHeight, hit.point, transform, yShear, frame.height, heightReal, diagTopScreenY, diagBottomScreenY, diagStart, diagEnd); SoftwareRenderer::drawPixels(x, diagStart, diagEnd, diagTopScreenY, diagBottomScreenY, nearZ + hit.innerZ, hit.u, 0.0, Constants::JustBelowOne, hit.normal, textures.at(diagData.id - 1), shadingInfo, occlusion, frame); } } else if (voxelData.dataType == VoxelDataType::TransparentWall) { // Draw transparent side. const VoxelData::TransparentWallData &transparentWallData = voxelData.transparentWall; const Double3 nearCeilingPoint( nearPoint.x, playerYFloor + voxelHeight, nearPoint.y); const Double3 nearFloorPoint( nearPoint.x, playerYFloor, nearPoint.y); const double nearCeilingScreenY = SoftwareRenderer::getProjectedY( nearCeilingPoint, transform, yShear) * heightReal; const double nearFloorScreenY = SoftwareRenderer::getProjectedY( nearFloorPoint, transform, yShear) * heightReal; const int wallStart = SoftwareRenderer::getLowerBoundedPixel( nearCeilingScreenY, frame.height); const int wallEnd = SoftwareRenderer::getUpperBoundedPixel( nearFloorScreenY, frame.height); SoftwareRenderer::drawTransparentPixels(x, wallStart, wallEnd, nearCeilingScreenY, nearFloorScreenY, nearZ, wallU, 0.0, Constants::JustBelowOne, wallNormal, textures.at(transparentWallData.id - 1), shadingInfo, occlusion, frame); } else if (voxelData.dataType == VoxelDataType::Edge) { const VoxelData::EdgeData &edgeData = voxelData.edge; // Find intersection. RayHit hit; const bool success = SoftwareRenderer::findEdgeIntersection( voxelX, voxelZ, edgeData.facing, nearPoint, farPoint, hit); if (success) { const Double3 edgeTopPoint( hit.point.x, playerYFloor + voxelHeight, hit.point.y); const Double3 edgeBottomPoint( hit.point.x, playerYFloor, hit.point.y); const double edgeTopScreenY = SoftwareRenderer::getProjectedY( edgeTopPoint, transform, yShear) * heightReal; const double edgeBottomScreenY = SoftwareRenderer::getProjectedY( edgeBottomPoint, transform, yShear) * heightReal; const int edgeStart = SoftwareRenderer::getLowerBoundedPixel( edgeTopScreenY, frame.height); const int edgeEnd = SoftwareRenderer::getUpperBoundedPixel( edgeBottomScreenY, frame.height); SoftwareRenderer::drawTransparentPixels(x, edgeStart, edgeEnd, edgeTopScreenY, edgeBottomScreenY, nearZ + hit.innerZ, hit.u, 0.0, Constants::JustBelowOne, hit.normal, textures.at(edgeData.id - 1), shadingInfo, occlusion, frame); } } else if (voxelData.dataType == VoxelDataType::Chasm) { // Render front and back-faces. const VoxelData::ChasmData &chasmData = voxelData.chasm; // To do. } else if (voxelData.dataType == VoxelDataType::Door) { // To do: find intersection via SoftwareRenderer::findDoorIntersection(). // Just render as transparent wall for now. const VoxelData::DoorData &doorData = voxelData.door; const Double3 nearCeilingPoint( nearPoint.x, playerYFloor + voxelHeight, nearPoint.y); const Double3 nearFloorPoint( nearPoint.x, playerYFloor, nearPoint.y); const double nearCeilingScreenY = SoftwareRenderer::getProjectedY( nearCeilingPoint, transform, yShear) * heightReal; const double nearFloorScreenY = SoftwareRenderer::getProjectedY( nearFloorPoint, transform, yShear) * heightReal; const int wallStart = SoftwareRenderer::getLowerBoundedPixel( nearCeilingScreenY, frame.height); const int wallEnd = SoftwareRenderer::getUpperBoundedPixel( nearFloorScreenY, frame.height); SoftwareRenderer::drawTransparentPixels(x, wallStart, wallEnd, nearCeilingScreenY, nearFloorScreenY, nearZ, wallU, 0.0, Constants::JustBelowOne, wallNormal, textures.at(doorData.id - 1), shadingInfo, occlusion, frame); } }; auto drawVoxelBelow = [x, voxelX, voxelZ, playerY, &wallNormal, &nearPoint, &farPoint, nearZ, farZ, wallU, &transform, yShear, &shadingInfo, ceilingHeight, &voxelGrid, &textures, &occlusion, &frame, heightReal](int voxelY) { const char voxelID = voxelGrid.getVoxels()[voxelX + (voxelY * voxelGrid.getWidth()) + (voxelZ * voxelGrid.getWidth() * voxelGrid.getHeight())]; const VoxelData &voxelData = voxelGrid.getVoxelData(voxelID); const double voxelYReal = static_cast<double>(voxelY); // Height of the voxel depends on whether it's the main floor. const double voxelHeight = (voxelY == 1) ? ceilingHeight : 1.0; if (voxelData.dataType == VoxelDataType::Wall) { const VoxelData::WallData &wallData = voxelData.wall; const Double3 farCeilingPoint( farPoint.x, voxelYReal + voxelHeight, farPoint.y); const Double3 nearCeilingPoint( nearPoint.x, farCeilingPoint.y, nearPoint.y); const Double3 nearFloorPoint( nearPoint.x, voxelYReal, nearPoint.y); const double farCeilingScreenY = SoftwareRenderer::getProjectedY( farCeilingPoint, transform, yShear) * heightReal; const double nearCeilingScreenY = SoftwareRenderer::getProjectedY( nearCeilingPoint, transform, yShear) * heightReal; const double nearFloorScreenY = SoftwareRenderer::getProjectedY( nearFloorPoint, transform, yShear) * heightReal; const int ceilingStart = SoftwareRenderer::getLowerBoundedPixel( farCeilingScreenY, frame.height); const int ceilingEnd = SoftwareRenderer::getUpperBoundedPixel( nearCeilingScreenY, frame.height); const int wallStart = ceilingEnd; const int wallEnd = SoftwareRenderer::getUpperBoundedPixel( nearFloorScreenY, frame.height); // Ceiling. SoftwareRenderer::drawPerspectivePixels(x, ceilingStart, ceilingEnd, farCeilingScreenY, nearCeilingScreenY, farPoint, nearPoint, farZ, nearZ, Double3::UnitY, textures.at(wallData.ceilingID - 1), shadingInfo, occlusion, frame); // Side. SoftwareRenderer::drawPixels(x, wallStart, wallEnd, nearCeilingScreenY, nearFloorScreenY, nearZ, wallU, 0.0, Constants::JustBelowOne, wallNormal, textures.at(wallData.sideID - 1), shadingInfo, occlusion, frame); } else if (voxelData.dataType == VoxelDataType::Floor) { // Draw top of floor voxel. const VoxelData::FloorData &floorData = voxelData.floor; const Double3 farCeilingPoint( farPoint.x, voxelYReal + voxelHeight, farPoint.y); const Double3 nearCeilingPoint( nearPoint.x, farCeilingPoint.y, nearPoint.y); const double farCeilingScreenY = SoftwareRenderer::getProjectedY( farCeilingPoint, transform, yShear) * heightReal; const double nearCeilingScreenY = SoftwareRenderer::getProjectedY( nearCeilingPoint, transform, yShear) * heightReal; const int ceilingStart = SoftwareRenderer::getLowerBoundedPixel( farCeilingScreenY, frame.height); const int ceilingEnd = SoftwareRenderer::getUpperBoundedPixel( nearCeilingScreenY, frame.height); SoftwareRenderer::drawPerspectivePixels(x, ceilingStart, ceilingEnd, farCeilingScreenY, nearCeilingScreenY, farPoint, nearPoint, farZ, nearZ, Double3::UnitY, textures.at(floorData.id), shadingInfo, occlusion, frame); } else if (voxelData.dataType == VoxelDataType::Ceiling) { // Do nothing. Ceilings can only be seen from below. } else if (voxelData.dataType == VoxelDataType::Raised) { const VoxelData::RaisedData &raisedData = voxelData.raised; const Double3 nearCeilingPoint( nearPoint.x, voxelYReal + ((raisedData.yOffset + raisedData.ySize) * voxelHeight), nearPoint.y); const Double3 nearFloorPoint( nearPoint.x, voxelYReal + (raisedData.yOffset * voxelHeight), nearPoint.y); const double nearCeilingScreenY = SoftwareRenderer::getProjectedY( nearCeilingPoint, transform, yShear) * heightReal; const double nearFloorScreenY = SoftwareRenderer::getProjectedY( nearFloorPoint, transform, yShear) * heightReal; const int wallStart = SoftwareRenderer::getLowerBoundedPixel( nearCeilingScreenY, frame.height); const int wallEnd = SoftwareRenderer::getUpperBoundedPixel( nearFloorScreenY, frame.height); // Draw order depends on the player's Y position relative to the platform. if (playerY > nearCeilingPoint.y) { // Above platform. const Double3 farCeilingPoint( farPoint.x, nearCeilingPoint.y, farPoint.y); const double farCeilingScreenY = SoftwareRenderer::getProjectedY( farCeilingPoint, transform, yShear) * heightReal; const int ceilingStart = SoftwareRenderer::getLowerBoundedPixel( farCeilingScreenY, frame.height); const int ceilingEnd = wallStart; // Ceiling. SoftwareRenderer::drawPerspectivePixels(x, ceilingStart, ceilingEnd, farCeilingScreenY, nearCeilingScreenY, farPoint, nearPoint, farZ, nearZ, Double3::UnitY, textures.at(raisedData.ceilingID - 1), shadingInfo, occlusion, frame); // Side. SoftwareRenderer::drawTransparentPixels(x, wallStart, wallEnd, nearCeilingScreenY, nearFloorScreenY, nearZ, wallU, raisedData.vTop, raisedData.vBottom, wallNormal, textures.at(raisedData.sideID - 1), shadingInfo, occlusion, frame); } else if (playerY < nearFloorPoint.y) { // Below platform. const Double3 farFloorPoint( farPoint.x, nearFloorPoint.y, farPoint.y); const double farFloorScreenY = SoftwareRenderer::getProjectedY( farFloorPoint, transform, yShear) * heightReal; const int floorStart = wallEnd; const int floorEnd = SoftwareRenderer::getUpperBoundedPixel( farFloorScreenY, frame.height); // Side. SoftwareRenderer::drawTransparentPixels(x, wallStart, wallEnd, nearCeilingScreenY, nearFloorScreenY, nearZ, wallU, raisedData.vTop, raisedData.vBottom, wallNormal, textures.at(raisedData.sideID - 1), shadingInfo, occlusion, frame); // Floor. SoftwareRenderer::drawPerspectivePixels(x, floorStart, floorEnd, nearFloorScreenY, farFloorScreenY, nearPoint, farPoint, nearZ, farZ, -Double3::UnitY, textures.at(raisedData.floorID - 1), shadingInfo, occlusion, frame); } else { // Between top and bottom. SoftwareRenderer::drawTransparentPixels(x, wallStart, wallEnd, nearCeilingScreenY, nearFloorScreenY, nearZ, wallU, raisedData.vTop, raisedData.vBottom, wallNormal, textures.at(raisedData.sideID - 1), shadingInfo, occlusion, frame); } } else if (voxelData.dataType == VoxelDataType::Diagonal) { const VoxelData::DiagonalData &diagData = voxelData.diagonal; // Find intersection. RayHit hit; const bool success = diagData.type1 ? SoftwareRenderer::findDiag1Intersection(voxelX, voxelZ, nearPoint, farPoint, hit) : SoftwareRenderer::findDiag2Intersection(voxelX, voxelZ, nearPoint, farPoint, hit); if (success) { double diagTopScreenY, diagBottomScreenY; int diagStart, diagEnd; SoftwareRenderer::diagProjection(voxelYReal, voxelHeight, hit.point, transform, yShear, frame.height, heightReal, diagTopScreenY, diagBottomScreenY, diagStart, diagEnd); SoftwareRenderer::drawPixels(x, diagStart, diagEnd, diagTopScreenY, diagBottomScreenY, nearZ + hit.innerZ, hit.u, 0.0, Constants::JustBelowOne, hit.normal, textures.at(diagData.id - 1), shadingInfo, occlusion, frame); } } else if (voxelData.dataType == VoxelDataType::TransparentWall) { // Draw transparent side. const VoxelData::TransparentWallData &transparentWallData = voxelData.transparentWall; const Double3 nearCeilingPoint( nearPoint.x, voxelYReal + voxelHeight, nearPoint.y); const Double3 nearFloorPoint( nearPoint.x, voxelYReal, nearPoint.y); const double nearCeilingScreenY = SoftwareRenderer::getProjectedY( nearCeilingPoint, transform, yShear) * heightReal; const double nearFloorScreenY = SoftwareRenderer::getProjectedY( nearFloorPoint, transform, yShear) * heightReal; const int wallStart = SoftwareRenderer::getLowerBoundedPixel( nearCeilingScreenY, frame.height); const int wallEnd = SoftwareRenderer::getUpperBoundedPixel( nearFloorScreenY, frame.height); SoftwareRenderer::drawTransparentPixels(x, wallStart, wallEnd, nearCeilingScreenY, nearFloorScreenY, nearZ, wallU, 0.0, Constants::JustBelowOne, wallNormal, textures.at(transparentWallData.id - 1), shadingInfo, occlusion, frame); } else if (voxelData.dataType == VoxelDataType::Edge) { const VoxelData::EdgeData &edgeData = voxelData.edge; // Find intersection. RayHit hit; const bool success = SoftwareRenderer::findEdgeIntersection( voxelX, voxelZ, edgeData.facing, nearPoint, farPoint, hit); if (success) { const Double3 edgeTopPoint( hit.point.x, voxelYReal + voxelHeight, hit.point.y); const Double3 edgeBottomPoint( hit.point.x, voxelYReal, hit.point.y); const double edgeTopScreenY = SoftwareRenderer::getProjectedY( edgeTopPoint, transform, yShear) * heightReal; const double edgeBottomScreenY = SoftwareRenderer::getProjectedY( edgeBottomPoint, transform, yShear) * heightReal; const int edgeStart = SoftwareRenderer::getLowerBoundedPixel( edgeTopScreenY, frame.height); const int edgeEnd = SoftwareRenderer::getUpperBoundedPixel( edgeBottomScreenY, frame.height); SoftwareRenderer::drawTransparentPixels(x, edgeStart, edgeEnd, edgeTopScreenY, edgeBottomScreenY, nearZ + hit.innerZ, hit.u, 0.0, Constants::JustBelowOne, hit.normal, textures.at(edgeData.id - 1), shadingInfo, occlusion, frame); } } else if (voxelData.dataType == VoxelDataType::Chasm) { // Render front and back-faces. const VoxelData::ChasmData &chasmData = voxelData.chasm; // To do. } else if (voxelData.dataType == VoxelDataType::Door) { // To do: find intersection via SoftwareRenderer::findDoorIntersection(). // Just render as transparent wall for now. const VoxelData::DoorData &doorData = voxelData.door; const Double3 nearCeilingPoint( nearPoint.x, voxelYReal + voxelHeight, nearPoint.y); const Double3 nearFloorPoint( nearPoint.x, voxelYReal, nearPoint.y); const double nearCeilingScreenY = SoftwareRenderer::getProjectedY( nearCeilingPoint, transform, yShear) * heightReal; const double nearFloorScreenY = SoftwareRenderer::getProjectedY( nearFloorPoint, transform, yShear) * heightReal; const int wallStart = SoftwareRenderer::getLowerBoundedPixel( nearCeilingScreenY, frame.height); const int wallEnd = SoftwareRenderer::getUpperBoundedPixel( nearFloorScreenY, frame.height); SoftwareRenderer::drawTransparentPixels(x, wallStart, wallEnd, nearCeilingScreenY, nearFloorScreenY, nearZ, wallU, 0.0, Constants::JustBelowOne, wallNormal, textures.at(doorData.id - 1), shadingInfo, occlusion, frame); } }; auto drawVoxelAbove = [x, voxelX, voxelZ, playerY, &wallNormal, &nearPoint, &farPoint, nearZ, farZ, wallU, &transform, yShear, &shadingInfo, ceilingHeight, &voxelGrid, &textures, &occlusion, &frame, heightReal](int voxelY) { const char voxelID = voxelGrid.getVoxels()[voxelX + (voxelY * voxelGrid.getWidth()) + (voxelZ * voxelGrid.getWidth() * voxelGrid.getHeight())]; const VoxelData &voxelData = voxelGrid.getVoxelData(voxelID); const double voxelYReal = static_cast<double>(voxelY); // Height of the voxel depends on whether it's the main floor. const double voxelHeight = (voxelY == 1) ? ceilingHeight : 1.0; if (voxelData.dataType == VoxelDataType::Wall) { const VoxelData::WallData &wallData = voxelData.wall; const Double3 nearCeilingPoint( nearPoint.x, voxelYReal + voxelHeight, nearPoint.y); const Double3 nearFloorPoint( nearPoint.x, voxelYReal, nearPoint.y); const Double3 farFloorPoint( farPoint.x, nearFloorPoint.y, farPoint.y); const double nearCeilingScreenY = SoftwareRenderer::getProjectedY( nearCeilingPoint, transform, yShear) * heightReal; const double nearFloorScreenY = SoftwareRenderer::getProjectedY( nearFloorPoint, transform, yShear) * heightReal; const double farFloorScreenY = SoftwareRenderer::getProjectedY( farFloorPoint, transform, yShear) * heightReal; const int wallStart = SoftwareRenderer::getLowerBoundedPixel( nearCeilingScreenY, frame.height); const int wallEnd = SoftwareRenderer::getUpperBoundedPixel( nearFloorScreenY, frame.height); const int floorStart = wallEnd; const int floorEnd = SoftwareRenderer::getUpperBoundedPixel( farFloorScreenY, frame.height); // Side. SoftwareRenderer::drawPixels(x, wallStart, wallEnd, nearCeilingScreenY, nearFloorScreenY, nearZ, wallU, 0.0, Constants::JustBelowOne, wallNormal, textures.at(wallData.sideID - 1), shadingInfo, occlusion, frame); // Floor. SoftwareRenderer::drawPerspectivePixels(x, floorStart, floorEnd, nearFloorScreenY, farFloorScreenY, nearPoint, farPoint, nearZ, farZ, -Double3::UnitY, textures.at(wallData.floorID - 1), shadingInfo, occlusion, frame); } else if (voxelData.dataType == VoxelDataType::Floor) { // Do nothing. Floors can only be seen from above. } else if (voxelData.dataType == VoxelDataType::Ceiling) { // Draw bottom of ceiling voxel. const VoxelData::CeilingData &ceilingData = voxelData.ceiling; const Double3 nearFloorPoint( nearPoint.x, 1.0 + ceilingHeight, nearPoint.y); const Double3 farFloorPoint( farPoint.x, nearFloorPoint.y, farPoint.y); const double nearFloorScreenY = SoftwareRenderer::getProjectedY( nearFloorPoint, transform, yShear) * heightReal; const double farFloorScreenY = SoftwareRenderer::getProjectedY( farFloorPoint, transform, yShear) * heightReal; const int floorStart = SoftwareRenderer::getLowerBoundedPixel( nearFloorScreenY, frame.height); const int floorEnd = SoftwareRenderer::getUpperBoundedPixel( farFloorScreenY, frame.height); SoftwareRenderer::drawPerspectivePixels(x, floorStart, floorEnd, nearFloorScreenY, farFloorScreenY, nearPoint, farPoint, nearZ, farZ, -Double3::UnitY, textures.at(ceilingData.id), shadingInfo, occlusion, frame); } else if (voxelData.dataType == VoxelDataType::Raised) { const VoxelData::RaisedData &raisedData = voxelData.raised; const Double3 nearCeilingPoint( nearPoint.x, voxelYReal + ((raisedData.yOffset + raisedData.ySize) * voxelHeight), nearPoint.y); const Double3 nearFloorPoint( nearPoint.x, voxelYReal + (raisedData.yOffset * voxelHeight), nearPoint.y); const double nearCeilingScreenY = SoftwareRenderer::getProjectedY( nearCeilingPoint, transform, yShear) * heightReal; const double nearFloorScreenY = SoftwareRenderer::getProjectedY( nearFloorPoint, transform, yShear) * heightReal; const int wallStart = SoftwareRenderer::getLowerBoundedPixel( nearCeilingScreenY, frame.height); const int wallEnd = SoftwareRenderer::getUpperBoundedPixel( nearFloorScreenY, frame.height); // Draw order depends on the player's Y position relative to the platform. if (playerY > nearCeilingPoint.y) { // Above platform. const Double3 farCeilingPoint( farPoint.x, nearCeilingPoint.y, farPoint.y); const double farCeilingScreenY = SoftwareRenderer::getProjectedY( farCeilingPoint, transform, yShear) * heightReal; const int ceilingStart = SoftwareRenderer::getLowerBoundedPixel( farCeilingScreenY, frame.height); const int ceilingEnd = wallStart; // Ceiling. SoftwareRenderer::drawPerspectivePixels(x, ceilingStart, ceilingEnd, farCeilingScreenY, nearCeilingScreenY, farPoint, nearPoint, farZ, nearZ, Double3::UnitY, textures.at(raisedData.ceilingID - 1), shadingInfo, occlusion, frame); // Side. SoftwareRenderer::drawTransparentPixels(x, wallStart, wallEnd, nearCeilingScreenY, nearFloorScreenY, nearZ, wallU, raisedData.vTop, raisedData.vBottom, wallNormal, textures.at(raisedData.sideID - 1), shadingInfo, occlusion, frame); } else if (playerY < nearFloorPoint.y) { // Below platform. const Double3 farFloorPoint( farPoint.x, nearFloorPoint.y, farPoint.y); const double farFloorScreenY = SoftwareRenderer::getProjectedY( farFloorPoint, transform, yShear) * heightReal; const int floorStart = wallEnd; const int floorEnd = SoftwareRenderer::getUpperBoundedPixel( farFloorScreenY, frame.height); // Side. SoftwareRenderer::drawTransparentPixels(x, wallStart, wallEnd, nearCeilingScreenY, nearFloorScreenY, nearZ, wallU, raisedData.vTop, raisedData.vBottom, wallNormal, textures.at(raisedData.sideID - 1), shadingInfo, occlusion, frame); // Floor. SoftwareRenderer::drawPerspectivePixels(x, floorStart, floorEnd, nearFloorScreenY, farFloorScreenY, nearPoint, farPoint, nearZ, farZ, -Double3::UnitY, textures.at(raisedData.floorID - 1), shadingInfo, occlusion, frame); } else { // Between top and bottom. SoftwareRenderer::drawTransparentPixels(x, wallStart, wallEnd, nearCeilingScreenY, nearFloorScreenY, nearZ, wallU, raisedData.vTop, raisedData.vBottom, wallNormal, textures.at(raisedData.sideID - 1), shadingInfo, occlusion, frame); } } else if (voxelData.dataType == VoxelDataType::Diagonal) { const VoxelData::DiagonalData &diagData = voxelData.diagonal; // Find intersection. RayHit hit; const bool success = diagData.type1 ? SoftwareRenderer::findDiag1Intersection(voxelX, voxelZ, nearPoint, farPoint, hit) : SoftwareRenderer::findDiag2Intersection(voxelX, voxelZ, nearPoint, farPoint, hit); if (success) { double diagTopScreenY, diagBottomScreenY; int diagStart, diagEnd; SoftwareRenderer::diagProjection(voxelYReal, voxelHeight, hit.point, transform, yShear, frame.height, heightReal, diagTopScreenY, diagBottomScreenY, diagStart, diagEnd); SoftwareRenderer::drawPixels(x, diagStart, diagEnd, diagTopScreenY, diagBottomScreenY, nearZ + hit.innerZ, hit.u, 0.0, Constants::JustBelowOne, hit.normal, textures.at(diagData.id - 1), shadingInfo, occlusion, frame); } } else if (voxelData.dataType == VoxelDataType::TransparentWall) { // Draw transparent side. const VoxelData::TransparentWallData &transparentWallData = voxelData.transparentWall; const Double3 nearCeilingPoint( nearPoint.x, voxelYReal + voxelHeight, nearPoint.y); const Double3 nearFloorPoint( nearPoint.x, voxelYReal, nearPoint.y); const double nearCeilingScreenY = SoftwareRenderer::getProjectedY( nearCeilingPoint, transform, yShear) * heightReal; const double nearFloorScreenY = SoftwareRenderer::getProjectedY( nearFloorPoint, transform, yShear) * heightReal; const int wallStart = SoftwareRenderer::getLowerBoundedPixel( nearCeilingScreenY, frame.height); const int wallEnd = SoftwareRenderer::getUpperBoundedPixel( nearFloorScreenY, frame.height); SoftwareRenderer::drawTransparentPixels(x, wallStart, wallEnd, nearCeilingScreenY, nearFloorScreenY, nearZ, wallU, 0.0, Constants::JustBelowOne, wallNormal, textures.at(transparentWallData.id - 1), shadingInfo, occlusion, frame); } else if (voxelData.dataType == VoxelDataType::Edge) { const VoxelData::EdgeData &edgeData = voxelData.edge; // Find intersection. RayHit hit; const bool success = SoftwareRenderer::findEdgeIntersection( voxelX, voxelZ, edgeData.facing, nearPoint, farPoint, hit); if (success) { const Double3 edgeTopPoint( hit.point.x, voxelYReal + voxelHeight, hit.point.y); const Double3 edgeBottomPoint( hit.point.x, voxelYReal, hit.point.y); const double edgeTopScreenY = SoftwareRenderer::getProjectedY( edgeTopPoint, transform, yShear) * heightReal; const double edgeBottomScreenY = SoftwareRenderer::getProjectedY( edgeBottomPoint, transform, yShear) * heightReal; const int edgeStart = SoftwareRenderer::getLowerBoundedPixel( edgeTopScreenY, frame.height); const int edgeEnd = SoftwareRenderer::getUpperBoundedPixel( edgeBottomScreenY, frame.height); SoftwareRenderer::drawTransparentPixels(x, edgeStart, edgeEnd, edgeTopScreenY, edgeBottomScreenY, nearZ + hit.innerZ, hit.u, 0.0, Constants::JustBelowOne, hit.normal, textures.at(edgeData.id - 1), shadingInfo, occlusion, frame); } } else if (voxelData.dataType == VoxelDataType::Chasm) { // Render front and back-faces. const VoxelData::ChasmData &chasmData = voxelData.chasm; // To do. } else if (voxelData.dataType == VoxelDataType::Door) { // To do: find intersection via SoftwareRenderer::findDoorIntersection(). // Just render as transparent wall for now. const VoxelData::DoorData &doorData = voxelData.door; const Double3 nearCeilingPoint( nearPoint.x, voxelYReal + voxelHeight, nearPoint.y); const Double3 nearFloorPoint( nearPoint.x, voxelYReal, nearPoint.y); const double nearCeilingScreenY = SoftwareRenderer::getProjectedY( nearCeilingPoint, transform, yShear) * heightReal; const double nearFloorScreenY = SoftwareRenderer::getProjectedY( nearFloorPoint, transform, yShear) * heightReal; const int wallStart = SoftwareRenderer::getLowerBoundedPixel( nearCeilingScreenY, frame.height); const int wallEnd = SoftwareRenderer::getUpperBoundedPixel( nearFloorScreenY, frame.height); SoftwareRenderer::drawTransparentPixels(x, wallStart, wallEnd, nearCeilingScreenY, nearFloorScreenY, nearZ, wallU, 0.0, Constants::JustBelowOne, wallNormal, textures.at(doorData.id - 1), shadingInfo, occlusion, frame); } }; // Draw voxel straight ahead first. drawVoxel(); // Draw voxels below the voxel. for (int voxelY = (playerVoxelY - 1); voxelY >= 0; voxelY--) { drawVoxelBelow(voxelY); } // Draw voxels above the voxel. for (int voxelY = (playerVoxelY + 1); voxelY < voxelGrid.getHeight(); voxelY++) { drawVoxelAbove(voxelY); } } void SoftwareRenderer::drawFlat(int startX, int endX, const Flat::Frame &flatFrame, const Double3 &normal, bool flipped, const Double2 &eye, const ShadingInfo &shadingInfo, const SoftwareTexture &texture, const FrameView &frame) { // Contribution from the sun. const double lightNormalDot = std::max(0.0, shadingInfo.sunDirection.dot(normal)); const Double3 sunComponent = (shadingInfo.sunColor * lightNormalDot).clamped( 0.0, 1.0 - shadingInfo.ambient); // X percents across the screen for the given start and end columns. const double startXPercent = (static_cast<double>(startX) + 0.50) / static_cast<double>(frame.width); const double endXPercent = (static_cast<double>(endX) + 0.50) / static_cast<double>(frame.width); const bool startsInRange = (flatFrame.startX >= startXPercent) && (flatFrame.startX <= endXPercent); const bool endsInRange = (flatFrame.endX >= startXPercent) && (flatFrame.endX <= endXPercent); const bool coversRange = (flatFrame.startX <= startXPercent) && (flatFrame.endX >= endXPercent); // Throw out the draw call if the flat is not in the X range. if (!startsInRange && !endsInRange && !coversRange) { return; } // Get the min and max X range of coordinates in screen-space. This range is completely // contained within the flat. const double clampedStartXPercent = std::max(startXPercent, std::min(flatFrame.startX, flatFrame.endX)); const double clampedEndXPercent = std::min(endXPercent, std::max(flatFrame.startX, flatFrame.endX)); // The percentages from start to end within the flat. const double startFlatPercent = (clampedStartXPercent - flatFrame.startX) / (flatFrame.endX - flatFrame.startX); const double endFlatPercent = (clampedEndXPercent - flatFrame.startX) / (flatFrame.endX - flatFrame.startX); // Points interpolated between for per-column depth calculations in the XZ plane. const Double3 startTopPoint = flatFrame.topStart.lerp(flatFrame.topEnd, startFlatPercent); const Double3 endTopPoint = flatFrame.topStart.lerp(flatFrame.topEnd, endFlatPercent); // Horizontal texture coordinates in the flat. Although the flat percent can be // equal to 1.0, the texture coordinate needs to be less than 1.0. const double startU = std::max(std::min(startFlatPercent, Constants::JustBelowOne), 0.0); const double endU = std::max(std::min(endFlatPercent, Constants::JustBelowOne), 0.0); // Get the start and end coordinates of the projected points (Y values potentially // outside the screen). const double widthReal = static_cast<double>(frame.width); const double heightReal = static_cast<double>(frame.height); const double projectedXStart = clampedStartXPercent * widthReal; const double projectedXEnd = clampedEndXPercent * widthReal; const double projectedYStart = flatFrame.startY * heightReal; const double projectedYEnd = flatFrame.endY * heightReal; // Clamp the coordinates for where the flat starts and stops on the screen. const int xStart = SoftwareRenderer::getLowerBoundedPixel(projectedXStart, frame.width); const int xEnd = SoftwareRenderer::getUpperBoundedPixel(projectedXEnd, frame.width); const int yStart = SoftwareRenderer::getLowerBoundedPixel(projectedYStart, frame.height); const int yEnd = SoftwareRenderer::getUpperBoundedPixel(projectedYEnd, frame.height); // Shading on the texture. // - To do: contribution from lights. const Double3 shading( shadingInfo.ambient + sunComponent.x, shadingInfo.ambient + sunComponent.y, shadingInfo.ambient + sunComponent.z); // Draw by-column, similar to wall rendering. for (int x = xStart; x < xEnd; x++) { const double xPercent = ((static_cast<double>(x) + 0.50) - projectedXStart) / (projectedXEnd - projectedXStart); // Horizontal texture coordinate. const double u = startU + ((endU - startU) * xPercent); // Horizontal texel position. const int textureX = static_cast<int>( (flipped ? (Constants::JustBelowOne - u) : u) * static_cast<double>(texture.width)); const Double3 topPoint = startTopPoint.lerp(endTopPoint, xPercent); // Get the true XZ distance for the depth. const double depth = (Double2(topPoint.x, topPoint.z) - eye).length(); // Linearly interpolated fog. const Double3 &fogColor = shadingInfo.horizonSkyColor; const double fogPercent = std::min(depth / shadingInfo.fogDistance, 1.0); for (int y = yStart; y < yEnd; y++) { const int index = x + (y * frame.width); if (depth <= frame.depthBuffer[index]) { const double yPercent = ((static_cast<double>(y) + 0.50) - projectedYStart) / (projectedYEnd - projectedYStart); // Vertical texture coordinate. const double startV = 0.0; const double endV = Constants::JustBelowOne; const double v = startV + ((endV - startV) * yPercent); // Vertical texel position. const int textureY = static_cast<int>(v * static_cast<double>(texture.height)); // Alpha is checked in this loop, and transparent texels are not drawn. // Flats do not have emission, so ignore it. const int textureIndex = textureX + (textureY * texture.width); const Double4 &texel = texture.texels[textureIndex]; if (texel.w > 0.0) { // Texture color with shading. const double shadingMax = 1.0; double colorR = texel.x * std::min(shading.x, shadingMax); double colorG = texel.y * std::min(shading.y, shadingMax); double colorB = texel.z * std::min(shading.z, shadingMax); // Linearly interpolate with fog. colorR += (fogColor.x - colorR) * fogPercent; colorG += (fogColor.y - colorG) * fogPercent; colorB += (fogColor.z - colorB) * fogPercent; // Clamp maximum (don't worry about negative values). const double high = 1.0; colorR = (colorR > high) ? high : colorR; colorG = (colorG > high) ? high : colorG; colorB = (colorB > high) ? high : colorB; // Convert floats to integers. const uint32_t colorRGB = static_cast<uint32_t>( ((static_cast<uint8_t>(colorR * 255.0)) << 16) | ((static_cast<uint8_t>(colorG * 255.0)) << 8) | ((static_cast<uint8_t>(colorB * 255.0)))); frame.colorBuffer[index] = colorRGB; frame.depthBuffer[index] = depth; } } } } } void SoftwareRenderer::rayCast2D(int x, const Double3 &eye, const Double2 &direction, const Matrix4d &transform, double yShear, const ShadingInfo &shadingInfo, double ceilingHeight, const VoxelGrid &voxelGrid, const std::vector<SoftwareTexture> &textures, OcclusionData &occlusion, const FrameView &frame) { // Initially based on Lode Vandevenne's algorithm, this method of rendering is more // expensive than cheap 2.5D ray casting, as it does not stop at the first wall // intersection, and it also renders walls above and below, but it is more correct // as a result. Assume "direction" is normalized. // Some floating point behavior assumptions: // -> (value / 0.0) == infinity // -> (value / infinity) == 0.0 // -> (int)(-0.8) == 0 // -> (int)floor(-0.8) == -1 // -> (int)ceil(-0.8) == 0 // Because 2D vectors use "X" and "Y", the Z component is actually // aliased as "Y", which is a minor annoyance. const double dirX = direction.x; const double dirZ = direction.y; const double dirXSquared = direction.x * direction.x; const double dirZSquared = direction.y * direction.y; const double deltaDistX = std::sqrt(1.0 + (dirZSquared / dirXSquared)); const double deltaDistZ = std::sqrt(1.0 + (dirXSquared / dirZSquared)); const bool nonNegativeDirX = direction.x >= 0.0; const bool nonNegativeDirZ = direction.y >= 0.0; // Constant DDA-related values. // - Technically, these could be moved out of the ray casting method, but they // are not a performance concern for now. It's just to minimize renderer state. const Double3 startCellReal( std::floor(eye.x), std::floor(eye.y), std::floor(eye.z)); const Int3 startCell( static_cast<int>(startCellReal.x), static_cast<int>(startCellReal.y), static_cast<int>(startCellReal.z)); int stepX, stepZ; double sideDistX, sideDistZ; if (nonNegativeDirX) { stepX = 1; sideDistX = (startCellReal.x + 1.0 - eye.x) * deltaDistX; } else { stepX = -1; sideDistX = (eye.x - startCellReal.x) * deltaDistX; } if (nonNegativeDirZ) { stepZ = 1; sideDistZ = (startCellReal.z + 1.0 - eye.z) * deltaDistZ; } else { stepZ = -1; sideDistZ = (eye.z - startCellReal.z) * deltaDistZ; } // Pointer to voxel ID grid data. const char *voxels = voxelGrid.getVoxels(); // The Z distance from the camera to the wall, and the X or Z normal of the intersected // voxel face. The first Z distance is a special case, so it's brought outside the // DDA loop. double zDistance; VoxelData::Facing facing; // Verify that the initial voxel coordinate is within the world bounds. bool voxelIsValid = (startCell.x >= 0) && (startCell.y >= 0) && (startCell.z >= 0) && (startCell.x < voxelGrid.getWidth()) && (startCell.y < voxelGrid.getHeight()) && (startCell.z < voxelGrid.getDepth()); if (voxelIsValid) { // Get the initial voxel ID and see how it should be rendered. const char initialVoxelID = voxels[startCell.x + (startCell.y * voxelGrid.getWidth()) + (startCell.z * voxelGrid.getWidth() * voxelGrid.getHeight())]; // Decide how far the wall is, and which voxel face was hit. if (sideDistX < sideDistZ) { zDistance = sideDistX; facing = nonNegativeDirX ? VoxelData::Facing::NegativeX : VoxelData::Facing::PositiveX; } else { zDistance = sideDistZ; facing = nonNegativeDirZ ? VoxelData::Facing::NegativeZ : VoxelData::Facing::PositiveZ; } // The initial near point is directly in front of the player in the near Z // camera plane. const Double2 initialNearPoint( eye.x + (dirX * SoftwareRenderer::NEAR_PLANE), eye.z + (dirZ * SoftwareRenderer::NEAR_PLANE)); // The initial far point is the wall hit. This is used with the player's position // for drawing the initial floor and ceiling. const Double2 initialFarPoint( eye.x + (dirX * zDistance), eye.z + (dirZ * zDistance)); // Draw all voxels in a column at the player's XZ coordinate. SoftwareRenderer::drawInitialVoxelColumn(x, startCell.x, startCell.z, eye.y, facing, initialNearPoint, initialFarPoint, SoftwareRenderer::NEAR_PLANE, zDistance, transform, yShear, shadingInfo, ceilingHeight, voxelGrid, textures, occlusion, frame); } // The current voxel coordinate in the DDA loop. For all intents and purposes, // the Y cell coordinate is constant. Int3 cell(startCell.x, startCell.y, startCell.z); // Lambda for stepping to the next XZ coordinate in the grid and updating the Z // distance for the current edge point. auto doDDAStep = [&eye, &voxelGrid, &sideDistX, &sideDistZ, &cell, &facing, &voxelIsValid, &zDistance, deltaDistX, deltaDistZ, stepX, stepZ, dirX, dirZ, nonNegativeDirX, nonNegativeDirZ]() { if (sideDistX < sideDistZ) { sideDistX += deltaDistX; cell.x += stepX; facing = nonNegativeDirX ? VoxelData::Facing::NegativeX : VoxelData::Facing::PositiveX; voxelIsValid &= (cell.x >= 0) && (cell.x < voxelGrid.getWidth()); } else { sideDistZ += deltaDistZ; cell.z += stepZ; facing = nonNegativeDirZ ? VoxelData::Facing::NegativeZ : VoxelData::Facing::PositiveZ; voxelIsValid &= (cell.z >= 0) && (cell.z < voxelGrid.getDepth()); } const bool onXAxis = (facing == VoxelData::Facing::PositiveX) || (facing == VoxelData::Facing::NegativeX); zDistance = onXAxis ? (static_cast<double>(cell.x) - eye.x + static_cast<double>((1 - stepX) / 2)) / dirX : (static_cast<double>(cell.z) - eye.z + static_cast<double>((1 - stepZ) / 2)) / dirZ; }; // Step forward in the grid once to leave the initial voxel and update the Z distance. doDDAStep(); // Step through the voxel grid while the current coordinate is valid, the // distance stepped is less than the distance at which fog is maximum, and // the column is not completely occluded. while (voxelIsValid && (zDistance < shadingInfo.fogDistance) && (occlusion.yMin != occlusion.yMax)) { // Store the cell coordinates, axis, and Z distance for wall rendering. The // loop needs to do another DDA step to calculate the far point. const int savedCellX = cell.x; const int savedCellZ = cell.z; const VoxelData::Facing savedNormal = facing; const double wallDistance = zDistance; // Decide which voxel in the XZ plane to step to next, and update the Z distance. doDDAStep(); // Near and far points in the XZ plane. The near point is where the wall is, and // the far point is used with the near point for drawing the floor and ceiling. const Double2 nearPoint( eye.x + (dirX * wallDistance), eye.z + (dirZ * wallDistance)); const Double2 farPoint( eye.x + (dirX * zDistance), eye.z + (dirZ * zDistance)); // Draw all voxels in a column at the given XZ coordinate. SoftwareRenderer::drawVoxelColumn(x, savedCellX, savedCellZ, eye.y, savedNormal, nearPoint, farPoint, wallDistance, zDistance, transform, yShear, shadingInfo, ceilingHeight, voxelGrid, textures, occlusion, frame); } } void SoftwareRenderer::render(const Double3 &eye, const Double3 &direction, double fovY, double ambient, double daytimePercent, double ceilingHeight, const VoxelGrid &voxelGrid, uint32_t *colorBuffer) { // Constants for screen dimensions. const double widthReal = static_cast<double>(this->width); const double heightReal = static_cast<double>(this->height); const double aspect = widthReal / heightReal; // Camera values for rendering. We trick the 2.5D ray caster into thinking the player is // always looking straight forward, but we use the Y component of the player's direction // to offset projected coordinates via Y-shearing. Assume "direction" is normalized. const Double3 forwardXZ = Double3(direction.x, 0.0, direction.z).normalized(); const Double3 rightXZ = forwardXZ.cross(Double3::UnitY).normalized(); const Double3 up = Double3::UnitY; // Zoom of the camera, based on vertical field of view. const double zoom = 1.0 / std::tan((fovY * 0.5) * Constants::DegToRad); // Refresh transformation matrix (model matrix isn't required because it's just // the identity matrix). const Matrix4d view = Matrix4d::view(eye, forwardXZ, rightXZ, up); const Matrix4d projection = Matrix4d::perspective(fovY, aspect, SoftwareRenderer::NEAR_PLANE, SoftwareRenderer::FAR_PLANE); const Matrix4d transform = projection * view; // Y-shearing is the distance that projected Y coordinates are translated by based on the // player's 3D direction and field of view. First get the player's angle relative to the // horizon, then get the tangent of that angle. The Y component of the player's direction // must be clamped less than 1 because 1 would imply they are looking straight up or down, // which is impossible in 2.5D rendering (the vertical line segment of the view frustum // would be infinitely high or low). The camera code should take care of the clamping for us. const double yShear = [&direction, zoom]() { // Get the vertical angle of the player's direction. const double angleRadians = [&direction]() { // Get the length of the direction vector's projection onto the XZ plane. const double xzProjection = std::sqrt( (direction.x * direction.x) + (direction.z * direction.z)); if (direction.y > 0.0) { // Above the horizon. return std::acos(xzProjection); } else if (direction.y < 0.0) { // Below the horizon. return -std::acos(xzProjection); } else { // At the horizon. return 0.0; } }(); // Get the number of screen heights to translate all projected Y coordinates by, // relative to the current zoom. As a reference, this should be some value roughly // between -1.0 and 1.0 for "acceptable skewing" at a vertical FOV of 90.0. If the // camera is not clamped, this could theoretically be between -infinity and infinity, // but it would result in far too much skewing. return std::tan(angleRadians) * zoom; }(); // Camera values for generating 2D rays with. const Double2 forwardComp = Double2(forwardXZ.x, forwardXZ.z).normalized() * zoom; const Double2 right2D = Double2(rightXZ.x, rightXZ.z).normalized() * aspect; // Calculate shading information. const Double3 horizonFogColor = this->getFogColor(daytimePercent); const Double3 zenithFogColor = horizonFogColor * 0.85; // Temp. const Double3 sunDirection = this->getSunDirection(daytimePercent); const Double3 sunColor = [&sunDirection]() { const Double3 baseColor(0.90, 0.875, 0.85); // Darken the sun color if it's below the horizon so wall faces aren't lit // as much during the night. This is just an artistic value to compensate // for the lack of shadows. return (sunDirection.y >= 0.0) ? baseColor : (baseColor * (1.0 - (5.0 * std::abs(sunDirection.y)))).clamped(); }(); // Create some helper structs to keep similar values together. const ShadingInfo shadingInfo(horizonFogColor, zenithFogColor, sunColor, sunDirection, ambient, this->fogDistance); const FrameView frame(colorBuffer, this->depthBuffer.data(), this->width, this->height); // Lambda for rendering some columns of pixels. The voxel rendering portion uses 2.5D // ray casting, which is the cheaper form of ray casting (although still not very // efficient overall), and results in a "fake" 3D scene. auto renderColumns = [this, &eye, ceilingHeight, &voxelGrid, &shadingInfo, widthReal, &transform, yShear, &forwardComp, &right2D, &frame](int startX, int endX) { for (int x = startX; x < endX; x++) { // X percent across the screen. const double xPercent = (static_cast<double>(x) + 0.50) / widthReal; // "Right" component of the ray direction, based on current screen X. const Double2 rightComp = right2D * ((2.0 * xPercent) - 1.0); // Calculate the ray direction through the pixel. // - If un-normalized, it uses the Z distance, but the insides of voxels // don't look right then. const Double2 direction = (forwardComp + rightComp).normalized(); // Cast the 2D ray and fill in the column's pixels with color. this->rayCast2D(x, eye, direction, transform, yShear, shadingInfo, ceilingHeight, voxelGrid, this->textures, this->occlusion.at(x), frame); } // Iterate through all flats, rendering those visible within the given X range of // the screen. for (const auto &pair : this->visibleFlats) { const Flat &flat = *pair.first; const Flat::Frame &flatFrame = pair.second; // Normal of the flat (always facing the camera). const Double3 flatNormal = Double3(-forwardComp.x, 0.0, -forwardComp.y).normalized(); // Texture of the flat. It might be flipped horizontally as well, given by // the "flat.flipped" value. const SoftwareTexture &texture = textures[flat.textureID]; const Double2 eye2D(eye.x, eye.z); SoftwareRenderer::drawFlat(startX, endX, flatFrame, flatNormal, flat.flipped, eye2D, shadingInfo, texture, frame); } }; // Lambda for clearing some rows on the frame buffer quickly. auto clearRows = [this, colorBuffer, &horizonFogColor, &zenithFogColor](int startY, int endY) { const int startIndex = startY * this->width; const int endIndex = endY * this->width; uint32_t *colorPtr = colorBuffer; double *depthPtr = this->depthBuffer.data(); const uint32_t colorValue = horizonFogColor.toRGB(); const double depthValue = std::numeric_limits<double>::infinity(); // Clear the color and depth of some rows. for (int i = startIndex; i < endIndex; i++) { colorPtr[i] = colorValue; depthPtr[i] = depthValue; } }; // Start a thread for refreshing the visible flats. This should erase the old list, // calculate a new list, and sort it by depth. std::thread sortThread([this, &eye, &forwardXZ, &transform, yShear, aspect, zoom] { const Double2 eye2D(eye.x, eye.z); const Double2 direction2D(forwardXZ.x, forwardXZ.z); this->updateVisibleFlats(eye2D, direction2D, transform, yShear, aspect, zoom); }); // Prepare render threads. These are used for clearing the frame buffer and rendering. std::vector<std::thread> renderThreads(this->renderThreadCount); // Start clearing the frame buffer with the render threads. for (size_t i = 0; i < renderThreads.size(); i++) { // "blockSize" is the approximate number of rows per thread. Rounding is involved so // the start and stop coordinates are correct for all resolutions. const double blockSize = heightReal / static_cast<double>(this->renderThreadCount); const int startY = static_cast<int>(std::round(static_cast<double>(i) * blockSize)); const int endY = static_cast<int>(std::round(static_cast<double>(i + 1) * blockSize)); // Make sure the rounding is correct. assert(startY >= 0); assert(endY <= this->height); renderThreads[i] = std::thread(clearRows, startY, endY); } // Reset occlusion. std::fill(this->occlusion.begin(), this->occlusion.end(), OcclusionData(0, this->height)); // Wait for the render threads to finish clearing. for (auto &thread : renderThreads) { thread.join(); } // Wait for the sorting thread to finish. sortThread.join(); // Start rendering the scene with the render threads. for (size_t i = 0; i < renderThreads.size(); i++) { // "blockSize" is the approximate number of columns per thread. Rounding is involved so // the start and stop coordinates are correct for all resolutions. const double blockSize = widthReal / static_cast<double>(this->renderThreadCount); const int startX = static_cast<int>(std::round(static_cast<double>(i) * blockSize)); const int endX = static_cast<int>(std::round(static_cast<double>(i + 1) * blockSize)); // Make sure the rounding is correct. assert(startX >= 0); assert(endX <= this->width); renderThreads[i] = std::thread(renderColumns, startX, endX); } // Wait for the render threads to finish rendering. for (auto &thread : renderThreads) { thread.join(); } } Slight vector calculation change. #include <algorithm> #include <cassert> #include <cmath> #include <limits> #include <thread> #include "SoftwareRenderer.h" #include "../Math/Constants.h" #include "../Media/Color.h" #include "../Utilities/Debug.h" #include "../Utilities/Platform.h" #include "../World/VoxelData.h" #include "../World/VoxelDataType.h" #include "../World/VoxelGrid.h" SoftwareRenderer::OcclusionData::OcclusionData(int yMin, int yMax) { this->yMin = yMin; this->yMax = yMax; } SoftwareRenderer::OcclusionData::OcclusionData() : OcclusionData(0, 0) { } void SoftwareRenderer::OcclusionData::clipRange(int *yStart, int *yEnd) const { // To do. /*const bool occluded = (*yEnd <= this->yMin) || (*yStart >= this->yMax); if (occluded) { // The drawing range is completely hidden. *yStart = *yEnd; } else { // To do: need to handle more cases (yStart == yEnd, outside of screen, etc.). // Clip the drawing range. *yStart = std::max(*yStart, this->yMin); *yEnd = std::min(*yEnd, this->yMax); }*/ } void SoftwareRenderer::OcclusionData::update(int yStart, int yEnd) { // To do. // Slightly different than clipRange() because values just needs to be adjacent // rather than overlap. /*const bool canIncreaseMin = yStart <= this->yMin; const bool canDecreaseMax = yEnd >= this->yMax; // To do: need to handle more cases (yStart == yEnd, outside of screen, etc.). // Determine how to update the occlusion ranges. if (canIncreaseMin && canDecreaseMax) { // The drawing range touches the top and bottom occlusion values, so the // entire column is occluded. this->yMin = this->yMax; } else if (canIncreaseMin) { this->yMin = std::min(yEnd, this->yMax); } else if (canDecreaseMax) { this->yMax = std::max(yStart, this->yMin); }*/ } SoftwareRenderer::ShadingInfo::ShadingInfo(const Double3 &horizonSkyColor, const Double3 &zenithSkyColor, const Double3 &sunColor, const Double3 &sunDirection, double ambient, double fogDistance) : horizonSkyColor(horizonSkyColor), zenithSkyColor(zenithSkyColor), sunColor(sunColor), sunDirection(sunDirection) { this->ambient = ambient; this->fogDistance = fogDistance; } SoftwareRenderer::FrameView::FrameView(uint32_t *colorBuffer, double *depthBuffer, int width, int height) { this->colorBuffer = colorBuffer; this->depthBuffer = depthBuffer; this->width = width; this->height = height; } const double SoftwareRenderer::NEAR_PLANE = 0.0001; const double SoftwareRenderer::FAR_PLANE = 1000.0; SoftwareRenderer::SoftwareRenderer(int width, int height) { // Initialize 2D frame buffer. const int pixelCount = width * height; this->depthBuffer = std::vector<double>(pixelCount, std::numeric_limits<double>::infinity()); // Initialize occlusion columns. this->occlusion = std::vector<OcclusionData>(width, OcclusionData(0, height)); this->width = width; this->height = height; // Obtain the number of threads to use. this->renderThreadCount = Platform::getThreadCount(); // Fog distance is zero by default. this->fogDistance = 0.0; } SoftwareRenderer::~SoftwareRenderer() { } void SoftwareRenderer::addFlat(int id, const Double3 &position, double width, double height, int textureID) { // Verify that the ID is not already in use. DebugAssert(this->flats.find(id) == this->flats.end(), "Flat ID \"" + std::to_string(id) + "\" already taken."); SoftwareRenderer::Flat flat; flat.position = position; flat.width = width; flat.height = height; flat.textureID = textureID; flat.flipped = false; // The initial value doesn't matter; it's updated frequently. // Add the flat (sprite, door, store sign, etc.). this->flats.insert(std::make_pair(id, flat)); } void SoftwareRenderer::addLight(int id, const Double3 &point, const Double3 &color, double intensity) { DebugNotImplemented(); } int SoftwareRenderer::addTexture(const uint32_t *texels, int width, int height) { const int texelCount = width * height; SoftwareTexture texture; texture.texels = std::vector<Double4>(texelCount); texture.emissionTexels = std::vector<double>(texelCount); std::fill(texture.emissionTexels.begin(), texture.emissionTexels.end(), 0.0); texture.width = width; texture.height = height; // Convert ARGB color from integer to double-precision format for speed. // This does waste an extreme amount of memory (32 bytes per pixel!), but // it's not a big deal for Arena's textures (mostly 64x64, so eight textures // would be a megabyte). Double4 *textureTexels = texture.texels.data(); for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { const int index = x + (y * width); textureTexels[index] = Double4::fromARGB(texels[index]); // If it's a white texel, it's used with night lights (i.e., yellow at night). const Double4 &texel = textureTexels[index]; const bool isWhite = (texel.x == 1.0) && (texel.y == 1.0) && (texel.z == 1.0); if (isWhite) { texture.lightTexels.push_back(Int2(x, y)); } } } this->textures.push_back(std::move(texture)); return static_cast<int>(this->textures.size() - 1); } void SoftwareRenderer::updateFlat(int id, const Double3 *position, const double *width, const double *height, const int *textureID, const bool *flipped) { const auto flatIter = this->flats.find(id); DebugAssert(flatIter != this->flats.end(), "Cannot update a non-existent flat (" + std::to_string(id) + ")."); SoftwareRenderer::Flat &flat = flatIter->second; // Check which values requested updating and update them. if (position != nullptr) { flat.position = *position; } if (width != nullptr) { flat.width = *width; } if (height != nullptr) { flat.height = *height; } if (textureID != nullptr) { flat.textureID = *textureID; } if (flipped != nullptr) { flat.flipped = *flipped; } } void SoftwareRenderer::updateLight(int id, const Double3 *point, const Double3 *color, const double *intensity) { DebugNotImplemented(); } void SoftwareRenderer::setFogDistance(double fogDistance) { this->fogDistance = fogDistance; } void SoftwareRenderer::setSkyPalette(const uint32_t *colors, int count) { this->skyPalette = std::vector<Double3>(count); for (size_t i = 0; i < this->skyPalette.size(); i++) { this->skyPalette[i] = Double3::fromRGB(colors[i]); } } void SoftwareRenderer::setNightLightsActive(bool active) { // To do: activate lights (don't worry about textures). // Change voxel texels based on whether it's night. const Double4 texelColor = Double4::fromARGB( (active ? Color(255, 166, 0) : Color::Black).toARGB()); const double texelEmission = active ? 1.0 : 0.0; for (auto &texture : this->textures) { std::vector<Double4> &texels = texture.texels; std::vector<double> &emissionTexels = texture.emissionTexels; for (const auto &lightTexels : texture.lightTexels) { const int index = lightTexels.x + (lightTexels.y * texture.width); texels.at(index) = texelColor; emissionTexels.at(index) = texelEmission; } } } void SoftwareRenderer::removeFlat(int id) { // Make sure the flat exists before removing it. const auto flatIter = this->flats.find(id); DebugAssert(flatIter != this->flats.end(), "Cannot remove a non-existent flat (" + std::to_string(id) + ")."); this->flats.erase(flatIter); } void SoftwareRenderer::removeLight(int id) { DebugNotImplemented(); } void SoftwareRenderer::removeAllTextures() { this->textures.clear(); } void SoftwareRenderer::resize(int width, int height) { const int pixelCount = width * height; this->depthBuffer.resize(pixelCount); std::fill(this->depthBuffer.begin(), this->depthBuffer.end(), std::numeric_limits<double>::infinity()); this->occlusion.resize(width); std::fill(this->occlusion.begin(), this->occlusion.end(), OcclusionData(0, height)); this->width = width; this->height = height; } void SoftwareRenderer::updateVisibleFlats(const Double2 &eye, const Double2 &direction, const Matrix4d &transform, double yShear, double aspect, double zoom) { assert(direction.isNormalized()); this->visibleFlats.clear(); // Each flat shares the same axes. The forward direction always faces opposite to // the camera direction. const Double3 flatForward = Double3(-direction.x, 0.0, -direction.y).normalized(); const Double3 flatUp = Double3::UnitY; const Double3 flatRight = flatForward.cross(flatUp).normalized(); // This is the visible flat determination algorithm. It goes through all flats and sees // which ones would be at least partially visible in the view frustum. for (const auto &pair : this->flats) { const Flat &flat = pair.second; // Scaled axes based on flat dimensions. const Double3 flatRightScaled = flatRight * (flat.width * 0.50); const Double3 flatUpScaled = flatUp * flat.height; // Calculate each corner of the flat in world space. Flat::Frame flatFrame; flatFrame.bottomStart = flat.position + flatRightScaled; flatFrame.bottomEnd = flat.position - flatRightScaled; flatFrame.topStart = flatFrame.bottomStart + flatUpScaled; flatFrame.topEnd = flatFrame.bottomEnd + flatUpScaled; // If the flat is somewhere in front of the camera, do further checks. const Double2 flatPosition2D(flat.position.x, flat.position.z); const Double2 flatEyeDiff = (flatPosition2D - eye).normalized(); const bool inFrontOfCamera = direction.dot(flatEyeDiff) > 0.0; if (inFrontOfCamera) { // Now project two of the flat's opposing corner points into camera space. // The Z value is used with flat sorting (not rendering), and the X and Y values // are used to find where the flat is on-screen. Double4 projStart = transform * Double4(flatFrame.topStart, 1.0); Double4 projEnd = transform * Double4(flatFrame.bottomEnd, 1.0); // Normalize coordinates. projStart = projStart / projStart.w; projEnd = projEnd / projEnd.w; // Assign each screen value to the flat frame data. flatFrame.startX = 0.50 + (projStart.x * 0.50); flatFrame.endX = 0.50 + (projEnd.x * 0.50); flatFrame.startY = (0.50 + yShear) - (projStart.y * 0.50); flatFrame.endY = (0.50 + yShear) - (projEnd.y * 0.50); flatFrame.z = projStart.z; // Check that the Z value is within the clipping planes. const bool inPlanes = (flatFrame.z >= SoftwareRenderer::NEAR_PLANE) && (flatFrame.z <= SoftwareRenderer::FAR_PLANE); if (inPlanes) { // Add the flat data to the draw list. this->visibleFlats.push_back(std::make_pair(&flat, std::move(flatFrame))); } } } // Sort the visible flats farthest to nearest (relevant for transparencies). std::sort(this->visibleFlats.begin(), this->visibleFlats.end(), [](const std::pair<const Flat*, Flat::Frame> &a, const std::pair<const Flat*, Flat::Frame> &b) { return a.second.z > b.second.z; }); } /*Double3 SoftwareRenderer::castRay(const Double3 &direction, const VoxelGrid &voxelGrid) const { // This is an extension of Lode Vandevenne's DDA algorithm from 2D to 3D. // Technically, it could be considered a "3D-DDA" algorithm. It will eventually // have some additional features so all of Arena's geometry can be represented. // To do: // - Figure out proper DDA lengths for variable-height voxels, and why using // voxelHeight squared instead of 1.0 in deltaDist.y looks weird (sideDist.y?). // - Cuboids within voxels (bridges, beds, shelves) with variable Y offset and size. // - Sprites (SpriteGrid? Sprite data, and list of sprite IDs per voxel). // - Transparent textures (check texel alpha in DDA loop). // - Sky (if hitID == 0). // - Shading (shadows from the sun, point lights). // Some floating point behavior assumptions: // -> (value / 0.0) == infinity // -> (value / infinity) == 0.0 // -> (int)(-0.8) == 0 // -> (int)floor(-0.8) == -1 // -> (int)ceil(-0.8) == 0 const Double3 dirSquared( direction.x * direction.x, direction.y * direction.y, direction.z * direction.z); // Height (Y size) of each voxel in the voxel grid. Some levels in Arena have // "tall" voxels, so the voxel height must be a variable. const double voxelHeight = voxelGrid.getVoxelHeight(); // A custom variable that represents the Y "floor" of the current voxel. const double eyeYRelativeFloor = std::floor(this->eye.y / voxelHeight) * voxelHeight; // Calculate delta distances along each axis. These determine how far // the ray has to go until the next X, Y, or Z side is hit, respectively. const Double3 deltaDist( std::sqrt(1.0 + (dirSquared.y / dirSquared.x) + (dirSquared.z / dirSquared.x)), std::sqrt(1.0 + (dirSquared.x / dirSquared.y) + (dirSquared.z / dirSquared.y)), std::sqrt(1.0 + (dirSquared.x / dirSquared.z) + (dirSquared.y / dirSquared.z))); // Booleans for whether a ray component is non-negative. Used with step directions // and texture coordinates. const bool nonNegativeDirX = direction.x >= 0.0; const bool nonNegativeDirY = direction.y >= 0.0; const bool nonNegativeDirZ = direction.z >= 0.0; // Calculate step directions and initial side distances. Int3 step; Double3 sideDist; if (nonNegativeDirX) { step.x = 1; sideDist.x = (this->startCellReal.x + 1.0 - this->eye.x) * deltaDist.x; } else { step.x = -1; sideDist.x = (this->eye.x - this->startCellReal.x) * deltaDist.x; } if (nonNegativeDirY) { step.y = 1; sideDist.y = (eyeYRelativeFloor + voxelHeight - this->eye.y) * deltaDist.y; } else { step.y = -1; sideDist.y = (this->eye.y - eyeYRelativeFloor) * deltaDist.y; } if (nonNegativeDirZ) { step.z = 1; sideDist.z = (this->startCellReal.z + 1.0 - this->eye.z) * deltaDist.z; } else { step.z = -1; sideDist.z = (this->eye.z - this->startCellReal.z) * deltaDist.z; } // Make a copy of the initial side distances. They are used for the special case // of the ray ending in the same voxel it started in. const Double3 initialSideDist = sideDist; // Make a copy of the step magnitudes, converted to doubles. const Double3 stepReal( static_cast<double>(step.x), static_cast<double>(step.y), static_cast<double>(step.z)); // Get initial voxel coordinates. Int3 cell = this->startCell; // ID of a hit voxel. Zero (air) by default. char hitID = 0; // Axis of a hit voxel's side. X by default. enum class Axis { X, Y, Z }; Axis axis = Axis::X; // Distance squared (in voxels) that the ray has stepped. Square roots are // too slow to use in the DDA loop, so this is used instead. // - When using variable-sized voxels, this may be calculated differently. double cellDistSquared = 0.0; // Offset values for which corner of a voxel to compare the distance // squared against. The correct corner to use is important when culling // shapes at max view distance. const Double3 startCellWithOffset( this->startCellReal.x + ((1.0 + stepReal.x) / 2.0), eyeYRelativeFloor + (((1.0 + stepReal.y) / 2.0) * voxelHeight), this->startCellReal.z + ((1.0 + stepReal.z) / 2.0)); const Double3 cellOffset( (1.0 - stepReal.x) / 2.0, ((1.0 - stepReal.y) / 2.0) * voxelHeight, (1.0 - stepReal.z) / 2.0); // Get dimensions of the voxel grid. const int gridWidth = voxelGrid.getWidth(); const int gridHeight = voxelGrid.getHeight(); const int gridDepth = voxelGrid.getDepth(); // Check world bounds on the start voxel. Bounds are partially recalculated // for axes that the DDA loop is stepping through. bool voxelIsValid = (cell.x >= 0) && (cell.y >= 0) && (cell.z >= 0) && (cell.x < gridWidth) && (cell.y < gridHeight) && (cell.z < gridDepth); // Step through the voxel grid while the current coordinate is valid and // the total voxel distance stepped is less than the view distance. // (Note that the "voxel distance" is not the same as "actual" distance.) const char *voxels = voxelGrid.getVoxels(); while (voxelIsValid && (cellDistSquared < this->viewDistSquared)) { // Get the index of the current voxel in the voxel grid. const int gridIndex = cell.x + (cell.y * gridWidth) + (cell.z * gridWidth * gridHeight); // Check if the current voxel is solid. const char voxelID = voxels[gridIndex]; if (voxelID > 0) { hitID = voxelID; break; } if ((sideDist.x < sideDist.y) && (sideDist.x < sideDist.z)) { sideDist.x += deltaDist.x; cell.x += step.x; axis = Axis::X; voxelIsValid &= (cell.x >= 0) && (cell.x < gridWidth); } else if (sideDist.y < sideDist.z) { sideDist.y += deltaDist.y; cell.y += step.y; axis = Axis::Y; voxelIsValid &= (cell.y >= 0) && (cell.y < gridHeight); } else { sideDist.z += deltaDist.z; cell.z += step.z; axis = Axis::Z; voxelIsValid &= (cell.z >= 0) && (cell.z < gridDepth); } // Refresh how far the current cell is from the start cell, squared. // The "offsets" move each point to the correct corner for each voxel // so that the stepping stops correctly at max view distance. const Double3 cellDiff( (static_cast<double>(cell.x) + cellOffset.x) - startCellWithOffset.x, (static_cast<double>(cell.y) + cellOffset.y) - startCellWithOffset.y, (static_cast<double>(cell.z) + cellOffset.z) - startCellWithOffset.z); cellDistSquared = (cellDiff.x * cellDiff.x) + (cellDiff.y * cellDiff.y) + (cellDiff.z * cellDiff.z); } // Boolean for whether the ray ended in the same voxel it started in. const bool stoppedInFirstVoxel = cell == this->startCell; // Get the distance from the camera to the hit point. It is a special case // if the ray stopped in the first voxel. double distance; if (stoppedInFirstVoxel) { if ((initialSideDist.x < initialSideDist.y) && (initialSideDist.x < initialSideDist.z)) { distance = initialSideDist.x; axis = Axis::X; } else if (initialSideDist.y < initialSideDist.z) { distance = initialSideDist.y; axis = Axis::Y; } else { distance = initialSideDist.z; axis = Axis::Z; } } else { const size_t axisIndex = static_cast<size_t>(axis); // Assign to distance based on which axis was hit. if (axis == Axis::X) { distance = (static_cast<double>(cell.x) - this->eye.x + ((1.0 - stepReal.x) / 2.0)) / direction.x; } else if (axis == Axis::Y) { distance = ((static_cast<double>(cell.y) * voxelHeight) - this->eye.y + (((1.0 - stepReal.y) / 2.0) * voxelHeight)) / direction.y; } else { distance = (static_cast<double>(cell.z) - this->eye.z + ((1.0 - stepReal.z) / 2.0)) / direction.z; } } // If there was a hit, get the shaded color. if (hitID > 0) { // Intersection point on the voxel. const Double3 hitPoint = this->eye + (direction * distance); // Boolean for whether the hit point is on the back of a voxel face. const bool backFace = stoppedInFirstVoxel; // Texture coordinates. U and V are affected by which side is hit (near, far), // and whether the hit point is on the front or back of the voxel face. // - Note, for edge cases where {u,v}Val == 1.0, the texture coordinate is // out of bounds by one pixel, so instead of 1.0, something like 0.9999999 // should be used instead. std::nextafter(1.0, -INFINITY)? double u, v; if (axis == Axis::X) { const double uVal = hitPoint.z - std::floor(hitPoint.z); u = (nonNegativeDirX ^ backFace) ? uVal : (1.0 - uVal); //v = 1.0 - (hitPoint.y - std::floor(hitPoint.y)); v = 1.0 - (std::fmod(hitPoint.y, voxelHeight) / voxelHeight); } else if (axis == Axis::Y) { const double vVal = hitPoint.x - std::floor(hitPoint.x); u = hitPoint.z - std::floor(hitPoint.z); v = (nonNegativeDirY ^ backFace) ? vVal : (1.0 - vVal); } else { const double uVal = hitPoint.x - std::floor(hitPoint.x); u = (nonNegativeDirZ ^ backFace) ? (1.0 - uVal) : uVal; //v = 1.0 - (hitPoint.y - std::floor(hitPoint.y)); v = 1.0 - (std::fmod(hitPoint.y, voxelHeight) / voxelHeight); } // -- temp -- // Display bad texture coordinates as magenta. If any of these is true, it // means something above is wrong. if ((u < 0.0) || (u >= 1.0) || (v < 0.0) || (v >= 1.0)) { return Double3(1.0, 0.0, 1.0); } // -- end temp -- // Get the voxel data associated with the ID. Subtract 1 because the first // entry is at index 0 but the lowest hitID is 1. const VoxelData &voxelData = voxelGrid.getVoxelData(hitID - 1); // Get the texture depending on which face was hit. const TextureData &texture = (axis == Axis::Y) ? this->textures[voxelData.floorAndCeilingID] : this->textures[voxelData.sideID]; // Calculate position in texture. const int textureX = static_cast<int>(u * texture.width); const int textureY = static_cast<int>(v * texture.height); // Get the texel color at the hit point. // - Later, the alpha component can be used for transparency and ignoring // intersections (in the DDA loop). const Double4 &texel = texture.pixels[textureX + (textureY * texture.width)]; // Convert the texel to a 3-component color. const Double3 color(texel.x, texel.y, texel.z); // Linearly interpolate with some depth. const double depth = std::min(distance, this->viewDistance) / this->viewDistance; return color.lerp(this->fogColor, depth); } else { // No intersection. Return sky color. return this->fogColor; } }*/ Double3 SoftwareRenderer::getFogColor(double daytimePercent) const { // Get the real index (not the integer index), so the color can be interpolated // between two samples. const double realIndex = static_cast<double>(this->skyPalette.size()) * daytimePercent; const size_t index = static_cast<size_t>(realIndex); const size_t nextIndex = (index + 1) % this->skyPalette.size(); const Double3 &color = this->skyPalette[index]; const Double3 &nextColor = this->skyPalette[nextIndex]; const double percent = realIndex - std::floor(realIndex); return color.lerp(nextColor, percent); } Double3 SoftwareRenderer::getSunDirection(double daytimePercent) const { // The sun rises in the east (+Z) and sets in the west (-Z). const double radians = daytimePercent * (2.0 * Constants::Pi); return Double3(0.0, -std::cos(radians), std::sin(radians)).normalized(); } Double3 SoftwareRenderer::getNormal(VoxelData::Facing facing) { // Decide what the normal is, based on the facing. It can only be on the X or Z axis // because floors and ceilings are drawn separately from walls, and their // normals are trivial. if (facing == VoxelData::Facing::PositiveX) { return Double3::UnitX; } else if (facing == VoxelData::Facing::NegativeX) { return -Double3::UnitX; } else if (facing == VoxelData::Facing::PositiveZ) { return Double3::UnitZ; } else { return -Double3::UnitZ; } } double SoftwareRenderer::getProjectedY(const Double3 &point, const Matrix4d &transform, double yShear) { // Just do 3D projection for the Y and W coordinates instead of a whole // matrix * vector4 multiplication to keep from doing some unnecessary work. double projectedY, projectedW; transform.ywMultiply(point, projectedY, projectedW); // Convert the projected Y to normalized coordinates. projectedY /= projectedW; // Calculate the Y position relative to the center row of the screen, and offset it by // the Y-shear. Multiply by 0.5 for the correct aspect ratio. return (0.50 + yShear) - (projectedY * 0.50); } int SoftwareRenderer::getLowerBoundedPixel(double projected, int frameDim) { return std::min(std::max(0, static_cast<int>(std::ceil(projected - 0.50))), frameDim); } int SoftwareRenderer::getUpperBoundedPixel(double projected, int frameDim) { return std::min(std::max(0, static_cast<int>(std::floor(projected + 0.50))), frameDim); } bool SoftwareRenderer::findDiag1Intersection(int voxelX, int voxelZ, const Double2 &nearPoint, const Double2 &farPoint, RayHit &hit) { // Start, middle, and end points of the diagonal line segment relative to the grid. const Double2 diagStart( static_cast<double>(voxelX), static_cast<double>(voxelZ)); const Double2 diagMiddle( static_cast<double>(voxelX) + 0.50, static_cast<double>(voxelZ) + 0.50); const Double2 diagEnd( static_cast<double>(voxelX) + Constants::JustBelowOne, static_cast<double>(voxelZ) + Constants::JustBelowOne); // Normals for the left and right faces of the wall, facing up-left and down-right // respectively (magic number is sqrt(2) / 2). const Double3 leftNormal(0.7071068, 0.0, -0.7071068); const Double3 rightNormal(-0.7071068, 0.0, 0.7071068); // An intersection occurs if the near point and far point are on different sides // of the diagonal line, or if the near point lies on the diagonal line. No need // to normalize the (localPoint - diagMiddle) vector because it's just checking // if it's greater than zero. const Double2 leftNormal2D(leftNormal.x, leftNormal.z); const bool nearOnLeft = leftNormal2D.dot(nearPoint - diagMiddle) >= 0.0; const bool farOnLeft = leftNormal2D.dot(farPoint - diagMiddle) >= 0.0; const bool intersectionOccurred = (nearOnLeft && !farOnLeft) || (!nearOnLeft && farOnLeft); // Only set the output data if an intersection occurred. if (intersectionOccurred) { // Change in X and change in Z of the incoming ray across the voxel. const double dx = farPoint.x - nearPoint.x; const double dz = farPoint.y - nearPoint.y; // The hit coordinate is a 0->1 value representing where the diagonal was hit. const double hitCoordinate = [&nearPoint, &diagStart, dx, dz]() { // Special cases: when the slope is horizontal or vertical. This method treats // the X axis as the vertical axis and the Z axis as the horizontal axis. const double isHorizontal = std::abs(dx) < Constants::Epsilon; const double isVertical = std::abs(dz) < Constants::Epsilon; if (isHorizontal) { // The X axis intercept is the intersection coordinate. return nearPoint.x - diagStart.x; } else if (isVertical) { // The Z axis intercept is the intersection coordinate. return nearPoint.y - diagStart.y; } else { // Slope of the diagonal line (trivial, x = z). const double diagSlope = 1.0; // Vertical axis intercept of the diagonal line. const double diagXIntercept = diagStart.x - diagStart.y; // Slope of the incoming ray. const double raySlope = dx / dz; // Get the vertical axis intercept of the incoming ray. const double rayXIntercept = nearPoint.x - (raySlope * nearPoint.y); // General line intersection calculation. return ((rayXIntercept - diagXIntercept) / (diagSlope - raySlope)) - diagStart.y; } }(); // Set the hit data. hit.u = std::max(std::min(hitCoordinate, Constants::JustBelowOne), 0.0); hit.point = Double2( static_cast<double>(voxelX) + hit.u, static_cast<double>(voxelZ) + hit.u); hit.innerZ = (hit.point - nearPoint).length(); hit.normal = nearOnLeft ? leftNormal : rightNormal; return true; } else { // No intersection. return false; } } bool SoftwareRenderer::findDiag2Intersection(int voxelX, int voxelZ, const Double2 &nearPoint, const Double2 &farPoint, RayHit &hit) { // Mostly a copy of findDiag1Intersection(), though with a couple different values // for the diagonal (end points, slope, etc.). // Start, middle, and end points of the diagonal line segment relative to the grid. const Double2 diagStart( static_cast<double>(voxelX) + Constants::JustBelowOne, static_cast<double>(voxelZ)); const Double2 diagMiddle( static_cast<double>(voxelX) + 0.50, static_cast<double>(voxelZ) + 0.50); const Double2 diagEnd( static_cast<double>(voxelX), static_cast<double>(voxelZ) + Constants::JustBelowOne); // Normals for the left and right faces of the wall, facing up-right and down-left // respectively (magic number is sqrt(2) / 2). const Double3 leftNormal(0.7071068, 0.0, 0.7071068); const Double3 rightNormal(-0.7071068, 0.0, -0.7071068); // An intersection occurs if the near point and far point are on different sides // of the diagonal line, or if the near point lies on the diagonal line. No need // to normalize the (localPoint - diagMiddle) vector because it's just checking // if it's greater than zero. const Double2 leftNormal2D(leftNormal.x, leftNormal.z); const bool nearOnLeft = leftNormal2D.dot(nearPoint - diagMiddle) >= 0.0; const bool farOnLeft = leftNormal2D.dot(farPoint - diagMiddle) >= 0.0; const bool intersectionOccurred = (nearOnLeft && !farOnLeft) || (!nearOnLeft && farOnLeft); // Only set the output data if an intersection occurred. if (intersectionOccurred) { // Change in X and change in Z of the incoming ray across the voxel. const double dx = farPoint.x - nearPoint.x; const double dz = farPoint.y - nearPoint.y; // The hit coordinate is a 0->1 value representing where the diagonal was hit. const double hitCoordinate = [&nearPoint, &diagStart, dx, dz]() { // Special cases: when the slope is horizontal or vertical. This method treats // the X axis as the vertical axis and the Z axis as the horizontal axis. const double isHorizontal = std::abs(dx) < Constants::Epsilon; const double isVertical = std::abs(dz) < Constants::Epsilon; if (isHorizontal) { // The X axis intercept is the compliment of the intersection coordinate. return Constants::JustBelowOne - (nearPoint.x - diagStart.x); } else if (isVertical) { // The Z axis intercept is the compliment of the intersection coordinate. return Constants::JustBelowOne - (nearPoint.y - diagStart.y); } else { // Slope of the diagonal line (trivial, x = -z). const double diagSlope = -1.0; // Vertical axis intercept of the diagonal line. const double diagXIntercept = diagStart.x + diagStart.y; // Slope of the incoming ray. const double raySlope = dx / dz; // Get the vertical axis intercept of the incoming ray. const double rayXIntercept = nearPoint.x - (raySlope * nearPoint.y); // General line intersection calculation. return ((rayXIntercept - diagXIntercept) / (diagSlope - raySlope)) - diagStart.y; } }(); // Set the hit data. hit.u = std::max(std::min(hitCoordinate, Constants::JustBelowOne), 0.0); hit.point = Double2( static_cast<double>(voxelX) + (Constants::JustBelowOne - hit.u), static_cast<double>(voxelZ) + hit.u); hit.innerZ = (hit.point - nearPoint).length(); hit.normal = nearOnLeft ? leftNormal : rightNormal; return true; } else { // No intersection. return false; } } bool SoftwareRenderer::findEdgeIntersection(int voxelX, int voxelZ, VoxelData::Facing facing, const Double2 &nearPoint, const Double2 &farPoint, RayHit &hit) { // To do. return false; } bool SoftwareRenderer::findDoorIntersection(int voxelX, int voxelZ, VoxelData::DoorData::Type doorType, const Double2 &nearPoint, const Double2 &farPoint, RayHit &hit) { // To do. return false; } void SoftwareRenderer::diagProjection(double voxelYReal, double voxelHeight, const Double2 &point, const Matrix4d &transform, double yShear, int frameHeight, double heightReal, double &diagTopScreenY, double &diagBottomScreenY, int &diagStart, int &diagEnd) { // Points in world space for the top and bottom of the diagonal wall slice. const Double3 diagTop(point.x, voxelYReal + voxelHeight, point.y); const Double3 diagBottom(point.x, voxelYReal, point.y); // Projected Y coordinates on-screen. diagTopScreenY = SoftwareRenderer::getProjectedY( diagTop, transform, yShear) * heightReal; diagBottomScreenY = SoftwareRenderer::getProjectedY( diagBottom, transform, yShear) * heightReal; // Y drawing range on-screen. diagStart = std::min(std::max(0, static_cast<int>(std::ceil(diagTopScreenY - 0.50))), frameHeight); diagEnd = std::min(std::max(0, static_cast<int>(std::floor(diagBottomScreenY + 0.50))), frameHeight); } void SoftwareRenderer::drawPixels(int x, int yStart, int yEnd, double projectedYStart, double projectedYEnd, double depth, double u, double vStart, double vEnd, const Double3 &normal, const SoftwareTexture &texture, const ShadingInfo &shadingInfo, OcclusionData &occlusion, const FrameView &frame) { // Horizontal offset in texture. const int textureX = static_cast<int>(u * static_cast<double>(texture.width)); // Linearly interpolated fog. const Double3 &fogColor = shadingInfo.horizonSkyColor; const double fogPercent = std::min(depth / shadingInfo.fogDistance, 1.0); // Contribution from the sun. const double lightNormalDot = std::max(0.0, shadingInfo.sunDirection.dot(normal)); const Double3 sunComponent = (shadingInfo.sunColor * lightNormalDot).clamped( 0.0, 1.0 - shadingInfo.ambient); // Shading on the texture. // - To do: contribution from lights. const Double3 shading( shadingInfo.ambient + sunComponent.x, shadingInfo.ambient + sunComponent.y, shadingInfo.ambient + sunComponent.z); // Clip the Y start and end coordinates as needed, and refresh the occlusion buffer. occlusion.clipRange(&yStart, &yEnd); occlusion.update(yStart, yEnd); // Draw the column to the output buffer. for (int y = yStart; y < yEnd; y++) { const int index = x + (y * frame.width); // Check depth of the pixel before rendering. // - To do: implement occlusion culling and back-to-front transparent rendering so // this depth check isn't needed. if (depth <= (frame.depthBuffer[index] - Constants::Epsilon)) { // Percent stepped from beginning to end on the column. const double yPercent = ((static_cast<double>(y) + 0.50) - projectedYStart) / (projectedYEnd - projectedYStart); // Vertical texture coordinate. const double v = vStart + ((vEnd - vStart) * yPercent); // Y position in texture. const int textureY = static_cast<int>(v * static_cast<double>(texture.height)); // Alpha is ignored in this loop, so transparent texels will appear black. const int textureIndex = textureX + (textureY * texture.width); const Double4 &texel = texture.texels[textureIndex]; const double emission = texture.emissionTexels[textureIndex]; // Texture color with shading. const double shadingMax = 1.0; double colorR = texel.x * std::min(shading.x + emission, shadingMax); double colorG = texel.y * std::min(shading.y + emission, shadingMax); double colorB = texel.z * std::min(shading.z + emission, shadingMax); // Linearly interpolate with fog. colorR += (fogColor.x - colorR) * fogPercent; colorG += (fogColor.y - colorG) * fogPercent; colorB += (fogColor.z - colorB) * fogPercent; // Clamp maximum (don't worry about negative values). const double high = 1.0; colorR = (colorR > high) ? high : colorR; colorG = (colorG > high) ? high : colorG; colorB = (colorB > high) ? high : colorB; // Convert floats to integers. const uint32_t colorRGB = static_cast<uint32_t>( ((static_cast<uint8_t>(colorR * 255.0)) << 16) | ((static_cast<uint8_t>(colorG * 255.0)) << 8) | ((static_cast<uint8_t>(colorB * 255.0)))); frame.colorBuffer[index] = colorRGB; frame.depthBuffer[index] = depth; } } } void SoftwareRenderer::drawPerspectivePixels(int x, int yStart, int yEnd, double projectedYStart, double projectedYEnd, const Double2 &startPoint, const Double2 &endPoint, double depthStart, double depthEnd, const Double3 &normal, const SoftwareTexture &texture, const ShadingInfo &shadingInfo, OcclusionData &occlusion, const FrameView &frame) { // Fog color to interpolate with. const Double3 &fogColor = shadingInfo.horizonSkyColor; // Contribution from the sun. const double lightNormalDot = std::max(0.0, shadingInfo.sunDirection.dot(normal)); const Double3 sunComponent = (shadingInfo.sunColor * lightNormalDot).clamped( 0.0, 1.0 - shadingInfo.ambient); // Shading on the texture. // - To do: contribution from lights. const Double3 shading( shadingInfo.ambient + sunComponent.x, shadingInfo.ambient + sunComponent.y, shadingInfo.ambient + sunComponent.z); // Values for perspective-correct interpolation. const double depthStartRecip = 1.0 / depthStart; const double depthEndRecip = 1.0 / depthEnd; const Double2 startPointDiv = startPoint * depthStartRecip; const Double2 endPointDiv = endPoint * depthEndRecip; const Double2 pointDivDiff = endPointDiv - startPointDiv; // Clip the Y start and end coordinates as needed, and refresh the occlusion buffer. occlusion.clipRange(&yStart, &yEnd); occlusion.update(yStart, yEnd); // Draw the column to the output buffer. for (int y = yStart; y < yEnd; y++) { const int index = x + (y * frame.width); // Percent stepped from beginning to end on the column. const double yPercent = ((static_cast<double>(y) + 0.50) - projectedYStart) / (projectedYEnd - projectedYStart); // Interpolate between the near and far depth. const double depth = 1.0 / (depthStartRecip + ((depthEndRecip - depthStartRecip) * yPercent)); // Check depth of the pixel before rendering. // - To do: implement occlusion culling and back-to-front transparent rendering so // this depth check isn't needed. if (depth <= frame.depthBuffer[index]) { // Linearly interpolated fog. const double fogPercent = std::min(depth / shadingInfo.fogDistance, 1.0); // Interpolate between start and end points. const double currentPointX = (startPointDiv.x + (pointDivDiff.x * yPercent)) * depth; const double currentPointY = (startPointDiv.y + (pointDivDiff.y * yPercent)) * depth; // Texture coordinates. const double u = std::max(std::min(Constants::JustBelowOne, Constants::JustBelowOne - (currentPointX - std::floor(currentPointX))), 0.0); const double v = std::max(std::min(Constants::JustBelowOne, Constants::JustBelowOne - (currentPointY - std::floor(currentPointY))), 0.0); // Offsets in texture. const int textureX = static_cast<int>(u * static_cast<double>(texture.width)); const int textureY = static_cast<int>(v * static_cast<double>(texture.height)); // Alpha is ignored in this loop, so transparent texels will appear black. const int textureIndex = textureX + (textureY * texture.width); const Double4 &texel = texture.texels[textureIndex]; const double emission = texture.emissionTexels[textureIndex]; // Texture color with shading. const double shadingMax = 1.0; double colorR = texel.x * std::min(shading.x + emission, shadingMax); double colorG = texel.y * std::min(shading.y + emission, shadingMax); double colorB = texel.z * std::min(shading.z + emission, shadingMax); // Linearly interpolate with fog. colorR += (fogColor.x - colorR) * fogPercent; colorG += (fogColor.y - colorG) * fogPercent; colorB += (fogColor.z - colorB) * fogPercent; // Clamp maximum (don't worry about negative values). const double high = 1.0; colorR = (colorR > high) ? high : colorR; colorG = (colorG > high) ? high : colorG; colorB = (colorB > high) ? high : colorB; // Convert floats to integers. const uint32_t colorRGB = static_cast<uint32_t>( ((static_cast<uint8_t>(colorR * 255.0)) << 16) | ((static_cast<uint8_t>(colorG * 255.0)) << 8) | ((static_cast<uint8_t>(colorB * 255.0)))); frame.colorBuffer[index] = colorRGB; frame.depthBuffer[index] = depth; } } } void SoftwareRenderer::drawTransparentPixels(int x, int yStart, int yEnd, double projectedYStart, double projectedYEnd, double depth, double u, double vStart, double vEnd, const Double3 &normal, const SoftwareTexture &texture, const ShadingInfo &shadingInfo, const OcclusionData &occlusion, const FrameView &frame) { // Horizontal offset in texture. const int textureX = static_cast<int>(u * static_cast<double>(texture.width)); // Linearly interpolated fog. const Double3 &fogColor = shadingInfo.horizonSkyColor; const double fogPercent = std::min(depth / shadingInfo.fogDistance, 1.0); // Contribution from the sun. const double lightNormalDot = std::max(0.0, shadingInfo.sunDirection.dot(normal)); const Double3 sunComponent = (shadingInfo.sunColor * lightNormalDot).clamped( 0.0, 1.0 - shadingInfo.ambient); // Shading on the texture. // - To do: contribution from lights. const Double3 shading( shadingInfo.ambient + sunComponent.x, shadingInfo.ambient + sunComponent.y, shadingInfo.ambient + sunComponent.z); // Clip the Y start and end coordinates as needed, but do not refresh the occlusion buffer, // because transparent ranges do not occlude as simply as opaque ranges. occlusion.clipRange(&yStart, &yEnd); // Draw the column to the output buffer. for (int y = yStart; y < yEnd; y++) { const int index = x + (y * frame.width); // Check depth of the pixel before rendering. if (depth <= (frame.depthBuffer[index] - Constants::Epsilon)) { // Percent stepped from beginning to end on the column. const double yPercent = ((static_cast<double>(y) + 0.50) - projectedYStart) / (projectedYEnd - projectedYStart); // Vertical texture coordinate. const double v = vStart + ((vEnd - vStart) * yPercent); // Y position in texture. const int textureY = static_cast<int>(v * static_cast<double>(texture.height)); // Alpha is checked in this loop, and transparent texels are not drawn. const int textureIndex = textureX + (textureY * texture.width); const Double4 &texel = texture.texels[textureIndex]; const double emission = texture.emissionTexels[textureIndex]; if (texel.w > 0.0) { // Texture color with shading. const double shadingMax = 1.0; double colorR = texel.x * std::min(shading.x + emission, shadingMax); double colorG = texel.y * std::min(shading.y + emission, shadingMax); double colorB = texel.z * std::min(shading.z + emission, shadingMax); // Linearly interpolate with fog. colorR += (fogColor.x - colorR) * fogPercent; colorG += (fogColor.y - colorG) * fogPercent; colorB += (fogColor.z - colorB) * fogPercent; // Clamp maximum (don't worry about negative values). const double high = 1.0; colorR = (colorR > high) ? high : colorR; colorG = (colorG > high) ? high : colorG; colorB = (colorB > high) ? high : colorB; // Convert floats to integers. const uint32_t colorRGB = static_cast<uint32_t>( ((static_cast<uint8_t>(colorR * 255.0)) << 16) | ((static_cast<uint8_t>(colorG * 255.0)) << 8) | ((static_cast<uint8_t>(colorB * 255.0)))); frame.colorBuffer[index] = colorRGB; frame.depthBuffer[index] = depth; } } } } void SoftwareRenderer::drawInitialVoxelColumn(int x, int voxelX, int voxelZ, double playerY, VoxelData::Facing facing, const Double2 &nearPoint, const Double2 &farPoint, double nearZ, double farZ, const Matrix4d &transform, double yShear, const ShadingInfo &shadingInfo, double ceilingHeight, const VoxelGrid &voxelGrid, const std::vector<SoftwareTexture> &textures, OcclusionData &occlusion, const FrameView &frame) { // This method handles some special cases such as drawing the back-faces of wall sides. // When clamping Y values for drawing ranges, subtract 0.5 from starts and add 0.5 to // ends before converting to integers because the drawing methods sample at the center // of pixels. The clamping function depends on which side of the range is being clamped; // either way, the drawing range should be contained within the projected range at the // sub-pixel level. This ensures that the vertical texture coordinate is always within 0->1. const double heightReal = static_cast<double>(frame.height); // Y position at the base of the player's voxel. const double playerYFloor = std::floor(playerY); // Voxel Y of the player. const int playerVoxelY = static_cast<int>(playerYFloor); const double wallU = [&farPoint, facing]() { const double uVal = [&farPoint, facing]() { if (facing == VoxelData::Facing::PositiveX) { return farPoint.y - std::floor(farPoint.y); } else if (facing == VoxelData::Facing::NegativeX) { return Constants::JustBelowOne - (farPoint.y - std::floor(farPoint.y)); } else if (facing == VoxelData::Facing::PositiveZ) { return Constants::JustBelowOne - (farPoint.x - std::floor(farPoint.x)); } else { return farPoint.x - std::floor(farPoint.x); } }(); return std::max(std::min(uVal, Constants::JustBelowOne), 0.0); }(); // Normal of the wall for the incoming ray, potentially shared between multiple voxels in // this voxel column. const Double3 wallNormal = -SoftwareRenderer::getNormal(facing); auto drawInitialVoxel = [x, voxelX, voxelZ, playerY, playerYFloor, &wallNormal, &nearPoint, &farPoint, nearZ, farZ, wallU, &transform, yShear, &shadingInfo, ceilingHeight, &voxelGrid, &textures, &occlusion, &frame, heightReal]() { const int voxelY = static_cast<int>(playerYFloor); const char voxelID = voxelGrid.getVoxels()[voxelX + (voxelY * voxelGrid.getWidth()) + (voxelZ * voxelGrid.getWidth() * voxelGrid.getHeight())]; const VoxelData &voxelData = voxelGrid.getVoxelData(voxelID); // Height of the voxel depends on whether it's the main floor. const double voxelHeight = (voxelY == 1) ? ceilingHeight : 1.0; if (voxelData.dataType == VoxelDataType::Wall) { // Draw inner ceiling, wall, and floor. const VoxelData::WallData &wallData = voxelData.wall; const Double3 farCeilingPoint( farPoint.x, playerYFloor + voxelHeight, farPoint.y); const Double3 nearCeilingPoint( nearPoint.x, farCeilingPoint.y, nearPoint.y); const Double3 farFloorPoint( farPoint.x, playerYFloor, farPoint.y); const Double3 nearFloorPoint( nearPoint.x, farFloorPoint.y, nearPoint.y); const double farCeilingScreenY = SoftwareRenderer::getProjectedY( farCeilingPoint, transform, yShear) * heightReal; const double nearCeilingScreenY = SoftwareRenderer::getProjectedY( nearCeilingPoint, transform, yShear) * heightReal; const double farFloorScreenY = SoftwareRenderer::getProjectedY( farFloorPoint, transform, yShear) * heightReal; const double nearFloorScreenY = SoftwareRenderer::getProjectedY( nearFloorPoint, transform, yShear) * heightReal; const int ceilingStart = SoftwareRenderer::getLowerBoundedPixel( nearCeilingScreenY, frame.height); const int ceilingEnd = SoftwareRenderer::getUpperBoundedPixel( farCeilingScreenY, frame.height); const int wallStart = ceilingEnd; const int wallEnd = SoftwareRenderer::getUpperBoundedPixel( farFloorScreenY, frame.height); const int floorStart = wallEnd; const int floorEnd = SoftwareRenderer::getUpperBoundedPixel( nearFloorScreenY, frame.height); // Ceiling. SoftwareRenderer::drawPerspectivePixels(x, ceilingStart, ceilingEnd, nearCeilingScreenY, farCeilingScreenY, nearPoint, farPoint, nearZ, farZ, -Double3::UnitY, textures.at(wallData.ceilingID - 1), shadingInfo, occlusion, frame); // Side. SoftwareRenderer::drawPixels(x, wallStart, wallEnd, farCeilingScreenY, farFloorScreenY, farZ, wallU, 0.0, Constants::JustBelowOne, wallNormal, textures.at(wallData.sideID - 1), shadingInfo, occlusion, frame); // Floor. SoftwareRenderer::drawPerspectivePixels(x, floorStart, floorEnd, farFloorScreenY, nearFloorScreenY, farPoint, nearPoint, farZ, nearZ, Double3::UnitY, textures.at(wallData.floorID - 1), shadingInfo, occlusion, frame); } else if (voxelData.dataType == VoxelDataType::Floor) { // Do nothing. Floors can only be seen from above. } else if (voxelData.dataType == VoxelDataType::Ceiling) { // Do nothing. Ceilings can only be seen from below. } else if (voxelData.dataType == VoxelDataType::Raised) { const VoxelData::RaisedData &raisedData = voxelData.raised; const Double3 nearCeilingPoint( nearPoint.x, playerYFloor + ((raisedData.yOffset + raisedData.ySize) * voxelHeight), nearPoint.y); const Double3 nearFloorPoint( nearPoint.x, playerYFloor + (raisedData.yOffset * voxelHeight), nearPoint.y); // Draw order depends on the player's Y position relative to the platform. if (playerY > nearCeilingPoint.y) { // Above platform. const Double3 farCeilingPoint( farPoint.x, nearCeilingPoint.y, farPoint.y); const double farCeilingScreenY = SoftwareRenderer::getProjectedY( farCeilingPoint, transform, yShear) * heightReal; const double nearCeilingScreenY = SoftwareRenderer::getProjectedY( nearCeilingPoint, transform, yShear) * heightReal; const int ceilingStart = SoftwareRenderer::getLowerBoundedPixel( farCeilingScreenY, frame.height); const int ceilingEnd = SoftwareRenderer::getUpperBoundedPixel( nearCeilingScreenY, frame.height); // Ceiling. SoftwareRenderer::drawPerspectivePixels(x, ceilingStart, ceilingEnd, farCeilingScreenY, nearCeilingScreenY, farPoint, nearPoint, farZ, nearZ, Double3::UnitY, textures.at(raisedData.ceilingID - 1), shadingInfo, occlusion, frame); } else if (playerY < nearFloorPoint.y) { // Below platform. const Double3 farFloorPoint( farPoint.x, nearFloorPoint.y, farPoint.y); const double nearFloorScreenY = SoftwareRenderer::getProjectedY( nearFloorPoint, transform, yShear) * heightReal; const double farFloorScreenY = SoftwareRenderer::getProjectedY( farFloorPoint, transform, yShear) * heightReal; const int floorStart = SoftwareRenderer::getLowerBoundedPixel( nearFloorScreenY, frame.height); const int floorEnd = SoftwareRenderer::getUpperBoundedPixel( farFloorScreenY, frame.height); // Floor. SoftwareRenderer::drawPerspectivePixels(x, floorStart, floorEnd, nearFloorScreenY, farFloorScreenY, nearPoint, farPoint, nearZ, farZ, -Double3::UnitY, textures.at(raisedData.floorID - 1), shadingInfo, occlusion, frame); } else { // Between top and bottom. const Double3 farCeilingPoint( farPoint.x, nearCeilingPoint.y, farPoint.y); const Double3 farFloorPoint( farPoint.x, nearFloorPoint.y, farPoint.y); const double farCeilingScreenY = SoftwareRenderer::getProjectedY( farCeilingPoint, transform, yShear) * heightReal; const double nearCeilingScreenY = SoftwareRenderer::getProjectedY( nearCeilingPoint, transform, yShear) * heightReal; const double farFloorScreenY = SoftwareRenderer::getProjectedY( farFloorPoint, transform, yShear) * heightReal; const double nearFloorScreenY = SoftwareRenderer::getProjectedY( nearFloorPoint, transform, yShear) * heightReal; const int ceilingStart = SoftwareRenderer::getLowerBoundedPixel( nearCeilingScreenY, frame.height); const int ceilingEnd = SoftwareRenderer::getUpperBoundedPixel( farCeilingScreenY, frame.height); const int wallStart = ceilingEnd; const int wallEnd = SoftwareRenderer::getUpperBoundedPixel( farFloorScreenY, frame.height); const int floorStart = wallEnd; const int floorEnd = SoftwareRenderer::getUpperBoundedPixel( nearFloorScreenY, frame.height); // Ceiling. SoftwareRenderer::drawPerspectivePixels(x, ceilingStart, ceilingEnd, nearCeilingScreenY, farCeilingScreenY, nearPoint, farPoint, nearZ, farZ, -Double3::UnitY, textures.at(raisedData.ceilingID - 1), shadingInfo, occlusion, frame); // Side. SoftwareRenderer::drawTransparentPixels(x, wallStart, wallEnd, farCeilingScreenY, farFloorScreenY, farZ, wallU, raisedData.vTop, raisedData.vBottom, wallNormal, textures.at(raisedData.sideID - 1), shadingInfo, occlusion, frame); // Floor. SoftwareRenderer::drawPerspectivePixels(x, floorStart, floorEnd, farFloorScreenY, nearFloorScreenY, farPoint, nearPoint, farZ, nearZ, Double3::UnitY, textures.at(raisedData.floorID - 1), shadingInfo, occlusion, frame); } } else if (voxelData.dataType == VoxelDataType::Diagonal) { const VoxelData::DiagonalData &diagData = voxelData.diagonal; // Find intersection. RayHit hit; const bool success = diagData.type1 ? SoftwareRenderer::findDiag1Intersection(voxelX, voxelZ, nearPoint, farPoint, hit) : SoftwareRenderer::findDiag2Intersection(voxelX, voxelZ, nearPoint, farPoint, hit); if (success) { double diagTopScreenY, diagBottomScreenY; int diagStart, diagEnd; SoftwareRenderer::diagProjection(playerYFloor, voxelHeight, hit.point, transform, yShear, frame.height, heightReal, diagTopScreenY, diagBottomScreenY, diagStart, diagEnd); SoftwareRenderer::drawPixels(x, diagStart, diagEnd, diagTopScreenY, diagBottomScreenY, nearZ + hit.innerZ, hit.u, 0.0, Constants::JustBelowOne, hit.normal, textures.at(diagData.id - 1), shadingInfo, occlusion, frame); } } else if (voxelData.dataType == VoxelDataType::TransparentWall) { // Do nothing. Transparent walls have no back-faces. } else if (voxelData.dataType == VoxelDataType::Edge) { const VoxelData::EdgeData &edgeData = voxelData.edge; // Find intersection. RayHit hit; const bool success = SoftwareRenderer::findEdgeIntersection( voxelX, voxelZ, edgeData.facing, nearPoint, farPoint, hit); if (success) { const Double3 edgeTopPoint( hit.point.x, playerYFloor + voxelHeight, hit.point.y); const Double3 edgeBottomPoint( hit.point.x, playerYFloor, hit.point.y); const double edgeTopScreenY = SoftwareRenderer::getProjectedY( edgeTopPoint, transform, yShear) * heightReal; const double edgeBottomScreenY = SoftwareRenderer::getProjectedY( edgeBottomPoint, transform, yShear) * heightReal; const int edgeStart = SoftwareRenderer::getLowerBoundedPixel( edgeTopScreenY, frame.height); const int edgeEnd = SoftwareRenderer::getUpperBoundedPixel( edgeBottomScreenY, frame.height); SoftwareRenderer::drawTransparentPixels(x, edgeStart, edgeEnd, edgeTopScreenY, edgeBottomScreenY, nearZ + hit.innerZ, hit.u, 0.0, Constants::JustBelowOne, hit.normal, textures.at(edgeData.id - 1), shadingInfo, occlusion, frame); } } else if (voxelData.dataType == VoxelDataType::Chasm) { // Render front and back-faces. const VoxelData::ChasmData &chasmData = voxelData.chasm; // To do. } else if (voxelData.dataType == VoxelDataType::Door) { // To do: find intersection via SoftwareRenderer::findDoorIntersection(). // Render nothing for now. } }; auto drawInitialVoxelBelow = [x, voxelX, voxelZ, playerY, &wallNormal, &nearPoint, &farPoint, nearZ, farZ, wallU, &transform, yShear, &shadingInfo, ceilingHeight, &voxelGrid, &textures, &occlusion, &frame, heightReal](int voxelY) { const char voxelID = voxelGrid.getVoxels()[voxelX + (voxelY * voxelGrid.getWidth()) + (voxelZ * voxelGrid.getWidth() * voxelGrid.getHeight())]; const VoxelData &voxelData = voxelGrid.getVoxelData(voxelID); const double voxelYReal = static_cast<double>(voxelY); // Height of the voxel depends on whether it's the main floor. const double voxelHeight = (voxelY == 1) ? ceilingHeight : 1.0; if (voxelData.dataType == VoxelDataType::Wall) { const VoxelData::WallData &wallData = voxelData.wall; const Double3 farCeilingPoint( farPoint.x, voxelYReal + voxelHeight, farPoint.y); const Double3 nearCeilingPoint( nearPoint.x, farCeilingPoint.y, nearPoint.y); const double farCeilingScreenY = SoftwareRenderer::getProjectedY( farCeilingPoint, transform, yShear) * heightReal; const double nearCeilingScreenY = SoftwareRenderer::getProjectedY( nearCeilingPoint, transform, yShear) * heightReal; const int ceilingStart = SoftwareRenderer::getLowerBoundedPixel( farCeilingScreenY, frame.height); const int ceilingEnd = SoftwareRenderer::getUpperBoundedPixel( nearCeilingScreenY, frame.height); // Ceiling. SoftwareRenderer::drawPerspectivePixels(x, ceilingStart, ceilingEnd, farCeilingScreenY, nearCeilingScreenY, farPoint, nearPoint, farZ, nearZ, Double3::UnitY, textures.at(wallData.ceilingID - 1), shadingInfo, occlusion, frame); } else if (voxelData.dataType == VoxelDataType::Floor) { // Draw top of floor voxel. const VoxelData::FloorData &floorData = voxelData.floor; const Double3 farCeilingPoint( farPoint.x, voxelYReal + voxelHeight, farPoint.y); const Double3 nearCeilingPoint( nearPoint.x, farCeilingPoint.y, nearPoint.y); const double farCeilingScreenY = SoftwareRenderer::getProjectedY( farCeilingPoint, transform, yShear) * heightReal; const double nearCeilingScreenY = SoftwareRenderer::getProjectedY( nearCeilingPoint, transform, yShear) * heightReal; const int ceilingStart = SoftwareRenderer::getLowerBoundedPixel( farCeilingScreenY, frame.height); const int ceilingEnd = SoftwareRenderer::getUpperBoundedPixel( nearCeilingScreenY, frame.height); // Ceiling. SoftwareRenderer::drawPerspectivePixels(x, ceilingStart, ceilingEnd, farCeilingScreenY, nearCeilingScreenY, farPoint, nearPoint, farZ, nearZ, Double3::UnitY, textures.at(floorData.id), shadingInfo, occlusion, frame); } else if (voxelData.dataType == VoxelDataType::Ceiling) { // Do nothing. Ceilings can only be seen from below. } else if (voxelData.dataType == VoxelDataType::Raised) { const VoxelData::RaisedData &raisedData = voxelData.raised; const Double3 nearCeilingPoint( nearPoint.x, voxelYReal + ((raisedData.yOffset + raisedData.ySize) * voxelHeight), nearPoint.y); const Double3 nearFloorPoint( nearPoint.x, voxelYReal + (raisedData.yOffset * voxelHeight), nearPoint.y); // Draw order depends on the player's Y position relative to the platform. if (playerY > nearCeilingPoint.y) { // Above platform. const Double3 farCeilingPoint( farPoint.x, nearCeilingPoint.y, farPoint.y); const double farCeilingScreenY = SoftwareRenderer::getProjectedY( farCeilingPoint, transform, yShear) * heightReal; const double nearCeilingScreenY = SoftwareRenderer::getProjectedY( nearCeilingPoint, transform, yShear) * heightReal; const int ceilingStart = SoftwareRenderer::getLowerBoundedPixel( farCeilingScreenY, frame.height); const int ceilingEnd = SoftwareRenderer::getUpperBoundedPixel( nearCeilingScreenY, frame.height); // Ceiling. SoftwareRenderer::drawPerspectivePixels(x, ceilingStart, ceilingEnd, farCeilingScreenY, nearCeilingScreenY, farPoint, nearPoint, farZ, nearZ, Double3::UnitY, textures.at(raisedData.ceilingID - 1), shadingInfo, occlusion, frame); } else if (playerY < nearFloorPoint.y) { // Below platform. const Double3 farFloorPoint( farPoint.x, nearFloorPoint.y, farPoint.y); const double nearFloorScreenY = SoftwareRenderer::getProjectedY( nearFloorPoint, transform, yShear) * heightReal; const double farFloorScreenY = SoftwareRenderer::getProjectedY( farFloorPoint, transform, yShear) * heightReal; const int floorStart = SoftwareRenderer::getLowerBoundedPixel( nearFloorScreenY, frame.height); const int floorEnd = SoftwareRenderer::getUpperBoundedPixel( farFloorScreenY, frame.height); // Floor. SoftwareRenderer::drawPerspectivePixels(x, floorStart, floorEnd, nearFloorScreenY, farFloorScreenY, nearPoint, farPoint, nearZ, farZ, -Double3::UnitY, textures.at(raisedData.floorID - 1), shadingInfo, occlusion, frame); } else { // Between top and bottom. const Double3 farCeilingPoint( farPoint.x, nearCeilingPoint.y, farPoint.y); const Double3 farFloorPoint( farPoint.x, nearFloorPoint.y, farPoint.y); const double farCeilingScreenY = SoftwareRenderer::getProjectedY( farCeilingPoint, transform, yShear) * heightReal; const double nearCeilingScreenY = SoftwareRenderer::getProjectedY( nearCeilingPoint, transform, yShear) * heightReal; const double farFloorScreenY = SoftwareRenderer::getProjectedY( farFloorPoint, transform, yShear) * heightReal; const double nearFloorScreenY = SoftwareRenderer::getProjectedY( nearFloorPoint, transform, yShear) * heightReal; const int ceilingStart = SoftwareRenderer::getLowerBoundedPixel( nearCeilingScreenY, frame.height); const int ceilingEnd = SoftwareRenderer::getUpperBoundedPixel( farCeilingScreenY, frame.height); const int wallStart = ceilingEnd; const int wallEnd = SoftwareRenderer::getUpperBoundedPixel( farFloorScreenY, frame.height); const int floorStart = wallEnd; const int floorEnd = SoftwareRenderer::getUpperBoundedPixel( nearFloorScreenY, frame.height); // Ceiling. SoftwareRenderer::drawPerspectivePixels(x, ceilingStart, ceilingEnd, nearCeilingScreenY, farCeilingScreenY, nearPoint, farPoint, nearZ, farZ, -Double3::UnitY, textures.at(raisedData.ceilingID - 1), shadingInfo, occlusion, frame); // Side. SoftwareRenderer::drawTransparentPixels(x, wallStart, wallEnd, farCeilingScreenY, farFloorScreenY, farZ, wallU, raisedData.vTop, raisedData.vBottom, wallNormal, textures.at(raisedData.sideID - 1), shadingInfo, occlusion, frame); // Floor. SoftwareRenderer::drawPerspectivePixels(x, floorStart, floorEnd, farFloorScreenY, nearFloorScreenY, farPoint, nearPoint, farZ, nearZ, Double3::UnitY, textures.at(raisedData.floorID - 1), shadingInfo, occlusion, frame); } } else if (voxelData.dataType == VoxelDataType::Diagonal) { const VoxelData::DiagonalData &diagData = voxelData.diagonal; // Find intersection. RayHit hit; const bool success = diagData.type1 ? SoftwareRenderer::findDiag1Intersection(voxelX, voxelZ, nearPoint, farPoint, hit) : SoftwareRenderer::findDiag2Intersection(voxelX, voxelZ, nearPoint, farPoint, hit); if (success) { double diagTopScreenY, diagBottomScreenY; int diagStart, diagEnd; SoftwareRenderer::diagProjection(voxelYReal, voxelHeight, hit.point, transform, yShear, frame.height, heightReal, diagTopScreenY, diagBottomScreenY, diagStart, diagEnd); SoftwareRenderer::drawPixels(x, diagStart, diagEnd, diagTopScreenY, diagBottomScreenY, nearZ + hit.innerZ, hit.u, 0.0, Constants::JustBelowOne, hit.normal, textures.at(diagData.id - 1), shadingInfo, occlusion, frame); } } else if (voxelData.dataType == VoxelDataType::TransparentWall) { // Do nothing. Transparent walls have no back-faces. } else if (voxelData.dataType == VoxelDataType::Edge) { const VoxelData::EdgeData &edgeData = voxelData.edge; // Find intersection. RayHit hit; const bool success = SoftwareRenderer::findEdgeIntersection( voxelX, voxelZ, edgeData.facing, nearPoint, farPoint, hit); if (success) { const Double3 edgeTopPoint( hit.point.x, voxelYReal + voxelHeight, hit.point.y); const Double3 edgeBottomPoint( hit.point.x, voxelYReal, hit.point.y); const double edgeTopScreenY = SoftwareRenderer::getProjectedY( edgeTopPoint, transform, yShear) * heightReal; const double edgeBottomScreenY = SoftwareRenderer::getProjectedY( edgeBottomPoint, transform, yShear) * heightReal; const int edgeStart = SoftwareRenderer::getLowerBoundedPixel( edgeTopScreenY, frame.height); const int edgeEnd = SoftwareRenderer::getUpperBoundedPixel( edgeBottomScreenY, frame.height); SoftwareRenderer::drawTransparentPixels(x, edgeStart, edgeEnd, edgeTopScreenY, edgeBottomScreenY, nearZ + hit.innerZ, hit.u, 0.0, Constants::JustBelowOne, hit.normal, textures.at(edgeData.id - 1), shadingInfo, occlusion, frame); } } else if (voxelData.dataType == VoxelDataType::Chasm) { // Render front and back-faces. const VoxelData::ChasmData &chasmData = voxelData.chasm; // To do. } else if (voxelData.dataType == VoxelDataType::Door) { // To do: find intersection via SoftwareRenderer::findDoorIntersection(). // Render nothing for now. } }; auto drawInitialVoxelAbove = [x, voxelX, voxelZ, playerY, &wallNormal, &nearPoint, &farPoint, nearZ, farZ, wallU, &transform, yShear, &shadingInfo, ceilingHeight, &voxelGrid, &textures, &occlusion, &frame, heightReal](int voxelY) { const char voxelID = voxelGrid.getVoxels()[voxelX + (voxelY * voxelGrid.getWidth()) + (voxelZ * voxelGrid.getWidth() * voxelGrid.getHeight())]; const VoxelData &voxelData = voxelGrid.getVoxelData(voxelID); const double voxelYReal = static_cast<double>(voxelY); // Height of the voxel depends on whether it's the main floor. const double voxelHeight = (voxelY == 1) ? ceilingHeight : 1.0; if (voxelData.dataType == VoxelDataType::Wall) { const VoxelData::WallData &wallData = voxelData.wall; const Double3 nearFloorPoint( nearPoint.x, voxelYReal, nearPoint.y); const Double3 farFloorPoint( farPoint.x, nearFloorPoint.y, farPoint.y); const double nearFloorScreenY = SoftwareRenderer::getProjectedY( nearFloorPoint, transform, yShear) * heightReal; const double farFloorScreenY = SoftwareRenderer::getProjectedY( farFloorPoint, transform, yShear) * heightReal; const int floorStart = SoftwareRenderer::getLowerBoundedPixel( nearFloorScreenY, frame.height); const int floorEnd = SoftwareRenderer::getUpperBoundedPixel( farFloorScreenY, frame.height); // Floor. SoftwareRenderer::drawPerspectivePixels(x, floorStart, floorEnd, nearFloorScreenY, farFloorScreenY, nearPoint, farPoint, nearZ, farZ, -Double3::UnitY, textures.at(wallData.floorID - 1), shadingInfo, occlusion, frame); } else if (voxelData.dataType == VoxelDataType::Floor) { // Do nothing. Floors can only be seen from above. } else if (voxelData.dataType == VoxelDataType::Ceiling) { // Draw bottom of ceiling voxel. const VoxelData::CeilingData &ceilingData = voxelData.ceiling; const Double3 nearFloorPoint( nearPoint.x, 1.0 + ceilingHeight, nearPoint.y); const Double3 farFloorPoint( farPoint.x, nearFloorPoint.y, farPoint.y); const double nearFloorScreenY = SoftwareRenderer::getProjectedY( nearFloorPoint, transform, yShear) * heightReal; const double farFloorScreenY = SoftwareRenderer::getProjectedY( farFloorPoint, transform, yShear) * heightReal; const int floorStart = SoftwareRenderer::getLowerBoundedPixel( nearFloorScreenY, frame.height); const int floorEnd = SoftwareRenderer::getUpperBoundedPixel( farFloorScreenY, frame.height); SoftwareRenderer::drawPerspectivePixels(x, floorStart, floorEnd, nearFloorScreenY, farFloorScreenY, nearPoint, farPoint, nearZ, farZ, -Double3::UnitY, textures.at(ceilingData.id), shadingInfo, occlusion, frame); } else if (voxelData.dataType == VoxelDataType::Raised) { const VoxelData::RaisedData &raisedData = voxelData.raised; const Double3 nearCeilingPoint( nearPoint.x, voxelYReal + ((raisedData.yOffset + raisedData.ySize) * voxelHeight), nearPoint.y); const Double3 nearFloorPoint( nearPoint.x, voxelYReal + (raisedData.yOffset * voxelHeight), nearPoint.y); // Draw order depends on the player's Y position relative to the platform. if (playerY > nearCeilingPoint.y) { // Above platform. const Double3 farCeilingPoint( farPoint.x, nearCeilingPoint.y, farPoint.y); const double farCeilingScreenY = SoftwareRenderer::getProjectedY( farCeilingPoint, transform, yShear) * heightReal; const double nearCeilingScreenY = SoftwareRenderer::getProjectedY( nearCeilingPoint, transform, yShear) * heightReal; const int ceilingStart = SoftwareRenderer::getLowerBoundedPixel( farCeilingScreenY, frame.height); const int ceilingEnd = SoftwareRenderer::getUpperBoundedPixel( nearCeilingScreenY, frame.height); // Ceiling. SoftwareRenderer::drawPerspectivePixels(x, ceilingStart, ceilingEnd, farCeilingScreenY, nearCeilingScreenY, farPoint, nearPoint, farZ, nearZ, Double3::UnitY, textures.at(raisedData.ceilingID - 1), shadingInfo, occlusion, frame); } else if (playerY < nearFloorPoint.y) { // Below platform. const Double3 farFloorPoint( farPoint.x, nearFloorPoint.y, farPoint.y); const double nearFloorScreenY = SoftwareRenderer::getProjectedY( nearFloorPoint, transform, yShear) * heightReal; const double farFloorScreenY = SoftwareRenderer::getProjectedY( farFloorPoint, transform, yShear) * heightReal; const int floorStart = SoftwareRenderer::getLowerBoundedPixel( nearFloorScreenY, frame.height); const int floorEnd = SoftwareRenderer::getUpperBoundedPixel( farFloorScreenY, frame.height); // Floor. SoftwareRenderer::drawPerspectivePixels(x, floorStart, floorEnd, nearFloorScreenY, farFloorScreenY, nearPoint, farPoint, nearZ, farZ, -Double3::UnitY, textures.at(raisedData.floorID - 1), shadingInfo, occlusion, frame); } else { // Between top and bottom. const Double3 farCeilingPoint( farPoint.x, nearCeilingPoint.y, farPoint.y); const Double3 farFloorPoint( farPoint.x, nearFloorPoint.y, farPoint.y); const double farCeilingScreenY = SoftwareRenderer::getProjectedY( farCeilingPoint, transform, yShear) * heightReal; const double nearCeilingScreenY = SoftwareRenderer::getProjectedY( nearCeilingPoint, transform, yShear) * heightReal; const double farFloorScreenY = SoftwareRenderer::getProjectedY( farFloorPoint, transform, yShear) * heightReal; const double nearFloorScreenY = SoftwareRenderer::getProjectedY( nearFloorPoint, transform, yShear) * heightReal; const int ceilingStart = SoftwareRenderer::getLowerBoundedPixel( nearCeilingScreenY, frame.height); const int ceilingEnd = SoftwareRenderer::getUpperBoundedPixel( farCeilingScreenY, frame.height); const int wallStart = ceilingEnd; const int wallEnd = SoftwareRenderer::getUpperBoundedPixel( farFloorScreenY, frame.height); const int floorStart = wallEnd; const int floorEnd = SoftwareRenderer::getUpperBoundedPixel( nearFloorScreenY, frame.height); // Ceiling. SoftwareRenderer::drawPerspectivePixels(x, ceilingStart, ceilingEnd, nearCeilingScreenY, farCeilingScreenY, nearPoint, farPoint, nearZ, farZ, -Double3::UnitY, textures.at(raisedData.ceilingID - 1), shadingInfo, occlusion, frame); // Side. SoftwareRenderer::drawTransparentPixels(x, wallStart, wallEnd, farCeilingScreenY, farFloorScreenY, farZ, wallU, raisedData.vTop, raisedData.vBottom, wallNormal, textures.at(raisedData.sideID - 1), shadingInfo, occlusion, frame); // Floor. SoftwareRenderer::drawPerspectivePixels(x, floorStart, floorEnd, farFloorScreenY, nearFloorScreenY, farPoint, nearPoint, farZ, nearZ, Double3::UnitY, textures.at(raisedData.floorID - 1), shadingInfo, occlusion, frame); } } else if (voxelData.dataType == VoxelDataType::Diagonal) { const VoxelData::DiagonalData &diagData = voxelData.diagonal; // Find intersection. RayHit hit; const bool success = diagData.type1 ? SoftwareRenderer::findDiag1Intersection(voxelX, voxelZ, nearPoint, farPoint, hit) : SoftwareRenderer::findDiag2Intersection(voxelX, voxelZ, nearPoint, farPoint, hit); if (success) { double diagTopScreenY, diagBottomScreenY; int diagStart, diagEnd; SoftwareRenderer::diagProjection(voxelYReal, voxelHeight, hit.point, transform, yShear, frame.height, heightReal, diagTopScreenY, diagBottomScreenY, diagStart, diagEnd); SoftwareRenderer::drawPixels(x, diagStart, diagEnd, diagTopScreenY, diagBottomScreenY, nearZ + hit.innerZ, hit.u, 0.0, Constants::JustBelowOne, hit.normal, textures.at(diagData.id - 1), shadingInfo, occlusion, frame); } } else if (voxelData.dataType == VoxelDataType::TransparentWall) { // Do nothing. Transparent walls have no back-faces. } else if (voxelData.dataType == VoxelDataType::Edge) { const VoxelData::EdgeData &edgeData = voxelData.edge; // Find intersection. RayHit hit; const bool success = SoftwareRenderer::findEdgeIntersection( voxelX, voxelZ, edgeData.facing, nearPoint, farPoint, hit); if (success) { const Double3 edgeTopPoint( hit.point.x, voxelYReal + voxelHeight, hit.point.y); const Double3 edgeBottomPoint( hit.point.x, voxelYReal, hit.point.y); const double edgeTopScreenY = SoftwareRenderer::getProjectedY( edgeTopPoint, transform, yShear) * heightReal; const double edgeBottomScreenY = SoftwareRenderer::getProjectedY( edgeBottomPoint, transform, yShear) * heightReal; const int edgeStart = SoftwareRenderer::getLowerBoundedPixel( edgeTopScreenY, frame.height); const int edgeEnd = SoftwareRenderer::getUpperBoundedPixel( edgeBottomScreenY, frame.height); SoftwareRenderer::drawTransparentPixels(x, edgeStart, edgeEnd, edgeTopScreenY, edgeBottomScreenY, nearZ + hit.innerZ, hit.u, 0.0, Constants::JustBelowOne, hit.normal, textures.at(edgeData.id - 1), shadingInfo, occlusion, frame); } } else if (voxelData.dataType == VoxelDataType::Chasm) { // Render front and back-faces. const VoxelData::ChasmData &chasmData = voxelData.chasm; // To do. } else if (voxelData.dataType == VoxelDataType::Door) { // To do: find intersection via SoftwareRenderer::findDoorIntersection(). // Render nothing for now. } }; // Draw the player's current voxel first. drawInitialVoxel(); // Draw voxels below the player's voxel. for (int voxelY = (playerVoxelY - 1); voxelY >= 0; voxelY--) { drawInitialVoxelBelow(voxelY); } // Draw voxels above the player's voxel. for (int voxelY = (playerVoxelY + 1); voxelY < voxelGrid.getHeight(); voxelY++) { drawInitialVoxelAbove(voxelY); } } void SoftwareRenderer::drawVoxelColumn(int x, int voxelX, int voxelZ, double playerY, VoxelData::Facing facing, const Double2 &nearPoint, const Double2 &farPoint, double nearZ, double farZ, const Matrix4d &transform, double yShear, const ShadingInfo &shadingInfo, double ceilingHeight, const VoxelGrid &voxelGrid, const std::vector<SoftwareTexture> &textures, OcclusionData &occlusion, const FrameView &frame) { // Much of the code here is duplicated from the initial voxel column drawing method, but // there are a couple differences, like the horizontal texture coordinate being flipped, // and the drawing orders being slightly modified. The reason for having so much code is // so we cover all the different ray casting cases efficiently. It would slow down this // method if it had an "initialColumn" boolean that was false 90% of the time. // When clamping Y values for drawing ranges, subtract 0.5 from starts and add 0.5 to // ends before converting to integers because the drawing methods sample at the center // of pixels. The clamping function depends on which side of the range is being clamped; // either way, the drawing range should be contained within the projected range at the // sub-pixel level. This ensures that the vertical texture coordinate is always within 0->1. const double heightReal = static_cast<double>(frame.height); // Y position at the base of the player's voxel. const double playerYFloor = std::floor(playerY); // Voxel Y of the player. const int playerVoxelY = static_cast<int>(playerYFloor); // Horizontal texture coordinate for the wall, potentially shared between multiple voxels // in this voxel column. const double wallU = [&nearPoint, facing]() { const double uVal = [&nearPoint, facing]() { if (facing == VoxelData::Facing::PositiveX) { return Constants::JustBelowOne - (nearPoint.y - std::floor(nearPoint.y)); } else if (facing == VoxelData::Facing::NegativeX) { return nearPoint.y - std::floor(nearPoint.y); } else if (facing == VoxelData::Facing::PositiveZ) { return nearPoint.x - std::floor(nearPoint.x); } else { return Constants::JustBelowOne - (nearPoint.x - std::floor(nearPoint.x)); } }(); return std::max(std::min(uVal, Constants::JustBelowOne), 0.0); }(); // Normal of the wall for the incoming ray, potentially shared between multiple voxels in // this voxel column. const Double3 wallNormal = SoftwareRenderer::getNormal(facing); auto drawVoxel = [x, voxelX, voxelZ, playerY, playerYFloor, &wallNormal, &nearPoint, &farPoint, nearZ, farZ, wallU, &transform, yShear, &shadingInfo, ceilingHeight, &voxelGrid, &textures, &occlusion, &frame, heightReal]() { const int voxelY = static_cast<int>(playerYFloor); const char voxelID = voxelGrid.getVoxels()[voxelX + (voxelY * voxelGrid.getWidth()) + (voxelZ * voxelGrid.getWidth() * voxelGrid.getHeight())]; const VoxelData &voxelData = voxelGrid.getVoxelData(voxelID); // Height of the voxel depends on whether it's the main floor. const double voxelHeight = (voxelY == 1) ? ceilingHeight : 1.0; if (voxelData.dataType == VoxelDataType::Wall) { // Draw side. const VoxelData::WallData &wallData = voxelData.wall; const Double3 nearCeilingPoint( nearPoint.x, playerYFloor + voxelHeight, nearPoint.y); const Double3 nearFloorPoint( nearPoint.x, playerYFloor, nearPoint.y); const double nearCeilingScreenY = SoftwareRenderer::getProjectedY( nearCeilingPoint, transform, yShear) * heightReal; const double nearFloorScreenY = SoftwareRenderer::getProjectedY( nearFloorPoint, transform, yShear) * heightReal; const int wallStart = SoftwareRenderer::getLowerBoundedPixel( nearCeilingScreenY, frame.height); const int wallEnd = SoftwareRenderer::getUpperBoundedPixel( nearFloorScreenY, frame.height); SoftwareRenderer::drawPixels(x, wallStart, wallEnd, nearCeilingScreenY, nearFloorScreenY, nearZ, wallU, 0.0, Constants::JustBelowOne, wallNormal, textures.at(wallData.sideID - 1), shadingInfo, occlusion, frame); } else if (voxelData.dataType == VoxelDataType::Floor) { // Do nothing. Floors can only be seen from above. } else if (voxelData.dataType == VoxelDataType::Ceiling) { // Do nothing. Ceilings can only be seen from below. } else if (voxelData.dataType == VoxelDataType::Raised) { const VoxelData::RaisedData &raisedData = voxelData.raised; const Double3 nearCeilingPoint( nearPoint.x, playerYFloor + ((raisedData.yOffset + raisedData.ySize) * voxelHeight), nearPoint.y); const Double3 nearFloorPoint( nearPoint.x, playerYFloor + (raisedData.yOffset * voxelHeight), nearPoint.y); const double nearCeilingScreenY = SoftwareRenderer::getProjectedY( nearCeilingPoint, transform, yShear) * heightReal; const double nearFloorScreenY = SoftwareRenderer::getProjectedY( nearFloorPoint, transform, yShear) * heightReal; const int wallStart = SoftwareRenderer::getLowerBoundedPixel( nearCeilingScreenY, frame.height); const int wallEnd = SoftwareRenderer::getUpperBoundedPixel( nearFloorScreenY, frame.height); // Draw order depends on the player's Y position relative to the platform. if (playerY > nearCeilingPoint.y) { // Above platform. const Double3 farCeilingPoint( farPoint.x, nearCeilingPoint.y, farPoint.y); const double farCeilingScreenY = SoftwareRenderer::getProjectedY( farCeilingPoint, transform, yShear) * heightReal; const int ceilingStart = SoftwareRenderer::getLowerBoundedPixel( farCeilingScreenY, frame.height); const int ceilingEnd = wallStart; // Ceiling. SoftwareRenderer::drawPerspectivePixels(x, ceilingStart, ceilingEnd, farCeilingScreenY, nearCeilingScreenY, farPoint, nearPoint, farZ, nearZ, Double3::UnitY, textures.at(raisedData.ceilingID - 1), shadingInfo, occlusion, frame); // Side. SoftwareRenderer::drawTransparentPixels(x, wallStart, wallEnd, nearCeilingScreenY, nearFloorScreenY, nearZ, wallU, raisedData.vTop, raisedData.vBottom, wallNormal, textures.at(raisedData.sideID - 1), shadingInfo, occlusion, frame); } else if (playerY < nearFloorPoint.y) { // Below platform. const Double3 farFloorPoint( farPoint.x, nearFloorPoint.y, farPoint.y); const double farFloorScreenY = SoftwareRenderer::getProjectedY( farFloorPoint, transform, yShear) * heightReal; const int floorStart = wallEnd; const int floorEnd = SoftwareRenderer::getUpperBoundedPixel( farFloorScreenY, frame.height); // Side. SoftwareRenderer::drawTransparentPixels(x, wallStart, wallEnd, nearCeilingScreenY, nearFloorScreenY, nearZ, wallU, raisedData.vTop, raisedData.vBottom, wallNormal, textures.at(raisedData.sideID - 1), shadingInfo, occlusion, frame); // Floor. SoftwareRenderer::drawPerspectivePixels(x, floorStart, floorEnd, nearFloorScreenY, farFloorScreenY, nearPoint, farPoint, nearZ, farZ, -Double3::UnitY, textures.at(raisedData.floorID - 1), shadingInfo, occlusion, frame); } else { // Between top and bottom. SoftwareRenderer::drawTransparentPixels(x, wallStart, wallEnd, nearCeilingScreenY, nearFloorScreenY, nearZ, wallU, raisedData.vTop, raisedData.vBottom, wallNormal, textures.at(raisedData.sideID - 1), shadingInfo, occlusion, frame); } } else if (voxelData.dataType == VoxelDataType::Diagonal) { const VoxelData::DiagonalData &diagData = voxelData.diagonal; // Find intersection. RayHit hit; const bool success = diagData.type1 ? SoftwareRenderer::findDiag1Intersection(voxelX, voxelZ, nearPoint, farPoint, hit) : SoftwareRenderer::findDiag2Intersection(voxelX, voxelZ, nearPoint, farPoint, hit); if (success) { double diagTopScreenY, diagBottomScreenY; int diagStart, diagEnd; SoftwareRenderer::diagProjection(playerYFloor, voxelHeight, hit.point, transform, yShear, frame.height, heightReal, diagTopScreenY, diagBottomScreenY, diagStart, diagEnd); SoftwareRenderer::drawPixels(x, diagStart, diagEnd, diagTopScreenY, diagBottomScreenY, nearZ + hit.innerZ, hit.u, 0.0, Constants::JustBelowOne, hit.normal, textures.at(diagData.id - 1), shadingInfo, occlusion, frame); } } else if (voxelData.dataType == VoxelDataType::TransparentWall) { // Draw transparent side. const VoxelData::TransparentWallData &transparentWallData = voxelData.transparentWall; const Double3 nearCeilingPoint( nearPoint.x, playerYFloor + voxelHeight, nearPoint.y); const Double3 nearFloorPoint( nearPoint.x, playerYFloor, nearPoint.y); const double nearCeilingScreenY = SoftwareRenderer::getProjectedY( nearCeilingPoint, transform, yShear) * heightReal; const double nearFloorScreenY = SoftwareRenderer::getProjectedY( nearFloorPoint, transform, yShear) * heightReal; const int wallStart = SoftwareRenderer::getLowerBoundedPixel( nearCeilingScreenY, frame.height); const int wallEnd = SoftwareRenderer::getUpperBoundedPixel( nearFloorScreenY, frame.height); SoftwareRenderer::drawTransparentPixels(x, wallStart, wallEnd, nearCeilingScreenY, nearFloorScreenY, nearZ, wallU, 0.0, Constants::JustBelowOne, wallNormal, textures.at(transparentWallData.id - 1), shadingInfo, occlusion, frame); } else if (voxelData.dataType == VoxelDataType::Edge) { const VoxelData::EdgeData &edgeData = voxelData.edge; // Find intersection. RayHit hit; const bool success = SoftwareRenderer::findEdgeIntersection( voxelX, voxelZ, edgeData.facing, nearPoint, farPoint, hit); if (success) { const Double3 edgeTopPoint( hit.point.x, playerYFloor + voxelHeight, hit.point.y); const Double3 edgeBottomPoint( hit.point.x, playerYFloor, hit.point.y); const double edgeTopScreenY = SoftwareRenderer::getProjectedY( edgeTopPoint, transform, yShear) * heightReal; const double edgeBottomScreenY = SoftwareRenderer::getProjectedY( edgeBottomPoint, transform, yShear) * heightReal; const int edgeStart = SoftwareRenderer::getLowerBoundedPixel( edgeTopScreenY, frame.height); const int edgeEnd = SoftwareRenderer::getUpperBoundedPixel( edgeBottomScreenY, frame.height); SoftwareRenderer::drawTransparentPixels(x, edgeStart, edgeEnd, edgeTopScreenY, edgeBottomScreenY, nearZ + hit.innerZ, hit.u, 0.0, Constants::JustBelowOne, hit.normal, textures.at(edgeData.id - 1), shadingInfo, occlusion, frame); } } else if (voxelData.dataType == VoxelDataType::Chasm) { // Render front and back-faces. const VoxelData::ChasmData &chasmData = voxelData.chasm; // To do. } else if (voxelData.dataType == VoxelDataType::Door) { // To do: find intersection via SoftwareRenderer::findDoorIntersection(). // Just render as transparent wall for now. const VoxelData::DoorData &doorData = voxelData.door; const Double3 nearCeilingPoint( nearPoint.x, playerYFloor + voxelHeight, nearPoint.y); const Double3 nearFloorPoint( nearPoint.x, playerYFloor, nearPoint.y); const double nearCeilingScreenY = SoftwareRenderer::getProjectedY( nearCeilingPoint, transform, yShear) * heightReal; const double nearFloorScreenY = SoftwareRenderer::getProjectedY( nearFloorPoint, transform, yShear) * heightReal; const int wallStart = SoftwareRenderer::getLowerBoundedPixel( nearCeilingScreenY, frame.height); const int wallEnd = SoftwareRenderer::getUpperBoundedPixel( nearFloorScreenY, frame.height); SoftwareRenderer::drawTransparentPixels(x, wallStart, wallEnd, nearCeilingScreenY, nearFloorScreenY, nearZ, wallU, 0.0, Constants::JustBelowOne, wallNormal, textures.at(doorData.id - 1), shadingInfo, occlusion, frame); } }; auto drawVoxelBelow = [x, voxelX, voxelZ, playerY, &wallNormal, &nearPoint, &farPoint, nearZ, farZ, wallU, &transform, yShear, &shadingInfo, ceilingHeight, &voxelGrid, &textures, &occlusion, &frame, heightReal](int voxelY) { const char voxelID = voxelGrid.getVoxels()[voxelX + (voxelY * voxelGrid.getWidth()) + (voxelZ * voxelGrid.getWidth() * voxelGrid.getHeight())]; const VoxelData &voxelData = voxelGrid.getVoxelData(voxelID); const double voxelYReal = static_cast<double>(voxelY); // Height of the voxel depends on whether it's the main floor. const double voxelHeight = (voxelY == 1) ? ceilingHeight : 1.0; if (voxelData.dataType == VoxelDataType::Wall) { const VoxelData::WallData &wallData = voxelData.wall; const Double3 farCeilingPoint( farPoint.x, voxelYReal + voxelHeight, farPoint.y); const Double3 nearCeilingPoint( nearPoint.x, farCeilingPoint.y, nearPoint.y); const Double3 nearFloorPoint( nearPoint.x, voxelYReal, nearPoint.y); const double farCeilingScreenY = SoftwareRenderer::getProjectedY( farCeilingPoint, transform, yShear) * heightReal; const double nearCeilingScreenY = SoftwareRenderer::getProjectedY( nearCeilingPoint, transform, yShear) * heightReal; const double nearFloorScreenY = SoftwareRenderer::getProjectedY( nearFloorPoint, transform, yShear) * heightReal; const int ceilingStart = SoftwareRenderer::getLowerBoundedPixel( farCeilingScreenY, frame.height); const int ceilingEnd = SoftwareRenderer::getUpperBoundedPixel( nearCeilingScreenY, frame.height); const int wallStart = ceilingEnd; const int wallEnd = SoftwareRenderer::getUpperBoundedPixel( nearFloorScreenY, frame.height); // Ceiling. SoftwareRenderer::drawPerspectivePixels(x, ceilingStart, ceilingEnd, farCeilingScreenY, nearCeilingScreenY, farPoint, nearPoint, farZ, nearZ, Double3::UnitY, textures.at(wallData.ceilingID - 1), shadingInfo, occlusion, frame); // Side. SoftwareRenderer::drawPixels(x, wallStart, wallEnd, nearCeilingScreenY, nearFloorScreenY, nearZ, wallU, 0.0, Constants::JustBelowOne, wallNormal, textures.at(wallData.sideID - 1), shadingInfo, occlusion, frame); } else if (voxelData.dataType == VoxelDataType::Floor) { // Draw top of floor voxel. const VoxelData::FloorData &floorData = voxelData.floor; const Double3 farCeilingPoint( farPoint.x, voxelYReal + voxelHeight, farPoint.y); const Double3 nearCeilingPoint( nearPoint.x, farCeilingPoint.y, nearPoint.y); const double farCeilingScreenY = SoftwareRenderer::getProjectedY( farCeilingPoint, transform, yShear) * heightReal; const double nearCeilingScreenY = SoftwareRenderer::getProjectedY( nearCeilingPoint, transform, yShear) * heightReal; const int ceilingStart = SoftwareRenderer::getLowerBoundedPixel( farCeilingScreenY, frame.height); const int ceilingEnd = SoftwareRenderer::getUpperBoundedPixel( nearCeilingScreenY, frame.height); SoftwareRenderer::drawPerspectivePixels(x, ceilingStart, ceilingEnd, farCeilingScreenY, nearCeilingScreenY, farPoint, nearPoint, farZ, nearZ, Double3::UnitY, textures.at(floorData.id), shadingInfo, occlusion, frame); } else if (voxelData.dataType == VoxelDataType::Ceiling) { // Do nothing. Ceilings can only be seen from below. } else if (voxelData.dataType == VoxelDataType::Raised) { const VoxelData::RaisedData &raisedData = voxelData.raised; const Double3 nearCeilingPoint( nearPoint.x, voxelYReal + ((raisedData.yOffset + raisedData.ySize) * voxelHeight), nearPoint.y); const Double3 nearFloorPoint( nearPoint.x, voxelYReal + (raisedData.yOffset * voxelHeight), nearPoint.y); const double nearCeilingScreenY = SoftwareRenderer::getProjectedY( nearCeilingPoint, transform, yShear) * heightReal; const double nearFloorScreenY = SoftwareRenderer::getProjectedY( nearFloorPoint, transform, yShear) * heightReal; const int wallStart = SoftwareRenderer::getLowerBoundedPixel( nearCeilingScreenY, frame.height); const int wallEnd = SoftwareRenderer::getUpperBoundedPixel( nearFloorScreenY, frame.height); // Draw order depends on the player's Y position relative to the platform. if (playerY > nearCeilingPoint.y) { // Above platform. const Double3 farCeilingPoint( farPoint.x, nearCeilingPoint.y, farPoint.y); const double farCeilingScreenY = SoftwareRenderer::getProjectedY( farCeilingPoint, transform, yShear) * heightReal; const int ceilingStart = SoftwareRenderer::getLowerBoundedPixel( farCeilingScreenY, frame.height); const int ceilingEnd = wallStart; // Ceiling. SoftwareRenderer::drawPerspectivePixels(x, ceilingStart, ceilingEnd, farCeilingScreenY, nearCeilingScreenY, farPoint, nearPoint, farZ, nearZ, Double3::UnitY, textures.at(raisedData.ceilingID - 1), shadingInfo, occlusion, frame); // Side. SoftwareRenderer::drawTransparentPixels(x, wallStart, wallEnd, nearCeilingScreenY, nearFloorScreenY, nearZ, wallU, raisedData.vTop, raisedData.vBottom, wallNormal, textures.at(raisedData.sideID - 1), shadingInfo, occlusion, frame); } else if (playerY < nearFloorPoint.y) { // Below platform. const Double3 farFloorPoint( farPoint.x, nearFloorPoint.y, farPoint.y); const double farFloorScreenY = SoftwareRenderer::getProjectedY( farFloorPoint, transform, yShear) * heightReal; const int floorStart = wallEnd; const int floorEnd = SoftwareRenderer::getUpperBoundedPixel( farFloorScreenY, frame.height); // Side. SoftwareRenderer::drawTransparentPixels(x, wallStart, wallEnd, nearCeilingScreenY, nearFloorScreenY, nearZ, wallU, raisedData.vTop, raisedData.vBottom, wallNormal, textures.at(raisedData.sideID - 1), shadingInfo, occlusion, frame); // Floor. SoftwareRenderer::drawPerspectivePixels(x, floorStart, floorEnd, nearFloorScreenY, farFloorScreenY, nearPoint, farPoint, nearZ, farZ, -Double3::UnitY, textures.at(raisedData.floorID - 1), shadingInfo, occlusion, frame); } else { // Between top and bottom. SoftwareRenderer::drawTransparentPixels(x, wallStart, wallEnd, nearCeilingScreenY, nearFloorScreenY, nearZ, wallU, raisedData.vTop, raisedData.vBottom, wallNormal, textures.at(raisedData.sideID - 1), shadingInfo, occlusion, frame); } } else if (voxelData.dataType == VoxelDataType::Diagonal) { const VoxelData::DiagonalData &diagData = voxelData.diagonal; // Find intersection. RayHit hit; const bool success = diagData.type1 ? SoftwareRenderer::findDiag1Intersection(voxelX, voxelZ, nearPoint, farPoint, hit) : SoftwareRenderer::findDiag2Intersection(voxelX, voxelZ, nearPoint, farPoint, hit); if (success) { double diagTopScreenY, diagBottomScreenY; int diagStart, diagEnd; SoftwareRenderer::diagProjection(voxelYReal, voxelHeight, hit.point, transform, yShear, frame.height, heightReal, diagTopScreenY, diagBottomScreenY, diagStart, diagEnd); SoftwareRenderer::drawPixels(x, diagStart, diagEnd, diagTopScreenY, diagBottomScreenY, nearZ + hit.innerZ, hit.u, 0.0, Constants::JustBelowOne, hit.normal, textures.at(diagData.id - 1), shadingInfo, occlusion, frame); } } else if (voxelData.dataType == VoxelDataType::TransparentWall) { // Draw transparent side. const VoxelData::TransparentWallData &transparentWallData = voxelData.transparentWall; const Double3 nearCeilingPoint( nearPoint.x, voxelYReal + voxelHeight, nearPoint.y); const Double3 nearFloorPoint( nearPoint.x, voxelYReal, nearPoint.y); const double nearCeilingScreenY = SoftwareRenderer::getProjectedY( nearCeilingPoint, transform, yShear) * heightReal; const double nearFloorScreenY = SoftwareRenderer::getProjectedY( nearFloorPoint, transform, yShear) * heightReal; const int wallStart = SoftwareRenderer::getLowerBoundedPixel( nearCeilingScreenY, frame.height); const int wallEnd = SoftwareRenderer::getUpperBoundedPixel( nearFloorScreenY, frame.height); SoftwareRenderer::drawTransparentPixels(x, wallStart, wallEnd, nearCeilingScreenY, nearFloorScreenY, nearZ, wallU, 0.0, Constants::JustBelowOne, wallNormal, textures.at(transparentWallData.id - 1), shadingInfo, occlusion, frame); } else if (voxelData.dataType == VoxelDataType::Edge) { const VoxelData::EdgeData &edgeData = voxelData.edge; // Find intersection. RayHit hit; const bool success = SoftwareRenderer::findEdgeIntersection( voxelX, voxelZ, edgeData.facing, nearPoint, farPoint, hit); if (success) { const Double3 edgeTopPoint( hit.point.x, voxelYReal + voxelHeight, hit.point.y); const Double3 edgeBottomPoint( hit.point.x, voxelYReal, hit.point.y); const double edgeTopScreenY = SoftwareRenderer::getProjectedY( edgeTopPoint, transform, yShear) * heightReal; const double edgeBottomScreenY = SoftwareRenderer::getProjectedY( edgeBottomPoint, transform, yShear) * heightReal; const int edgeStart = SoftwareRenderer::getLowerBoundedPixel( edgeTopScreenY, frame.height); const int edgeEnd = SoftwareRenderer::getUpperBoundedPixel( edgeBottomScreenY, frame.height); SoftwareRenderer::drawTransparentPixels(x, edgeStart, edgeEnd, edgeTopScreenY, edgeBottomScreenY, nearZ + hit.innerZ, hit.u, 0.0, Constants::JustBelowOne, hit.normal, textures.at(edgeData.id - 1), shadingInfo, occlusion, frame); } } else if (voxelData.dataType == VoxelDataType::Chasm) { // Render front and back-faces. const VoxelData::ChasmData &chasmData = voxelData.chasm; // To do. } else if (voxelData.dataType == VoxelDataType::Door) { // To do: find intersection via SoftwareRenderer::findDoorIntersection(). // Just render as transparent wall for now. const VoxelData::DoorData &doorData = voxelData.door; const Double3 nearCeilingPoint( nearPoint.x, voxelYReal + voxelHeight, nearPoint.y); const Double3 nearFloorPoint( nearPoint.x, voxelYReal, nearPoint.y); const double nearCeilingScreenY = SoftwareRenderer::getProjectedY( nearCeilingPoint, transform, yShear) * heightReal; const double nearFloorScreenY = SoftwareRenderer::getProjectedY( nearFloorPoint, transform, yShear) * heightReal; const int wallStart = SoftwareRenderer::getLowerBoundedPixel( nearCeilingScreenY, frame.height); const int wallEnd = SoftwareRenderer::getUpperBoundedPixel( nearFloorScreenY, frame.height); SoftwareRenderer::drawTransparentPixels(x, wallStart, wallEnd, nearCeilingScreenY, nearFloorScreenY, nearZ, wallU, 0.0, Constants::JustBelowOne, wallNormal, textures.at(doorData.id - 1), shadingInfo, occlusion, frame); } }; auto drawVoxelAbove = [x, voxelX, voxelZ, playerY, &wallNormal, &nearPoint, &farPoint, nearZ, farZ, wallU, &transform, yShear, &shadingInfo, ceilingHeight, &voxelGrid, &textures, &occlusion, &frame, heightReal](int voxelY) { const char voxelID = voxelGrid.getVoxels()[voxelX + (voxelY * voxelGrid.getWidth()) + (voxelZ * voxelGrid.getWidth() * voxelGrid.getHeight())]; const VoxelData &voxelData = voxelGrid.getVoxelData(voxelID); const double voxelYReal = static_cast<double>(voxelY); // Height of the voxel depends on whether it's the main floor. const double voxelHeight = (voxelY == 1) ? ceilingHeight : 1.0; if (voxelData.dataType == VoxelDataType::Wall) { const VoxelData::WallData &wallData = voxelData.wall; const Double3 nearCeilingPoint( nearPoint.x, voxelYReal + voxelHeight, nearPoint.y); const Double3 nearFloorPoint( nearPoint.x, voxelYReal, nearPoint.y); const Double3 farFloorPoint( farPoint.x, nearFloorPoint.y, farPoint.y); const double nearCeilingScreenY = SoftwareRenderer::getProjectedY( nearCeilingPoint, transform, yShear) * heightReal; const double nearFloorScreenY = SoftwareRenderer::getProjectedY( nearFloorPoint, transform, yShear) * heightReal; const double farFloorScreenY = SoftwareRenderer::getProjectedY( farFloorPoint, transform, yShear) * heightReal; const int wallStart = SoftwareRenderer::getLowerBoundedPixel( nearCeilingScreenY, frame.height); const int wallEnd = SoftwareRenderer::getUpperBoundedPixel( nearFloorScreenY, frame.height); const int floorStart = wallEnd; const int floorEnd = SoftwareRenderer::getUpperBoundedPixel( farFloorScreenY, frame.height); // Side. SoftwareRenderer::drawPixels(x, wallStart, wallEnd, nearCeilingScreenY, nearFloorScreenY, nearZ, wallU, 0.0, Constants::JustBelowOne, wallNormal, textures.at(wallData.sideID - 1), shadingInfo, occlusion, frame); // Floor. SoftwareRenderer::drawPerspectivePixels(x, floorStart, floorEnd, nearFloorScreenY, farFloorScreenY, nearPoint, farPoint, nearZ, farZ, -Double3::UnitY, textures.at(wallData.floorID - 1), shadingInfo, occlusion, frame); } else if (voxelData.dataType == VoxelDataType::Floor) { // Do nothing. Floors can only be seen from above. } else if (voxelData.dataType == VoxelDataType::Ceiling) { // Draw bottom of ceiling voxel. const VoxelData::CeilingData &ceilingData = voxelData.ceiling; const Double3 nearFloorPoint( nearPoint.x, 1.0 + ceilingHeight, nearPoint.y); const Double3 farFloorPoint( farPoint.x, nearFloorPoint.y, farPoint.y); const double nearFloorScreenY = SoftwareRenderer::getProjectedY( nearFloorPoint, transform, yShear) * heightReal; const double farFloorScreenY = SoftwareRenderer::getProjectedY( farFloorPoint, transform, yShear) * heightReal; const int floorStart = SoftwareRenderer::getLowerBoundedPixel( nearFloorScreenY, frame.height); const int floorEnd = SoftwareRenderer::getUpperBoundedPixel( farFloorScreenY, frame.height); SoftwareRenderer::drawPerspectivePixels(x, floorStart, floorEnd, nearFloorScreenY, farFloorScreenY, nearPoint, farPoint, nearZ, farZ, -Double3::UnitY, textures.at(ceilingData.id), shadingInfo, occlusion, frame); } else if (voxelData.dataType == VoxelDataType::Raised) { const VoxelData::RaisedData &raisedData = voxelData.raised; const Double3 nearCeilingPoint( nearPoint.x, voxelYReal + ((raisedData.yOffset + raisedData.ySize) * voxelHeight), nearPoint.y); const Double3 nearFloorPoint( nearPoint.x, voxelYReal + (raisedData.yOffset * voxelHeight), nearPoint.y); const double nearCeilingScreenY = SoftwareRenderer::getProjectedY( nearCeilingPoint, transform, yShear) * heightReal; const double nearFloorScreenY = SoftwareRenderer::getProjectedY( nearFloorPoint, transform, yShear) * heightReal; const int wallStart = SoftwareRenderer::getLowerBoundedPixel( nearCeilingScreenY, frame.height); const int wallEnd = SoftwareRenderer::getUpperBoundedPixel( nearFloorScreenY, frame.height); // Draw order depends on the player's Y position relative to the platform. if (playerY > nearCeilingPoint.y) { // Above platform. const Double3 farCeilingPoint( farPoint.x, nearCeilingPoint.y, farPoint.y); const double farCeilingScreenY = SoftwareRenderer::getProjectedY( farCeilingPoint, transform, yShear) * heightReal; const int ceilingStart = SoftwareRenderer::getLowerBoundedPixel( farCeilingScreenY, frame.height); const int ceilingEnd = wallStart; // Ceiling. SoftwareRenderer::drawPerspectivePixels(x, ceilingStart, ceilingEnd, farCeilingScreenY, nearCeilingScreenY, farPoint, nearPoint, farZ, nearZ, Double3::UnitY, textures.at(raisedData.ceilingID - 1), shadingInfo, occlusion, frame); // Side. SoftwareRenderer::drawTransparentPixels(x, wallStart, wallEnd, nearCeilingScreenY, nearFloorScreenY, nearZ, wallU, raisedData.vTop, raisedData.vBottom, wallNormal, textures.at(raisedData.sideID - 1), shadingInfo, occlusion, frame); } else if (playerY < nearFloorPoint.y) { // Below platform. const Double3 farFloorPoint( farPoint.x, nearFloorPoint.y, farPoint.y); const double farFloorScreenY = SoftwareRenderer::getProjectedY( farFloorPoint, transform, yShear) * heightReal; const int floorStart = wallEnd; const int floorEnd = SoftwareRenderer::getUpperBoundedPixel( farFloorScreenY, frame.height); // Side. SoftwareRenderer::drawTransparentPixels(x, wallStart, wallEnd, nearCeilingScreenY, nearFloorScreenY, nearZ, wallU, raisedData.vTop, raisedData.vBottom, wallNormal, textures.at(raisedData.sideID - 1), shadingInfo, occlusion, frame); // Floor. SoftwareRenderer::drawPerspectivePixels(x, floorStart, floorEnd, nearFloorScreenY, farFloorScreenY, nearPoint, farPoint, nearZ, farZ, -Double3::UnitY, textures.at(raisedData.floorID - 1), shadingInfo, occlusion, frame); } else { // Between top and bottom. SoftwareRenderer::drawTransparentPixels(x, wallStart, wallEnd, nearCeilingScreenY, nearFloorScreenY, nearZ, wallU, raisedData.vTop, raisedData.vBottom, wallNormal, textures.at(raisedData.sideID - 1), shadingInfo, occlusion, frame); } } else if (voxelData.dataType == VoxelDataType::Diagonal) { const VoxelData::DiagonalData &diagData = voxelData.diagonal; // Find intersection. RayHit hit; const bool success = diagData.type1 ? SoftwareRenderer::findDiag1Intersection(voxelX, voxelZ, nearPoint, farPoint, hit) : SoftwareRenderer::findDiag2Intersection(voxelX, voxelZ, nearPoint, farPoint, hit); if (success) { double diagTopScreenY, diagBottomScreenY; int diagStart, diagEnd; SoftwareRenderer::diagProjection(voxelYReal, voxelHeight, hit.point, transform, yShear, frame.height, heightReal, diagTopScreenY, diagBottomScreenY, diagStart, diagEnd); SoftwareRenderer::drawPixels(x, diagStart, diagEnd, diagTopScreenY, diagBottomScreenY, nearZ + hit.innerZ, hit.u, 0.0, Constants::JustBelowOne, hit.normal, textures.at(diagData.id - 1), shadingInfo, occlusion, frame); } } else if (voxelData.dataType == VoxelDataType::TransparentWall) { // Draw transparent side. const VoxelData::TransparentWallData &transparentWallData = voxelData.transparentWall; const Double3 nearCeilingPoint( nearPoint.x, voxelYReal + voxelHeight, nearPoint.y); const Double3 nearFloorPoint( nearPoint.x, voxelYReal, nearPoint.y); const double nearCeilingScreenY = SoftwareRenderer::getProjectedY( nearCeilingPoint, transform, yShear) * heightReal; const double nearFloorScreenY = SoftwareRenderer::getProjectedY( nearFloorPoint, transform, yShear) * heightReal; const int wallStart = SoftwareRenderer::getLowerBoundedPixel( nearCeilingScreenY, frame.height); const int wallEnd = SoftwareRenderer::getUpperBoundedPixel( nearFloorScreenY, frame.height); SoftwareRenderer::drawTransparentPixels(x, wallStart, wallEnd, nearCeilingScreenY, nearFloorScreenY, nearZ, wallU, 0.0, Constants::JustBelowOne, wallNormal, textures.at(transparentWallData.id - 1), shadingInfo, occlusion, frame); } else if (voxelData.dataType == VoxelDataType::Edge) { const VoxelData::EdgeData &edgeData = voxelData.edge; // Find intersection. RayHit hit; const bool success = SoftwareRenderer::findEdgeIntersection( voxelX, voxelZ, edgeData.facing, nearPoint, farPoint, hit); if (success) { const Double3 edgeTopPoint( hit.point.x, voxelYReal + voxelHeight, hit.point.y); const Double3 edgeBottomPoint( hit.point.x, voxelYReal, hit.point.y); const double edgeTopScreenY = SoftwareRenderer::getProjectedY( edgeTopPoint, transform, yShear) * heightReal; const double edgeBottomScreenY = SoftwareRenderer::getProjectedY( edgeBottomPoint, transform, yShear) * heightReal; const int edgeStart = SoftwareRenderer::getLowerBoundedPixel( edgeTopScreenY, frame.height); const int edgeEnd = SoftwareRenderer::getUpperBoundedPixel( edgeBottomScreenY, frame.height); SoftwareRenderer::drawTransparentPixels(x, edgeStart, edgeEnd, edgeTopScreenY, edgeBottomScreenY, nearZ + hit.innerZ, hit.u, 0.0, Constants::JustBelowOne, hit.normal, textures.at(edgeData.id - 1), shadingInfo, occlusion, frame); } } else if (voxelData.dataType == VoxelDataType::Chasm) { // Render front and back-faces. const VoxelData::ChasmData &chasmData = voxelData.chasm; // To do. } else if (voxelData.dataType == VoxelDataType::Door) { // To do: find intersection via SoftwareRenderer::findDoorIntersection(). // Just render as transparent wall for now. const VoxelData::DoorData &doorData = voxelData.door; const Double3 nearCeilingPoint( nearPoint.x, voxelYReal + voxelHeight, nearPoint.y); const Double3 nearFloorPoint( nearPoint.x, voxelYReal, nearPoint.y); const double nearCeilingScreenY = SoftwareRenderer::getProjectedY( nearCeilingPoint, transform, yShear) * heightReal; const double nearFloorScreenY = SoftwareRenderer::getProjectedY( nearFloorPoint, transform, yShear) * heightReal; const int wallStart = SoftwareRenderer::getLowerBoundedPixel( nearCeilingScreenY, frame.height); const int wallEnd = SoftwareRenderer::getUpperBoundedPixel( nearFloorScreenY, frame.height); SoftwareRenderer::drawTransparentPixels(x, wallStart, wallEnd, nearCeilingScreenY, nearFloorScreenY, nearZ, wallU, 0.0, Constants::JustBelowOne, wallNormal, textures.at(doorData.id - 1), shadingInfo, occlusion, frame); } }; // Draw voxel straight ahead first. drawVoxel(); // Draw voxels below the voxel. for (int voxelY = (playerVoxelY - 1); voxelY >= 0; voxelY--) { drawVoxelBelow(voxelY); } // Draw voxels above the voxel. for (int voxelY = (playerVoxelY + 1); voxelY < voxelGrid.getHeight(); voxelY++) { drawVoxelAbove(voxelY); } } void SoftwareRenderer::drawFlat(int startX, int endX, const Flat::Frame &flatFrame, const Double3 &normal, bool flipped, const Double2 &eye, const ShadingInfo &shadingInfo, const SoftwareTexture &texture, const FrameView &frame) { // Contribution from the sun. const double lightNormalDot = std::max(0.0, shadingInfo.sunDirection.dot(normal)); const Double3 sunComponent = (shadingInfo.sunColor * lightNormalDot).clamped( 0.0, 1.0 - shadingInfo.ambient); // X percents across the screen for the given start and end columns. const double startXPercent = (static_cast<double>(startX) + 0.50) / static_cast<double>(frame.width); const double endXPercent = (static_cast<double>(endX) + 0.50) / static_cast<double>(frame.width); const bool startsInRange = (flatFrame.startX >= startXPercent) && (flatFrame.startX <= endXPercent); const bool endsInRange = (flatFrame.endX >= startXPercent) && (flatFrame.endX <= endXPercent); const bool coversRange = (flatFrame.startX <= startXPercent) && (flatFrame.endX >= endXPercent); // Throw out the draw call if the flat is not in the X range. if (!startsInRange && !endsInRange && !coversRange) { return; } // Get the min and max X range of coordinates in screen-space. This range is completely // contained within the flat. const double clampedStartXPercent = std::max(startXPercent, std::min(flatFrame.startX, flatFrame.endX)); const double clampedEndXPercent = std::min(endXPercent, std::max(flatFrame.startX, flatFrame.endX)); // The percentages from start to end within the flat. const double startFlatPercent = (clampedStartXPercent - flatFrame.startX) / (flatFrame.endX - flatFrame.startX); const double endFlatPercent = (clampedEndXPercent - flatFrame.startX) / (flatFrame.endX - flatFrame.startX); // Points interpolated between for per-column depth calculations in the XZ plane. const Double3 startTopPoint = flatFrame.topStart.lerp(flatFrame.topEnd, startFlatPercent); const Double3 endTopPoint = flatFrame.topStart.lerp(flatFrame.topEnd, endFlatPercent); // Horizontal texture coordinates in the flat. Although the flat percent can be // equal to 1.0, the texture coordinate needs to be less than 1.0. const double startU = std::max(std::min(startFlatPercent, Constants::JustBelowOne), 0.0); const double endU = std::max(std::min(endFlatPercent, Constants::JustBelowOne), 0.0); // Get the start and end coordinates of the projected points (Y values potentially // outside the screen). const double widthReal = static_cast<double>(frame.width); const double heightReal = static_cast<double>(frame.height); const double projectedXStart = clampedStartXPercent * widthReal; const double projectedXEnd = clampedEndXPercent * widthReal; const double projectedYStart = flatFrame.startY * heightReal; const double projectedYEnd = flatFrame.endY * heightReal; // Clamp the coordinates for where the flat starts and stops on the screen. const int xStart = SoftwareRenderer::getLowerBoundedPixel(projectedXStart, frame.width); const int xEnd = SoftwareRenderer::getUpperBoundedPixel(projectedXEnd, frame.width); const int yStart = SoftwareRenderer::getLowerBoundedPixel(projectedYStart, frame.height); const int yEnd = SoftwareRenderer::getUpperBoundedPixel(projectedYEnd, frame.height); // Shading on the texture. // - To do: contribution from lights. const Double3 shading( shadingInfo.ambient + sunComponent.x, shadingInfo.ambient + sunComponent.y, shadingInfo.ambient + sunComponent.z); // Draw by-column, similar to wall rendering. for (int x = xStart; x < xEnd; x++) { const double xPercent = ((static_cast<double>(x) + 0.50) - projectedXStart) / (projectedXEnd - projectedXStart); // Horizontal texture coordinate. const double u = startU + ((endU - startU) * xPercent); // Horizontal texel position. const int textureX = static_cast<int>( (flipped ? (Constants::JustBelowOne - u) : u) * static_cast<double>(texture.width)); const Double3 topPoint = startTopPoint.lerp(endTopPoint, xPercent); // Get the true XZ distance for the depth. const double depth = (Double2(topPoint.x, topPoint.z) - eye).length(); // Linearly interpolated fog. const Double3 &fogColor = shadingInfo.horizonSkyColor; const double fogPercent = std::min(depth / shadingInfo.fogDistance, 1.0); for (int y = yStart; y < yEnd; y++) { const int index = x + (y * frame.width); if (depth <= frame.depthBuffer[index]) { const double yPercent = ((static_cast<double>(y) + 0.50) - projectedYStart) / (projectedYEnd - projectedYStart); // Vertical texture coordinate. const double startV = 0.0; const double endV = Constants::JustBelowOne; const double v = startV + ((endV - startV) * yPercent); // Vertical texel position. const int textureY = static_cast<int>(v * static_cast<double>(texture.height)); // Alpha is checked in this loop, and transparent texels are not drawn. // Flats do not have emission, so ignore it. const int textureIndex = textureX + (textureY * texture.width); const Double4 &texel = texture.texels[textureIndex]; if (texel.w > 0.0) { // Texture color with shading. const double shadingMax = 1.0; double colorR = texel.x * std::min(shading.x, shadingMax); double colorG = texel.y * std::min(shading.y, shadingMax); double colorB = texel.z * std::min(shading.z, shadingMax); // Linearly interpolate with fog. colorR += (fogColor.x - colorR) * fogPercent; colorG += (fogColor.y - colorG) * fogPercent; colorB += (fogColor.z - colorB) * fogPercent; // Clamp maximum (don't worry about negative values). const double high = 1.0; colorR = (colorR > high) ? high : colorR; colorG = (colorG > high) ? high : colorG; colorB = (colorB > high) ? high : colorB; // Convert floats to integers. const uint32_t colorRGB = static_cast<uint32_t>( ((static_cast<uint8_t>(colorR * 255.0)) << 16) | ((static_cast<uint8_t>(colorG * 255.0)) << 8) | ((static_cast<uint8_t>(colorB * 255.0)))); frame.colorBuffer[index] = colorRGB; frame.depthBuffer[index] = depth; } } } } } void SoftwareRenderer::rayCast2D(int x, const Double3 &eye, const Double2 &direction, const Matrix4d &transform, double yShear, const ShadingInfo &shadingInfo, double ceilingHeight, const VoxelGrid &voxelGrid, const std::vector<SoftwareTexture> &textures, OcclusionData &occlusion, const FrameView &frame) { // Initially based on Lode Vandevenne's algorithm, this method of rendering is more // expensive than cheap 2.5D ray casting, as it does not stop at the first wall // intersection, and it also renders walls above and below, but it is more correct // as a result. Assume "direction" is normalized. // Some floating point behavior assumptions: // -> (value / 0.0) == infinity // -> (value / infinity) == 0.0 // -> (int)(-0.8) == 0 // -> (int)floor(-0.8) == -1 // -> (int)ceil(-0.8) == 0 // Because 2D vectors use "X" and "Y", the Z component is actually // aliased as "Y", which is a minor annoyance. const double dirX = direction.x; const double dirZ = direction.y; const double dirXSquared = direction.x * direction.x; const double dirZSquared = direction.y * direction.y; const double deltaDistX = std::sqrt(1.0 + (dirZSquared / dirXSquared)); const double deltaDistZ = std::sqrt(1.0 + (dirXSquared / dirZSquared)); const bool nonNegativeDirX = direction.x >= 0.0; const bool nonNegativeDirZ = direction.y >= 0.0; // Constant DDA-related values. // - Technically, these could be moved out of the ray casting method, but they // are not a performance concern for now. It's just to minimize renderer state. const Double3 startCellReal( std::floor(eye.x), std::floor(eye.y), std::floor(eye.z)); const Int3 startCell( static_cast<int>(startCellReal.x), static_cast<int>(startCellReal.y), static_cast<int>(startCellReal.z)); int stepX, stepZ; double sideDistX, sideDistZ; if (nonNegativeDirX) { stepX = 1; sideDistX = (startCellReal.x + 1.0 - eye.x) * deltaDistX; } else { stepX = -1; sideDistX = (eye.x - startCellReal.x) * deltaDistX; } if (nonNegativeDirZ) { stepZ = 1; sideDistZ = (startCellReal.z + 1.0 - eye.z) * deltaDistZ; } else { stepZ = -1; sideDistZ = (eye.z - startCellReal.z) * deltaDistZ; } // Pointer to voxel ID grid data. const char *voxels = voxelGrid.getVoxels(); // The Z distance from the camera to the wall, and the X or Z normal of the intersected // voxel face. The first Z distance is a special case, so it's brought outside the // DDA loop. double zDistance; VoxelData::Facing facing; // Verify that the initial voxel coordinate is within the world bounds. bool voxelIsValid = (startCell.x >= 0) && (startCell.y >= 0) && (startCell.z >= 0) && (startCell.x < voxelGrid.getWidth()) && (startCell.y < voxelGrid.getHeight()) && (startCell.z < voxelGrid.getDepth()); if (voxelIsValid) { // Get the initial voxel ID and see how it should be rendered. const char initialVoxelID = voxels[startCell.x + (startCell.y * voxelGrid.getWidth()) + (startCell.z * voxelGrid.getWidth() * voxelGrid.getHeight())]; // Decide how far the wall is, and which voxel face was hit. if (sideDistX < sideDistZ) { zDistance = sideDistX; facing = nonNegativeDirX ? VoxelData::Facing::NegativeX : VoxelData::Facing::PositiveX; } else { zDistance = sideDistZ; facing = nonNegativeDirZ ? VoxelData::Facing::NegativeZ : VoxelData::Facing::PositiveZ; } // The initial near point is directly in front of the player in the near Z // camera plane. const Double2 initialNearPoint( eye.x + (dirX * SoftwareRenderer::NEAR_PLANE), eye.z + (dirZ * SoftwareRenderer::NEAR_PLANE)); // The initial far point is the wall hit. This is used with the player's position // for drawing the initial floor and ceiling. const Double2 initialFarPoint( eye.x + (dirX * zDistance), eye.z + (dirZ * zDistance)); // Draw all voxels in a column at the player's XZ coordinate. SoftwareRenderer::drawInitialVoxelColumn(x, startCell.x, startCell.z, eye.y, facing, initialNearPoint, initialFarPoint, SoftwareRenderer::NEAR_PLANE, zDistance, transform, yShear, shadingInfo, ceilingHeight, voxelGrid, textures, occlusion, frame); } // The current voxel coordinate in the DDA loop. For all intents and purposes, // the Y cell coordinate is constant. Int3 cell(startCell.x, startCell.y, startCell.z); // Lambda for stepping to the next XZ coordinate in the grid and updating the Z // distance for the current edge point. auto doDDAStep = [&eye, &voxelGrid, &sideDistX, &sideDistZ, &cell, &facing, &voxelIsValid, &zDistance, deltaDistX, deltaDistZ, stepX, stepZ, dirX, dirZ, nonNegativeDirX, nonNegativeDirZ]() { if (sideDistX < sideDistZ) { sideDistX += deltaDistX; cell.x += stepX; facing = nonNegativeDirX ? VoxelData::Facing::NegativeX : VoxelData::Facing::PositiveX; voxelIsValid &= (cell.x >= 0) && (cell.x < voxelGrid.getWidth()); } else { sideDistZ += deltaDistZ; cell.z += stepZ; facing = nonNegativeDirZ ? VoxelData::Facing::NegativeZ : VoxelData::Facing::PositiveZ; voxelIsValid &= (cell.z >= 0) && (cell.z < voxelGrid.getDepth()); } const bool onXAxis = (facing == VoxelData::Facing::PositiveX) || (facing == VoxelData::Facing::NegativeX); zDistance = onXAxis ? (static_cast<double>(cell.x) - eye.x + static_cast<double>((1 - stepX) / 2)) / dirX : (static_cast<double>(cell.z) - eye.z + static_cast<double>((1 - stepZ) / 2)) / dirZ; }; // Step forward in the grid once to leave the initial voxel and update the Z distance. doDDAStep(); // Step through the voxel grid while the current coordinate is valid, the // distance stepped is less than the distance at which fog is maximum, and // the column is not completely occluded. while (voxelIsValid && (zDistance < shadingInfo.fogDistance) && (occlusion.yMin != occlusion.yMax)) { // Store the cell coordinates, axis, and Z distance for wall rendering. The // loop needs to do another DDA step to calculate the far point. const int savedCellX = cell.x; const int savedCellZ = cell.z; const VoxelData::Facing savedNormal = facing; const double wallDistance = zDistance; // Decide which voxel in the XZ plane to step to next, and update the Z distance. doDDAStep(); // Near and far points in the XZ plane. The near point is where the wall is, and // the far point is used with the near point for drawing the floor and ceiling. const Double2 nearPoint( eye.x + (dirX * wallDistance), eye.z + (dirZ * wallDistance)); const Double2 farPoint( eye.x + (dirX * zDistance), eye.z + (dirZ * zDistance)); // Draw all voxels in a column at the given XZ coordinate. SoftwareRenderer::drawVoxelColumn(x, savedCellX, savedCellZ, eye.y, savedNormal, nearPoint, farPoint, wallDistance, zDistance, transform, yShear, shadingInfo, ceilingHeight, voxelGrid, textures, occlusion, frame); } } void SoftwareRenderer::render(const Double3 &eye, const Double3 &direction, double fovY, double ambient, double daytimePercent, double ceilingHeight, const VoxelGrid &voxelGrid, uint32_t *colorBuffer) { // Constants for screen dimensions. const double widthReal = static_cast<double>(this->width); const double heightReal = static_cast<double>(this->height); const double aspect = widthReal / heightReal; // Camera values for rendering. We trick the 2.5D ray caster into thinking the player is // always looking straight forward, but we use the Y component of the player's direction // to offset projected coordinates via Y-shearing. Assume "direction" is normalized. const Double3 forwardXZ = Double3(direction.x, 0.0, direction.z).normalized(); const Double3 rightXZ = forwardXZ.cross(Double3::UnitY).normalized(); const Double3 up = Double3::UnitY; // Zoom of the camera, based on vertical field of view. const double zoom = 1.0 / std::tan((fovY * 0.5) * Constants::DegToRad); // Refresh transformation matrix (model matrix isn't required because it's just // the identity matrix). const Matrix4d view = Matrix4d::view(eye, forwardXZ, rightXZ, up); const Matrix4d projection = Matrix4d::perspective(fovY, aspect, SoftwareRenderer::NEAR_PLANE, SoftwareRenderer::FAR_PLANE); const Matrix4d transform = projection * view; // Y-shearing is the distance that projected Y coordinates are translated by based on the // player's 3D direction and field of view. First get the player's angle relative to the // horizon, then get the tangent of that angle. The Y component of the player's direction // must be clamped less than 1 because 1 would imply they are looking straight up or down, // which is impossible in 2.5D rendering (the vertical line segment of the view frustum // would be infinitely high or low). The camera code should take care of the clamping for us. const double yShear = [&direction, zoom]() { // Get the vertical angle of the player's direction. const double angleRadians = [&direction]() { // Get the length of the direction vector's projection onto the XZ plane. const double xzProjection = std::sqrt( (direction.x * direction.x) + (direction.z * direction.z)); if (direction.y > 0.0) { // Above the horizon. return std::acos(xzProjection); } else if (direction.y < 0.0) { // Below the horizon. return -std::acos(xzProjection); } else { // At the horizon. return 0.0; } }(); // Get the number of screen heights to translate all projected Y coordinates by, // relative to the current zoom. As a reference, this should be some value roughly // between -1.0 and 1.0 for "acceptable skewing" at a vertical FOV of 90.0. If the // camera is not clamped, this could theoretically be between -infinity and infinity, // but it would result in far too much skewing. return std::tan(angleRadians) * zoom; }(); // Camera values for generating 2D rays with. const Double2 forwardComp = Double2(forwardXZ.x, forwardXZ.z).normalized() * zoom; const Double2 right2D = Double2(rightXZ.x, rightXZ.z).normalized() * aspect; // Calculate shading information. const Double3 horizonFogColor = this->getFogColor(daytimePercent); const Double3 zenithFogColor = horizonFogColor * 0.85; // Temp. const Double3 sunDirection = this->getSunDirection(daytimePercent); const Double3 sunColor = [&sunDirection]() { const Double3 baseColor(0.90, 0.875, 0.85); // Darken the sun color if it's below the horizon so wall faces aren't lit // as much during the night. This is just an artistic value to compensate // for the lack of shadows. return (sunDirection.y >= 0.0) ? baseColor : (baseColor * (1.0 - (5.0 * std::abs(sunDirection.y)))).clamped(); }(); // Create some helper structs to keep similar values together. const ShadingInfo shadingInfo(horizonFogColor, zenithFogColor, sunColor, sunDirection, ambient, this->fogDistance); const FrameView frame(colorBuffer, this->depthBuffer.data(), this->width, this->height); // Lambda for rendering some columns of pixels. The voxel rendering portion uses 2.5D // ray casting, which is the cheaper form of ray casting (although still not very // efficient overall), and results in a "fake" 3D scene. auto renderColumns = [this, &eye, ceilingHeight, &voxelGrid, &shadingInfo, widthReal, &transform, yShear, &forwardComp, &right2D, &frame](int startX, int endX) { for (int x = startX; x < endX; x++) { // X percent across the screen. const double xPercent = (static_cast<double>(x) + 0.50) / widthReal; // "Right" component of the ray direction, based on current screen X. const Double2 rightComp = right2D * ((2.0 * xPercent) - 1.0); // Calculate the ray direction through the pixel. // - If un-normalized, it uses the Z distance, but the insides of voxels // don't look right then. const Double2 direction = (forwardComp + rightComp).normalized(); // Cast the 2D ray and fill in the column's pixels with color. this->rayCast2D(x, eye, direction, transform, yShear, shadingInfo, ceilingHeight, voxelGrid, this->textures, this->occlusion.at(x), frame); } // Iterate through all flats, rendering those visible within the given X range of // the screen. for (const auto &pair : this->visibleFlats) { const Flat &flat = *pair.first; const Flat::Frame &flatFrame = pair.second; // Normal of the flat (always facing the camera). const Double3 flatNormal = Double3(-forwardComp.x, 0.0, -forwardComp.y).normalized(); // Texture of the flat. It might be flipped horizontally as well, given by // the "flat.flipped" value. const SoftwareTexture &texture = textures[flat.textureID]; const Double2 eye2D(eye.x, eye.z); SoftwareRenderer::drawFlat(startX, endX, flatFrame, flatNormal, flat.flipped, eye2D, shadingInfo, texture, frame); } }; // Lambda for clearing some rows on the frame buffer quickly. auto clearRows = [this, colorBuffer, &horizonFogColor, &zenithFogColor](int startY, int endY) { const int startIndex = startY * this->width; const int endIndex = endY * this->width; uint32_t *colorPtr = colorBuffer; double *depthPtr = this->depthBuffer.data(); const uint32_t colorValue = horizonFogColor.toRGB(); const double depthValue = std::numeric_limits<double>::infinity(); // Clear the color and depth of some rows. for (int i = startIndex; i < endIndex; i++) { colorPtr[i] = colorValue; depthPtr[i] = depthValue; } }; // Start a thread for refreshing the visible flats. This should erase the old list, // calculate a new list, and sort it by depth. std::thread sortThread([this, &eye, &forwardXZ, &transform, yShear, aspect, zoom] { const Double2 eye2D(eye.x, eye.z); const Double2 direction2D(forwardXZ.x, forwardXZ.z); this->updateVisibleFlats(eye2D, direction2D, transform, yShear, aspect, zoom); }); // Prepare render threads. These are used for clearing the frame buffer and rendering. std::vector<std::thread> renderThreads(this->renderThreadCount); // Start clearing the frame buffer with the render threads. for (size_t i = 0; i < renderThreads.size(); i++) { // "blockSize" is the approximate number of rows per thread. Rounding is involved so // the start and stop coordinates are correct for all resolutions. const double blockSize = heightReal / static_cast<double>(this->renderThreadCount); const int startY = static_cast<int>(std::round(static_cast<double>(i) * blockSize)); const int endY = static_cast<int>(std::round(static_cast<double>(i + 1) * blockSize)); // Make sure the rounding is correct. assert(startY >= 0); assert(endY <= this->height); renderThreads[i] = std::thread(clearRows, startY, endY); } // Reset occlusion. std::fill(this->occlusion.begin(), this->occlusion.end(), OcclusionData(0, this->height)); // Wait for the render threads to finish clearing. for (auto &thread : renderThreads) { thread.join(); } // Wait for the sorting thread to finish. sortThread.join(); // Start rendering the scene with the render threads. for (size_t i = 0; i < renderThreads.size(); i++) { // "blockSize" is the approximate number of columns per thread. Rounding is involved so // the start and stop coordinates are correct for all resolutions. const double blockSize = widthReal / static_cast<double>(this->renderThreadCount); const int startX = static_cast<int>(std::round(static_cast<double>(i) * blockSize)); const int endX = static_cast<int>(std::round(static_cast<double>(i + 1) * blockSize)); // Make sure the rounding is correct. assert(startX >= 0); assert(endX <= this->width); renderThreads[i] = std::thread(renderColumns, startX, endX); } // Wait for the render threads to finish rendering. for (auto &thread : renderThreads) { thread.join(); } }
#include <iostream> #include "dstar_lite/dstar.h" int main(int argc, char **argv) { // Check that there are 3 arguments, aka argc == 4. if (argc != 4) { std::cerr << "Terminating. Incorrect number of arguments." << "Expected 3." << std::endl; return EXIT_FAILURE; } // Parse grid. std::string flat_grid = argv[3]; // Construct a grid. const uint grid_size = (uint)std::sqrt(flat_grid.size()); std::vector<std::vector<int>> occupancy_grid (grid_size, vector<int>(grid_size)); // Parse input // Retrieve start position const uint start = std::atoi(argv[1]); std::array<uint, 2> start_indices; start_indices[0] = std::floor(start / grid_size); //x index start_indices[1] = start - start_indices[0] * grid_size; //y index // Retrieve goal position const uint goal = std::atoi(argv[2]); std::array<uint, 2> goal_indices; goal_indices[0] = std::floor(goal / grid_size); //x index goal_indices[1] = goal - goal_indices[0] * grid_size; //y index // Reshape input to a grid with x, y coordinates for (uint i = 0, j = 0, k = 0; k < flat_grid.size(); k++) { j = k % grid_size; // Check that we are not out of bounds. if ( i < grid_size && j < grid_size) { const int a = (int)flat_grid.at(k) - 48; occupancy_grid[i][j] = a; } else { std::cerr << "Index out of bounds, check that" " input grid is squared." << std::endl; return EXIT_FAILURE; } if (j == (grid_size - 1)) { i++; } } Dstar* dstar = new Dstar(); dstar->init(start_indices[0], start_indices[1], goal_indices[0], goal_indices[1]); for (uint i = 0; i < occupancy_grid.size(); i++) { for (uint j = 0; j < occupancy_grid.at(i).size(); j++) { std::cout << "Occ grid vals: " << occupancy_grid[i][j] << '\n'; if (occupancy_grid.at(i).at(j) == 1) { dstar->updateCell(i+1, j+1, -1); } } } if (!dstar->replan()) { std::cerr << "No found path to goal" << std::endl; return EXIT_FAILURE; } list<state> path = dstar->getPath(); for(const state& waypoint: path) { std::cout << "Waypoint: " << waypoint.x << ", " << waypoint.y << std::endl; } return EXIT_SUCCESS; } Inverse occupancy_grid values #include <iostream> #include "dstar_lite/dstar.h" int main(int argc, char **argv) { // Check that there are 3 arguments, aka argc == 4. if (argc != 4) { std::cerr << "Terminating. Incorrect number of arguments." << "Expected 3." << std::endl; return EXIT_FAILURE; } // Parse grid. std::string flat_grid = argv[3]; // Construct a grid. const uint grid_size = (uint)std::sqrt(flat_grid.size()); std::vector<std::vector<int>> occupancy_grid (grid_size, vector<int>(grid_size)); // Parse input // Retrieve start position const uint start = std::atoi(argv[1]); std::array<uint, 2> start_indices; start_indices[0] = std::floor(start / grid_size); //x index start_indices[1] = start - start_indices[0] * grid_size; //y index // Retrieve goal position const uint goal = std::atoi(argv[2]); std::array<uint, 2> goal_indices; goal_indices[0] = std::floor(goal / grid_size); //x index goal_indices[1] = goal - goal_indices[0] * grid_size; //y index // Reshape input to a grid with x, y coordinates for (uint i = 0, j = 0, k = 0; k < flat_grid.size(); k++) { j = k % grid_size; // Check that we are not out of bounds. if ( i < grid_size && j < grid_size) { const int a = 1 - ((int)flat_grid.at(k) - 48); occupancy_grid[i][j] = a; } else { std::cerr << "Index out of bounds, check that" " input grid is squared." << std::endl; return EXIT_FAILURE; } if (j == (grid_size - 1)) { i++; } } Dstar* dstar = new Dstar(); dstar->init(start_indices[0], start_indices[1], goal_indices[0], goal_indices[1]); for (uint i = 0; i < occupancy_grid.size(); i++) { for (uint j = 0; j < occupancy_grid.at(i).size(); j++) { std::cout << "Occ grid vals: " << occupancy_grid[i][j] << '\n'; if (occupancy_grid.at(i).at(j) == 1) { dstar->updateCell(i+1, j+1, -1); } } } if (!dstar->replan()) { std::cerr << "No found path to goal" << std::endl; return EXIT_FAILURE; } list<state> path = dstar->getPath(); for(const state& waypoint: path) { std::cout << "Waypoint: " << waypoint.x << ", " << waypoint.y << std::endl; } return EXIT_SUCCESS; }
/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: tokstack.hxx,v $ * * $Revision: 1.12 $ * * last change: $Author: obo $ $Date: 2007-06-13 09:12:06 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _TOKSTACK_HXX #define _TOKSTACK_HXX #ifndef _INC_STRING #include <string.h> #endif #ifndef _DEBUG_HXX //autogen #include <tools/debug.hxx> #endif #ifndef SC_COMPILER_HXX #include "compiler.hxx" #endif typedef OpCode DefTokenId; // in PRODUCT version: ambiguity between OpCode (being USHORT) and UINT16 // Unfortunately a typedef is just a dumb alias and not a real type ... //typedef UINT16 TokenId; struct TokenId { UINT16 nId; TokenId() : nId( 0 ) {} TokenId( UINT16 n ) : nId( n ) {} TokenId( const TokenId& r ) : nId( r.nId ) {} inline TokenId& operator =( const TokenId& r ) { nId = r.nId; return *this; } inline TokenId& operator =( UINT16 n ) { nId = n; return *this; } inline operator UINT16&() { return nId; } inline operator const UINT16&() const { return nId; } inline BOOL operator <( UINT16 n ) const { return nId < n; } inline BOOL operator >( UINT16 n ) const { return nId > n; } inline BOOL operator <=( UINT16 n ) const { return nId <= n; } inline BOOL operator >=( UINT16 n ) const { return nId >= n; } inline BOOL operator ==( UINT16 n ) const { return nId == n; } inline BOOL operator !=( UINT16 n ) const { return nId != n; } }; //------------------------------------------------------------------------ struct ComplRefData; class TokenStack; class ScToken; enum E_TYPE { T_Id, // Id-Folge T_Str, // String T_D, // Double T_RefC, // Cell Reference T_RefA, // Area Reference T_RN, // Range Name T_Ext, // irgendwas Unbekanntes mit Funktionsnamen T_Nlf, // token for natural language formula T_Matrix, // token for inline arrays T_Error // fuer Abfrage im Fehlerfall }; class TokenPool { // !ACHTUNG!: externe Id-Basis ist 1, interne 0! // Ausgabe Id = 0 -> Fehlerfall private: String** ppP_Str; // Pool fuer Strings UINT16 nP_Str; // ...mit Groesse UINT16 nP_StrAkt; // ...und Schreibmarke double* pP_Dbl; // Pool fuer Doubles UINT16 nP_Dbl; UINT16 nP_DblAkt; SingleRefData** ppP_RefTr; // Pool fuer Referenzen UINT16 nP_RefTr; UINT16 nP_RefTrAkt; UINT16* pP_Id; // Pool fuer Id-Folgen UINT16 nP_Id; UINT16 nP_IdAkt; UINT16 nP_IdLast; // letzter Folgen-Beginn struct EXTCONT { DefTokenId eId; String aText; EXTCONT( const DefTokenId e, const String& r ) : eId( e ), aText( r ){} }; EXTCONT** ppP_Ext; UINT16 nP_Ext; UINT16 nP_ExtAkt; struct NLFCONT { SingleRefData aRef; NLFCONT( const SingleRefData& r ) : aRef( r ) {} }; NLFCONT** ppP_Nlf; UINT16 nP_Nlf; UINT16 nP_NlfAkt; ScMatrix** ppP_Matrix; // Pool fuer Matricies UINT16 nP_Matrix; UINT16 nP_MatrixAkt; UINT16* pElement; // Array mit Indizes fuer Elemente E_TYPE* pType; // ...mit Typ-Info UINT16* pSize; // ...mit Laengenangabe (Anz. UINT16) UINT16 nElement; UINT16 nElementAkt; static const UINT16 nScTokenOff;// Offset fuer SC-Token #ifdef DBG_UTIL UINT16 nRek; // Rekursionszaehler #endif ScTokenArray* pScToken; // Tokenbastler void GrowString( void ); void GrowDouble( void ); void GrowTripel( void ); void GrowId( void ); void GrowElement( void ); void GrowExt( void ); void GrowNlf( void ); void GrowMatrix( void ); void GetElement( const UINT16 nId ); void GetElementRek( const UINT16 nId ); public: TokenPool( void ); ~TokenPool(); inline TokenPool& operator <<( const TokenId nId ); inline TokenPool& operator <<( const DefTokenId eId ); inline TokenPool& operator <<( TokenStack& rStack ); void operator >>( TokenId& rId ); inline void operator >>( TokenStack& rStack ); inline const TokenId Store( void ); const TokenId Store( const double& rDouble ); // nur fuer Range-Names const TokenId Store( const UINT16 nIndex ); inline const TokenId Store( const INT16 nWert ); const TokenId Store( const String& rString ); const TokenId Store( const SingleRefData& rTr ); const TokenId Store( const ComplRefData& rTr ); const TokenId Store( const DefTokenId eId, const String& rName ); // 4 externals (e.g. AddIns, Makros...) const TokenId StoreNlf( const SingleRefData& rTr ); const TokenId StoreMatrix( SCSIZE nC, SCSIZE nR ); inline const TokenId LastId( void ) const; inline const ScTokenArray* operator []( const TokenId nId ); void Reset( void ); inline E_TYPE GetType( const TokenId& nId ) const; inline const SingleRefData* GetSRD( const TokenId& nId ) const; BOOL IsSingleOp( const TokenId& nId, const DefTokenId eId ) const; const String* GetExternal( const TokenId& nId ) const; const String* GetString( const TokenId& nId ) const; ScMatrix* GetMatrix( unsigned int n ) const; }; class TokenStack // Stack fuer Token-Ids: Id 0 sollte reserviert bleiben als // fehlerhafte Id, da z.B. Get() im Fehlerfall 0 liefert { private: TokenId* pStack; // Stack als Array UINT16 nPos; // Schreibmarke UINT16 nSize; // Erster Index ausserhalb des Stacks public: TokenStack( UINT16 nNewSize = 1024 ); ~TokenStack(); inline TokenStack& operator <<( const TokenId nNewId ); inline void operator >>( TokenId &rId ); inline void Reset( void ); inline bool HasMoreTokens() const { return nPos > 0; } inline const TokenId Get( void ); }; inline const TokenId TokenStack::Get( void ) { DBG_ASSERT( nPos > 0, "*TokenStack::Get(): Leer ist leer, ist leer, ist leer, ist..." ); TokenId nRet; if( nPos == 0 ) nRet = 0; else { nPos--; nRet = pStack[ nPos ]; } return nRet; } inline TokenStack &TokenStack::operator <<( const TokenId nNewId ) {// Element auf Stack DBG_ASSERT( nPos < nSize, "*TokenStack::<<(): Stackueberlauf" ); if( nPos < nSize ) { pStack[ nPos ] = nNewId; nPos++; } return *this; } inline void TokenStack::operator >>( TokenId& rId ) {// Element von Stack DBG_ASSERT( nPos > 0, "*TokenStack::>>(): Leer ist leer, ist leer, ist leer, ..." ); if( nPos > 0 ) { nPos--; rId = pStack[ nPos ]; } } inline void TokenStack::Reset( void ) { nPos = 0; } inline TokenPool& TokenPool::operator <<( const TokenId nId ) { // POST: nId's werden hintereinander im Pool unter einer neuen Id // abgelegt. Vorgang wird mit >> oder Store() abgeschlossen // nId -> ( UINT16 ) nId - 1; DBG_ASSERT( ( UINT16 ) nId < nScTokenOff, "-TokenPool::operator <<: TokenId im DefToken-Bereich!" ); if( nP_IdAkt >= nP_Id ) GrowId(); pP_Id[ nP_IdAkt ] = ( ( UINT16 ) nId ) - 1; nP_IdAkt++; return *this; } inline TokenPool& TokenPool::operator <<( const DefTokenId eId ) { DBG_ASSERT( ( UINT32 ) eId + nScTokenOff < 0xFFFF, "-TokenPool::operator<<: enmum zu gross!" ); if( nP_IdAkt >= nP_Id ) GrowId(); pP_Id[ nP_IdAkt ] = ( ( UINT16 ) eId ) + nScTokenOff; nP_IdAkt++; return *this; } inline TokenPool& TokenPool::operator <<( TokenStack& rStack ) { if( nP_IdAkt >= nP_Id ) GrowId(); pP_Id[ nP_IdAkt ] = ( ( UINT16 ) rStack.Get() ) - 1; nP_IdAkt++; return *this; } inline void TokenPool::operator >>( TokenStack& rStack ) { TokenId nId; *this >> nId; rStack << nId; } inline const TokenId TokenPool::Store( void ) { TokenId nId; *this >> nId; return nId; } inline const TokenId TokenPool::Store( const INT16 nWert ) { return Store( ( double ) nWert ); } inline const TokenId TokenPool::LastId( void ) const { return ( TokenId ) nElementAkt; // stimmt, da Ausgabe mit Offset 1! } const inline ScTokenArray* TokenPool::operator []( const TokenId nId ) { pScToken->Clear(); if( nId ) {//...nur wenn nId > 0! #ifdef DBG_UTIL nRek = 0; #endif GetElement( ( UINT16 ) nId - 1 ); } return pScToken; } inline E_TYPE TokenPool::GetType( const TokenId& rId ) const { E_TYPE nRet; UINT16 nId = (UINT16) rId - 1; if( nId < nElementAkt ) nRet = pType[ nId ] ; else nRet = T_Error; return nRet; } inline const SingleRefData* TokenPool::GetSRD( const TokenId& rId ) const { SingleRefData* pRet; UINT16 nId = (UINT16) rId - 1; if( nId < nElementAkt && pType[ nId ] == T_RefC ) pRet = ppP_RefTr[ pElement[ nId ] ]; else pRet = NULL; return pRet; } #endif INTEGRATION: CWS odff (1.12.90); FILE MERGED 2008/01/10 14:40:27 dr 1.12.90.1: import/export error codes /************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: tokstack.hxx,v $ * * $Revision: 1.13 $ * * last change: $Author: kz $ $Date: 2008-03-06 15:49:21 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _TOKSTACK_HXX #define _TOKSTACK_HXX #ifndef _INC_STRING #include <string.h> #endif #ifndef _DEBUG_HXX //autogen #include <tools/debug.hxx> #endif #ifndef SC_COMPILER_HXX #include "compiler.hxx" #endif typedef OpCode DefTokenId; // in PRODUCT version: ambiguity between OpCode (being USHORT) and UINT16 // Unfortunately a typedef is just a dumb alias and not a real type ... //typedef UINT16 TokenId; struct TokenId { UINT16 nId; TokenId() : nId( 0 ) {} TokenId( UINT16 n ) : nId( n ) {} TokenId( const TokenId& r ) : nId( r.nId ) {} inline TokenId& operator =( const TokenId& r ) { nId = r.nId; return *this; } inline TokenId& operator =( UINT16 n ) { nId = n; return *this; } inline operator UINT16&() { return nId; } inline operator const UINT16&() const { return nId; } inline BOOL operator <( UINT16 n ) const { return nId < n; } inline BOOL operator >( UINT16 n ) const { return nId > n; } inline BOOL operator <=( UINT16 n ) const { return nId <= n; } inline BOOL operator >=( UINT16 n ) const { return nId >= n; } inline BOOL operator ==( UINT16 n ) const { return nId == n; } inline BOOL operator !=( UINT16 n ) const { return nId != n; } }; //------------------------------------------------------------------------ struct ComplRefData; class TokenStack; class ScToken; enum E_TYPE { T_Id, // Id-Folge T_Str, // String T_D, // Double T_Err, // Error code T_RefC, // Cell Reference T_RefA, // Area Reference T_RN, // Range Name T_Ext, // irgendwas Unbekanntes mit Funktionsnamen T_Nlf, // token for natural language formula T_Matrix, // token for inline arrays T_Error // fuer Abfrage im Fehlerfall }; class TokenPool { // !ACHTUNG!: externe Id-Basis ist 1, interne 0! // Ausgabe Id = 0 -> Fehlerfall private: String** ppP_Str; // Pool fuer Strings UINT16 nP_Str; // ...mit Groesse UINT16 nP_StrAkt; // ...und Schreibmarke double* pP_Dbl; // Pool fuer Doubles UINT16 nP_Dbl; UINT16 nP_DblAkt; USHORT* pP_Err; // Pool for error codes UINT16 nP_Err; UINT16 nP_ErrAkt; SingleRefData** ppP_RefTr; // Pool fuer Referenzen UINT16 nP_RefTr; UINT16 nP_RefTrAkt; UINT16* pP_Id; // Pool fuer Id-Folgen UINT16 nP_Id; UINT16 nP_IdAkt; UINT16 nP_IdLast; // letzter Folgen-Beginn struct EXTCONT { DefTokenId eId; String aText; EXTCONT( const DefTokenId e, const String& r ) : eId( e ), aText( r ){} }; EXTCONT** ppP_Ext; UINT16 nP_Ext; UINT16 nP_ExtAkt; struct NLFCONT { SingleRefData aRef; NLFCONT( const SingleRefData& r ) : aRef( r ) {} }; NLFCONT** ppP_Nlf; UINT16 nP_Nlf; UINT16 nP_NlfAkt; ScMatrix** ppP_Matrix; // Pool fuer Matricies UINT16 nP_Matrix; UINT16 nP_MatrixAkt; UINT16* pElement; // Array mit Indizes fuer Elemente E_TYPE* pType; // ...mit Typ-Info UINT16* pSize; // ...mit Laengenangabe (Anz. UINT16) UINT16 nElement; UINT16 nElementAkt; static const UINT16 nScTokenOff;// Offset fuer SC-Token #ifdef DBG_UTIL UINT16 nRek; // Rekursionszaehler #endif ScTokenArray* pScToken; // Tokenbastler void GrowString( void ); void GrowDouble( void ); void GrowError( void ); void GrowTripel( void ); void GrowId( void ); void GrowElement( void ); void GrowExt( void ); void GrowNlf( void ); void GrowMatrix( void ); void GetElement( const UINT16 nId ); void GetElementRek( const UINT16 nId ); public: TokenPool( void ); ~TokenPool(); inline TokenPool& operator <<( const TokenId nId ); inline TokenPool& operator <<( const DefTokenId eId ); inline TokenPool& operator <<( TokenStack& rStack ); void operator >>( TokenId& rId ); inline void operator >>( TokenStack& rStack ); inline const TokenId Store( void ); const TokenId Store( const double& rDouble ); const TokenId StoreError( USHORT nError ); // nur fuer Range-Names const TokenId Store( const UINT16 nIndex ); inline const TokenId Store( const INT16 nWert ); const TokenId Store( const String& rString ); const TokenId Store( const SingleRefData& rTr ); const TokenId Store( const ComplRefData& rTr ); const TokenId Store( const DefTokenId eId, const String& rName ); // 4 externals (e.g. AddIns, Makros...) const TokenId StoreNlf( const SingleRefData& rTr ); const TokenId StoreMatrix( SCSIZE nC, SCSIZE nR ); inline const TokenId LastId( void ) const; inline const ScTokenArray* operator []( const TokenId nId ); void Reset( void ); inline E_TYPE GetType( const TokenId& nId ) const; inline const SingleRefData* GetSRD( const TokenId& nId ) const; BOOL IsSingleOp( const TokenId& nId, const DefTokenId eId ) const; const String* GetExternal( const TokenId& nId ) const; const String* GetString( const TokenId& nId ) const; ScMatrix* GetMatrix( unsigned int n ) const; }; class TokenStack // Stack fuer Token-Ids: Id 0 sollte reserviert bleiben als // fehlerhafte Id, da z.B. Get() im Fehlerfall 0 liefert { private: TokenId* pStack; // Stack als Array UINT16 nPos; // Schreibmarke UINT16 nSize; // Erster Index ausserhalb des Stacks public: TokenStack( UINT16 nNewSize = 1024 ); ~TokenStack(); inline TokenStack& operator <<( const TokenId nNewId ); inline void operator >>( TokenId &rId ); inline void Reset( void ); inline bool HasMoreTokens() const { return nPos > 0; } inline const TokenId Get( void ); }; inline const TokenId TokenStack::Get( void ) { DBG_ASSERT( nPos > 0, "*TokenStack::Get(): Leer ist leer, ist leer, ist leer, ist..." ); TokenId nRet; if( nPos == 0 ) nRet = 0; else { nPos--; nRet = pStack[ nPos ]; } return nRet; } inline TokenStack &TokenStack::operator <<( const TokenId nNewId ) {// Element auf Stack DBG_ASSERT( nPos < nSize, "*TokenStack::<<(): Stackueberlauf" ); if( nPos < nSize ) { pStack[ nPos ] = nNewId; nPos++; } return *this; } inline void TokenStack::operator >>( TokenId& rId ) {// Element von Stack DBG_ASSERT( nPos > 0, "*TokenStack::>>(): Leer ist leer, ist leer, ist leer, ..." ); if( nPos > 0 ) { nPos--; rId = pStack[ nPos ]; } } inline void TokenStack::Reset( void ) { nPos = 0; } inline TokenPool& TokenPool::operator <<( const TokenId nId ) { // POST: nId's werden hintereinander im Pool unter einer neuen Id // abgelegt. Vorgang wird mit >> oder Store() abgeschlossen // nId -> ( UINT16 ) nId - 1; DBG_ASSERT( ( UINT16 ) nId < nScTokenOff, "-TokenPool::operator <<: TokenId im DefToken-Bereich!" ); if( nP_IdAkt >= nP_Id ) GrowId(); pP_Id[ nP_IdAkt ] = ( ( UINT16 ) nId ) - 1; nP_IdAkt++; return *this; } inline TokenPool& TokenPool::operator <<( const DefTokenId eId ) { DBG_ASSERT( ( UINT32 ) eId + nScTokenOff < 0xFFFF, "-TokenPool::operator<<: enmum zu gross!" ); if( nP_IdAkt >= nP_Id ) GrowId(); pP_Id[ nP_IdAkt ] = ( ( UINT16 ) eId ) + nScTokenOff; nP_IdAkt++; return *this; } inline TokenPool& TokenPool::operator <<( TokenStack& rStack ) { if( nP_IdAkt >= nP_Id ) GrowId(); pP_Id[ nP_IdAkt ] = ( ( UINT16 ) rStack.Get() ) - 1; nP_IdAkt++; return *this; } inline void TokenPool::operator >>( TokenStack& rStack ) { TokenId nId; *this >> nId; rStack << nId; } inline const TokenId TokenPool::Store( void ) { TokenId nId; *this >> nId; return nId; } inline const TokenId TokenPool::Store( const INT16 nWert ) { return Store( ( double ) nWert ); } inline const TokenId TokenPool::LastId( void ) const { return ( TokenId ) nElementAkt; // stimmt, da Ausgabe mit Offset 1! } const inline ScTokenArray* TokenPool::operator []( const TokenId nId ) { pScToken->Clear(); if( nId ) {//...nur wenn nId > 0! #ifdef DBG_UTIL nRek = 0; #endif GetElement( ( UINT16 ) nId - 1 ); } return pScToken; } inline E_TYPE TokenPool::GetType( const TokenId& rId ) const { E_TYPE nRet; UINT16 nId = (UINT16) rId - 1; if( nId < nElementAkt ) nRet = pType[ nId ] ; else nRet = T_Error; return nRet; } inline const SingleRefData* TokenPool::GetSRD( const TokenId& rId ) const { SingleRefData* pRet; UINT16 nId = (UINT16) rId - 1; if( nId < nElementAkt && pType[ nId ] == T_RefC ) pRet = ppP_RefTr[ pElement[ nId ] ]; else pRet = NULL; return pRet; } #endif
/************************************************************************* * * $RCSfile: xmlannoi.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2004-07-13 07:47:42 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef SC_XMLANNOI_HXX #define SC_XMLANNOI_HXX #ifndef _XMLOFF_XMLICTXT_HXX #include <xmloff/xmlictxt.hxx> #endif #ifndef _XMLOFF_XMLIMP_HXX #include <xmloff/xmlimp.hxx> #endif #ifndef _RTL_USTRBUF_HXX_ #include <rtl/ustrbuf.hxx> #endif class ScXMLImport; class ScXMLTableRowCellContext; class ScXMLAnnotationContext : public SvXMLImportContext { rtl::OUStringBuffer sOUText; rtl::OUStringBuffer sAuthorBuffer; rtl::OUStringBuffer sCreateDateBuffer; rtl::OUStringBuffer sCreateDateStringBuffer; sal_Int32 nParagraphCount; sal_Bool bDisplay : 1; sal_Bool bHasTextP : 1; ScXMLTableRowCellContext* pCellContext; const ScXMLImport& GetScImport() const { return (const ScXMLImport&)GetImport(); } ScXMLImport& GetScImport() { return (ScXMLImport&)GetImport(); } public: ScXMLAnnotationContext( ScXMLImport& rImport, USHORT nPrfx, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList, ScXMLTableRowCellContext* pCellContext); virtual ~ScXMLAnnotationContext(); virtual SvXMLImportContext *CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLocalName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList ); virtual void Characters( const ::rtl::OUString& rChars ); virtual void EndElement(); }; #endif INTEGRATION: CWS dr12 (1.4.306); FILE MERGED 2004/08/09 13:44:36 sab 1.4.306.3: #i21253#; make old notes work 2004/07/27 01:44:10 sab 1.4.306.2: RESYNC: (1.4-1.5); FILE MERGED 2004/07/23 20:58:26 sab 1.4.306.1: #i21253#; add formatted notes /************************************************************************* * * $RCSfile: xmlannoi.hxx,v $ * * $Revision: 1.6 $ * * last change: $Author: hr $ $Date: 2004-09-08 13:50:33 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef SC_XMLANNOI_HXX #define SC_XMLANNOI_HXX #ifndef _XMLOFF_XMLICTXT_HXX #include <xmloff/xmlictxt.hxx> #endif #ifndef _XMLOFF_XMLIMP_HXX #include <xmloff/xmlimp.hxx> #endif #ifndef _RTL_USTRBUF_HXX_ #include <rtl/ustrbuf.hxx> #endif #ifndef _COM_SUN_STAR_DRAWING_XSHAPE_HPP_ #include <com/sun/star/drawing/XShape.hpp> #endif #ifndef _COM_SUN_STAR_DRAWING_XSHAPES_HPP_ #include <com/sun/star/drawing/XShapes.hpp> #endif class ScXMLImport; class ScXMLTableRowCellContext; class ScXMLAnnotationContext : public SvXMLImportContext { rtl::OUStringBuffer sOUText; rtl::OUStringBuffer sAuthorBuffer; rtl::OUStringBuffer sCreateDateBuffer; rtl::OUStringBuffer sCreateDateStringBuffer; sal_Int32 nParagraphCount; sal_Bool bDisplay; sal_Bool bHasTextP; sal_Bool bHasPos; ScXMLTableRowCellContext* pCellContext; SvXMLImportContext* pShapeContext; com::sun::star::uno::Reference< com::sun::star::drawing::XShape > xShape; com::sun::star::uno::Reference< com::sun::star::drawing::XShapes > xShapes; const ScXMLImport& GetScImport() const { return (const ScXMLImport&)GetImport(); } ScXMLImport& GetScImport() { return (ScXMLImport&)GetImport(); } public: ScXMLAnnotationContext( ScXMLImport& rImport, USHORT nPrfx, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList, ScXMLTableRowCellContext* pCellContext); virtual ~ScXMLAnnotationContext(); virtual SvXMLImportContext *CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLocalName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList ); virtual void StartElement(const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList); virtual void Characters( const ::rtl::OUString& rChars ); virtual void EndElement(); void SetShape(const com::sun::star::uno::Reference< com::sun::star::drawing::XShape >& xTempShape, const com::sun::star::uno::Reference< com::sun::star::drawing::XShapes >& xTempShapes) { xShape.set(xTempShape); xShapes.set(xTempShapes); } }; #endif
#ifndef DUNE_STUFF_FUNCTION_CHECKERBOARD_HH #define DUNE_STUFF_FUNCTION_CHECKERBOARD_HH #include <vector> #include <dune/common/exceptions.hh> #include <dune/common/static_assert.hh> #include <dune/stuff/common/parameter/tree.hh> #include <dune/stuff/common/color.hh> #include "interface.hh" namespace Dune { namespace Stuff { // forward, to allow for specialization template< class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDim > class FunctionCheckerboard; template< class DomainFieldImp, int domainDim, class RangeFieldImp > class FunctionCheckerboard< DomainFieldImp, domainDim, RangeFieldImp, 1 > : public FunctionInterface< DomainFieldImp, domainDim, RangeFieldImp, 1 > { public: typedef FunctionCheckerboard< DomainFieldImp, domainDim, RangeFieldImp, 1 > ThisType; typedef FunctionInterface< DomainFieldImp, domainDim, RangeFieldImp, 1 > BaseType; typedef typename BaseType::DomainFieldType DomainFieldType; static const int dimDomain = BaseType::dimDomain; typedef typename BaseType::DomainType DomainType; typedef typename BaseType::RangeFieldType RangeFieldType; static const int dimRange = BaseType::dimRange; typedef typename BaseType::RangeType RangeType; static const std::string id() { return BaseType::id() + ".checkerboard"; } FunctionCheckerboard(const DomainType _lowerLeft, const DomainType _upperRight, const std::vector< size_t > _numElements, const std::vector< RangeFieldType > _values, const std::string _name = id()) : lowerLeft_(_lowerLeft) , upperRight_(_upperRight) , numElements_(_numElements) , values_(_values) , name_(_name) { // checks dune_static_assert((dimDomain > 0), "Really?"); dune_static_assert((dimDomain <= 3), "Not implemented!"); dune_static_assert((dimRange > 0), "Really?"); // get total number of subdomains size_t totalSubdomains = 1; for (int dd = 0; dd < dimDomain; ++dd) { totalSubdomains *= numElements_[dd]; } if (values_.size() < totalSubdomains) DUNE_THROW(Dune::InvalidStateException, "\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " please provide at least as many '_values' as subdomains given by '_numElements'!"); } // FunctionCheckerboard(...) static Dune::ParameterTree createSampleDescription(const std::string subName = "") { Dune::ParameterTree description; description["lowerLeft"] = "[0.0; 0.0; 0.0]"; description["upperRight"] = "[1.0; 1.0; 1.0]"; description["numElements"] = "[2; 2; 2]"; description["values"] = "[1.0; 2.0; 3.0; 4.0; 5.0; 6.0; 7.0; 8.0]"; description["name"] = id(); if (subName.empty()) return description; else { Dune::Stuff::Common::ExtendedParameterTree extendedDescription; extendedDescription.add(description, subName); return extendedDescription; } } // ... createSampleDescription(...) static ThisType* create(const DSC::ExtendedParameterTree description) { // get data const std::vector< DomainFieldType > lowerLefts = description.getVector("lowerLeft", DomainFieldType(0), dimDomain); const std::vector< DomainFieldType > upperRights = description.getVector("upperRight", DomainFieldType(1), dimDomain); const std::vector< size_t > numElements = description.getVector("numElements", size_t(1), dimDomain); size_t subdomains = 1; for (size_t ii = 0; ii < numElements.size(); ++ii) subdomains *= numElements[ii]; const std::vector< RangeFieldType > values = description.getVector("values", RangeFieldType(1), subdomains); // convert and leave the checks to the constructor DomainType lowerLeft; DomainType upperRight; for (int dd = 0; dd < dimDomain; ++dd) { lowerLeft[dd] = lowerLefts[dd]; upperRight[dd] = upperRights[dd]; } // create and return return new ThisType(lowerLeft, upperRight, numElements, values); } // ... create(...) const DomainType& lowerLeft() const { return lowerLeft_; } const DomainType& upperRight() const { return upperRight_; } const std::vector< size_t >& numElements() const { return numElements_; } const std::vector< RangeFieldType >& values() const { return values_; } virtual std::string name() const { return name_; } virtual int order() const { return 0; } virtual void evaluate(const DomainType& x, RangeType& ret) const { // decide on the subdomain the point x belongs to std::vector< size_t > whichPartition; for (int d = 0; d < dimDomain; ++d) { whichPartition.push_back(std::floor(numElements_[d]*((x[d] - lowerLeft_[d])/(upperRight_[d] - lowerLeft_[d])))); } size_t subdomain = 0; if (dimDomain == 1) subdomain = whichPartition[0]; else if (dimDomain == 2) subdomain = whichPartition[0] + whichPartition[1]*numElements_[0]; else // has to be 3, see checks in constructor subdomain = whichPartition[0] + whichPartition[1]*numElements_[0] + whichPartition[2]*numElements_[1]*numElements_[0]; // return the component that belongs to the subdomain of x ret = values_[subdomain]; } // virtual void evaluate(const DomainType& x, RangeType& ret) const private: DomainType lowerLeft_; DomainType upperRight_; std::vector< size_t > numElements_; std::vector< RangeFieldType > values_; std::string name_; }; // class FunctionCheckerboard } // namespace Stuff } // namespace Dune #endif // DUNE_STUFF_FUNCTION_CHECKERBOARD_HH [function.checkerboard] fixed possible overflow #ifndef DUNE_STUFF_FUNCTION_CHECKERBOARD_HH #define DUNE_STUFF_FUNCTION_CHECKERBOARD_HH #include <vector> #include <dune/common/exceptions.hh> #include <dune/common/static_assert.hh> #include <dune/stuff/common/parameter/tree.hh> #include <dune/stuff/common/color.hh> #include "interface.hh" namespace Dune { namespace Stuff { // forward, to allow for specialization template< class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDim > class FunctionCheckerboard; template< class DomainFieldImp, int domainDim, class RangeFieldImp > class FunctionCheckerboard< DomainFieldImp, domainDim, RangeFieldImp, 1 > : public FunctionInterface< DomainFieldImp, domainDim, RangeFieldImp, 1 > { public: typedef FunctionCheckerboard< DomainFieldImp, domainDim, RangeFieldImp, 1 > ThisType; typedef FunctionInterface< DomainFieldImp, domainDim, RangeFieldImp, 1 > BaseType; typedef typename BaseType::DomainFieldType DomainFieldType; static const int dimDomain = BaseType::dimDomain; typedef typename BaseType::DomainType DomainType; typedef typename BaseType::RangeFieldType RangeFieldType; static const int dimRange = BaseType::dimRange; typedef typename BaseType::RangeType RangeType; static const std::string id() { return BaseType::id() + ".checkerboard"; } FunctionCheckerboard(const DomainType _lowerLeft, const DomainType _upperRight, const std::vector< size_t > _numElements, const std::vector< RangeFieldType > _values, const std::string _name = id()) : lowerLeft_(_lowerLeft) , upperRight_(_upperRight) , numElements_(_numElements) , values_(_values) , name_(_name) { // checks dune_static_assert((dimDomain > 0), "Really?"); dune_static_assert((dimDomain <= 3), "Not implemented!"); dune_static_assert((dimRange > 0), "Really?"); // get total number of subdomains size_t totalSubdomains = 1; for (int dd = 0; dd < dimDomain; ++dd) { totalSubdomains *= numElements_[dd]; } if (values_.size() < totalSubdomains) DUNE_THROW(Dune::InvalidStateException, "\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " please provide at least as many '_values' as subdomains given by '_numElements'!"); } // FunctionCheckerboard(...) static Dune::ParameterTree createSampleDescription(const std::string subName = "") { Dune::ParameterTree description; description["lowerLeft"] = "[0.0; 0.0; 0.0]"; description["upperRight"] = "[1.0; 1.0; 1.0]"; description["numElements"] = "[2; 2; 2]"; description["values"] = "[1.0; 2.0; 3.0; 4.0; 5.0; 6.0; 7.0; 8.0]"; description["name"] = id(); if (subName.empty()) return description; else { Dune::Stuff::Common::ExtendedParameterTree extendedDescription; extendedDescription.add(description, subName); return extendedDescription; } } // ... createSampleDescription(...) static ThisType* create(const DSC::ExtendedParameterTree description) { // get data const std::vector< DomainFieldType > lowerLefts = description.getVector("lowerLeft", DomainFieldType(0), dimDomain); const std::vector< DomainFieldType > upperRights = description.getVector("upperRight", DomainFieldType(1), dimDomain); const std::vector< size_t > numElements = description.getVector("numElements", size_t(1), dimDomain); size_t subdomains = 1; for (size_t ii = 0; ii < numElements.size(); ++ii) subdomains *= numElements[ii]; const std::vector< RangeFieldType > values = description.getVector("values", RangeFieldType(1), subdomains); // convert and leave the checks to the constructor DomainType lowerLeft; DomainType upperRight; for (int dd = 0; dd < dimDomain; ++dd) { lowerLeft[dd] = lowerLefts[dd]; upperRight[dd] = upperRights[dd]; } // create and return return new ThisType(lowerLeft, upperRight, numElements, values); } // ... create(...) const DomainType& lowerLeft() const { return lowerLeft_; } const DomainType& upperRight() const { return upperRight_; } const std::vector< size_t >& numElements() const { return numElements_; } const std::vector< RangeFieldType >& values() const { return values_; } virtual std::string name() const { return name_; } virtual int order() const { return 0; } /** * \todo put this stuff in an expression, that is expanded at compile time (dimension dependent) */ virtual void evaluate(const DomainType& x, RangeType& ret) const { // decide on the subdomain the point x belongs to std::vector< size_t > whichPartition; for (int d = 0; d < dimDomain; ++d) { // for points that are on upperRight_[d], this selects one partition too much // so we need to cap this whichPartition.push_back(std::min(size_t(std::floor(numElements_[d]*((x[d] - lowerLeft_[d])/(upperRight_[d] - lowerLeft_[d])))), numElements_[d] - 1)); } size_t subdomain = 0; if (dimDomain == 1) subdomain = whichPartition[0]; else if (dimDomain == 2) subdomain = whichPartition[0] + whichPartition[1]*numElements_[0]; else // has to be 3, see checks in constructor subdomain = whichPartition[0] + whichPartition[1]*numElements_[0] + whichPartition[2]*numElements_[1]*numElements_[0]; // return the component that belongs to the subdomain of x ret = values_[subdomain]; } // virtual void evaluate(const DomainType& x, RangeType& ret) const private: DomainType lowerLeft_; DomainType upperRight_; std::vector< size_t > numElements_; std::vector< RangeFieldType > values_; std::string name_; }; // class FunctionCheckerboard } // namespace Stuff } // namespace Dune #endif // DUNE_STUFF_FUNCTION_CHECKERBOARD_HH
/************************************************************************* * * $RCSfile: xmlcelli.cxx,v $ * * $Revision: 1.47 $ * * last change: $Author: sab $ $Date: 2001-05-18 13:57:25 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifdef PCH #include "filt_pch.hxx" #endif #pragma hdrstop // INCLUDE --------------------------------------------------------------- #include "xmlcelli.hxx" #include "xmlimprt.hxx" #include "xmltabi.hxx" #include "xmlstyli.hxx" #include "xmlannoi.hxx" #include "global.hxx" #include "document.hxx" #include "cellsuno.hxx" #include "docuno.hxx" #ifndef _SC_XMLTABLESHAPEIMPORTHELPER_HXX #include "XMLTableShapeImportHelper.hxx" #endif #ifndef _SC_XMLTEXTPCONTEXT_HXX #include "XMLTextPContext.hxx" #endif #ifndef _SC_XMLSTYLESIMPORTHELPER_HXX #include "XMLStylesImportHelper.hxx" #endif #ifndef SC_UNONAMES_HXX #include "unonames.hxx" #endif // core implementation #ifndef SC_AREALINK_HXX #include "arealink.hxx" #endif // core implementation #ifndef _SVXLINKMGR_HXX #include <svx/linkmgr.hxx> #endif #ifndef SC_CONVUNO_HXX #include "convuno.hxx" #endif #ifndef _SC_XMLCONVERTER_HXX #include "XMLConverter.hxx" #endif #include <xmloff/xmltkmap.hxx> #include <xmloff/xmlkywd.hxx> #include <xmloff/nmspmap.hxx> #include <xmloff/xmluconv.hxx> #include <xmloff/families.hxx> #ifndef XMLOFF_NUMEHELP_HXX #include <xmloff/numehelp.hxx> #endif #include <svtools/zforlist.hxx> #include <com/sun/star/frame/XModel.hpp> #include <com/sun/star/text/XText.hpp> #include <com/sun/star/sheet/XSpreadsheets.hpp> #include <com/sun/star/sheet/XSpreadsheet.hpp> #include <com/sun/star/sheet/XCellRangeAddressable.hpp> #ifndef _COM_SUN_STAR_UTIL_XMERGEABLE_HPP_ #include <com/sun/star/util/XMergeable.hpp> #endif #ifndef _COM_SUN_STAR_SHEET_XSHEETCONDITION_HPP_ #include <com/sun/star/sheet/XSheetCondition.hpp> #endif #ifndef _COM_SUN_STAR_TABLE_XCELLRANGE_HPP_ #include <com/sun/star/table/XCellRange.hpp> #endif #ifndef _COM_SUN_STAR_TABLE_CELLADDRESS_HPP_ #include <com/sun/star/table/CellAddress.hpp> #endif #ifndef _COM_SUN_STAR_UTIL_NUMBERFORMAT_HPP_ #include <com/sun/star/util/NumberFormat.hpp> #endif #ifndef _COM_SUN_STAR_UTIL_XNUMBERFORMATSSUPPLIER_HPP_ #include <com/sun/star/util/XNumberFormatsSupplier.hpp> #endif #ifndef _COM_SUN_STAR_UTIL_XNUMBERFORMATTYPES_HPP_ #include <com/sun/star/util/XNumberFormatTypes.hpp> #endif #ifndef _COM_SUN_STAR_UTIL_DATE_HPP_ #include <com/sun/star/util/Date.hpp> #endif #ifndef _COM_SUN_STAR_LANG_LOCALE_HPP_ #include <com/sun/star/lang/Locale.hpp> #endif #ifndef _COM_SUN_STAR_text_CONTROLCHARACTER_HPP_ #include <com/sun/star/text/ControlCharacter.hpp> #endif #ifndef _RTL_USTRBUF_HXX_ #include <rtl/ustrbuf.hxx> #endif #ifndef _DATE_HXX #include <tools/date.hxx> #endif #ifndef _TOOLS_SOLMATH_HXX #include <tools/solmath.hxx> #endif #ifndef _ISOLANG_HXX #include <tools/isolang.hxx> #endif #ifndef _COMPHELPER_EXTRACT_HXX_ #include <comphelper/extract.hxx> #endif #define SC_CURRENCYSYMBOL "CurrencySymbol" using namespace com::sun::star; //------------------------------------------------------------------ ScXMLTableRowCellContext::ScXMLTableRowCellContext( ScXMLImport& rImport, USHORT nPrfx, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList, const sal_Bool bTempIsCovered, const sal_Int32 nTempRepeatedRows ) : SvXMLImportContext( rImport, nPrfx, rLName ), bIsMerged(sal_False), bIsMatrix(sal_False), bIsFormula(sal_False), bHasSubTable(sal_False), bIsCovered(bTempIsCovered), bHasAnnotation(sal_False), nRepeatedRows(nTempRepeatedRows), bIsEmpty(sal_True), bHasTextImport(sal_False), bIsFirstTextImport(sal_False), aDetectiveObjVec(), aCellRangeSource(), nCellType(util::NumberFormat::TEXT), nMergedCols(1), nMergedRows(1), nCellsRepeated(1), fValue(0.0) { GetScImport().SetRemoveLastChar(sal_False); GetScImport().GetTables().AddColumn(bTempIsCovered); sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0; const SvXMLTokenMap& rAttrTokenMap = GetScImport().GetTableRowCellAttrTokenMap(); for( sal_Int16 i=0; i < nAttrCount; i++ ) { rtl::OUString sAttrName = xAttrList->getNameByIndex( i ); rtl::OUString aLocalName; sal_uInt16 nPrefix = GetScImport().GetNamespaceMap().GetKeyByAttrName( sAttrName, &aLocalName ); rtl::OUString sValue = xAttrList->getValueByIndex( i ); switch( rAttrTokenMap.Get( nPrefix, aLocalName ) ) { case XML_TOK_TABLE_ROW_CELL_ATTR_STYLE_NAME: { sStyleName = sValue; } break; case XML_TOK_TABLE_ROW_CELL_ATTR_CONTENT_VALIDATION_NAME: { sContentValidationName = sValue; } break; case XML_TOK_TABLE_ROW_CELL_ATTR_SPANNED_ROWS: { bIsMerged = sal_True; nMergedRows = sValue.toInt32(); } break; case XML_TOK_TABLE_ROW_CELL_ATTR_SPANNED_COLS: { bIsMerged = sal_True; nMergedCols = sValue.toInt32(); } break; case XML_TOK_TABLE_ROW_CELL_ATTR_REPEATED: { nCellsRepeated = sValue.toInt32(); } break; case XML_TOK_TABLE_ROW_CELL_ATTR_VALUE_TYPE: { nCellType = GetCellType(sValue); bIsEmpty = sal_False; } break; case XML_TOK_TABLE_ROW_CELL_ATTR_VALUE: { GetScImport().GetMM100UnitConverter().convertDouble(fValue, sValue); bIsEmpty = sal_False; } break; case XML_TOK_TABLE_ROW_CELL_ATTR_DATE_VALUE: { sOUDateValue = sValue; bIsEmpty = sal_False; } break; case XML_TOK_TABLE_ROW_CELL_ATTR_TIME_VALUE: { sOUTimeValue = sValue; bIsEmpty = sal_False; } break; case XML_TOK_TABLE_ROW_CELL_ATTR_BOOLEAN_VALUE: { sOUBooleanValue = sValue; bIsEmpty = sal_False; } break; case XML_TOK_TABLE_ROW_CELL_ATTR_STRING_VALUE: { sOUTextValue = sValue; bIsEmpty = sal_False; } break; case XML_TOK_TABLE_ROW_CELL_ATTR_FORMULA: { bIsFormula = sal_True; sOUFormula = sValue; } break; case XML_TOK_TABLE_ROW_CELL_ATTR_CURRENCY : { sCurrencySymbol = sValue; } break; case XML_TOK_TABLE_ROW_CELL_ATTR_SPANNED_MATRIX_COLS : { bIsMatrix = sal_True; nMatrixCols = sValue.toInt32(); } break; case XML_TOK_TABLE_ROW_CELL_ATTR_SPANNED_MATRIX_ROWS : { bIsMatrix = sal_True; nMatrixRows = sValue.toInt32(); } break; } } GetScImport().GetStylesImportHelper()->SetAttributes(sStyleName, sCurrencySymbol, nCellType); } sal_Int16 ScXMLTableRowCellContext::GetCellType(const rtl::OUString& sOUValue) const { if (sOUValue.equals(GetScImport().sSC_float)) return util::NumberFormat::NUMBER; else if (sOUValue.equals(GetScImport().sSC_string)) return util::NumberFormat::TEXT; else if (sOUValue.equals(GetScImport().sSC_time)) return util::NumberFormat::TIME; else if (sOUValue.equals(GetScImport().sSC_date)) return util::NumberFormat::DATETIME; else if (sOUValue.equals(GetScImport().sSC_percentage)) return util::NumberFormat::PERCENT; else if (sOUValue.equals(GetScImport().sSC_currency)) return util::NumberFormat::CURRENCY; else if (sOUValue.equals(GetScImport().sSC_boolean)) return util::NumberFormat::LOGICAL; else return 0; } ScXMLTableRowCellContext::~ScXMLTableRowCellContext() { } void ScXMLTableRowCellContext::SetCursorOnTextImport() { com::sun::star::table::CellAddress aCellPos = GetScImport().GetTables().GetRealCellPos(); uno::Reference<table::XCellRange> xCellRange = GetScImport().GetTables().GetCurrentXCellRange(); if (xCellRange.is()) { if (aCellPos.Column > MAXCOL) aCellPos.Column = MAXCOL; if (aCellPos.Row > MAXROW) aCellPos.Row = MAXROW; uno::Reference <table::XCell> xCell = xCellRange->getCellByPosition(aCellPos.Column, aCellPos.Row); if (xCell.is()) { uno::Reference<text::XText> xText(xCell, uno::UNO_QUERY); if (xText.is()) { uno::Reference<text::XTextCursor> xTextCursor = xText->createTextCursor(); if (xTextCursor.is()) GetScImport().GetTextImport()->SetCursor(xTextCursor); } } } } SvXMLImportContext *ScXMLTableRowCellContext::CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList ) { SvXMLImportContext *pContext = 0; const SvXMLTokenMap& rTokenMap = GetScImport().GetTableRowCellElemTokenMap(); sal_Bool bHeader(sal_False); sal_Bool bTextP(sal_False); switch( rTokenMap.Get( nPrefix, rLName ) ) { case XML_TOK_TABLE_ROW_CELL_P: { bIsEmpty = sal_False; bTextP = sal_True; if (nCellType == util::NumberFormat::TEXT) { ScXMLImport& rXMLImport = GetScImport(); if (!bHasTextImport) { bIsFirstTextImport = sal_True; bHasTextImport = sal_True; pContext = new ScXMLTextPContext(GetScImport(), nPrefix, rLName, xAttrList, this); } else { if (bIsFirstTextImport && !GetScImport().GetRemoveLastChar()) { SetCursorOnTextImport(); GetScImport().SetRemoveLastChar(sal_True); uno::Reference<text::XTextCursor> xTextCursor = GetScImport().GetTextImport()->GetCursor(); xTextCursor->setString(sOUTextContent); sOUTextContent = sEmpty; uno::Reference < text::XText > xText (xTextCursor->getText()); uno::Reference < text::XTextRange > xTextRange (xTextCursor, uno::UNO_QUERY); if (xText.is() && xTextRange.is()) xText->insertControlCharacter(xTextRange, text::ControlCharacter::PARAGRAPH_BREAK, sal_False); } pContext = rXMLImport.GetTextImport()->CreateTextChildContext( GetScImport(), nPrefix, rLName, xAttrList); bIsFirstTextImport = sal_False; } } } break; case XML_TOK_TABLE_ROW_CELL_SUBTABLE: { bHasSubTable = sal_True; pContext = new ScXMLTableContext( GetScImport() , nPrefix, rLName, xAttrList, sal_True, nMergedCols); nMergedCols = 1; bIsMerged = sal_False; } break; case XML_TOK_TABLE_ROW_CELL_ANNOTATION: { bIsEmpty = sal_False; pContext = new ScXMLAnnotationContext( GetScImport(), nPrefix, rLName, xAttrList, this); } break; case XML_TOK_TABLE_ROW_CELL_DETECTIVE: { bIsEmpty = sal_False; pContext = new ScXMLDetectiveContext( GetScImport(), nPrefix, rLName, aDetectiveObjVec ); } break; case XML_TOK_TABLE_ROW_CELL_CELL_RANGE_SOURCE: { bIsEmpty = sal_False; pContext = new ScXMLCellRangeSourceContext( GetScImport(), nPrefix, rLName, xAttrList, aCellRangeSource ); } break; } if (!pContext && !bTextP) { ScXMLImport& rXMLImport = GetScImport(); com::sun::star::table::CellAddress aCellPos = rXMLImport.GetTables().GetRealCellPos(); uno::Reference<drawing::XShapes> xShapes (rXMLImport.GetTables().GetCurrentXShapes()); if (xShapes.is()) { if (aCellPos.Column > MAXCOL) aCellPos.Column = MAXCOL; if (aCellPos.Row > MAXROW) aCellPos.Row = MAXROW; ScDocument* pDoc = GetScImport().GetDocument(); XMLTableShapeImportHelper* pTableShapeImport = (XMLTableShapeImportHelper*)rXMLImport.GetShapeImport().get(); pTableShapeImport->SetOnTable(sal_False); pTableShapeImport->SetCell(aCellPos); pContext = rXMLImport.GetShapeImport()->CreateGroupChildContext( rXMLImport, nPrefix, rLName, xAttrList, xShapes); if (pContext) bIsEmpty = sal_False; } } if( !pContext ) pContext = new SvXMLImportContext( GetImport(), nPrefix, rLName ); return pContext; } sal_Bool ScXMLTableRowCellContext::IsMerged (const uno::Reference <table::XCellRange>& xCellRange, const sal_Int32 nCol, const sal_Int32 nRow, table::CellRangeAddress& aCellAddress) const { uno::Reference <table::XCellRange> xMergeCellRange = xCellRange->getCellRangeByPosition(nCol,nRow,nCol,nRow); uno::Reference <util::XMergeable> xMergeable (xMergeCellRange, uno::UNO_QUERY); if (xMergeable.is()) { uno::Reference<sheet::XSheetCellRange> xMergeSheetCellRange (xMergeCellRange, uno::UNO_QUERY); uno::Reference<sheet::XSpreadsheet> xTable = xMergeSheetCellRange->getSpreadsheet(); uno::Reference<sheet::XSheetCellCursor> xMergeSheetCursor = xTable->createCursorByRange(xMergeSheetCellRange); if (xMergeSheetCursor.is()) { xMergeSheetCursor->collapseToMergedArea(); uno::Reference<sheet::XCellRangeAddressable> xMergeCellAddress (xMergeSheetCursor, uno::UNO_QUERY); if (xMergeCellAddress.is()) { aCellAddress = xMergeCellAddress->getRangeAddress(); if (aCellAddress.StartColumn == nCol && aCellAddress.EndColumn == nCol && aCellAddress.StartRow == nRow && aCellAddress.EndRow == nRow) return sal_False; else return sal_True; } } } return sal_False; } void ScXMLTableRowCellContext::DoMerge(const com::sun::star::table::CellAddress& aCellPos, const sal_Int32 nCols, const sal_Int32 nRows) { uno::Reference<table::XCellRange> xCellRange = GetScImport().GetTables().GetCurrentXCellRange(); if ( xCellRange.is() ) { table::CellRangeAddress aCellAddress; if (IsMerged(xCellRange, aCellPos.Column, aCellPos.Row, aCellAddress)) { //unmerge uno::Reference <table::XCellRange> xMergeCellRange = xCellRange->getCellRangeByPosition(aCellAddress.StartColumn, aCellAddress.StartRow, aCellAddress.EndColumn, aCellAddress.EndRow); uno::Reference <util::XMergeable> xMergeable (xMergeCellRange, uno::UNO_QUERY); if (xMergeable.is()) xMergeable->merge(sal_False); } //merge uno::Reference <table::XCellRange> xMergeCellRange = xCellRange->getCellRangeByPosition(aCellAddress.StartColumn, aCellAddress.StartRow, aCellAddress.EndColumn + nCols, aCellAddress.EndRow + nRows); uno::Reference <util::XMergeable> xMergeable (xMergeCellRange, uno::UNO_QUERY); if (xMergeable.is()) xMergeable->merge(sal_True); } } void ScXMLTableRowCellContext::SetContentValidation(com::sun::star::uno::Reference<com::sun::star::beans::XPropertySet>& xPropSet) { ScMyImportValidation aValidation; if (GetScImport().GetValidation(sContentValidationName, aValidation)) { uno::Any aAny = xPropSet->getPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_VALIDAT))); uno::Reference<beans::XPropertySet> xPropertySet; if (aAny >>= xPropertySet) { if (aValidation.sErrorMessage.getLength()) { aAny <<= aValidation.sErrorMessage; xPropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_ERRMESS)), aAny); } if (aValidation.sErrorTitle.getLength()) { aAny <<= aValidation.sErrorTitle; xPropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_ERRTITLE)), aAny); } if (aValidation.sImputMessage.getLength()) { aAny <<= aValidation.sImputMessage; xPropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_INPMESS)), aAny); } if (aValidation.sImputTitle.getLength()) { aAny <<= aValidation.sImputTitle; xPropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_INPTITLE)), aAny); } aAny = ::cppu::bool2any(aValidation.bShowErrorMessage); xPropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_SHOWERR)), aAny); aAny = ::cppu::bool2any(aValidation.bShowImputMessage); xPropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_SHOWINP)), aAny); aAny <<= aValidation.aValidationType; xPropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_TYPE)), aAny); aAny = ::cppu::bool2any(aValidation.bIgnoreBlanks); xPropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_IGNOREBL)), aAny); aAny <<= aValidation.aAlertStyle; xPropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_ERRALSTY)), aAny); uno::Reference<sheet::XSheetCondition> xCondition(xPropertySet, uno::UNO_QUERY); if (xCondition.is()) { xCondition->setFormula1(aValidation.sFormula1); xCondition->setFormula2(aValidation.sFormula2); xCondition->setOperator(aValidation.aOperator); xCondition->setSourcePosition(aValidation.aBaseCellAddress); } } aAny <<= xPropertySet; xPropSet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_VALIDAT)), aAny); } } void ScXMLTableRowCellContext::SetCellProperties(const uno::Reference<table::XCellRange>& xCellRange, const table::CellAddress& aCellAddress) { if (sContentValidationName.getLength()) { ScXMLImport& rXMLImport = GetScImport(); sal_Int32 nBottom = aCellAddress.Row + nRepeatedRows - 1; sal_Int32 nRight = aCellAddress.Column + nCellsRepeated - 1; if (nBottom > MAXROW) nBottom = MAXROW; if (nRight > MAXCOL) nRight = MAXCOL; uno::Reference <table::XCellRange> xPropCellRange = xCellRange->getCellRangeByPosition(aCellAddress.Column, aCellAddress.Row, nRight, nBottom); if (xPropCellRange.is()) { uno::Reference <beans::XPropertySet> xProperties (xPropCellRange, uno::UNO_QUERY); if (xProperties.is()) SetContentValidation(xProperties); } } } void ScXMLTableRowCellContext::SetCellProperties(const uno::Reference<table::XCell>& xCell) { if (sContentValidationName.getLength()) { ScXMLImport& rXMLImport = GetScImport(); uno::Reference <beans::XPropertySet> xProperties (xCell, uno::UNO_QUERY); if (xProperties.is()) SetContentValidation(xProperties); } } void ScXMLTableRowCellContext::SetAnnotation(const uno::Reference<table::XCell>& xCell) { /*uno::Reference<sheet::XSheetAnnotationAnchor> xSheetAnnotationAnchor(xCell, uno::UNO_QUERY); if (xSheetAnnotationAnchor.is()) { uno::Reference <sheet::XSheetAnnotation> xSheetAnnotation = xSheetAnnotationAnchor->getAnnotation(); uno::Reference<text::XSimpleText> xSimpleText(xSheetAnnotation, uno::UNO_QUERY); if (xSheetAnnotation.is() && xSimpleText.is()) { xSimpleText->setString(aMyAnnotation.sText); //xSheetAnnotation->setAuthor(aMyAnnotation.sAuthor); //xSheetAnnotation->setDate(); xSheetAnnotation->setIsVisible(aMyAnnotation.bDisplay); } }*/ if( bHasAnnotation ) { uno::Reference<sheet::XCellAddressable> xCellAddressable(xCell, uno::UNO_QUERY); if (xCellAddressable.is()) { table::CellAddress aCellAddress = xCellAddressable->getCellAddress(); double fDate; GetScImport().GetMM100UnitConverter().convertDateTime(fDate, aMyAnnotation.sCreateDate); ScDocument* pDoc = GetScImport().GetDocument(); SvNumberFormatter* pNumForm = pDoc->GetFormatTable(); sal_uInt32 nfIndex = pNumForm->GetFormatIndex(NF_DATE_SYS_DDMMYYYY, LANGUAGE_SYSTEM); String sDate; Color* pColor = NULL; Color** ppColor = &pColor; pNumForm->GetOutputString(fDate, nfIndex, sDate, ppColor); ScPostIt aNote(String(aMyAnnotation.sText), sDate, String(aMyAnnotation.sAuthor)); aNote.SetShown(aMyAnnotation.bDisplay); pDoc->SetNote(static_cast<USHORT>(aCellAddress.Column), static_cast<USHORT>(aCellAddress.Row), aCellAddress.Sheet, aNote); if (aMyAnnotation.bDisplay) { uno::Reference < drawing::XShapes > xShapes (GetScImport().GetTables().GetCurrentXShapes()); // make draw page ScDetectiveFunc aDetFunc(pDoc, aCellAddress.Sheet); aDetFunc.ShowComment(static_cast<USHORT>(aCellAddress.Column), static_cast<USHORT>(aCellAddress.Row), sal_False); uno::Reference<container::XIndexAccess> xShapesIndex (xShapes, uno::UNO_QUERY); if (xShapesIndex.is()) { sal_Int32 nShapes = xShapesIndex->getCount(); uno::Reference < drawing::XShape > xShape; GetScImport().GetShapeImport()->shapeWithZIndexAdded(xShape, nShapes); } } } } } // core implementation void ScXMLTableRowCellContext::SetDetectiveObj( const table::CellAddress& rPosition ) { if( aDetectiveObjVec.size() ) { ScDetectiveFunc aDetFunc( GetScImport().GetDocument(), rPosition.Sheet ); uno::Reference < drawing::XShapes > xShapes (GetScImport().GetTables().GetCurrentXShapes()); // make draw page for( ScMyImpDetectiveObjVec::iterator aItr = aDetectiveObjVec.begin(); aItr != aDetectiveObjVec.end(); aItr++ ) { ScAddress aScAddress; ScUnoConversion::FillScAddress( aScAddress, rPosition ); aDetFunc.InsertObject( aItr->eObjType, aScAddress, aItr->aSourceRange, aItr->bHasError ); uno::Reference<container::XIndexAccess> xShapesIndex (xShapes, uno::UNO_QUERY); if (xShapesIndex.is()) { sal_Int32 nShapes = xShapesIndex->getCount(); uno::Reference < drawing::XShape > xShape; GetScImport().GetShapeImport()->shapeWithZIndexAdded(xShape, nShapes); } } } } // core implementation void ScXMLTableRowCellContext::SetCellRangeSource( const table::CellAddress& rPosition ) { if( aCellRangeSource.bHas ) { ScRange aDestRange( static_cast<USHORT>(rPosition.Column), static_cast<USHORT>(rPosition.Row), rPosition.Sheet, rPosition.Column + aCellRangeSource.nColumns - 1, rPosition.Row + aCellRangeSource.nRows - 1, rPosition.Sheet ); String sFilterName( aCellRangeSource.sFilterName ); String sSourceStr( aCellRangeSource.sSourceStr ); ScDocument* pDoc = GetScImport().GetDocument(); ScAreaLink* pLink = new ScAreaLink( pDoc->GetDocumentShell(), aCellRangeSource.sURL, sFilterName, aCellRangeSource.sFilterOptions, sSourceStr, aDestRange, aCellRangeSource.nRefresh ); SvxLinkManager* pLinkManager = pDoc->GetLinkManager(); pLinkManager->InsertFileLink( *pLink, OBJECT_CLIENT_FILE, aCellRangeSource.sURL, &sFilterName, &sSourceStr ); } } void ScXMLTableRowCellContext::EndElement() { if (bHasTextImport && GetScImport().GetRemoveLastChar()) { if (GetImport().GetTextImport()->GetCursor().is()) { //GetImport().GetTextImport()->GetCursor()->gotoEnd(sal_False); if( GetImport().GetTextImport()->GetCursor()->goLeft( 1, sal_True ) ) { OUString sEmpty; GetImport().GetTextImport()->GetText()->insertString( GetImport().GetTextImport()->GetCursorAsRange(), sEmpty, sal_True ); } } } GetScImport().GetTextImport()->ResetCursor(); if (!bHasSubTable) { ScXMLImport& rXMLImport = GetScImport(); table::CellAddress aCellPos = rXMLImport.GetTables().GetRealCellPos(); if (aCellPos.Column > 0 && nRepeatedRows > 1) aCellPos.Row -= (nRepeatedRows - 1); uno::Reference<table::XCellRange> xCellRange = rXMLImport.GetTables().GetCurrentXCellRange(); if (xCellRange.is()) { if (aCellPos.Column > MAXCOL) aCellPos.Column = MAXCOL - nCellsRepeated + 1; if (aCellPos.Row > MAXROW) aCellPos.Row = MAXROW - nRepeatedRows + 1; if (bIsMerged) DoMerge(aCellPos, nMergedCols - 1, nMergedRows - 1); if ( !bIsFormula ) { if((nCellType == util::NumberFormat::TEXT) && (nCellsRepeated > 1) && (nRepeatedRows > 1)) { uno::Reference <table::XCell> xTempCell = xCellRange->getCellByPosition(aCellPos.Column, aCellPos.Row); uno::Reference <text::XText> xTempText (xTempCell, uno::UNO_QUERY); if (xTempText.is()) sOUText=xTempText->getString(); } uno::Reference <table::XCell> xCell; table::CellAddress aCurrentPos( aCellPos ); for (sal_Int32 i = 0; i < nCellsRepeated; i++) { aCurrentPos.Column = aCellPos.Column + i; if (i > 0) rXMLImport.GetTables().AddColumn(sal_False); if (!bIsEmpty) { for (sal_Int32 j = 0; j < nRepeatedRows; j++) { aCurrentPos.Row = aCellPos.Row + j; if ((aCurrentPos.Column == 0) && (j > 0)) rXMLImport.GetTables().AddRow(); xCell = xCellRange->getCellByPosition(aCurrentPos.Column, aCurrentPos.Row); if ((!(bIsCovered) || (xCell->getType() == table::CellContentType_EMPTY))) { switch (nCellType) { case util::NumberFormat::TEXT: { uno::Reference <text::XText> xText (xCell, uno::UNO_QUERY); if (xText.is()) { if(sOUTextValue.getLength()) xText->setString(sOUTextValue); else if (sOUTextContent.getLength()) xText->setString(sOUTextContent); else if (i > 0) xText->setString(sOUText); } } break; case util::NumberFormat::NUMBER: case util::NumberFormat::PERCENT: case util::NumberFormat::CURRENCY: { xCell->setValue(fValue); } break; case util::NumberFormat::TIME: { rXMLImport.GetMM100UnitConverter().convertTime(fValue, sOUTimeValue); xCell->setValue(fValue); } break; case util::NumberFormat::DATETIME: { if (rXMLImport.GetMM100UnitConverter().setNullDate(rXMLImport.GetModel())) { rXMLImport.GetMM100UnitConverter().convertDateTime(fValue, sOUDateValue); double fTempValue = SolarMath::ApproxFloor(fValue); if ( SolarMath::ApproxEqual (fValue, fTempValue) ) { nCellType = util::NumberFormat::DATE; } xCell->setValue(fValue); } } break; case util::NumberFormat::LOGICAL: { if ( 0 == sOUBooleanValue.compareToAscii(sXML_true) ) xCell->setValue(1.0); else xCell->setValue(0.0); } break; default: { DBG_ERROR("no cell type given"); } break; } } SetAnnotation(xCell); SetDetectiveObj( aCurrentPos ); SetCellRangeSource( aCurrentPos ); } } else if ((i == 0) && (aCellPos.Column == 0)) for (sal_Int32 j = 1; j < nRepeatedRows; j++) { rXMLImport.GetTables().AddRow(); rXMLImport.GetTables().AddColumn(sal_False); } } if (nCellsRepeated > 1 || nRepeatedRows > 1) { SetCellProperties(xCellRange, aCellPos); // set now only the validation //SetType(xCellRange, aCellPos); ScRange aScRange( static_cast<USHORT>(aCellPos.Column), static_cast<USHORT>(aCellPos.Row), aCellPos.Sheet, static_cast<USHORT>(aCellPos.Column + nCellsRepeated - 1), static_cast<USHORT>(aCellPos.Row + nRepeatedRows - 1), aCellPos.Sheet ); GetScImport().GetStylesImportHelper()->AddRange(aScRange); } else { GetScImport().GetStylesImportHelper()->AddCell(aCellPos); SetCellProperties(xCell); // set now only the validation //SetType(xTempCell); } } else { uno::Reference <table::XCell> xCell = xCellRange->getCellByPosition(aCellPos.Column , aCellPos.Row); SetCellProperties(xCell); // set now only the validation DBG_ASSERT(((nCellsRepeated == 1) && (nRepeatedRows == 1)), "repeated cells with formula not possible now"); GetScImport().GetStylesImportHelper()->AddCell(aCellPos); ScXMLConverter::ParseFormula(sOUFormula); if (!bIsMatrix) xCell->setFormula(sOUFormula); else { if (nMatrixCols > 0 && nMatrixRows > 0) { uno::Reference <table::XCellRange> xMatrixCellRange = xCellRange->getCellRangeByPosition(aCellPos.Column, aCellPos.Row, aCellPos.Column + nMatrixCols - 1, aCellPos.Row + nMatrixRows - 1); if (xMatrixCellRange.is()) { uno::Reference <sheet::XArrayFormulaRange> xArrayFormulaRange(xMatrixCellRange, uno::UNO_QUERY); if (xArrayFormulaRange.is()) xArrayFormulaRange->setArrayFormula(sOUFormula); } } } SetAnnotation(xCell); SetDetectiveObj( aCellPos ); SetCellRangeSource( aCellPos ); } } } bIsMerged = sal_False; bHasSubTable = sal_False; nMergedCols = 1; nMergedRows = 1; nCellsRepeated = 1; } #79771#; remove some unnecassary calls /************************************************************************* * * $RCSfile: xmlcelli.cxx,v $ * * $Revision: 1.48 $ * * last change: $Author: sab $ $Date: 2001-05-21 10:15:38 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifdef PCH #include "filt_pch.hxx" #endif #pragma hdrstop // INCLUDE --------------------------------------------------------------- #include "xmlcelli.hxx" #include "xmlimprt.hxx" #include "xmltabi.hxx" #include "xmlstyli.hxx" #include "xmlannoi.hxx" #include "global.hxx" #include "document.hxx" #include "cellsuno.hxx" #include "docuno.hxx" #ifndef _SC_XMLTABLESHAPEIMPORTHELPER_HXX #include "XMLTableShapeImportHelper.hxx" #endif #ifndef _SC_XMLTEXTPCONTEXT_HXX #include "XMLTextPContext.hxx" #endif #ifndef _SC_XMLSTYLESIMPORTHELPER_HXX #include "XMLStylesImportHelper.hxx" #endif #ifndef SC_UNONAMES_HXX #include "unonames.hxx" #endif // core implementation #ifndef SC_AREALINK_HXX #include "arealink.hxx" #endif // core implementation #ifndef _SVXLINKMGR_HXX #include <svx/linkmgr.hxx> #endif #ifndef SC_CONVUNO_HXX #include "convuno.hxx" #endif #ifndef _SC_XMLCONVERTER_HXX #include "XMLConverter.hxx" #endif #include <xmloff/xmltkmap.hxx> #include <xmloff/xmlkywd.hxx> #include <xmloff/nmspmap.hxx> #include <xmloff/xmluconv.hxx> #include <xmloff/families.hxx> #ifndef XMLOFF_NUMEHELP_HXX #include <xmloff/numehelp.hxx> #endif #include <svtools/zforlist.hxx> #include <com/sun/star/frame/XModel.hpp> #include <com/sun/star/text/XText.hpp> #include <com/sun/star/sheet/XSpreadsheets.hpp> #include <com/sun/star/sheet/XSpreadsheet.hpp> #include <com/sun/star/sheet/XCellRangeAddressable.hpp> #ifndef _COM_SUN_STAR_UTIL_XMERGEABLE_HPP_ #include <com/sun/star/util/XMergeable.hpp> #endif #ifndef _COM_SUN_STAR_SHEET_XSHEETCONDITION_HPP_ #include <com/sun/star/sheet/XSheetCondition.hpp> #endif #ifndef _COM_SUN_STAR_TABLE_XCELLRANGE_HPP_ #include <com/sun/star/table/XCellRange.hpp> #endif #ifndef _COM_SUN_STAR_TABLE_CELLADDRESS_HPP_ #include <com/sun/star/table/CellAddress.hpp> #endif #ifndef _COM_SUN_STAR_UTIL_NUMBERFORMAT_HPP_ #include <com/sun/star/util/NumberFormat.hpp> #endif #ifndef _COM_SUN_STAR_UTIL_XNUMBERFORMATSSUPPLIER_HPP_ #include <com/sun/star/util/XNumberFormatsSupplier.hpp> #endif #ifndef _COM_SUN_STAR_UTIL_XNUMBERFORMATTYPES_HPP_ #include <com/sun/star/util/XNumberFormatTypes.hpp> #endif #ifndef _COM_SUN_STAR_UTIL_DATE_HPP_ #include <com/sun/star/util/Date.hpp> #endif #ifndef _COM_SUN_STAR_LANG_LOCALE_HPP_ #include <com/sun/star/lang/Locale.hpp> #endif #ifndef _COM_SUN_STAR_text_CONTROLCHARACTER_HPP_ #include <com/sun/star/text/ControlCharacter.hpp> #endif #ifndef _RTL_USTRBUF_HXX_ #include <rtl/ustrbuf.hxx> #endif #ifndef _DATE_HXX #include <tools/date.hxx> #endif #ifndef _TOOLS_SOLMATH_HXX #include <tools/solmath.hxx> #endif #ifndef _ISOLANG_HXX #include <tools/isolang.hxx> #endif #ifndef _COMPHELPER_EXTRACT_HXX_ #include <comphelper/extract.hxx> #endif #define SC_CURRENCYSYMBOL "CurrencySymbol" using namespace com::sun::star; //------------------------------------------------------------------ ScXMLTableRowCellContext::ScXMLTableRowCellContext( ScXMLImport& rImport, USHORT nPrfx, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList, const sal_Bool bTempIsCovered, const sal_Int32 nTempRepeatedRows ) : SvXMLImportContext( rImport, nPrfx, rLName ), bIsMerged(sal_False), bIsMatrix(sal_False), bIsFormula(sal_False), bHasSubTable(sal_False), bIsCovered(bTempIsCovered), bHasAnnotation(sal_False), nRepeatedRows(nTempRepeatedRows), bIsEmpty(sal_True), bHasTextImport(sal_False), bIsFirstTextImport(sal_False), aDetectiveObjVec(), aCellRangeSource(), nCellType(util::NumberFormat::TEXT), nMergedCols(1), nMergedRows(1), nCellsRepeated(1), fValue(0.0) { GetScImport().SetRemoveLastChar(sal_False); GetScImport().GetTables().AddColumn(bTempIsCovered); sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0; const SvXMLTokenMap& rAttrTokenMap = GetScImport().GetTableRowCellAttrTokenMap(); rtl::OUString aLocalName; rtl::OUString sValue; for( sal_Int16 i=0; i < nAttrCount; i++ ) { sal_uInt16 nPrefix = GetScImport().GetNamespaceMap().GetKeyByAttrName( xAttrList->getNameByIndex( i ), &aLocalName ); sValue = xAttrList->getValueByIndex( i ); switch( rAttrTokenMap.Get( nPrefix, aLocalName ) ) { case XML_TOK_TABLE_ROW_CELL_ATTR_STYLE_NAME: { sStyleName = sValue; } break; case XML_TOK_TABLE_ROW_CELL_ATTR_CONTENT_VALIDATION_NAME: { sContentValidationName = sValue; } break; case XML_TOK_TABLE_ROW_CELL_ATTR_SPANNED_ROWS: { bIsMerged = sal_True; nMergedRows = sValue.toInt32(); } break; case XML_TOK_TABLE_ROW_CELL_ATTR_SPANNED_COLS: { bIsMerged = sal_True; nMergedCols = sValue.toInt32(); } break; case XML_TOK_TABLE_ROW_CELL_ATTR_REPEATED: { nCellsRepeated = sValue.toInt32(); } break; case XML_TOK_TABLE_ROW_CELL_ATTR_VALUE_TYPE: { nCellType = GetCellType(sValue); bIsEmpty = sal_False; } break; case XML_TOK_TABLE_ROW_CELL_ATTR_VALUE: { GetScImport().GetMM100UnitConverter().convertDouble(fValue, sValue); bIsEmpty = sal_False; } break; case XML_TOK_TABLE_ROW_CELL_ATTR_DATE_VALUE: { sOUDateValue = sValue; bIsEmpty = sal_False; } break; case XML_TOK_TABLE_ROW_CELL_ATTR_TIME_VALUE: { sOUTimeValue = sValue; bIsEmpty = sal_False; } break; case XML_TOK_TABLE_ROW_CELL_ATTR_BOOLEAN_VALUE: { sOUBooleanValue = sValue; bIsEmpty = sal_False; } break; case XML_TOK_TABLE_ROW_CELL_ATTR_STRING_VALUE: { sOUTextValue = sValue; bIsEmpty = sal_False; } break; case XML_TOK_TABLE_ROW_CELL_ATTR_FORMULA: { bIsFormula = sal_True; sOUFormula = sValue; } break; case XML_TOK_TABLE_ROW_CELL_ATTR_CURRENCY : { sCurrencySymbol = sValue; } break; case XML_TOK_TABLE_ROW_CELL_ATTR_SPANNED_MATRIX_COLS : { bIsMatrix = sal_True; nMatrixCols = sValue.toInt32(); } break; case XML_TOK_TABLE_ROW_CELL_ATTR_SPANNED_MATRIX_ROWS : { bIsMatrix = sal_True; nMatrixRows = sValue.toInt32(); } break; } } GetScImport().GetStylesImportHelper()->SetAttributes(sStyleName, sCurrencySymbol, nCellType); } sal_Int16 ScXMLTableRowCellContext::GetCellType(const rtl::OUString& sOUValue) const { if (sOUValue.equals(GetScImport().sSC_float)) return util::NumberFormat::NUMBER; else if (sOUValue.equals(GetScImport().sSC_string)) return util::NumberFormat::TEXT; else if (sOUValue.equals(GetScImport().sSC_time)) return util::NumberFormat::TIME; else if (sOUValue.equals(GetScImport().sSC_date)) return util::NumberFormat::DATETIME; else if (sOUValue.equals(GetScImport().sSC_percentage)) return util::NumberFormat::PERCENT; else if (sOUValue.equals(GetScImport().sSC_currency)) return util::NumberFormat::CURRENCY; else if (sOUValue.equals(GetScImport().sSC_boolean)) return util::NumberFormat::LOGICAL; else return 0; } ScXMLTableRowCellContext::~ScXMLTableRowCellContext() { } void ScXMLTableRowCellContext::SetCursorOnTextImport() { com::sun::star::table::CellAddress aCellPos = GetScImport().GetTables().GetRealCellPos(); uno::Reference<table::XCellRange> xCellRange = GetScImport().GetTables().GetCurrentXCellRange(); if (xCellRange.is()) { if (aCellPos.Column > MAXCOL) aCellPos.Column = MAXCOL; if (aCellPos.Row > MAXROW) aCellPos.Row = MAXROW; uno::Reference <table::XCell> xCell = xCellRange->getCellByPosition(aCellPos.Column, aCellPos.Row); if (xCell.is()) { uno::Reference<text::XText> xText(xCell, uno::UNO_QUERY); if (xText.is()) { uno::Reference<text::XTextCursor> xTextCursor = xText->createTextCursor(); if (xTextCursor.is()) GetScImport().GetTextImport()->SetCursor(xTextCursor); } } } } SvXMLImportContext *ScXMLTableRowCellContext::CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList ) { SvXMLImportContext *pContext = 0; const SvXMLTokenMap& rTokenMap = GetScImport().GetTableRowCellElemTokenMap(); sal_Bool bHeader(sal_False); sal_Bool bTextP(sal_False); switch( rTokenMap.Get( nPrefix, rLName ) ) { case XML_TOK_TABLE_ROW_CELL_P: { bIsEmpty = sal_False; bTextP = sal_True; if (nCellType == util::NumberFormat::TEXT) { ScXMLImport& rXMLImport = GetScImport(); if (!bHasTextImport) { bIsFirstTextImport = sal_True; bHasTextImport = sal_True; pContext = new ScXMLTextPContext(GetScImport(), nPrefix, rLName, xAttrList, this); } else { if (bIsFirstTextImport && !GetScImport().GetRemoveLastChar()) { SetCursorOnTextImport(); GetScImport().SetRemoveLastChar(sal_True); uno::Reference<text::XTextCursor> xTextCursor = GetScImport().GetTextImport()->GetCursor(); xTextCursor->setString(sOUTextContent); sOUTextContent = sEmpty; uno::Reference < text::XText > xText (xTextCursor->getText()); uno::Reference < text::XTextRange > xTextRange (xTextCursor, uno::UNO_QUERY); if (xText.is() && xTextRange.is()) xText->insertControlCharacter(xTextRange, text::ControlCharacter::PARAGRAPH_BREAK, sal_False); } pContext = rXMLImport.GetTextImport()->CreateTextChildContext( GetScImport(), nPrefix, rLName, xAttrList); bIsFirstTextImport = sal_False; } } } break; case XML_TOK_TABLE_ROW_CELL_SUBTABLE: { bHasSubTable = sal_True; pContext = new ScXMLTableContext( GetScImport() , nPrefix, rLName, xAttrList, sal_True, nMergedCols); nMergedCols = 1; bIsMerged = sal_False; } break; case XML_TOK_TABLE_ROW_CELL_ANNOTATION: { bIsEmpty = sal_False; pContext = new ScXMLAnnotationContext( GetScImport(), nPrefix, rLName, xAttrList, this); } break; case XML_TOK_TABLE_ROW_CELL_DETECTIVE: { bIsEmpty = sal_False; pContext = new ScXMLDetectiveContext( GetScImport(), nPrefix, rLName, aDetectiveObjVec ); } break; case XML_TOK_TABLE_ROW_CELL_CELL_RANGE_SOURCE: { bIsEmpty = sal_False; pContext = new ScXMLCellRangeSourceContext( GetScImport(), nPrefix, rLName, xAttrList, aCellRangeSource ); } break; } if (!pContext && !bTextP) { ScXMLImport& rXMLImport = GetScImport(); com::sun::star::table::CellAddress aCellPos = rXMLImport.GetTables().GetRealCellPos(); uno::Reference<drawing::XShapes> xShapes (rXMLImport.GetTables().GetCurrentXShapes()); if (xShapes.is()) { if (aCellPos.Column > MAXCOL) aCellPos.Column = MAXCOL; if (aCellPos.Row > MAXROW) aCellPos.Row = MAXROW; ScDocument* pDoc = GetScImport().GetDocument(); XMLTableShapeImportHelper* pTableShapeImport = (XMLTableShapeImportHelper*)rXMLImport.GetShapeImport().get(); pTableShapeImport->SetOnTable(sal_False); pTableShapeImport->SetCell(aCellPos); pContext = rXMLImport.GetShapeImport()->CreateGroupChildContext( rXMLImport, nPrefix, rLName, xAttrList, xShapes); if (pContext) bIsEmpty = sal_False; } } if( !pContext ) pContext = new SvXMLImportContext( GetImport(), nPrefix, rLName ); return pContext; } sal_Bool ScXMLTableRowCellContext::IsMerged (const uno::Reference <table::XCellRange>& xCellRange, const sal_Int32 nCol, const sal_Int32 nRow, table::CellRangeAddress& aCellAddress) const { uno::Reference <table::XCellRange> xMergeCellRange = xCellRange->getCellRangeByPosition(nCol,nRow,nCol,nRow); uno::Reference <util::XMergeable> xMergeable (xMergeCellRange, uno::UNO_QUERY); if (xMergeable.is()) { uno::Reference<sheet::XSheetCellRange> xMergeSheetCellRange (xMergeCellRange, uno::UNO_QUERY); uno::Reference<sheet::XSpreadsheet> xTable = xMergeSheetCellRange->getSpreadsheet(); uno::Reference<sheet::XSheetCellCursor> xMergeSheetCursor = xTable->createCursorByRange(xMergeSheetCellRange); if (xMergeSheetCursor.is()) { xMergeSheetCursor->collapseToMergedArea(); uno::Reference<sheet::XCellRangeAddressable> xMergeCellAddress (xMergeSheetCursor, uno::UNO_QUERY); if (xMergeCellAddress.is()) { aCellAddress = xMergeCellAddress->getRangeAddress(); if (aCellAddress.StartColumn == nCol && aCellAddress.EndColumn == nCol && aCellAddress.StartRow == nRow && aCellAddress.EndRow == nRow) return sal_False; else return sal_True; } } } return sal_False; } void ScXMLTableRowCellContext::DoMerge(const com::sun::star::table::CellAddress& aCellPos, const sal_Int32 nCols, const sal_Int32 nRows) { uno::Reference<table::XCellRange> xCellRange = GetScImport().GetTables().GetCurrentXCellRange(); if ( xCellRange.is() ) { table::CellRangeAddress aCellAddress; if (IsMerged(xCellRange, aCellPos.Column, aCellPos.Row, aCellAddress)) { //unmerge uno::Reference <table::XCellRange> xMergeCellRange = xCellRange->getCellRangeByPosition(aCellAddress.StartColumn, aCellAddress.StartRow, aCellAddress.EndColumn, aCellAddress.EndRow); uno::Reference <util::XMergeable> xMergeable (xMergeCellRange, uno::UNO_QUERY); if (xMergeable.is()) xMergeable->merge(sal_False); } //merge uno::Reference <table::XCellRange> xMergeCellRange = xCellRange->getCellRangeByPosition(aCellAddress.StartColumn, aCellAddress.StartRow, aCellAddress.EndColumn + nCols, aCellAddress.EndRow + nRows); uno::Reference <util::XMergeable> xMergeable (xMergeCellRange, uno::UNO_QUERY); if (xMergeable.is()) xMergeable->merge(sal_True); } } void ScXMLTableRowCellContext::SetContentValidation(com::sun::star::uno::Reference<com::sun::star::beans::XPropertySet>& xPropSet) { ScMyImportValidation aValidation; if (GetScImport().GetValidation(sContentValidationName, aValidation)) { uno::Any aAny = xPropSet->getPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_VALIDAT))); uno::Reference<beans::XPropertySet> xPropertySet; if (aAny >>= xPropertySet) { if (aValidation.sErrorMessage.getLength()) { aAny <<= aValidation.sErrorMessage; xPropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_ERRMESS)), aAny); } if (aValidation.sErrorTitle.getLength()) { aAny <<= aValidation.sErrorTitle; xPropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_ERRTITLE)), aAny); } if (aValidation.sImputMessage.getLength()) { aAny <<= aValidation.sImputMessage; xPropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_INPMESS)), aAny); } if (aValidation.sImputTitle.getLength()) { aAny <<= aValidation.sImputTitle; xPropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_INPTITLE)), aAny); } aAny = ::cppu::bool2any(aValidation.bShowErrorMessage); xPropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_SHOWERR)), aAny); aAny = ::cppu::bool2any(aValidation.bShowImputMessage); xPropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_SHOWINP)), aAny); aAny <<= aValidation.aValidationType; xPropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_TYPE)), aAny); aAny = ::cppu::bool2any(aValidation.bIgnoreBlanks); xPropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_IGNOREBL)), aAny); aAny <<= aValidation.aAlertStyle; xPropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_ERRALSTY)), aAny); uno::Reference<sheet::XSheetCondition> xCondition(xPropertySet, uno::UNO_QUERY); if (xCondition.is()) { xCondition->setFormula1(aValidation.sFormula1); xCondition->setFormula2(aValidation.sFormula2); xCondition->setOperator(aValidation.aOperator); xCondition->setSourcePosition(aValidation.aBaseCellAddress); } } aAny <<= xPropertySet; xPropSet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_VALIDAT)), aAny); } } void ScXMLTableRowCellContext::SetCellProperties(const uno::Reference<table::XCellRange>& xCellRange, const table::CellAddress& aCellAddress) { if (sContentValidationName.getLength()) { ScXMLImport& rXMLImport = GetScImport(); sal_Int32 nBottom = aCellAddress.Row + nRepeatedRows - 1; sal_Int32 nRight = aCellAddress.Column + nCellsRepeated - 1; if (nBottom > MAXROW) nBottom = MAXROW; if (nRight > MAXCOL) nRight = MAXCOL; uno::Reference <table::XCellRange> xPropCellRange = xCellRange->getCellRangeByPosition(aCellAddress.Column, aCellAddress.Row, nRight, nBottom); if (xPropCellRange.is()) { uno::Reference <beans::XPropertySet> xProperties (xPropCellRange, uno::UNO_QUERY); if (xProperties.is()) SetContentValidation(xProperties); } } } void ScXMLTableRowCellContext::SetCellProperties(const uno::Reference<table::XCell>& xCell) { if (sContentValidationName.getLength()) { ScXMLImport& rXMLImport = GetScImport(); uno::Reference <beans::XPropertySet> xProperties (xCell, uno::UNO_QUERY); if (xProperties.is()) SetContentValidation(xProperties); } } void ScXMLTableRowCellContext::SetAnnotation(const uno::Reference<table::XCell>& xCell) { /*uno::Reference<sheet::XSheetAnnotationAnchor> xSheetAnnotationAnchor(xCell, uno::UNO_QUERY); if (xSheetAnnotationAnchor.is()) { uno::Reference <sheet::XSheetAnnotation> xSheetAnnotation = xSheetAnnotationAnchor->getAnnotation(); uno::Reference<text::XSimpleText> xSimpleText(xSheetAnnotation, uno::UNO_QUERY); if (xSheetAnnotation.is() && xSimpleText.is()) { xSimpleText->setString(aMyAnnotation.sText); //xSheetAnnotation->setAuthor(aMyAnnotation.sAuthor); //xSheetAnnotation->setDate(); xSheetAnnotation->setIsVisible(aMyAnnotation.bDisplay); } }*/ if( bHasAnnotation ) { uno::Reference<sheet::XCellAddressable> xCellAddressable(xCell, uno::UNO_QUERY); if (xCellAddressable.is()) { table::CellAddress aCellAddress = xCellAddressable->getCellAddress(); double fDate; GetScImport().GetMM100UnitConverter().convertDateTime(fDate, aMyAnnotation.sCreateDate); ScDocument* pDoc = GetScImport().GetDocument(); SvNumberFormatter* pNumForm = pDoc->GetFormatTable(); sal_uInt32 nfIndex = pNumForm->GetFormatIndex(NF_DATE_SYS_DDMMYYYY, LANGUAGE_SYSTEM); String sDate; Color* pColor = NULL; Color** ppColor = &pColor; pNumForm->GetOutputString(fDate, nfIndex, sDate, ppColor); ScPostIt aNote(String(aMyAnnotation.sText), sDate, String(aMyAnnotation.sAuthor)); aNote.SetShown(aMyAnnotation.bDisplay); pDoc->SetNote(static_cast<USHORT>(aCellAddress.Column), static_cast<USHORT>(aCellAddress.Row), aCellAddress.Sheet, aNote); if (aMyAnnotation.bDisplay) { uno::Reference < drawing::XShapes > xShapes (GetScImport().GetTables().GetCurrentXShapes()); // make draw page ScDetectiveFunc aDetFunc(pDoc, aCellAddress.Sheet); aDetFunc.ShowComment(static_cast<USHORT>(aCellAddress.Column), static_cast<USHORT>(aCellAddress.Row), sal_False); uno::Reference<container::XIndexAccess> xShapesIndex (xShapes, uno::UNO_QUERY); if (xShapesIndex.is()) { sal_Int32 nShapes = xShapesIndex->getCount(); uno::Reference < drawing::XShape > xShape; GetScImport().GetShapeImport()->shapeWithZIndexAdded(xShape, nShapes); } } } } } // core implementation void ScXMLTableRowCellContext::SetDetectiveObj( const table::CellAddress& rPosition ) { if( aDetectiveObjVec.size() ) { ScDetectiveFunc aDetFunc( GetScImport().GetDocument(), rPosition.Sheet ); uno::Reference < drawing::XShapes > xShapes (GetScImport().GetTables().GetCurrentXShapes()); // make draw page for( ScMyImpDetectiveObjVec::iterator aItr = aDetectiveObjVec.begin(); aItr != aDetectiveObjVec.end(); aItr++ ) { ScAddress aScAddress; ScUnoConversion::FillScAddress( aScAddress, rPosition ); aDetFunc.InsertObject( aItr->eObjType, aScAddress, aItr->aSourceRange, aItr->bHasError ); uno::Reference<container::XIndexAccess> xShapesIndex (xShapes, uno::UNO_QUERY); if (xShapesIndex.is()) { sal_Int32 nShapes = xShapesIndex->getCount(); uno::Reference < drawing::XShape > xShape; GetScImport().GetShapeImport()->shapeWithZIndexAdded(xShape, nShapes); } } } } // core implementation void ScXMLTableRowCellContext::SetCellRangeSource( const table::CellAddress& rPosition ) { if( aCellRangeSource.bHas ) { ScRange aDestRange( static_cast<USHORT>(rPosition.Column), static_cast<USHORT>(rPosition.Row), rPosition.Sheet, rPosition.Column + aCellRangeSource.nColumns - 1, rPosition.Row + aCellRangeSource.nRows - 1, rPosition.Sheet ); String sFilterName( aCellRangeSource.sFilterName ); String sSourceStr( aCellRangeSource.sSourceStr ); ScDocument* pDoc = GetScImport().GetDocument(); ScAreaLink* pLink = new ScAreaLink( pDoc->GetDocumentShell(), aCellRangeSource.sURL, sFilterName, aCellRangeSource.sFilterOptions, sSourceStr, aDestRange, aCellRangeSource.nRefresh ); SvxLinkManager* pLinkManager = pDoc->GetLinkManager(); pLinkManager->InsertFileLink( *pLink, OBJECT_CLIENT_FILE, aCellRangeSource.sURL, &sFilterName, &sSourceStr ); } } void ScXMLTableRowCellContext::EndElement() { if (bHasTextImport && GetScImport().GetRemoveLastChar()) { if (GetImport().GetTextImport()->GetCursor().is()) { //GetImport().GetTextImport()->GetCursor()->gotoEnd(sal_False); if( GetImport().GetTextImport()->GetCursor()->goLeft( 1, sal_True ) ) { OUString sEmpty; GetImport().GetTextImport()->GetText()->insertString( GetImport().GetTextImport()->GetCursorAsRange(), sEmpty, sal_True ); } } } GetScImport().GetTextImport()->ResetCursor(); if (!bHasSubTable) { ScXMLImport& rXMLImport = GetScImport(); table::CellAddress aCellPos = rXMLImport.GetTables().GetRealCellPos(); if (aCellPos.Column > 0 && nRepeatedRows > 1) aCellPos.Row -= (nRepeatedRows - 1); uno::Reference<table::XCellRange> xCellRange = rXMLImport.GetTables().GetCurrentXCellRange(); if (xCellRange.is()) { if (aCellPos.Column > MAXCOL) aCellPos.Column = MAXCOL - nCellsRepeated + 1; if (aCellPos.Row > MAXROW) aCellPos.Row = MAXROW - nRepeatedRows + 1; if (bIsMerged) DoMerge(aCellPos, nMergedCols - 1, nMergedRows - 1); if ( !bIsFormula ) { if((nCellType == util::NumberFormat::TEXT) && (nCellsRepeated > 1) && (nRepeatedRows > 1)) { uno::Reference <table::XCell> xTempCell = xCellRange->getCellByPosition(aCellPos.Column, aCellPos.Row); uno::Reference <text::XText> xTempText (xTempCell, uno::UNO_QUERY); if (xTempText.is()) sOUText=xTempText->getString(); } uno::Reference <table::XCell> xCell; table::CellAddress aCurrentPos( aCellPos ); for (sal_Int32 i = 0; i < nCellsRepeated; i++) { aCurrentPos.Column = aCellPos.Column + i; if (i > 0) rXMLImport.GetTables().AddColumn(sal_False); if (!bIsEmpty) { for (sal_Int32 j = 0; j < nRepeatedRows; j++) { aCurrentPos.Row = aCellPos.Row + j; if ((aCurrentPos.Column == 0) && (j > 0)) rXMLImport.GetTables().AddRow(); xCell = xCellRange->getCellByPosition(aCurrentPos.Column, aCurrentPos.Row); if ((!(bIsCovered) || (xCell->getType() == table::CellContentType_EMPTY))) { switch (nCellType) { case util::NumberFormat::TEXT: { uno::Reference <text::XText> xText (xCell, uno::UNO_QUERY); if (xText.is()) { if(sOUTextValue.getLength()) xText->setString(sOUTextValue); else if (sOUTextContent.getLength()) xText->setString(sOUTextContent); else if (i > 0) xText->setString(sOUText); } } break; case util::NumberFormat::NUMBER: case util::NumberFormat::PERCENT: case util::NumberFormat::CURRENCY: { xCell->setValue(fValue); } break; case util::NumberFormat::TIME: { rXMLImport.GetMM100UnitConverter().convertTime(fValue, sOUTimeValue); xCell->setValue(fValue); } break; case util::NumberFormat::DATETIME: { if (rXMLImport.GetMM100UnitConverter().setNullDate(rXMLImport.GetModel())) { rXMLImport.GetMM100UnitConverter().convertDateTime(fValue, sOUDateValue); double fTempValue = SolarMath::ApproxFloor(fValue); if ( SolarMath::ApproxEqual (fValue, fTempValue) ) { nCellType = util::NumberFormat::DATE; } xCell->setValue(fValue); } } break; case util::NumberFormat::LOGICAL: { if ( 0 == sOUBooleanValue.compareToAscii(sXML_true) ) xCell->setValue(1.0); else xCell->setValue(0.0); } break; default: { DBG_ERROR("no cell type given"); } break; } } SetAnnotation(xCell); SetDetectiveObj( aCurrentPos ); SetCellRangeSource( aCurrentPos ); } } else if ((i == 0) && (aCellPos.Column == 0)) for (sal_Int32 j = 1; j < nRepeatedRows; j++) { rXMLImport.GetTables().AddRow(); rXMLImport.GetTables().AddColumn(sal_False); } } if (nCellsRepeated > 1 || nRepeatedRows > 1) { SetCellProperties(xCellRange, aCellPos); // set now only the validation //SetType(xCellRange, aCellPos); ScRange aScRange( static_cast<USHORT>(aCellPos.Column), static_cast<USHORT>(aCellPos.Row), aCellPos.Sheet, static_cast<USHORT>(aCellPos.Column + nCellsRepeated - 1), static_cast<USHORT>(aCellPos.Row + nRepeatedRows - 1), aCellPos.Sheet ); GetScImport().GetStylesImportHelper()->AddRange(aScRange); } else { GetScImport().GetStylesImportHelper()->AddCell(aCellPos); SetCellProperties(xCell); // set now only the validation //SetType(xTempCell); } } else { uno::Reference <table::XCell> xCell = xCellRange->getCellByPosition(aCellPos.Column , aCellPos.Row); SetCellProperties(xCell); // set now only the validation DBG_ASSERT(((nCellsRepeated == 1) && (nRepeatedRows == 1)), "repeated cells with formula not possible now"); GetScImport().GetStylesImportHelper()->AddCell(aCellPos); ScXMLConverter::ParseFormula(sOUFormula); if (!bIsMatrix) xCell->setFormula(sOUFormula); else { if (nMatrixCols > 0 && nMatrixRows > 0) { uno::Reference <table::XCellRange> xMatrixCellRange = xCellRange->getCellRangeByPosition(aCellPos.Column, aCellPos.Row, aCellPos.Column + nMatrixCols - 1, aCellPos.Row + nMatrixRows - 1); if (xMatrixCellRange.is()) { uno::Reference <sheet::XArrayFormulaRange> xArrayFormulaRange(xMatrixCellRange, uno::UNO_QUERY); if (xArrayFormulaRange.is()) xArrayFormulaRange->setArrayFormula(sOUFormula); } } } SetAnnotation(xCell); SetDetectiveObj( aCellPos ); SetCellRangeSource( aCellPos ); } } } bIsMerged = sal_False; bHasSubTable = sal_False; nMergedCols = 1; nMergedRows = 1; nCellsRepeated = 1; }
#include <archie/utils/fused/zip.h> #include <archie/utils/test.h> namespace fused = archie::utils::fused; void canZipTwoTuples() { auto a = fused::make_tuple(1, 2u, '3'); auto b = fused::make_tuple('4', 5.0, 6u); auto x = fused::zip(a, b); EXPECT_EQ(3u, fused::tuple_size<decltype(x)>::value); EXPECT_EQ(fused::make_tuple(1, '4'), fused::get<0>(x)); EXPECT_EQ(fused::make_tuple(2u, 5.0), fused::get<1>(x)); EXPECT_EQ(fused::make_tuple('3', 6u), fused::get<2>(x)); } void canZipViewTwoTuples() { auto a = fused::make_tuple(1, 2u, '3'); auto b = fused::make_tuple('4', 5.0, 6u); auto x = fused::zip_view(a, b); static_assert(fused::tuple_size<decltype(x)>::value == 3u, ""); auto const& x0 = fused::get<0>(x); auto const& x1 = fused::get<1>(x); auto const& x2 = fused::get<2>(x); static_assert( std::is_same<decltype(x0), fused::tuple<int&, char&> const&>::value, ""); static_assert(std::is_same<decltype(x1), fused::tuple<unsigned&, double&> const&>::value, ""); static_assert( std::is_same<decltype(x2), fused::tuple<char&, unsigned&> const&>::value, ""); EXPECT_EQ(&fused::get<0>(a), &fused::get<0>(x0)); EXPECT_EQ(&fused::get<1>(a), &fused::get<0>(x1)); EXPECT_EQ(&fused::get<2>(a), &fused::get<0>(x2)); EXPECT_EQ(&fused::get<0>(b), &fused::get<1>(x0)); EXPECT_EQ(&fused::get<1>(b), &fused::get<1>(x1)); EXPECT_EQ(&fused::get<2>(b), &fused::get<1>(x2)); fused::get<0>(x1) = 7u; EXPECT_EQ(7u, fused::get<1>(a)); fused::get<1>(x2) = 8u; EXPECT_EQ(8u, fused::get<2>(b)); } void canZipViewTwoConstTuples() { auto const a = fused::make_tuple(1, 2u, '3'); auto const b = fused::make_tuple('4', 5.0, 6u); auto x = fused::zip_view(a, b); static_assert(fused::tuple_size<decltype(x)>::value == 3u, ""); auto x0 = fused::get<0>(x); auto x1 = fused::get<1>(x); auto x2 = fused::get<2>(x); EXPECT_EQ(&fused::get<0>(a), &fused::get<0>(x0)); EXPECT_EQ(&fused::get<1>(a), &fused::get<0>(x1)); EXPECT_EQ(&fused::get<2>(a), &fused::get<0>(x2)); EXPECT_EQ(&fused::get<0>(b), &fused::get<1>(x0)); EXPECT_EQ(&fused::get<1>(b), &fused::get<1>(x1)); EXPECT_EQ(&fused::get<2>(b), &fused::get<1>(x2)); } void canZipViewTwoTuplesWithConsts() { auto const c = 2u; auto const d = 5.0; auto a = fused::tuple<int, const unsigned, char>{1, c, '3'}; static_assert(std::is_same<std::remove_reference_t<decltype(a)>, fused::tuple<int, const unsigned, char>>::value, ""); auto b = fused::make_tuple('4', d, 6u); static_assert(std::is_same<std::remove_reference_t<decltype(b)>, fused::tuple<char, const double, unsigned>>::value, ""); auto x = fused::zip_view(a, b); static_assert(fused::tuple_size<decltype(x)>::value == 3u, ""); auto x0 = fused::get<0>(x); auto x1 = fused::get<1>(x); auto x2 = fused::get<2>(x); EXPECT_EQ(&fused::get<0>(a), &fused::get<0>(x0)); EXPECT_EQ(&fused::get<1>(a), &fused::get<0>(x1)); EXPECT_EQ(&fused::get<2>(a), &fused::get<0>(x2)); EXPECT_EQ(&fused::get<0>(b), &fused::get<1>(x0)); EXPECT_EQ(&fused::get<1>(b), &fused::get<1>(x1)); EXPECT_EQ(&fused::get<2>(b), &fused::get<1>(x2)); fused::get<0>(x0) = 7; fused::get<1>(x2) = 8u; EXPECT_EQ(7, fused::get<0>(a)); EXPECT_EQ(8u, fused::get<2>(b)); } int main() { canZipTwoTuples(); canZipViewTwoTuples(); canZipViewTwoConstTuples(); canZipViewTwoTuplesWithConsts(); return 0; } fused::tuple type is an implementation detail of used tie function skip static assert #include <archie/utils/fused/zip.h> #include <archie/utils/test.h> namespace fused = archie::utils::fused; void canZipTwoTuples() { auto a = fused::make_tuple(1, 2u, '3'); auto b = fused::make_tuple('4', 5.0, 6u); auto x = fused::zip(a, b); EXPECT_EQ(3u, fused::tuple_size<decltype(x)>::value); EXPECT_EQ(fused::make_tuple(1, '4'), fused::get<0>(x)); EXPECT_EQ(fused::make_tuple(2u, 5.0), fused::get<1>(x)); EXPECT_EQ(fused::make_tuple('3', 6u), fused::get<2>(x)); } void canZipViewTwoTuples() { auto a = fused::make_tuple(1, 2u, '3'); auto b = fused::make_tuple('4', 5.0, 6u); auto x = fused::zip_view(a, b); static_assert(fused::tuple_size<decltype(x)>::value == 3u, ""); auto const& x0 = fused::get<0>(x); auto const& x1 = fused::get<1>(x); auto const& x2 = fused::get<2>(x); static_assert( std::is_same<decltype(x0), fused::tuple<int&, char&> const&>::value, ""); static_assert(std::is_same<decltype(x1), fused::tuple<unsigned&, double&> const&>::value, ""); static_assert( std::is_same<decltype(x2), fused::tuple<char&, unsigned&> const&>::value, ""); EXPECT_EQ(&fused::get<0>(a), &fused::get<0>(x0)); EXPECT_EQ(&fused::get<1>(a), &fused::get<0>(x1)); EXPECT_EQ(&fused::get<2>(a), &fused::get<0>(x2)); EXPECT_EQ(&fused::get<0>(b), &fused::get<1>(x0)); EXPECT_EQ(&fused::get<1>(b), &fused::get<1>(x1)); EXPECT_EQ(&fused::get<2>(b), &fused::get<1>(x2)); fused::get<0>(x1) = 7u; EXPECT_EQ(7u, fused::get<1>(a)); fused::get<1>(x2) = 8u; EXPECT_EQ(8u, fused::get<2>(b)); } void canZipViewTwoConstTuples() { auto const a = fused::make_tuple(1, 2u, '3'); auto const b = fused::make_tuple('4', 5.0, 6u); auto x = fused::zip_view(a, b); static_assert(fused::tuple_size<decltype(x)>::value == 3u, ""); auto x0 = fused::get<0>(x); auto x1 = fused::get<1>(x); auto x2 = fused::get<2>(x); EXPECT_EQ(&fused::get<0>(a), &fused::get<0>(x0)); EXPECT_EQ(&fused::get<1>(a), &fused::get<0>(x1)); EXPECT_EQ(&fused::get<2>(a), &fused::get<0>(x2)); EXPECT_EQ(&fused::get<0>(b), &fused::get<1>(x0)); EXPECT_EQ(&fused::get<1>(b), &fused::get<1>(x1)); EXPECT_EQ(&fused::get<2>(b), &fused::get<1>(x2)); } void canZipViewTwoTuplesWithConsts() { auto const c = 2u; auto const d = 5.0; auto a = fused::tuple<int, const unsigned, char>{1, c, '3'}; auto b = fused::make_tuple('4', d, 6u); auto x = fused::zip_view(a, b); static_assert(fused::tuple_size<decltype(x)>::value == 3u, ""); auto x0 = fused::get<0>(x); auto x1 = fused::get<1>(x); auto x2 = fused::get<2>(x); EXPECT_EQ(&fused::get<0>(a), &fused::get<0>(x0)); EXPECT_EQ(&fused::get<1>(a), &fused::get<0>(x1)); EXPECT_EQ(&fused::get<2>(a), &fused::get<0>(x2)); EXPECT_EQ(&fused::get<0>(b), &fused::get<1>(x0)); EXPECT_EQ(&fused::get<1>(b), &fused::get<1>(x1)); EXPECT_EQ(&fused::get<2>(b), &fused::get<1>(x2)); fused::get<0>(x0) = 7; fused::get<1>(x2) = 8u; EXPECT_EQ(7, fused::get<0>(a)); EXPECT_EQ(8u, fused::get<2>(b)); } int main() { canZipTwoTuples(); canZipViewTwoTuples(); canZipViewTwoConstTuples(); canZipViewTwoTuplesWithConsts(); return 0; }
/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: xmldrani.cxx,v $ * * $Revision: 1.27 $ * * last change: $Author: rt $ $Date: 2005-09-08 20:06:44 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifdef PCH #include "filt_pch.hxx" #endif #pragma hdrstop // INCLUDE --------------------------------------------------------------- #include "xmldrani.hxx" #include "xmlimprt.hxx" #include "xmlfilti.hxx" #include "xmlsorti.hxx" #include "document.hxx" #include "globstr.hrc" #include "docuno.hxx" #include "dbcolect.hxx" #include "datauno.hxx" #ifndef SC_SCATTR_HXX #include "attrib.hxx" #endif #ifndef SC_UNONAMES_HXX #include "unonames.hxx" #endif #ifndef SC_CONVUNO_HXX #include "convuno.hxx" #endif #ifndef _SC_XMLCONVERTER_HXX #include "XMLConverter.hxx" #endif #include <xmloff/xmltkmap.hxx> #include <xmloff/nmspmap.hxx> #ifndef _XMLOFF_XMLTOKEN_HXX #include <xmloff/xmltoken.hxx> #endif #ifndef _XMLOFF_XMLNMSPE_HXX #include <xmloff/xmlnmspe.hxx> #endif #ifndef _XMLOFF_XMLUCONV_HXX #include <xmloff/xmluconv.hxx> #endif #ifndef _XMLOFF_XMLERROR_HXX #include <xmloff/xmlerror.hxx> #endif #include <com/sun/star/sheet/XSpreadsheetDocument.hpp> #include <com/sun/star/sheet/XDatabaseRanges.hpp> #include <com/sun/star/sheet/XDatabaseRange.hpp> #include <com/sun/star/table/CellRangeAddress.hpp> #ifndef _COMPHELPER_EXTRACT_HXX_ #include <comphelper/extract.hxx> #endif #ifndef _COM_SUN_STAR_UNO_RUNTIMEEXCEPTION_HPP_ #include <com/sun/star/uno/RuntimeException.hpp> #endif #ifndef _COM_SUN_STAR_XML_SAX_XLOCATOR_HPP_ #include <com/sun/star/xml/sax/XLocator.hpp> #endif #define SC_ENABLEUSERSORTLIST "EnableUserSortList" #define SC_USERSORTLISTINDEX "UserSortListIndex" #define SC_USERLIST "UserList" using namespace com::sun::star; using namespace xmloff::token; //------------------------------------------------------------------ ScXMLDatabaseRangesContext::ScXMLDatabaseRangesContext( ScXMLImport& rImport, USHORT nPrfx, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList) : SvXMLImportContext( rImport, nPrfx, rLName ) { // has no attributes rImport.LockSolarMutex(); } ScXMLDatabaseRangesContext::~ScXMLDatabaseRangesContext() { GetScImport().UnlockSolarMutex(); } SvXMLImportContext *ScXMLDatabaseRangesContext::CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList ) { SvXMLImportContext *pContext = 0; const SvXMLTokenMap& rTokenMap = GetScImport().GetDatabaseRangesElemTokenMap(); switch( rTokenMap.Get( nPrefix, rLName ) ) { case XML_TOK_DATABASE_RANGE : { pContext = new ScXMLDatabaseRangeContext( GetScImport(), nPrefix, rLName, xAttrList); } break; } if( !pContext ) pContext = new SvXMLImportContext( GetImport(), nPrefix, rLName ); return pContext; } void ScXMLDatabaseRangesContext::EndElement() { } ScXMLDatabaseRangeContext::ScXMLDatabaseRangeContext( ScXMLImport& rImport, USHORT nPrfx, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList) : SvXMLImportContext( rImport, nPrfx, rLName ), nRefresh(0), nSubTotalsUserListIndex(0), bContainsSort(sal_False), bContainsSubTotal(sal_False), bIsSelection(sal_False), bKeepFormats(sal_False), bMoveCells(sal_False), bStripData(sal_False), eOrientation(table::TableOrientation_ROWS), bContainsHeader(sal_True), bAutoFilter(sal_False), bFilterCopyOutputData(sal_False), bFilterIsCaseSensitive(sal_False), bFilterSkipDuplicates(sal_False), bFilterUseRegularExpressions(sal_False), bFilterConditionSourceRange(sal_False), bSubTotalsBindFormatsToContent(sal_False), bSubTotalsIsCaseSensitive(sal_False), bSubTotalsInsertPageBreaks(sal_False), bSubTotalsSortGroups(sal_False), bSubTotalsEnabledUserList(sal_False), bSubTotalsAscending(sal_True), bNative(sal_True), aSortSequence(), sDatabaseRangeName(ScGlobal::GetRscString(STR_DB_NONAME)) { nSourceType = sheet::DataImportMode_NONE; sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0; const SvXMLTokenMap& rAttrTokenMap = GetScImport().GetDatabaseRangeAttrTokenMap(); for( sal_Int16 i=0; i < nAttrCount; ++i ) { const rtl::OUString& sAttrName(xAttrList->getNameByIndex( i )); rtl::OUString aLocalName; USHORT nPrefix = GetScImport().GetNamespaceMap().GetKeyByAttrName( sAttrName, &aLocalName ); const rtl::OUString& sValue(xAttrList->getValueByIndex( i )); switch( rAttrTokenMap.Get( nPrefix, aLocalName ) ) { case XML_TOK_DATABASE_RANGE_ATTR_NAME : { sDatabaseRangeName = sValue; } break; case XML_TOK_DATABASE_RANGE_ATTR_IS_SELECTION : { bIsSelection = IsXMLToken(sValue, XML_TRUE); } break; case XML_TOK_DATABASE_RANGE_ATTR_ON_UPDATE_KEEP_STYLES : { bKeepFormats = IsXMLToken(sValue, XML_TRUE); } break; case XML_TOK_DATABASE_RANGE_ATTR_ON_UPDATE_KEEP_SIZE : { bMoveCells = !IsXMLToken(sValue, XML_TRUE); } break; case XML_TOK_DATABASE_RANGE_ATTR_HAS_PERSISTENT_DATA : { bStripData = !IsXMLToken(sValue, XML_TRUE); } break; case XML_TOK_DATABASE_RANGE_ATTR_ORIENTATION : { if (IsXMLToken(sValue, XML_COLUMN)) eOrientation = table::TableOrientation_COLUMNS; } break; case XML_TOK_DATABASE_RANGE_ATTR_CONTAINS_HEADER : { bContainsHeader = IsXMLToken(sValue, XML_TRUE); } break; case XML_TOK_DATABASE_RANGE_ATTR_DISPLAY_FILTER_BUTTONS : { bAutoFilter = IsXMLToken(sValue, XML_TRUE); } break; case XML_TOK_DATABASE_RANGE_ATTR_TARGET_RANGE_ADDRESS : { sRangeAddress = sValue; } break; case XML_TOK_DATABASE_RANGE_ATTR_REFRESH_DELAY : { double fTime; if( SvXMLUnitConverter::convertTime( fTime, sValue ) ) nRefresh = Max( (sal_Int32)(fTime * 86400.0), (sal_Int32)0 ); } break; } } } ScXMLDatabaseRangeContext::~ScXMLDatabaseRangeContext() { } SvXMLImportContext *ScXMLDatabaseRangeContext::CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList ) { SvXMLImportContext *pContext = 0; const SvXMLTokenMap& rTokenMap = GetScImport().GetDatabaseRangeElemTokenMap(); switch( rTokenMap.Get( nPrefix, rLName ) ) { case XML_TOK_DATABASE_RANGE_SOURCE_SQL : { pContext = new ScXMLSourceSQLContext( GetScImport(), nPrefix, rLName, xAttrList, this); } break; case XML_TOK_DATABASE_RANGE_SOURCE_TABLE : { pContext = new ScXMLSourceTableContext( GetScImport(), nPrefix, rLName, xAttrList, this); } break; case XML_TOK_DATABASE_RANGE_SOURCE_QUERY : { pContext = new ScXMLSourceQueryContext( GetScImport(), nPrefix, rLName, xAttrList, this); } break; case XML_TOK_FILTER : { pContext = new ScXMLFilterContext( GetScImport(), nPrefix, rLName, xAttrList, this); } break; case XML_TOK_SORT : { bContainsSort = sal_True; pContext = new ScXMLSortContext( GetScImport(), nPrefix, rLName, xAttrList, this); } break; case XML_TOK_DATABASE_RANGE_SUBTOTAL_RULES : { bContainsSubTotal = sal_True; pContext = new ScXMLSubTotalRulesContext( GetScImport(), nPrefix, rLName, xAttrList, this); } break; } if( !pContext ) pContext = new SvXMLImportContext( GetImport(), nPrefix, rLName ); return pContext; } void ScXMLDatabaseRangeContext::EndElement() { if (GetScImport().GetModel().is()) { uno::Reference <beans::XPropertySet> xPropertySet( GetScImport().GetModel(), uno::UNO_QUERY ); ScDocument* pDoc = GetScImport().GetDocument(); if (pDoc && xPropertySet.is()) { uno::Reference <sheet::XDatabaseRanges> xDatabaseRanges(xPropertySet->getPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNO_DATABASERNG))), uno::UNO_QUERY); if (xDatabaseRanges.is()) { table::CellRangeAddress aCellRangeAddress; sal_Int32 nOffset(0); if (ScXMLConverter::GetRangeFromString( aCellRangeAddress, sRangeAddress, pDoc, nOffset )) { sal_Bool bInsert(sal_True); try { xDatabaseRanges->addNewByName(sDatabaseRangeName, aCellRangeAddress); } catch ( uno::RuntimeException& rRuntimeException ) { bInsert = sal_False; rtl::OUString sErrorMessage(RTL_CONSTASCII_USTRINGPARAM("DatabaseRange ")); sErrorMessage += sDatabaseRangeName; sErrorMessage += rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(" could not be created with the range ")); sErrorMessage += sRangeAddress; uno::Sequence<rtl::OUString> aSeq(1); aSeq[0] = sErrorMessage; uno::Reference<xml::sax::XLocator> xLocator; GetScImport().SetError(XMLERROR_API | XMLERROR_FLAG_ERROR, aSeq, rRuntimeException.Message, xLocator); } if (bInsert) { uno::Reference <sheet::XDatabaseRange> xDatabaseRange(xDatabaseRanges->getByName(sDatabaseRangeName), uno::UNO_QUERY); if (xDatabaseRange.is()) { uno::Reference <beans::XPropertySet> xDatabaseRangePropertySet (xDatabaseRange, uno::UNO_QUERY); if (xDatabaseRangePropertySet.is()) { xDatabaseRangePropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_KEEPFORM)), uno::makeAny(bKeepFormats)); xDatabaseRangePropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_MOVCELLS)), uno::makeAny(bMoveCells)); xDatabaseRangePropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_STRIPDAT)), uno::makeAny(bStripData)); } uno::Sequence <beans::PropertyValue> aImportDescriptor(xDatabaseRange->getImportDescriptor()); sal_Int32 nImportProperties = aImportDescriptor.getLength(); for (sal_Int16 i = 0; i < nImportProperties; ++i) { if (aImportDescriptor[i].Name == rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_DBNAME))) { if (sDatabaseName.getLength()) { aImportDescriptor[i].Value <<= sDatabaseName; } else { aImportDescriptor[i].Name = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_CONRES)); aImportDescriptor[i].Value <<= sConnectionRessource; } } else if (aImportDescriptor[i].Name == rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_SRCOBJ))) aImportDescriptor[i].Value <<= sSourceObject; else if (aImportDescriptor[i].Name == rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_SRCTYPE))) aImportDescriptor[i].Value <<= nSourceType; else if (aImportDescriptor[i].Name == rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_ISNATIVE))) aImportDescriptor[i].Value <<= bNative; } ScDBCollection* pDBCollection = pDoc->GetDBCollection(); sal_uInt16 nIndex; pDBCollection->SearchName(sDatabaseRangeName, nIndex); ScDBData* pDBData = (*pDBCollection)[nIndex]; pDBData->SetImportSelection(bIsSelection); pDBData->SetAutoFilter(bAutoFilter); if (bAutoFilter) pDoc->ApplyFlagsTab( static_cast<SCCOL>(aCellRangeAddress.StartColumn), static_cast<SCROW>(aCellRangeAddress.StartRow), static_cast<SCCOL>(aCellRangeAddress.EndColumn), static_cast<SCROW>(aCellRangeAddress.StartRow), aCellRangeAddress.Sheet, SC_MF_AUTO ); ScImportParam aImportParam; ScImportDescriptor::FillImportParam(aImportParam, aImportDescriptor); pDBData->SetImportParam(aImportParam); if (bContainsSort) { sal_uInt32 nOldSize(aSortSequence.getLength()); aSortSequence.realloc(nOldSize + 1); beans::PropertyValue aProperty; aProperty.Name = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_ORIENT)); aProperty.Value <<= eOrientation; aSortSequence[nOldSize] = aProperty; ScSortParam aSortParam; ScSortDescriptor::FillSortParam(aSortParam, aSortSequence); //#98317#; until now the Fields are relative to the left top edge of the range, but the // core wants to have the absolute position (column/row) SCCOLROW nFieldStart = aSortParam.bByRow ? static_cast<SCCOLROW>(aCellRangeAddress.StartColumn) : static_cast<SCCOLROW>(aCellRangeAddress.StartRow); for (sal_uInt16 i = 0; i < MAXSORT; ++i) { if (aSortParam.bDoSort[i]) aSortParam.nField[i] += nFieldStart; } pDBData->SetSortParam(aSortParam); } uno::Reference <sheet::XSheetFilterDescriptor> xSheetFilterDescriptor(xDatabaseRange->getFilterDescriptor()); if (xSheetFilterDescriptor.is()) { uno::Reference <beans::XPropertySet> xFilterPropertySet (xSheetFilterDescriptor, uno::UNO_QUERY); if (xFilterPropertySet.is()) { sal_Bool bOrientation(table::TableOrientation_COLUMNS == eOrientation); xFilterPropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_ORIENT)), uno::makeAny(bOrientation)); xFilterPropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_CONTHDR)), uno::makeAny(bContainsHeader)); xFilterPropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_COPYOUT)), uno::makeAny(bFilterCopyOutputData)); xFilterPropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_ISCASE)), uno::makeAny(bFilterIsCaseSensitive)); xFilterPropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_SKIPDUP)), uno::makeAny(bFilterSkipDuplicates)); xFilterPropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_USEREGEX)), uno::makeAny(bFilterUseRegularExpressions)); xFilterPropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_OUTPOS)), uno::makeAny(aFilterOutputPosition)); } xSheetFilterDescriptor->setFilterFields(aFilterFields); if (bFilterConditionSourceRange) { ScRange aAdvSource; ScUnoConversion::FillScRange( aAdvSource, aFilterConditionSourceRangeAddress ); pDBData->SetAdvancedQuerySource(&aAdvSource); } } if (bContainsSubTotal) { uno::Reference <sheet::XSubTotalDescriptor> xSubTotalDescriptor(xDatabaseRange->getSubTotalDescriptor()); if (xSubTotalDescriptor.is()) { uno::Reference <beans::XPropertySet> xSubTotalPropertySet (xSubTotalDescriptor, uno::UNO_QUERY); if( xSubTotalPropertySet.is()) { xSubTotalPropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_BINDFMT)), uno::makeAny(bSubTotalsBindFormatsToContent)); xSubTotalPropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_ENABLEUSERSORTLIST)), uno::makeAny(bSubTotalsEnabledUserList)); xSubTotalPropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_USERSORTLISTINDEX)), uno::makeAny(nSubTotalsUserListIndex)); xSubTotalPropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_INSBRK)), uno::makeAny(bSubTotalsInsertPageBreaks)); xSubTotalPropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_ISCASE)), uno::makeAny(bSubTotalsIsCaseSensitive)); } ScSubTotalParam aSubTotalParam; aSubTotalParam.bDoSort = bSubTotalsSortGroups; aSubTotalParam.bAscending = bSubTotalsAscending; aSubTotalParam.bUserDef = bSubTotalsEnabledUserList; aSubTotalParam.nUserIndex = nSubTotalsUserListIndex; pDBData->SetSubTotalParam(aSubTotalParam); std::vector < ScSubTotalRule >::iterator aItr(aSubTotalRules.begin()); while (!aSubTotalRules.empty()) { xSubTotalDescriptor->addNew(aItr->aSubTotalColumns, aItr->nSubTotalRuleGroupFieldNumber); aItr = aSubTotalRules.erase(aItr); } } } if ( pDBData->HasImportParam() && !pDBData->HasImportSelection() ) { pDBData->SetRefreshDelay( nRefresh ); pDBData->SetRefreshHandler( pDBCollection->GetRefreshHandler() ); pDBData->SetRefreshControl( pDoc->GetRefreshTimerControlAddress() ); } } } } } } } } ScXMLSourceSQLContext::ScXMLSourceSQLContext( ScXMLImport& rImport, USHORT nPrfx, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList, ScXMLDatabaseRangeContext* pTempDatabaseRangeContext) : SvXMLImportContext( rImport, nPrfx, rLName ), pDatabaseRangeContext(pTempDatabaseRangeContext) { sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0; const SvXMLTokenMap& rAttrTokenMap = GetScImport().GetDatabaseRangeSourceSQLAttrTokenMap(); for( sal_Int16 i=0; i < nAttrCount; ++i ) { const rtl::OUString& sAttrName(xAttrList->getNameByIndex( i )); rtl::OUString aLocalName; USHORT nPrefix = GetScImport().GetNamespaceMap().GetKeyByAttrName( sAttrName, &aLocalName ); const rtl::OUString& sValue(xAttrList->getValueByIndex( i )); switch( rAttrTokenMap.Get( nPrefix, aLocalName ) ) { case XML_TOK_SOURCE_SQL_ATTR_DATABASE_NAME : { sDBName = sValue; } break; case XML_TOK_SOURCE_SQL_ATTR_SQL_STATEMENT : { pDatabaseRangeContext->SetSourceObject(sValue); } break; case XML_TOK_SOURCE_SQL_ATTR_PARSE_SQL_STATEMENT : { pDatabaseRangeContext->SetNative(IsXMLToken(sValue, XML_TRUE)); } break; } } pDatabaseRangeContext->SetSourceType(sheet::DataImportMode_SQL); } ScXMLSourceSQLContext::~ScXMLSourceSQLContext() { } SvXMLImportContext *ScXMLSourceSQLContext::CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList ) { SvXMLImportContext *pContext = 0; if ( nPrefix == XML_NAMESPACE_FORM ) { if (IsXMLToken(rLName, XML_CONNECTION_RESOURCE) && (sDBName.getLength() == 0)) { pContext = new ScXMLConResContext( GetScImport(), nPrefix, rLName, xAttrList, pDatabaseRangeContext); } } if( !pContext ) pContext = new SvXMLImportContext( GetImport(), nPrefix, rLName ); return pContext; } void ScXMLSourceSQLContext::EndElement() { if (sDBName.getLength()) pDatabaseRangeContext->SetDatabaseName(sDBName); } ScXMLSourceTableContext::ScXMLSourceTableContext( ScXMLImport& rImport, USHORT nPrfx, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList, ScXMLDatabaseRangeContext* pTempDatabaseRangeContext) : SvXMLImportContext( rImport, nPrfx, rLName ), pDatabaseRangeContext(pTempDatabaseRangeContext) { sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0; const SvXMLTokenMap& rAttrTokenMap = GetScImport().GetDatabaseRangeSourceTableAttrTokenMap(); for( sal_Int16 i=0; i < nAttrCount; ++i ) { const rtl::OUString& sAttrName(xAttrList->getNameByIndex( i )); rtl::OUString aLocalName; USHORT nPrefix = GetScImport().GetNamespaceMap().GetKeyByAttrName( sAttrName, &aLocalName ); const rtl::OUString& sValue(xAttrList->getValueByIndex( i )); switch( rAttrTokenMap.Get( nPrefix, aLocalName ) ) { case XML_TOK_SOURCE_TABLE_ATTR_DATABASE_NAME : { sDBName = sValue; } break; case XML_TOK_SOURCE_TABLE_ATTR_TABLE_NAME : { pDatabaseRangeContext->SetSourceObject(sValue); } break; } } pDatabaseRangeContext->SetSourceType(sheet::DataImportMode_TABLE); } ScXMLSourceTableContext::~ScXMLSourceTableContext() { } SvXMLImportContext *ScXMLSourceTableContext::CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList ) { SvXMLImportContext *pContext = 0; if ( nPrefix == XML_NAMESPACE_FORM ) { if (IsXMLToken(rLName, XML_CONNECTION_RESOURCE) && (sDBName.getLength() == 0)) { pContext = new ScXMLConResContext( GetScImport(), nPrefix, rLName, xAttrList, pDatabaseRangeContext); } } if( !pContext ) pContext = new SvXMLImportContext( GetImport(), nPrefix, rLName ); return pContext; } void ScXMLSourceTableContext::EndElement() { if (sDBName.getLength()) pDatabaseRangeContext->SetDatabaseName(sDBName); } ScXMLSourceQueryContext::ScXMLSourceQueryContext( ScXMLImport& rImport, USHORT nPrfx, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList, ScXMLDatabaseRangeContext* pTempDatabaseRangeContext) : SvXMLImportContext( rImport, nPrfx, rLName ), pDatabaseRangeContext(pTempDatabaseRangeContext) { sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0; const SvXMLTokenMap& rAttrTokenMap = GetScImport().GetDatabaseRangeSourceQueryAttrTokenMap(); for( sal_Int16 i=0; i < nAttrCount; ++i ) { const rtl::OUString& sAttrName(xAttrList->getNameByIndex( i )); rtl::OUString aLocalName; USHORT nPrefix = GetScImport().GetNamespaceMap().GetKeyByAttrName( sAttrName, &aLocalName ); const rtl::OUString& sValue(xAttrList->getValueByIndex( i )); switch( rAttrTokenMap.Get( nPrefix, aLocalName ) ) { case XML_TOK_SOURCE_QUERY_ATTR_DATABASE_NAME : { sDBName = sValue; } break; case XML_TOK_SOURCE_QUERY_ATTR_QUERY_NAME : { pDatabaseRangeContext->SetSourceObject(sValue); } break; } } pDatabaseRangeContext->SetSourceType(sheet::DataImportMode_QUERY); } ScXMLSourceQueryContext::~ScXMLSourceQueryContext() { } SvXMLImportContext *ScXMLSourceQueryContext::CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList ) { SvXMLImportContext *pContext = 0; if ( nPrefix == XML_NAMESPACE_FORM ) { if (IsXMLToken(rLName, XML_CONNECTION_RESOURCE) && (sDBName.getLength() == 0)) { pContext = new ScXMLConResContext( GetScImport(), nPrefix, rLName, xAttrList, pDatabaseRangeContext); } } if( !pContext ) pContext = new SvXMLImportContext( GetImport(), nPrefix, rLName ); return pContext; } void ScXMLSourceQueryContext::EndElement() { if (sDBName.getLength()) pDatabaseRangeContext->SetDatabaseName(sDBName); } ScXMLConResContext::ScXMLConResContext( ScXMLImport& rImport, USHORT nPrfx, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList, ScXMLDatabaseRangeContext* pTempDatabaseRangeContext) : SvXMLImportContext( rImport, nPrfx, rLName ), pDatabaseRangeContext( pTempDatabaseRangeContext ) { rtl::OUString sConRes; sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0; const SvXMLTokenMap& rAttrTokenMap = GetScImport().GetDatabaseRangeSourceSQLAttrTokenMap(); for( sal_Int16 i=0; i < nAttrCount; i++ ) { rtl::OUString sAttrName = xAttrList->getNameByIndex( i ); rtl::OUString aLocalName; USHORT nPrefix = GetScImport().GetNamespaceMap().GetKeyByAttrName( sAttrName, &aLocalName ); rtl::OUString sValue = xAttrList->getValueByIndex( i ); if (nPrefix == XML_NAMESPACE_XLINK) { if (IsXMLToken(aLocalName, XML_HREF)) sConRes = sValue; } } if (sConRes.getLength()) pDatabaseRangeContext->SetConnectionRessource(sConRes); } ScXMLConResContext::~ScXMLConResContext() { } SvXMLImportContext *ScXMLConResContext::CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList ) { SvXMLImportContext *pContext = 0; if( !pContext ) pContext = new SvXMLImportContext( GetImport(), nPrefix, rLName ); return pContext; } void ScXMLConResContext::EndElement() { } ScXMLSubTotalRulesContext::ScXMLSubTotalRulesContext( ScXMLImport& rImport, USHORT nPrfx, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList, ScXMLDatabaseRangeContext* pTempDatabaseRangeContext) : SvXMLImportContext( rImport, nPrfx, rLName ), pDatabaseRangeContext(pTempDatabaseRangeContext) { sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0; const SvXMLTokenMap& rAttrTokenMap = GetScImport().GetDatabaseRangeSubTotalRulesAttrTokenMap(); for( sal_Int16 i=0; i < nAttrCount; ++i ) { const rtl::OUString& sAttrName(xAttrList->getNameByIndex( i )); rtl::OUString aLocalName; USHORT nPrefix = GetScImport().GetNamespaceMap().GetKeyByAttrName( sAttrName, &aLocalName ); const rtl::OUString& sValue(xAttrList->getValueByIndex( i )); switch( rAttrTokenMap.Get( nPrefix, aLocalName ) ) { case XML_TOK_SUBTOTAL_RULES_ATTR_BIND_STYLES_TO_CONTENT : { pDatabaseRangeContext->SetSubTotalsBindFormatsToContent(IsXMLToken(sValue, XML_TRUE)); } break; case XML_TOK_SUBTOTAL_RULES_ATTR_CASE_SENSITIVE : { pDatabaseRangeContext->SetSubTotalsIsCaseSensitive(IsXMLToken(sValue, XML_TRUE)); } break; case XML_TOK_SUBTOTAL_RULES_ATTR_PAGE_BREAKS_ON_GROUP_CHANGE : { pDatabaseRangeContext->SetSubTotalsInsertPageBreaks(IsXMLToken(sValue, XML_TRUE)); } break; } } } ScXMLSubTotalRulesContext::~ScXMLSubTotalRulesContext() { } SvXMLImportContext *ScXMLSubTotalRulesContext::CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList ) { SvXMLImportContext *pContext = 0; const SvXMLTokenMap& rTokenMap = GetScImport().GetDatabaseRangeSubTotalRulesElemTokenMap(); switch( rTokenMap.Get( nPrefix, rLName ) ) { case XML_TOK_SUBTOTAL_RULES_SORT_GROUPS : { pContext = new ScXMLSortGroupsContext( GetScImport(), nPrefix, rLName, xAttrList, pDatabaseRangeContext); } break; case XML_TOK_SUBTOTAL_RULES_SUBTOTAL_RULE : { pContext = new ScXMLSubTotalRuleContext( GetScImport(), nPrefix, rLName, xAttrList, pDatabaseRangeContext); } break; } if( !pContext ) pContext = new SvXMLImportContext( GetImport(), nPrefix, rLName ); return pContext; } void ScXMLSubTotalRulesContext::EndElement() { } ScXMLSortGroupsContext::ScXMLSortGroupsContext( ScXMLImport& rImport, USHORT nPrfx, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList, ScXMLDatabaseRangeContext* pTempDatabaseRangeContext) : SvXMLImportContext( rImport, nPrfx, rLName ), pDatabaseRangeContext(pTempDatabaseRangeContext) { pDatabaseRangeContext->SetSubTotalsSortGroups(sal_True); sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0; const SvXMLTokenMap& rAttrTokenMap = GetScImport().GetSubTotalRulesSortGroupsAttrTokenMap(); for( sal_Int16 i=0; i < nAttrCount; ++i ) { const rtl::OUString& sAttrName(xAttrList->getNameByIndex( i )); rtl::OUString aLocalName; USHORT nPrefix = GetScImport().GetNamespaceMap().GetKeyByAttrName( sAttrName, &aLocalName ); const rtl::OUString& sValue(xAttrList->getValueByIndex( i )); switch( rAttrTokenMap.Get( nPrefix, aLocalName ) ) { case XML_TOK_SORT_GROUPS_ATTR_DATA_TYPE : { if (sValue.getLength() > 8) { rtl::OUString sTemp = sValue.copy(0, 8); if (sTemp.compareToAscii(SC_USERLIST) == 0) { pDatabaseRangeContext->SetSubTotalsEnabledUserList(sal_True); sTemp = sValue.copy(8); pDatabaseRangeContext->SetSubTotalsUserListIndex(static_cast<sal_Int16>(sTemp.toInt32())); } else { //if (IsXMLToken(sValue, XML_AUTOMATIC)) //aSortField.FieldType = util::SortFieldType_AUTOMATIC; // is not supported by StarOffice } } else { //if (IsXMLToken(sValue, XML_TEXT)) //aSortField.FieldType = util::SortFieldType_ALPHANUMERIC; // is not supported by StarOffice //else if (IsXMLToken(sValue, XML_NUMBER)) //aSortField.FieldType = util::SortFieldType_NUMERIC; // is not supported by StarOffice } } break; case XML_TOK_SORT_GROUPS_ATTR_ORDER : { if (IsXMLToken(sValue, XML_ASCENDING)) pDatabaseRangeContext->SetSubTotalsAscending(sal_True); else pDatabaseRangeContext->SetSubTotalsAscending(sal_False); } break; } } } ScXMLSortGroupsContext::~ScXMLSortGroupsContext() { } SvXMLImportContext *ScXMLSortGroupsContext::CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList ) { SvXMLImportContext *pContext = 0; if( !pContext ) pContext = new SvXMLImportContext( GetImport(), nPrefix, rLName ); return pContext; } void ScXMLSortGroupsContext::EndElement() { } ScXMLSubTotalRuleContext::ScXMLSubTotalRuleContext( ScXMLImport& rImport, USHORT nPrfx, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList, ScXMLDatabaseRangeContext* pTempDatabaseRangeContext) : SvXMLImportContext( rImport, nPrfx, rLName ), pDatabaseRangeContext(pTempDatabaseRangeContext) { sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0; const SvXMLTokenMap& rAttrTokenMap = GetScImport().GetSubTotalRulesSubTotalRuleAttrTokenMap(); for( sal_Int16 i=0; i < nAttrCount; ++i ) { const rtl::OUString& sAttrName(xAttrList->getNameByIndex( i )); rtl::OUString aLocalName; USHORT nPrefix = GetScImport().GetNamespaceMap().GetKeyByAttrName( sAttrName, &aLocalName ); const rtl::OUString& sValue(xAttrList->getValueByIndex( i )); switch( rAttrTokenMap.Get( nPrefix, aLocalName ) ) { case XML_TOK_SUBTOTAL_RULE_ATTR_GROUP_BY_FIELD_NUMBER : { aSubTotalRule.nSubTotalRuleGroupFieldNumber = static_cast<sal_Int16>(sValue.toInt32()); } break; } } } ScXMLSubTotalRuleContext::~ScXMLSubTotalRuleContext() { } SvXMLImportContext *ScXMLSubTotalRuleContext::CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList ) { SvXMLImportContext *pContext = 0; const SvXMLTokenMap& rTokenMap = GetScImport().GetSubTotalRulesSubTotalRuleElemTokenMap(); switch( rTokenMap.Get( nPrefix, rLName ) ) { case XML_TOK_SUBTOTAL_RULE_SUBTOTAL_FIELD : { pContext = new ScXMLSubTotalFieldContext( GetScImport(), nPrefix, rLName, xAttrList, this); } break; } if( !pContext ) pContext = new SvXMLImportContext( GetImport(), nPrefix, rLName ); return pContext; } void ScXMLSubTotalRuleContext::EndElement() { if (pDatabaseRangeContext) pDatabaseRangeContext->AddSubTotalRule(aSubTotalRule); } ScXMLSubTotalFieldContext::ScXMLSubTotalFieldContext( ScXMLImport& rImport, USHORT nPrfx, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList, ScXMLSubTotalRuleContext* pTempSubTotalRuleContext) : SvXMLImportContext( rImport, nPrfx, rLName ), pSubTotalRuleContext(pTempSubTotalRuleContext) { sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0; const SvXMLTokenMap& rAttrTokenMap = GetScImport().GetSubTotalRuleSubTotalFieldAttrTokenMap(); for( sal_Int16 i=0; i < nAttrCount; ++i ) { const rtl::OUString& sAttrName(xAttrList->getNameByIndex( i )); rtl::OUString aLocalName; USHORT nPrefix = GetScImport().GetNamespaceMap().GetKeyByAttrName( sAttrName, &aLocalName ); const rtl::OUString& sValue(xAttrList->getValueByIndex( i )); switch( rAttrTokenMap.Get( nPrefix, aLocalName ) ) { case XML_TOK_SUBTOTAL_FIELD_ATTR_FIELD_NUMBER : { sFieldNumber = sValue; } break; case XML_TOK_SUBTOTAL_FIELD_ATTR_FUNCTION : { sFunction = sValue; } break; } } } ScXMLSubTotalFieldContext::~ScXMLSubTotalFieldContext() { } SvXMLImportContext *ScXMLSubTotalFieldContext::CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList ) { SvXMLImportContext *pContext = 0; if( !pContext ) pContext = new SvXMLImportContext( GetImport(), nPrefix, rLName ); return pContext; } void ScXMLSubTotalFieldContext::EndElement() { sheet::SubTotalColumn aSubTotalColumn; aSubTotalColumn.Column = sFieldNumber.toInt32(); aSubTotalColumn.Function = ScXMLConverter::GetFunctionFromString( sFunction ); pSubTotalRuleContext->AddSubTotalColumn(aSubTotalColumn); } INTEGRATION: CWS pchfix01 (1.27.214); FILE MERGED 2006/07/12 10:02:10 kaib 1.27.214.1: #i67080# Converted cxx files in sc, added initial project level pch and stripped old PCH definitions. /************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: xmldrani.cxx,v $ * * $Revision: 1.28 $ * * last change: $Author: kz $ $Date: 2006-07-21 12:52:26 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sc.hxx" // INCLUDE --------------------------------------------------------------- #include "xmldrani.hxx" #include "xmlimprt.hxx" #include "xmlfilti.hxx" #include "xmlsorti.hxx" #include "document.hxx" #include "globstr.hrc" #include "docuno.hxx" #include "dbcolect.hxx" #include "datauno.hxx" #ifndef SC_SCATTR_HXX #include "attrib.hxx" #endif #ifndef SC_UNONAMES_HXX #include "unonames.hxx" #endif #ifndef SC_CONVUNO_HXX #include "convuno.hxx" #endif #ifndef _SC_XMLCONVERTER_HXX #include "XMLConverter.hxx" #endif #include <xmloff/xmltkmap.hxx> #include <xmloff/nmspmap.hxx> #ifndef _XMLOFF_XMLTOKEN_HXX #include <xmloff/xmltoken.hxx> #endif #ifndef _XMLOFF_XMLNMSPE_HXX #include <xmloff/xmlnmspe.hxx> #endif #ifndef _XMLOFF_XMLUCONV_HXX #include <xmloff/xmluconv.hxx> #endif #ifndef _XMLOFF_XMLERROR_HXX #include <xmloff/xmlerror.hxx> #endif #include <com/sun/star/sheet/XSpreadsheetDocument.hpp> #include <com/sun/star/sheet/XDatabaseRanges.hpp> #include <com/sun/star/sheet/XDatabaseRange.hpp> #include <com/sun/star/table/CellRangeAddress.hpp> #ifndef _COMPHELPER_EXTRACT_HXX_ #include <comphelper/extract.hxx> #endif #ifndef _COM_SUN_STAR_UNO_RUNTIMEEXCEPTION_HPP_ #include <com/sun/star/uno/RuntimeException.hpp> #endif #ifndef _COM_SUN_STAR_XML_SAX_XLOCATOR_HPP_ #include <com/sun/star/xml/sax/XLocator.hpp> #endif #define SC_ENABLEUSERSORTLIST "EnableUserSortList" #define SC_USERSORTLISTINDEX "UserSortListIndex" #define SC_USERLIST "UserList" using namespace com::sun::star; using namespace xmloff::token; //------------------------------------------------------------------ ScXMLDatabaseRangesContext::ScXMLDatabaseRangesContext( ScXMLImport& rImport, USHORT nPrfx, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList) : SvXMLImportContext( rImport, nPrfx, rLName ) { // has no attributes rImport.LockSolarMutex(); } ScXMLDatabaseRangesContext::~ScXMLDatabaseRangesContext() { GetScImport().UnlockSolarMutex(); } SvXMLImportContext *ScXMLDatabaseRangesContext::CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList ) { SvXMLImportContext *pContext = 0; const SvXMLTokenMap& rTokenMap = GetScImport().GetDatabaseRangesElemTokenMap(); switch( rTokenMap.Get( nPrefix, rLName ) ) { case XML_TOK_DATABASE_RANGE : { pContext = new ScXMLDatabaseRangeContext( GetScImport(), nPrefix, rLName, xAttrList); } break; } if( !pContext ) pContext = new SvXMLImportContext( GetImport(), nPrefix, rLName ); return pContext; } void ScXMLDatabaseRangesContext::EndElement() { } ScXMLDatabaseRangeContext::ScXMLDatabaseRangeContext( ScXMLImport& rImport, USHORT nPrfx, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList) : SvXMLImportContext( rImport, nPrfx, rLName ), nRefresh(0), nSubTotalsUserListIndex(0), bContainsSort(sal_False), bContainsSubTotal(sal_False), bIsSelection(sal_False), bKeepFormats(sal_False), bMoveCells(sal_False), bStripData(sal_False), eOrientation(table::TableOrientation_ROWS), bContainsHeader(sal_True), bAutoFilter(sal_False), bFilterCopyOutputData(sal_False), bFilterIsCaseSensitive(sal_False), bFilterSkipDuplicates(sal_False), bFilterUseRegularExpressions(sal_False), bFilterConditionSourceRange(sal_False), bSubTotalsBindFormatsToContent(sal_False), bSubTotalsIsCaseSensitive(sal_False), bSubTotalsInsertPageBreaks(sal_False), bSubTotalsSortGroups(sal_False), bSubTotalsEnabledUserList(sal_False), bSubTotalsAscending(sal_True), bNative(sal_True), aSortSequence(), sDatabaseRangeName(ScGlobal::GetRscString(STR_DB_NONAME)) { nSourceType = sheet::DataImportMode_NONE; sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0; const SvXMLTokenMap& rAttrTokenMap = GetScImport().GetDatabaseRangeAttrTokenMap(); for( sal_Int16 i=0; i < nAttrCount; ++i ) { const rtl::OUString& sAttrName(xAttrList->getNameByIndex( i )); rtl::OUString aLocalName; USHORT nPrefix = GetScImport().GetNamespaceMap().GetKeyByAttrName( sAttrName, &aLocalName ); const rtl::OUString& sValue(xAttrList->getValueByIndex( i )); switch( rAttrTokenMap.Get( nPrefix, aLocalName ) ) { case XML_TOK_DATABASE_RANGE_ATTR_NAME : { sDatabaseRangeName = sValue; } break; case XML_TOK_DATABASE_RANGE_ATTR_IS_SELECTION : { bIsSelection = IsXMLToken(sValue, XML_TRUE); } break; case XML_TOK_DATABASE_RANGE_ATTR_ON_UPDATE_KEEP_STYLES : { bKeepFormats = IsXMLToken(sValue, XML_TRUE); } break; case XML_TOK_DATABASE_RANGE_ATTR_ON_UPDATE_KEEP_SIZE : { bMoveCells = !IsXMLToken(sValue, XML_TRUE); } break; case XML_TOK_DATABASE_RANGE_ATTR_HAS_PERSISTENT_DATA : { bStripData = !IsXMLToken(sValue, XML_TRUE); } break; case XML_TOK_DATABASE_RANGE_ATTR_ORIENTATION : { if (IsXMLToken(sValue, XML_COLUMN)) eOrientation = table::TableOrientation_COLUMNS; } break; case XML_TOK_DATABASE_RANGE_ATTR_CONTAINS_HEADER : { bContainsHeader = IsXMLToken(sValue, XML_TRUE); } break; case XML_TOK_DATABASE_RANGE_ATTR_DISPLAY_FILTER_BUTTONS : { bAutoFilter = IsXMLToken(sValue, XML_TRUE); } break; case XML_TOK_DATABASE_RANGE_ATTR_TARGET_RANGE_ADDRESS : { sRangeAddress = sValue; } break; case XML_TOK_DATABASE_RANGE_ATTR_REFRESH_DELAY : { double fTime; if( SvXMLUnitConverter::convertTime( fTime, sValue ) ) nRefresh = Max( (sal_Int32)(fTime * 86400.0), (sal_Int32)0 ); } break; } } } ScXMLDatabaseRangeContext::~ScXMLDatabaseRangeContext() { } SvXMLImportContext *ScXMLDatabaseRangeContext::CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList ) { SvXMLImportContext *pContext = 0; const SvXMLTokenMap& rTokenMap = GetScImport().GetDatabaseRangeElemTokenMap(); switch( rTokenMap.Get( nPrefix, rLName ) ) { case XML_TOK_DATABASE_RANGE_SOURCE_SQL : { pContext = new ScXMLSourceSQLContext( GetScImport(), nPrefix, rLName, xAttrList, this); } break; case XML_TOK_DATABASE_RANGE_SOURCE_TABLE : { pContext = new ScXMLSourceTableContext( GetScImport(), nPrefix, rLName, xAttrList, this); } break; case XML_TOK_DATABASE_RANGE_SOURCE_QUERY : { pContext = new ScXMLSourceQueryContext( GetScImport(), nPrefix, rLName, xAttrList, this); } break; case XML_TOK_FILTER : { pContext = new ScXMLFilterContext( GetScImport(), nPrefix, rLName, xAttrList, this); } break; case XML_TOK_SORT : { bContainsSort = sal_True; pContext = new ScXMLSortContext( GetScImport(), nPrefix, rLName, xAttrList, this); } break; case XML_TOK_DATABASE_RANGE_SUBTOTAL_RULES : { bContainsSubTotal = sal_True; pContext = new ScXMLSubTotalRulesContext( GetScImport(), nPrefix, rLName, xAttrList, this); } break; } if( !pContext ) pContext = new SvXMLImportContext( GetImport(), nPrefix, rLName ); return pContext; } void ScXMLDatabaseRangeContext::EndElement() { if (GetScImport().GetModel().is()) { uno::Reference <beans::XPropertySet> xPropertySet( GetScImport().GetModel(), uno::UNO_QUERY ); ScDocument* pDoc = GetScImport().GetDocument(); if (pDoc && xPropertySet.is()) { uno::Reference <sheet::XDatabaseRanges> xDatabaseRanges(xPropertySet->getPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNO_DATABASERNG))), uno::UNO_QUERY); if (xDatabaseRanges.is()) { table::CellRangeAddress aCellRangeAddress; sal_Int32 nOffset(0); if (ScXMLConverter::GetRangeFromString( aCellRangeAddress, sRangeAddress, pDoc, nOffset )) { sal_Bool bInsert(sal_True); try { xDatabaseRanges->addNewByName(sDatabaseRangeName, aCellRangeAddress); } catch ( uno::RuntimeException& rRuntimeException ) { bInsert = sal_False; rtl::OUString sErrorMessage(RTL_CONSTASCII_USTRINGPARAM("DatabaseRange ")); sErrorMessage += sDatabaseRangeName; sErrorMessage += rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(" could not be created with the range ")); sErrorMessage += sRangeAddress; uno::Sequence<rtl::OUString> aSeq(1); aSeq[0] = sErrorMessage; uno::Reference<xml::sax::XLocator> xLocator; GetScImport().SetError(XMLERROR_API | XMLERROR_FLAG_ERROR, aSeq, rRuntimeException.Message, xLocator); } if (bInsert) { uno::Reference <sheet::XDatabaseRange> xDatabaseRange(xDatabaseRanges->getByName(sDatabaseRangeName), uno::UNO_QUERY); if (xDatabaseRange.is()) { uno::Reference <beans::XPropertySet> xDatabaseRangePropertySet (xDatabaseRange, uno::UNO_QUERY); if (xDatabaseRangePropertySet.is()) { xDatabaseRangePropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_KEEPFORM)), uno::makeAny(bKeepFormats)); xDatabaseRangePropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_MOVCELLS)), uno::makeAny(bMoveCells)); xDatabaseRangePropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_STRIPDAT)), uno::makeAny(bStripData)); } uno::Sequence <beans::PropertyValue> aImportDescriptor(xDatabaseRange->getImportDescriptor()); sal_Int32 nImportProperties = aImportDescriptor.getLength(); for (sal_Int16 i = 0; i < nImportProperties; ++i) { if (aImportDescriptor[i].Name == rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_DBNAME))) { if (sDatabaseName.getLength()) { aImportDescriptor[i].Value <<= sDatabaseName; } else { aImportDescriptor[i].Name = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_CONRES)); aImportDescriptor[i].Value <<= sConnectionRessource; } } else if (aImportDescriptor[i].Name == rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_SRCOBJ))) aImportDescriptor[i].Value <<= sSourceObject; else if (aImportDescriptor[i].Name == rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_SRCTYPE))) aImportDescriptor[i].Value <<= nSourceType; else if (aImportDescriptor[i].Name == rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_ISNATIVE))) aImportDescriptor[i].Value <<= bNative; } ScDBCollection* pDBCollection = pDoc->GetDBCollection(); sal_uInt16 nIndex; pDBCollection->SearchName(sDatabaseRangeName, nIndex); ScDBData* pDBData = (*pDBCollection)[nIndex]; pDBData->SetImportSelection(bIsSelection); pDBData->SetAutoFilter(bAutoFilter); if (bAutoFilter) pDoc->ApplyFlagsTab( static_cast<SCCOL>(aCellRangeAddress.StartColumn), static_cast<SCROW>(aCellRangeAddress.StartRow), static_cast<SCCOL>(aCellRangeAddress.EndColumn), static_cast<SCROW>(aCellRangeAddress.StartRow), aCellRangeAddress.Sheet, SC_MF_AUTO ); ScImportParam aImportParam; ScImportDescriptor::FillImportParam(aImportParam, aImportDescriptor); pDBData->SetImportParam(aImportParam); if (bContainsSort) { sal_uInt32 nOldSize(aSortSequence.getLength()); aSortSequence.realloc(nOldSize + 1); beans::PropertyValue aProperty; aProperty.Name = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_ORIENT)); aProperty.Value <<= eOrientation; aSortSequence[nOldSize] = aProperty; ScSortParam aSortParam; ScSortDescriptor::FillSortParam(aSortParam, aSortSequence); //#98317#; until now the Fields are relative to the left top edge of the range, but the // core wants to have the absolute position (column/row) SCCOLROW nFieldStart = aSortParam.bByRow ? static_cast<SCCOLROW>(aCellRangeAddress.StartColumn) : static_cast<SCCOLROW>(aCellRangeAddress.StartRow); for (sal_uInt16 i = 0; i < MAXSORT; ++i) { if (aSortParam.bDoSort[i]) aSortParam.nField[i] += nFieldStart; } pDBData->SetSortParam(aSortParam); } uno::Reference <sheet::XSheetFilterDescriptor> xSheetFilterDescriptor(xDatabaseRange->getFilterDescriptor()); if (xSheetFilterDescriptor.is()) { uno::Reference <beans::XPropertySet> xFilterPropertySet (xSheetFilterDescriptor, uno::UNO_QUERY); if (xFilterPropertySet.is()) { sal_Bool bOrientation(table::TableOrientation_COLUMNS == eOrientation); xFilterPropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_ORIENT)), uno::makeAny(bOrientation)); xFilterPropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_CONTHDR)), uno::makeAny(bContainsHeader)); xFilterPropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_COPYOUT)), uno::makeAny(bFilterCopyOutputData)); xFilterPropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_ISCASE)), uno::makeAny(bFilterIsCaseSensitive)); xFilterPropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_SKIPDUP)), uno::makeAny(bFilterSkipDuplicates)); xFilterPropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_USEREGEX)), uno::makeAny(bFilterUseRegularExpressions)); xFilterPropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_OUTPOS)), uno::makeAny(aFilterOutputPosition)); } xSheetFilterDescriptor->setFilterFields(aFilterFields); if (bFilterConditionSourceRange) { ScRange aAdvSource; ScUnoConversion::FillScRange( aAdvSource, aFilterConditionSourceRangeAddress ); pDBData->SetAdvancedQuerySource(&aAdvSource); } } if (bContainsSubTotal) { uno::Reference <sheet::XSubTotalDescriptor> xSubTotalDescriptor(xDatabaseRange->getSubTotalDescriptor()); if (xSubTotalDescriptor.is()) { uno::Reference <beans::XPropertySet> xSubTotalPropertySet (xSubTotalDescriptor, uno::UNO_QUERY); if( xSubTotalPropertySet.is()) { xSubTotalPropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_BINDFMT)), uno::makeAny(bSubTotalsBindFormatsToContent)); xSubTotalPropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_ENABLEUSERSORTLIST)), uno::makeAny(bSubTotalsEnabledUserList)); xSubTotalPropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_USERSORTLISTINDEX)), uno::makeAny(nSubTotalsUserListIndex)); xSubTotalPropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_INSBRK)), uno::makeAny(bSubTotalsInsertPageBreaks)); xSubTotalPropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_ISCASE)), uno::makeAny(bSubTotalsIsCaseSensitive)); } ScSubTotalParam aSubTotalParam; aSubTotalParam.bDoSort = bSubTotalsSortGroups; aSubTotalParam.bAscending = bSubTotalsAscending; aSubTotalParam.bUserDef = bSubTotalsEnabledUserList; aSubTotalParam.nUserIndex = nSubTotalsUserListIndex; pDBData->SetSubTotalParam(aSubTotalParam); std::vector < ScSubTotalRule >::iterator aItr(aSubTotalRules.begin()); while (!aSubTotalRules.empty()) { xSubTotalDescriptor->addNew(aItr->aSubTotalColumns, aItr->nSubTotalRuleGroupFieldNumber); aItr = aSubTotalRules.erase(aItr); } } } if ( pDBData->HasImportParam() && !pDBData->HasImportSelection() ) { pDBData->SetRefreshDelay( nRefresh ); pDBData->SetRefreshHandler( pDBCollection->GetRefreshHandler() ); pDBData->SetRefreshControl( pDoc->GetRefreshTimerControlAddress() ); } } } } } } } } ScXMLSourceSQLContext::ScXMLSourceSQLContext( ScXMLImport& rImport, USHORT nPrfx, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList, ScXMLDatabaseRangeContext* pTempDatabaseRangeContext) : SvXMLImportContext( rImport, nPrfx, rLName ), pDatabaseRangeContext(pTempDatabaseRangeContext) { sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0; const SvXMLTokenMap& rAttrTokenMap = GetScImport().GetDatabaseRangeSourceSQLAttrTokenMap(); for( sal_Int16 i=0; i < nAttrCount; ++i ) { const rtl::OUString& sAttrName(xAttrList->getNameByIndex( i )); rtl::OUString aLocalName; USHORT nPrefix = GetScImport().GetNamespaceMap().GetKeyByAttrName( sAttrName, &aLocalName ); const rtl::OUString& sValue(xAttrList->getValueByIndex( i )); switch( rAttrTokenMap.Get( nPrefix, aLocalName ) ) { case XML_TOK_SOURCE_SQL_ATTR_DATABASE_NAME : { sDBName = sValue; } break; case XML_TOK_SOURCE_SQL_ATTR_SQL_STATEMENT : { pDatabaseRangeContext->SetSourceObject(sValue); } break; case XML_TOK_SOURCE_SQL_ATTR_PARSE_SQL_STATEMENT : { pDatabaseRangeContext->SetNative(IsXMLToken(sValue, XML_TRUE)); } break; } } pDatabaseRangeContext->SetSourceType(sheet::DataImportMode_SQL); } ScXMLSourceSQLContext::~ScXMLSourceSQLContext() { } SvXMLImportContext *ScXMLSourceSQLContext::CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList ) { SvXMLImportContext *pContext = 0; if ( nPrefix == XML_NAMESPACE_FORM ) { if (IsXMLToken(rLName, XML_CONNECTION_RESOURCE) && (sDBName.getLength() == 0)) { pContext = new ScXMLConResContext( GetScImport(), nPrefix, rLName, xAttrList, pDatabaseRangeContext); } } if( !pContext ) pContext = new SvXMLImportContext( GetImport(), nPrefix, rLName ); return pContext; } void ScXMLSourceSQLContext::EndElement() { if (sDBName.getLength()) pDatabaseRangeContext->SetDatabaseName(sDBName); } ScXMLSourceTableContext::ScXMLSourceTableContext( ScXMLImport& rImport, USHORT nPrfx, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList, ScXMLDatabaseRangeContext* pTempDatabaseRangeContext) : SvXMLImportContext( rImport, nPrfx, rLName ), pDatabaseRangeContext(pTempDatabaseRangeContext) { sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0; const SvXMLTokenMap& rAttrTokenMap = GetScImport().GetDatabaseRangeSourceTableAttrTokenMap(); for( sal_Int16 i=0; i < nAttrCount; ++i ) { const rtl::OUString& sAttrName(xAttrList->getNameByIndex( i )); rtl::OUString aLocalName; USHORT nPrefix = GetScImport().GetNamespaceMap().GetKeyByAttrName( sAttrName, &aLocalName ); const rtl::OUString& sValue(xAttrList->getValueByIndex( i )); switch( rAttrTokenMap.Get( nPrefix, aLocalName ) ) { case XML_TOK_SOURCE_TABLE_ATTR_DATABASE_NAME : { sDBName = sValue; } break; case XML_TOK_SOURCE_TABLE_ATTR_TABLE_NAME : { pDatabaseRangeContext->SetSourceObject(sValue); } break; } } pDatabaseRangeContext->SetSourceType(sheet::DataImportMode_TABLE); } ScXMLSourceTableContext::~ScXMLSourceTableContext() { } SvXMLImportContext *ScXMLSourceTableContext::CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList ) { SvXMLImportContext *pContext = 0; if ( nPrefix == XML_NAMESPACE_FORM ) { if (IsXMLToken(rLName, XML_CONNECTION_RESOURCE) && (sDBName.getLength() == 0)) { pContext = new ScXMLConResContext( GetScImport(), nPrefix, rLName, xAttrList, pDatabaseRangeContext); } } if( !pContext ) pContext = new SvXMLImportContext( GetImport(), nPrefix, rLName ); return pContext; } void ScXMLSourceTableContext::EndElement() { if (sDBName.getLength()) pDatabaseRangeContext->SetDatabaseName(sDBName); } ScXMLSourceQueryContext::ScXMLSourceQueryContext( ScXMLImport& rImport, USHORT nPrfx, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList, ScXMLDatabaseRangeContext* pTempDatabaseRangeContext) : SvXMLImportContext( rImport, nPrfx, rLName ), pDatabaseRangeContext(pTempDatabaseRangeContext) { sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0; const SvXMLTokenMap& rAttrTokenMap = GetScImport().GetDatabaseRangeSourceQueryAttrTokenMap(); for( sal_Int16 i=0; i < nAttrCount; ++i ) { const rtl::OUString& sAttrName(xAttrList->getNameByIndex( i )); rtl::OUString aLocalName; USHORT nPrefix = GetScImport().GetNamespaceMap().GetKeyByAttrName( sAttrName, &aLocalName ); const rtl::OUString& sValue(xAttrList->getValueByIndex( i )); switch( rAttrTokenMap.Get( nPrefix, aLocalName ) ) { case XML_TOK_SOURCE_QUERY_ATTR_DATABASE_NAME : { sDBName = sValue; } break; case XML_TOK_SOURCE_QUERY_ATTR_QUERY_NAME : { pDatabaseRangeContext->SetSourceObject(sValue); } break; } } pDatabaseRangeContext->SetSourceType(sheet::DataImportMode_QUERY); } ScXMLSourceQueryContext::~ScXMLSourceQueryContext() { } SvXMLImportContext *ScXMLSourceQueryContext::CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList ) { SvXMLImportContext *pContext = 0; if ( nPrefix == XML_NAMESPACE_FORM ) { if (IsXMLToken(rLName, XML_CONNECTION_RESOURCE) && (sDBName.getLength() == 0)) { pContext = new ScXMLConResContext( GetScImport(), nPrefix, rLName, xAttrList, pDatabaseRangeContext); } } if( !pContext ) pContext = new SvXMLImportContext( GetImport(), nPrefix, rLName ); return pContext; } void ScXMLSourceQueryContext::EndElement() { if (sDBName.getLength()) pDatabaseRangeContext->SetDatabaseName(sDBName); } ScXMLConResContext::ScXMLConResContext( ScXMLImport& rImport, USHORT nPrfx, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList, ScXMLDatabaseRangeContext* pTempDatabaseRangeContext) : SvXMLImportContext( rImport, nPrfx, rLName ), pDatabaseRangeContext( pTempDatabaseRangeContext ) { rtl::OUString sConRes; sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0; const SvXMLTokenMap& rAttrTokenMap = GetScImport().GetDatabaseRangeSourceSQLAttrTokenMap(); for( sal_Int16 i=0; i < nAttrCount; i++ ) { rtl::OUString sAttrName = xAttrList->getNameByIndex( i ); rtl::OUString aLocalName; USHORT nPrefix = GetScImport().GetNamespaceMap().GetKeyByAttrName( sAttrName, &aLocalName ); rtl::OUString sValue = xAttrList->getValueByIndex( i ); if (nPrefix == XML_NAMESPACE_XLINK) { if (IsXMLToken(aLocalName, XML_HREF)) sConRes = sValue; } } if (sConRes.getLength()) pDatabaseRangeContext->SetConnectionRessource(sConRes); } ScXMLConResContext::~ScXMLConResContext() { } SvXMLImportContext *ScXMLConResContext::CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList ) { SvXMLImportContext *pContext = 0; if( !pContext ) pContext = new SvXMLImportContext( GetImport(), nPrefix, rLName ); return pContext; } void ScXMLConResContext::EndElement() { } ScXMLSubTotalRulesContext::ScXMLSubTotalRulesContext( ScXMLImport& rImport, USHORT nPrfx, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList, ScXMLDatabaseRangeContext* pTempDatabaseRangeContext) : SvXMLImportContext( rImport, nPrfx, rLName ), pDatabaseRangeContext(pTempDatabaseRangeContext) { sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0; const SvXMLTokenMap& rAttrTokenMap = GetScImport().GetDatabaseRangeSubTotalRulesAttrTokenMap(); for( sal_Int16 i=0; i < nAttrCount; ++i ) { const rtl::OUString& sAttrName(xAttrList->getNameByIndex( i )); rtl::OUString aLocalName; USHORT nPrefix = GetScImport().GetNamespaceMap().GetKeyByAttrName( sAttrName, &aLocalName ); const rtl::OUString& sValue(xAttrList->getValueByIndex( i )); switch( rAttrTokenMap.Get( nPrefix, aLocalName ) ) { case XML_TOK_SUBTOTAL_RULES_ATTR_BIND_STYLES_TO_CONTENT : { pDatabaseRangeContext->SetSubTotalsBindFormatsToContent(IsXMLToken(sValue, XML_TRUE)); } break; case XML_TOK_SUBTOTAL_RULES_ATTR_CASE_SENSITIVE : { pDatabaseRangeContext->SetSubTotalsIsCaseSensitive(IsXMLToken(sValue, XML_TRUE)); } break; case XML_TOK_SUBTOTAL_RULES_ATTR_PAGE_BREAKS_ON_GROUP_CHANGE : { pDatabaseRangeContext->SetSubTotalsInsertPageBreaks(IsXMLToken(sValue, XML_TRUE)); } break; } } } ScXMLSubTotalRulesContext::~ScXMLSubTotalRulesContext() { } SvXMLImportContext *ScXMLSubTotalRulesContext::CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList ) { SvXMLImportContext *pContext = 0; const SvXMLTokenMap& rTokenMap = GetScImport().GetDatabaseRangeSubTotalRulesElemTokenMap(); switch( rTokenMap.Get( nPrefix, rLName ) ) { case XML_TOK_SUBTOTAL_RULES_SORT_GROUPS : { pContext = new ScXMLSortGroupsContext( GetScImport(), nPrefix, rLName, xAttrList, pDatabaseRangeContext); } break; case XML_TOK_SUBTOTAL_RULES_SUBTOTAL_RULE : { pContext = new ScXMLSubTotalRuleContext( GetScImport(), nPrefix, rLName, xAttrList, pDatabaseRangeContext); } break; } if( !pContext ) pContext = new SvXMLImportContext( GetImport(), nPrefix, rLName ); return pContext; } void ScXMLSubTotalRulesContext::EndElement() { } ScXMLSortGroupsContext::ScXMLSortGroupsContext( ScXMLImport& rImport, USHORT nPrfx, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList, ScXMLDatabaseRangeContext* pTempDatabaseRangeContext) : SvXMLImportContext( rImport, nPrfx, rLName ), pDatabaseRangeContext(pTempDatabaseRangeContext) { pDatabaseRangeContext->SetSubTotalsSortGroups(sal_True); sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0; const SvXMLTokenMap& rAttrTokenMap = GetScImport().GetSubTotalRulesSortGroupsAttrTokenMap(); for( sal_Int16 i=0; i < nAttrCount; ++i ) { const rtl::OUString& sAttrName(xAttrList->getNameByIndex( i )); rtl::OUString aLocalName; USHORT nPrefix = GetScImport().GetNamespaceMap().GetKeyByAttrName( sAttrName, &aLocalName ); const rtl::OUString& sValue(xAttrList->getValueByIndex( i )); switch( rAttrTokenMap.Get( nPrefix, aLocalName ) ) { case XML_TOK_SORT_GROUPS_ATTR_DATA_TYPE : { if (sValue.getLength() > 8) { rtl::OUString sTemp = sValue.copy(0, 8); if (sTemp.compareToAscii(SC_USERLIST) == 0) { pDatabaseRangeContext->SetSubTotalsEnabledUserList(sal_True); sTemp = sValue.copy(8); pDatabaseRangeContext->SetSubTotalsUserListIndex(static_cast<sal_Int16>(sTemp.toInt32())); } else { //if (IsXMLToken(sValue, XML_AUTOMATIC)) //aSortField.FieldType = util::SortFieldType_AUTOMATIC; // is not supported by StarOffice } } else { //if (IsXMLToken(sValue, XML_TEXT)) //aSortField.FieldType = util::SortFieldType_ALPHANUMERIC; // is not supported by StarOffice //else if (IsXMLToken(sValue, XML_NUMBER)) //aSortField.FieldType = util::SortFieldType_NUMERIC; // is not supported by StarOffice } } break; case XML_TOK_SORT_GROUPS_ATTR_ORDER : { if (IsXMLToken(sValue, XML_ASCENDING)) pDatabaseRangeContext->SetSubTotalsAscending(sal_True); else pDatabaseRangeContext->SetSubTotalsAscending(sal_False); } break; } } } ScXMLSortGroupsContext::~ScXMLSortGroupsContext() { } SvXMLImportContext *ScXMLSortGroupsContext::CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList ) { SvXMLImportContext *pContext = 0; if( !pContext ) pContext = new SvXMLImportContext( GetImport(), nPrefix, rLName ); return pContext; } void ScXMLSortGroupsContext::EndElement() { } ScXMLSubTotalRuleContext::ScXMLSubTotalRuleContext( ScXMLImport& rImport, USHORT nPrfx, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList, ScXMLDatabaseRangeContext* pTempDatabaseRangeContext) : SvXMLImportContext( rImport, nPrfx, rLName ), pDatabaseRangeContext(pTempDatabaseRangeContext) { sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0; const SvXMLTokenMap& rAttrTokenMap = GetScImport().GetSubTotalRulesSubTotalRuleAttrTokenMap(); for( sal_Int16 i=0; i < nAttrCount; ++i ) { const rtl::OUString& sAttrName(xAttrList->getNameByIndex( i )); rtl::OUString aLocalName; USHORT nPrefix = GetScImport().GetNamespaceMap().GetKeyByAttrName( sAttrName, &aLocalName ); const rtl::OUString& sValue(xAttrList->getValueByIndex( i )); switch( rAttrTokenMap.Get( nPrefix, aLocalName ) ) { case XML_TOK_SUBTOTAL_RULE_ATTR_GROUP_BY_FIELD_NUMBER : { aSubTotalRule.nSubTotalRuleGroupFieldNumber = static_cast<sal_Int16>(sValue.toInt32()); } break; } } } ScXMLSubTotalRuleContext::~ScXMLSubTotalRuleContext() { } SvXMLImportContext *ScXMLSubTotalRuleContext::CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList ) { SvXMLImportContext *pContext = 0; const SvXMLTokenMap& rTokenMap = GetScImport().GetSubTotalRulesSubTotalRuleElemTokenMap(); switch( rTokenMap.Get( nPrefix, rLName ) ) { case XML_TOK_SUBTOTAL_RULE_SUBTOTAL_FIELD : { pContext = new ScXMLSubTotalFieldContext( GetScImport(), nPrefix, rLName, xAttrList, this); } break; } if( !pContext ) pContext = new SvXMLImportContext( GetImport(), nPrefix, rLName ); return pContext; } void ScXMLSubTotalRuleContext::EndElement() { if (pDatabaseRangeContext) pDatabaseRangeContext->AddSubTotalRule(aSubTotalRule); } ScXMLSubTotalFieldContext::ScXMLSubTotalFieldContext( ScXMLImport& rImport, USHORT nPrfx, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList, ScXMLSubTotalRuleContext* pTempSubTotalRuleContext) : SvXMLImportContext( rImport, nPrfx, rLName ), pSubTotalRuleContext(pTempSubTotalRuleContext) { sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0; const SvXMLTokenMap& rAttrTokenMap = GetScImport().GetSubTotalRuleSubTotalFieldAttrTokenMap(); for( sal_Int16 i=0; i < nAttrCount; ++i ) { const rtl::OUString& sAttrName(xAttrList->getNameByIndex( i )); rtl::OUString aLocalName; USHORT nPrefix = GetScImport().GetNamespaceMap().GetKeyByAttrName( sAttrName, &aLocalName ); const rtl::OUString& sValue(xAttrList->getValueByIndex( i )); switch( rAttrTokenMap.Get( nPrefix, aLocalName ) ) { case XML_TOK_SUBTOTAL_FIELD_ATTR_FIELD_NUMBER : { sFieldNumber = sValue; } break; case XML_TOK_SUBTOTAL_FIELD_ATTR_FUNCTION : { sFunction = sValue; } break; } } } ScXMLSubTotalFieldContext::~ScXMLSubTotalFieldContext() { } SvXMLImportContext *ScXMLSubTotalFieldContext::CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList ) { SvXMLImportContext *pContext = 0; if( !pContext ) pContext = new SvXMLImportContext( GetImport(), nPrefix, rLName ); return pContext; } void ScXMLSubTotalFieldContext::EndElement() { sheet::SubTotalColumn aSubTotalColumn; aSubTotalColumn.Column = sFieldNumber.toInt32(); aSubTotalColumn.Function = ScXMLConverter::GetFunctionFromString( sFunction ); pSubTotalRuleContext->AddSubTotalColumn(aSubTotalColumn); }
// Copyright (c) 2015 Flowgrammable.org // All rights reserved #include "../libmatch/basic_trie.cpp" #include <iostream> #include <vector> #include <string> #include <stdio.h> #include <fstream> #include <cstdint> #include <sstream> #include <iomanip> #include <math.h> #include <chrono> #include <algorithm> #include <functional> using namespace std; using ns = chrono::nanoseconds; using ms = chrono::microseconds; using get_time = chrono::steady_clock ; struct Result { // define the result struct for merging algorithm int flag = -1; // show the different bit position int dif = 0; // the number bit of difference }; // Matches integer type Rule strTint(string rulestr) { Rule rule; rule.mask = 0; rule.value = 0; // Find the position of ".", which spilit IP address to 4 parts size_t p1 = rulestr.find_first_of(" "); string substr1 = rulestr.substr(0,p1); string substr2 = rulestr.substr((p1 + 1)); rule.value = stoull(substr1); // unsigned long long 64bit rule.mask = stoull(substr2); return rule; } /* * Check the mask part relation * whether is subset * the "1" bit position */ bool is_subset(Rule a, Rule b) { vector<int> vec_a; vector<int> vec_b; // Get the "1" bit position for the mask part of two rules for (int i = 0; i < 64; i++) { if ((a.mask & (uint64_t(1) << i)) == 1) { vec_a.push_back(i); } if ((b.mask & (uint64_t(1) << i)) == 1) { vec_b.push_back(i); } } // Check the vec_a and vec_b is subset or not std::sort(vec_a.begin(),vec_a.end()); std::sort(vec_b.begin(),vec_b.end()); if (std::includes (vec_a.begin(), vec_a.end(), vec_b.begin(),vec_b.end()) || std::includes (vec_b.begin(), vec_b.end(), vec_a.begin(),vec_a.end())) { return true; } else { return false; } } /* * Merge the rules between the first rule and second rule * depends on the bits of every column * if in each column, it has "1" and "0" or "*" */ Result is_mergeable(Rule firstrule, Rule secondrule) { Result ret; Rule rule1; rule1.mask = firstrule.mask | secondrule.mask; //cout << "rule1.mask = " << rule1.mask << endl; if (rule1.mask == 0) { // Check the value part is the same or not, because there is no "*" for (int q = 0; q < 64; q++) { // Check every bit position on the value part if ((firstrule.value & (uint64_t(1) << q)) != (secondrule.value & (uint64_t(1) << q)) ) { // If the bit position are not the same, flag and dif value changes ret.flag = q; // show the bit position ret.dif++; } else { continue; } } // Get all the difference bit position between two rules (mask value = 0) } else { // If the mask value is not 0, which means the mask value part has the "*", wildcard for (int k = 0; k < 64; k++) { // Get all the bit positions of "0" in mask value part if ((rule1.mask & (uint64_t(1) << k)) == 0) { // check the value part, the hamming distance // Check the hamming distance between the value part in the "0" positions if ((firstrule.value & (uint64_t(1) << k)) != (secondrule.value & (uint64_t(1) << k)) ) { ret.flag = k; // show the bit position ret.dif++; } else { continue; } } else { continue; } } } return ret; // The condition for merging, hamming distance smaller than 1 } vector<Rule> merge_rules(vector<Rule>& ruleList) { // Copy into a new vector vector<Rule> new_rule_list(ruleList); Rule newRule7; for (int i = 0; i < new_rule_list.size() - 1; i++) { for (int j = i+1; j < new_rule_list.size(); j++) { // The condition for able to merging // If the two rules' mask value part is the same if (new_rule_list.at(i).action == new_rule_list.at(j).action) { if (new_rule_list.at(i).mask == new_rule_list.at(j).mask) { // Just compare the value part when the mask part is "0", ignor the "1" part Result ret2 = is_mergeable(new_rule_list.at(i), new_rule_list.at(j)); // Get the ret2 value, to see the bit position difference and the flag value //cout << "i =" << i << " " << "j =" << j << " " << "dif =" << ret2.dif << " " << "flag =" << ret2.flag << endl; if (ret2.dif == 0) { // the value part is the same on the "0" positions at mask part //cout << "Merge rules" << endl; newRule7.mask = (new_rule_list.at(i).mask | new_rule_list.at(j).mask); newRule7.value = new_rule_list.at(i).value & new_rule_list.at(j).value; // The merged rule's priority should equal to the highest priority newRule7.priority = min( new_rule_list.at(i).priority, new_rule_list.at(j).priority ); newRule7.action = new_rule_list.at(i).action; //newRule7.priority = new_rule_list.size() - 1; //cout << "value = " << newRule7.value << " " << "mask = " << newRule7.mask << " " << "priority = " << newRule7.priority << endl; new_rule_list.erase(new_rule_list.begin() + i); new_rule_list.erase(new_rule_list.begin() + (j-1)); // Insert the new merged rule into the beginning of the vector new_rule_list.push_back(newRule7); i = -1; break; } if (ret2.dif == 1) { // There is just one bit position different //cout << "Merge rules" << endl; newRule7.mask = (new_rule_list.at(i).mask | new_rule_list.at(j).mask) + (uint64_t(1) << ret2.flag); newRule7.value = new_rule_list.at(i).value & new_rule_list.at(j).value; newRule7.priority = min( new_rule_list.at(i).priority, new_rule_list.at(j).priority ); newRule7.action = new_rule_list.at(i).action; //newRule7.priority = new_rule_list.size() - 1; //cout << "value = " << newRule7.value << " " << "mask = " << newRule7.mask << " " << "priority = " << newRule7.priority << endl; new_rule_list.erase(new_rule_list.begin() + i); new_rule_list.erase(new_rule_list.begin() + (j-1)); // Insert the new merged rule into the beginning of the vector new_rule_list.push_back(newRule7); i = -1; break; } else { continue; } } else { continue; } } else { continue; } } } /* for (int k = 0; k < new_rule_list.size(); k++) { cout << "value part:" << new_rule_list.at(k).value << " " << "mask part:" << new_rule_list.at(k).mask << endl; } */ return new_rule_list; } /* * Check whether the new rule is a prefix rule * if yes, do the LPM insertion * if not, do the expand rule function */ bool is_prefix(Rule& rule) { // Store the wildcard postion into vector maskPosion vector<uint32_t> maskPosition; // Check the mask field from the lower bit for(int i = 0; i < 64; i++) { // if this: get the position whose bit is 1 (have wildcard) if((rule.mask >> i) & uint64_t(1) == 1) { maskPosition.push_back(i); } } uint32_t num = maskPosition.size(); // num is the number of wildcard if (rule.mask == (uint64_t(1) << num)-1) { return true; } else { return false; } } // Sorting the rules in an asscending order bool wayToSort(Rule aa, Rule bb) { return (aa.mask < bb.mask); } bool wayToSort1(Rule aaa, Rule bbb) { return (aaa.value < bbb.value); } /* * Sorting the prefix format rules into asscending order, denpending on the prefix length * using the std::sort function */ vector<Rule> sort_rules(vector<Rule>& ruleList) { std::sort(ruleList.begin(), ruleList.end(), wayToSort); /* cout << "mark" << "===============" << endl; for (int k = 0; k < ruleList.size(); k ++) { cout << ruleList[k].value << ", " << ruleList[k].mask << endl; } */ vector<Rule> sortTable; vector<Rule> sortTotalTable; // Determine the size of combined table sortTotalTable.reserve(ruleList.size()); for (int i = 0; i < ruleList.size(); i ++) { if (i != ruleList.size() - 1) { if (ruleList.at(i).mask == ruleList.at(i+1).mask) { // if the mask value is the same, push into the same vector //cout << "test" << endl; sortTable.push_back(ruleList.at(i)); continue; } else { sortTable.push_back(ruleList.at(i)); //cout << "i = " << i << endl; std::sort(sortTable.begin(), sortTable.end(), wayToSort1); sortTotalTable.insert( sortTotalTable.end(), sortTable.begin(), sortTable.end() ); /* for (int k = 0; k < sortTotalTable.size(); k ++) { cout << sortTotalTable[k].value << ", " << sortTotalTable[k].mask << endl; } cout << "sortTotalTable size = " << sortTotalTable.size() << endl; */ // Delete the current contents, clear the memory sortTable.clear(); //cout << "sortTable size = " << sortTable.size() << endl; continue; } } else { // for the last element in the vector // for avoiding the over-range of the vector if (ruleList.at(i).mask == ruleList.at(i-1).mask) { sortTable.push_back(ruleList.at(i)); //cout << "i = " << i << endl; std::sort(sortTable.begin(), sortTable.end(), wayToSort1); sortTotalTable.insert( sortTotalTable.end(), sortTable.begin(), sortTable.end() ); } else { std::sort(sortTable.begin(), sortTable.end(), wayToSort1); sortTotalTable.insert( sortTotalTable.end(), sortTable.begin(), sortTable.end() ); sortTable.clear(); sortTable.push_back(ruleList.at(i)); sortTotalTable.insert( sortTotalTable.end(), sortTable.begin(), sortTable.end() ); } } } return sortTotalTable; } /* * Generate the two dimensional array (generate delta array) from the pingRulesTable array * With all the bits in each rule, including "0" and "1" * Caculate the score--the sum of column */ vector<int> generate_delta(vector<Rule>& ruleList) { vector<uint64_t> sumColumn; for (int j = 0; j < 64; j++) { uint32_t score = 0; for (int i = 0; i < ruleList.size(); i++) { score += ((((ruleList.at(i)).mask) >> j) & uint64_t(1)); } sumColumn.push_back(score); } // Copy the sumColumn vector to a new vector vector<uint64_t> newSumColumn(sumColumn); /* * Checked the newSumColumn vector is the same with the sumColumn vector cout << newSumColumn.size() << endl; for (i = 0; i < newSumColumn.size(); i++) { cout << newSumColumn[i] << endl; } */ // Sort the newSumColumn vector in descending order std::sort(newSumColumn.begin(), newSumColumn.end(), std::greater<uint64_t>()); /* * Checked the descending order is correct or not for (i = 0; i < newSumColumn.size(); i++) { cout << newSumColumn[i] << endl; } */ // Construct the delta(): the rearrangement operation {left shift, right shift, and no change} // the element in delta vector, can be negative, positive and "0" vector<int> delta; // checkpoint is the index/subscript of the newSumColumn has the same value with the sumColumn uint32_t checkpoint = 0; int gap = 0; // Gap is the difference between the original and new sumcolumn vectors for (int i = 0; i < sumColumn.size(); i++) { //cout << "mark1" << " " << sumColumn[i] << endl; for (int j = 0; j < newSumColumn.size(); j++) { //cout << newSumColumn[j] << endl; // Check the first equal element, if it is true, then return the checkpoint if (newSumColumn[j] != sumColumn[i]) { continue; } else if (newSumColumn[j] == sumColumn[i]) { checkpoint = j; newSumColumn[j] = 132; // make the matched column invalid break; } else { // Search all the 64 values, still didn't find the same value cout << "Error occurs" << endl; } } // Get the difference between the original vector data and the sorted vector data // Create the rearrangement operation gap = i - checkpoint; delta.push_back(gap); } return delta; } /* * Generate the new rule after the delta operations * if the element value of delta vector is negative, which means left shift * if the element value of delta vector is positive, which means right shift * if the element value of delta vector is "0", which means no change */ // Create a new pingRulesTable for the new rearrangement rules //vector<Rule> newPingRulesTable; // for each bit of each rule vector<Rule> rules_rearrange(vector<Rule>& oldRuleList, vector<int> delta_array) { vector<Rule> sumRulesTable; // for a new rule for (int i = 0; i < oldRuleList.size(); i++) { Rule newRule; for (int j = 0; j < 64; j++) { Rule subRule; if (delta_array[j] < 0) { // if it is negative, do the left shift // from the lsb position, do the correct operations // Note: because here is 64 bit, if we just use 1 to do left shift, it will occur overflow // since "1" is 32bit by default subRule.value = ( (( (oldRuleList[i].value) & (uint64_t(1) << j) ) ) << (abs(delta_array[j])) ); subRule.mask = ( (( (oldRuleList[i].mask) & (uint64_t(1) << j) ) ) << (abs(delta_array[j])) ); } else if (delta_array[j] > 0) { // if it is positive, do the right shift subRule.value = ( (( (oldRuleList[i].value) & (uint64_t(1) << j) ) ) >> (abs(delta_array[j])) ); subRule.mask = ( (( (oldRuleList[i].mask) & (uint64_t(1) << j) ) ) >> (abs(delta_array[j])) ); } else if (delta_array[j] == 0) { // if it is "0", no change subRule.value = (( (oldRuleList[i].value) & (uint64_t(1) << j) ) ); subRule.mask = (( (oldRuleList[i].mask) & (uint64_t(1) << j) ) ); } newRule.value |= subRule.value; newRule.mask |= subRule.mask; //cout << j << " " << newRule.mask << endl; newRule.priority = oldRuleList[i].priority; newRule.action = oldRuleList[i].action; } sumRulesTable.push_back(newRule); } return sumRulesTable; } /* * Rearrange each key in the keyTable according to the delta vector * because the rules are being reordered by the delta vector */ uint64_t keys_rearrange(uint64_t key, vector<int> delta_array) { // Calculate the key rearrangement configure time basing on the delta vector uint64_t newKey = 0; // new key after reordering for (int j = 0; j < 64; j++) { uint64_t subKey = 0; // subKey is the single bit value of each key if (delta_array[j] < 0) { subKey = ( (( key & (uint64_t(1) << j) ) ) << (abs(delta_array[j])) ); } else if (delta_array[j] > 0) { // if it is positive, do the right shift subKey = ( (( key & (uint64_t(1) << j) ) ) >> (abs(delta_array[j])) ); } else if (delta_array[j] == 0) { // if it is "0", no change subKey = (( key & (uint64_t(1) << j) ) ); } newKey |= subKey; } return newKey; //cout << newKey << endl; } /* *Create a function called construct the data structure *Insert rules */ /* *Create a function called the whole search process *search rules */ static int threshold; // Set the wildcard num as a variable int main(int argc, char* argv[]) { // Input the action file vector<int> actions; string line1; uint32_t action1; ifstream file2 (argv[3]); // Read action from the txt file if (file2.is_open()) { while (!file2.eof()) { getline(file2, line1); if (!line1.empty()) { action1 = stoull(line1); actions.push_back(action1); } } } file2.close(); // Set the hard line for the memory cost == number of trie node threshold = stoull(argv[4]); ifstream file (argv[1]); // Read the rules from txt file vector<Rule> oldpingRulesTable; int i = 0; if (file.is_open()) { while (!file.eof()) { // Read lines as long as the file is string line; getline(file,line); if(!line.empty()) { Rule rule = strTint(line); // Add the priority feature when generating rules // Priority is in-order of generating rule.action = actions[i]; i = i + 1; rule.priority = i; //rule.priority = ++i; // Push the input file into ruleArray oldpingRulesTable.push_back(rule); } } } file.close(); // Need to check the priority preserve the same after sorting vector<Rule> pingRulesTable = sort_rules(oldpingRulesTable); //cout << "Sorted total size = " << pingRulesTable.size() << endl; //vector<Rule> pingRulesTable = merge_rules(oldpingRulesTable); //cout << "Merged total size = " << pingRulesTable.size() << endl; /* for (int k = 0; k < pingRulesTable.size(); k++) { cout << pingRulesTable[k].priority << " " << pingRulesTable[k].action << " " << pingRulesTable[k].value << " " << pingRulesTable[k].mask << endl; } */ // Read in keys from file: ifstream file1 (argv[2]); vector<uint64_t> keyTable; if (file1.is_open()) { while (!file1.eof()) { // Read lines as long as the file is string packet; getline(file1,packet); if(!packet.empty()) { uint64_t key = stoull(packet); // Push the input file into ruleArray keyTable.push_back(key); } } } file1.close(); cout << "The num of keys: " << keyTable.size() << endl; // Genearte the different size of key nums /* vector<uint64_t> keyTable; for (int i = 0; i < 17642000; i++) { keyTable.push_back(keyTable1[i]); } */ /* * Grouping algorithm * Use the is_cross_pattern function to check the grouping number * Avoid the expanding number is too large * how to improve the grouping algorithm?? * add the threshold, to adjust the grouping seperation */ // For the grouped rule table vector<uint32_t> groupVector; vector<Rule> newList; // avoid the bad allocation memory // The grouping algorithm is to create the most number of // groups without expansion /* * Noexpand group algorithm */ for ( int i = 0; i < pingRulesTable.size(); i++ ) { if (i < (pingRulesTable.size()-1)) { newList.push_back(pingRulesTable[i]); vector<int> new_generated_delta = generate_delta(newList); // Create the rearranged rule set vector<Rule> new_table_list = rules_rearrange( newList, new_generated_delta ); for ( int k = 0; k < new_table_list.size(); k++ ) { //Trie trie1; // for caculating the trie1.new_num // for guarantee avoding the bad memory alloc if ( is_prefix(new_table_list.at (k)) ) { // if this is prefix rules, don't need to expand //trie1.insert_prefix_rule_priority(new_table_list.at(k)); continue; } else { groupVector.push_back(i-1); // clear the newList vector, becasue this is a seperated group newList.clear(); i = i -1; break; } } } else { groupVector.push_back(i); } } //========================================== // Copy the groupVector, in order to recover the deleted element later vector<uint32_t> original_groupVector(groupVector); cout << "(No expand) Num of Original groups is:" << " " << original_groupVector.size() << endl; /* for (i = 0; i < original_groupVector.size(); i++) { cout << "Original Group index: " << i << "," << original_groupVector[i] << endl; } */ /* Create all the subgroups * The big array is called bigArray * insert the whole rule set into the separate groups */ int test_flag = 0; // This variable is used to break the nested loop for (int v = 0; v < original_groupVector.size(); v++) { vector< vector<Rule> > bigArray; // it's a intermediate variable, two-dimensional array // Create a new sub group by copying the related rules for (int m = 0; m < groupVector.size(); m++) { bigArray.push_back(vector<Rule> ()); } for (int j = 0; j < groupVector.size(); j++) { if (j == 0) { for (int i = 0; i < (groupVector[j] + 1); i++) { bigArray[j].push_back(pingRulesTable.at(i)); } continue; } else { for (int k = (groupVector[j-1] + 1); k < (groupVector[j] + 1); k++) { bigArray[j].push_back(pingRulesTable.at(k)); } continue; } } //================================================ /* * Start to build the newRules in each group * We get the new rearrangement rules table here, named sumRulesTabel * Next, we will do the rules insertion * Here, we just insert prefix rules, follow the LPM insertion function * So we need to check whether each new rules is prefix rule * If it is, then do the insertion * if not, do the expansion algorithm to make it is prefix rule */ int expandRule_num = 0; int insertRule_num = 0; uint64_t sum_trie_expand_count = 0; uint64_t sum_trie_count = 0; uint64_t sum_trie_node_count = 0; int ping_test = 0; //get time1 //auto start = get_time::now(); // use auto keyword to minimize typing strokes :) // Define a 2D vector for storing delta vector vector< vector<int> > delta_vector; // Allocate an array to hold my class objects vector<Trie> tries(groupVector.size()); // Start to construct the trie data structure here for (int j = 0; j < groupVector.size(); j++) { // Initilize a trie // Each group is a seperate trie // Initialize each trie vector<int> delta_need = generate_delta(bigArray[j]); // Push each delta vector into the 2D vector delta_vector.push_back(delta_need); vector<Rule> newnewTable = rules_rearrange(bigArray[j], delta_need); // Doing the rule insertion for (int k = 0; k < newnewTable.size(); k++) { if ( is_prefix(newnewTable.at(k)) ) { tries[j].insert_prefix_rule_priority(newnewTable.at(k)); insertRule_num ++; } else { // Avoid the memory overflow, expand too much // Set the threshold to "20" if ( tries[j].get_new_num( newnewTable.at (k)) < 20 ) { // becasue we control the number of expanding wildcard // so don't need to delete rules manually tries[j].expand_rule(newnewTable.at(k)); expandRule_num ++; } else { test_flag = 100; // make sure to break out of the loop cout << "test test==expand too much" << endl; // If expand too much cout << "ping test....." << endl; break; } } } cout << "j=" << j << ", " << "trie node num: " << tries[j].node_count << endl; sum_trie_expand_count += tries[j].expand_count; // correct sum_trie_count += tries[j].count; sum_trie_node_count += tries[j].node_count; } cout << "ping ping test...." << endl; cout << "test_flag: " << test_flag << endl; cout << "Num of trie node: " << sum_trie_node_count << endl; // Check the memory cost, compared with the hard threshold==200,000 trie node // If the total cost of trie node is smaller than the threshold, // do the merge group operation if ( test_flag == 100 ){ cout << "Index of v: " << v-1 << "," << original_groupVector[v-1] << endl; // Insert the element to the beginning of the vector, "0" position groupVector.insert(groupVector.begin(), original_groupVector[v-1]); break; } if ( original_groupVector.size() == 1 ) { // The original group is 1, cannot merge anymore, would be "-1" break; } if ( groupVector.size() == 1 ) { break; } else { if ( sum_trie_node_count < threshold ) { // do the grouping merge, which means change the groupVector // show the original group vector without expansion // erase the first element in the groupVector vector<uint32_t> flag_groupVector(groupVector); groupVector.erase(groupVector.begin()); /* if ( groupVector.size() == 1 ) { break; } */ //else { vector< vector<Rule> > newbigArray; // Create a new sub group by copying the related rules for (int m = 0; m < groupVector.size(); m++) { newbigArray.push_back(vector<Rule> ()); } for (int j = 0; j < groupVector.size(); j++) { if (j == 0) { for (int i = 0; i < (groupVector[j] + 1); i++) { newbigArray[j].push_back(pingRulesTable.at(i)); } continue; } else { for (int k = (groupVector[j-1] + 1); k < (groupVector[j] + 1); k++) { newbigArray[j].push_back(pingRulesTable.at(k)); } continue; } } // Start to build the newRules in each group /* * We get the new rearrangement rules table here, named sumRulesTabel * Next, we will do the rules insertion * Here, we just insert prefix rules, follow the LPM insertion function * So we need to check whether each new rules is prefix rule * If it is, then do the insertion * if not, do the expansion algorithm to make it is prefix rule */ int newexpandRule_num = 0; int newinsertRule_num = 0; uint64_t newsum_trie_expand_count = 0; uint64_t newsum_trie_count = 0; uint64_t newsum_trie_node_count = 0; auto newsum_rule_rearrange_time = 0; auto newsum_rule_insertion_time = 0; //get time1 //auto start = get_time::now(); // use auto keyword to minimize typing strokes :) // Define a 2D vector for storing delta vector vector< vector<int> > newdelta_vector; // Allocate an array to hold my class objects vector<Trie> newtries(groupVector.size()); //Trie* trie = new Trie[groupVector.size()]; // Start to construct the trie data structure here for (int j = 0; j < groupVector.size(); j++) { // Initilize a trie // Each group is a seperate trie // Initialize each trie auto start1 = get_time::now(); vector<int> delta_need = generate_delta(newbigArray[j]); // Push each delta vector into the 2D vector newdelta_vector.push_back(delta_need); vector<Rule> newnewnewTable = rules_rearrange(newbigArray[j], delta_need); // Sorting the rules in each group into asscending order // prepare for the merging next //vector<Rule> newnewTable = merge_rules(newSumRuleTable); auto end1 = get_time::now(); auto diff1 = end1 - start1; newsum_rule_rearrange_time += chrono::duration_cast<ms>(diff1).count(); // Doing the rule insertion auto start2 = get_time::now(); for (int k = 0; k < newnewnewTable.size(); k++) { if ( is_prefix(newnewnewTable.at(k)) ) { newtries[j].insert_prefix_rule_priority(newnewnewTable.at(k)); newinsertRule_num ++; } else { // becasue we control the number of expanding wildcard // so don't need to delete rules manually //cout << "group index=" << j << ", index num: " << k << "," << "value: "<< newnewnewTable[k].value << "," << "mask: " //<< newnewnewTable[k].mask << endl; if ( newtries[j].get_new_num( newnewnewTable.at (k)) < 20 ) { // becasue we control the number of expanding wildcard // so don't need to delete rules manually newtries[j].expand_rule(newnewnewTable.at(k)); expandRule_num ++; } else { cout << "888888888888888888888" << endl; cout << "test test==expand too much" << endl; // If expand too much ping_test = 100; // make sure to break out of the loop break; } } } //cout << "j=" << j << ", " << "count number: " << tries[j].count << endl; cout << "j=" << j << ", " << "trie node num: " << newtries[j].node_count << endl; auto end2 = get_time::now(); auto diff2 = end2 - start2; newsum_rule_insertion_time += chrono::duration_cast<ms>(diff2).count(); newsum_trie_expand_count += newtries[j].expand_count; // correct newsum_trie_count += newtries[j].count; newsum_trie_node_count += newtries[j].node_count; } if ( ping_test == 100 ) { cout << "break the j" << endl; groupVector.insert(groupVector.begin(), flag_groupVector[0]); break; // break the j loop, uppter layer } cout << "Num of groups is:" << " " << groupVector.size() << endl; // Finished the rearranged rule insertion for each subtrie // Doing the rule searching char output[][32] = {"Not present in rulesTable", "Present in rulesTable"}; uint64_t actionSum = 0; uint64_t checksum = 0; // show the sum of matching priority uint64_t match = 0; // how many keys are being matched in these new rules auto newsum_key_rearrange_time = 0; auto newsum_key_search_time = 0; for (int i = 0; i < keyTable.size(); i++) { // Check each key auto start3 = get_time::now(); vector<uint64_t> matchVector; vector<uint32_t> decisionVector; for (int m = 0; m < groupVector.size(); m++) { uint64_t newGenKey = keys_rearrange(keyTable[i], newdelta_vector[m]); auto end3 = get_time::now(); auto diff3 = end3 - start3; newsum_key_rearrange_time += chrono::duration_cast<ms>(diff3).count(); auto start4 = get_time::now(); trie_result search_ret = newtries[m].LPM1_search_rule(newGenKey); //uint64_t priority = tries[m].LPM1_search_rule(newGenKey); //cout << "Priority value: " << search_ret.priority << ", Action value: " << search_ret.action << endl; auto end4 = get_time::now(); auto diff4 = end4 - start4; // Insert all the priority value, including match and no_match //matchVector.push_back(priority); matchVector.push_back(search_ret.priority); // Store the priority value decisionVector.push_back(search_ret.action); //cout << "test value: " << search_ret.action << endl; // Has a bug here....... action should not be 0 // Find the bug, the expand function did not insert the action attribute value newsum_key_search_time += chrono::duration_cast<ns>(diff4).count(); } //cout << "matchVector size: " << matchVector.size() << endl; //cout << "decisionVector size: " << decisionVector.size() << endl; // should be the same vector<uint64_t> test1; // Store the priority value vector<uint32_t> test2; // Store the action value for (int v = 0; v < matchVector.size(); v++) { if (matchVector[v] == 0) { continue; } else { uint64_t test = matchVector[v]; uint32_t action2 = decisionVector[v]; test1.push_back(test); test2.push_back(action2); continue; } } // Choose the smallest one, which means the highest priority if (test1.size() > 0) { uint64_t match_final = *min_element(test1.begin(), test1.end()); checksum += match_final; match++; vector<uint64_t>::iterator it; it = find(test1.begin(), test1.end(),match_final); int position1 = distance(test1.begin(), it); //cout << "action size: " << test2.size() << endl; /* for (int q = 0; q < test2.size(); q++) { cout << "action set===" << q << " " << test2[q] << endl; } */ actionSum += test2.at(position1); //cout << "i index:" << j << ", action=:" << decision << endl; //cout << "i index:" << i << ", action=" << test2.at(position1) << endl; //cout << "i index:" << i << " " << "priority=:" << match_final << ", action=" << test2.at(position1) << endl; } } //get time2 //auto end = get_time::now(); //auto diff = end - start; cout << "Total rules rearrange configure time is:" << newsum_rule_rearrange_time << endl; cout << "Total rules insertion configure time is:" << newsum_rule_insertion_time << endl; cout << "Total keys rearrange configure time is:" << newsum_key_rearrange_time << endl; cout << "Total keys search time is:" << newsum_key_search_time << endl; cout << "Total expanded count is:" << " " << newsum_trie_expand_count << endl; cout << "Expand rule num is:" << " " << newexpandRule_num << endl; cout << "Insert rule num is:" << " " << newinsertRule_num << endl; cout << "Total insert rule num is:" << " " << newsum_trie_count << endl; cout << "Total insert trie_node count is:" << " " << newsum_trie_node_count << endl; cout << "Checksum: " << checksum << endl; cout << "ActionSum: " << actionSum << endl; cout << "Total matches: " << match << endl; cout << "==================================================" << endl; //} continue; } // If the trie node > 200000, break the for loop else { cout << "trie node num threshold ==> Index of v: " << v-1 << "," << original_groupVector[v-1] << endl; // Insert the element to the beginning of the vector, "0" position groupVector.insert(groupVector.begin(), original_groupVector[v-1]); break; } } // return groupVector, in order to build the final groups } cout << "Num of groups is:" << " " << groupVector.size() << endl; /* for (i = 0; i < groupVector.size(); i++) { cout << "Group index: " << i << "," << groupVector[i] << endl; } */ vector< vector<Rule> > newbigArray; // Create a new sub group by copying the related rules for (int m = 0; m < groupVector.size(); m++) { newbigArray.push_back(vector<Rule> ()); } for (int j = 0; j < groupVector.size(); j++) { if (j == 0) { for (int i = 0; i < (groupVector[j] + 1); i++) { newbigArray[j].push_back(pingRulesTable.at(i)); } continue; } else { for (int k = (groupVector[j-1] + 1); k < (groupVector[j] + 1); k++) { newbigArray[j].push_back(pingRulesTable.at(k)); } continue; } } // Start to build the newRules in each group /* * We get the new rearrangement rules table here, named sumRulesTabel * Next, we will do the rules insertion * Here, we just insert prefix rules, follow the LPM insertion function * So we need to check whether each new rules is prefix rule * If it is, then do the insertion * if not, do the expansion algorithm to make it is prefix rule */ int newexpandRule_num = 0; int newinsertRule_num = 0; uint64_t newsum_trie_expand_count = 0; uint64_t newsum_trie_count = 0; uint64_t newsum_trie_node_count = 0; auto newsum_rule_rearrange_time = 0; auto newsum_rule_insertion_time = 0; //get time1 //auto start = get_time::now(); // use auto keyword to minimize typing strokes :) // Define a 2D vector for storing delta vector vector< vector<int> > newdelta_vector; // Allocate an array to hold my class objects vector<Trie> newtries(groupVector.size()); //Trie* trie = new Trie[groupVector.size()]; // Start to construct the trie data structure here for (int j = 0; j < groupVector.size(); j++) { // Initilize a trie // Each group is a seperate trie // Initialize each trie auto start1 = get_time::now(); vector<int> delta_need = generate_delta(newbigArray[j]); // Push each delta vector into the 2D vector newdelta_vector.push_back(delta_need); vector<Rule> newnewnewTable = rules_rearrange(newbigArray[j], delta_need); // Sorting the rules in each group into asscending order // prepare for the merging next //vector<Rule> newnewTable = merge_rules(newSumRuleTable); auto end1 = get_time::now(); auto diff1 = end1 - start1; newsum_rule_rearrange_time += chrono::duration_cast<ms>(diff1).count(); // Doing the rule insertion auto start2 = get_time::now(); for (int k = 0; k < newnewnewTable.size(); k++) { if ( is_prefix(newnewnewTable.at(k)) ) { newtries[j].insert_prefix_rule_priority(newnewnewTable.at(k)); newinsertRule_num ++; } else { // becasue we control the number of expanding wildcard // so don't need to delete rules manually //cout << "group index=" << j << ", index num: " << k << "," << "value: "<< newnewnewTable[k].value << "," << "mask: " //<< newnewnewTable[k].mask << endl; newtries[j].expand_rule(newnewnewTable.at(k)); newexpandRule_num ++; } } //cout << "j=" << j << ", " << "count number: " << tries[j].count << endl; cout << "j=" << j << ", " << "trie node num: " << newtries[j].node_count << endl; auto end2 = get_time::now(); auto diff2 = end2 - start2; newsum_rule_insertion_time += chrono::duration_cast<ms>(diff2).count(); newsum_trie_expand_count += newtries[j].expand_count; // correct newsum_trie_count += newtries[j].count; newsum_trie_node_count += newtries[j].node_count; } // Finished the rearranged rule insertion for each subtrie // Doing the rule searching char output[][32] = {"Not present in rulesTable", "Present in rulesTable"}; uint64_t actionSum = 0; uint64_t checksum = 0; // show the sum of matching priority uint64_t match = 0; // how many keys are being matched in these new rules auto newsum_key_rearrange_time = 0; auto newsum_key_search_time = 0; for (int i = 0; i < keyTable.size(); i++) { // Check each key auto start3 = get_time::now(); vector<uint64_t> matchVector; vector<uint32_t> decisionVector; for (int m = 0; m < groupVector.size(); m++) { uint64_t newGenKey = keys_rearrange(keyTable[i], newdelta_vector[m]); auto end3 = get_time::now(); auto diff3 = end3 - start3; newsum_key_rearrange_time += chrono::duration_cast<ms>(diff3).count(); auto start4 = get_time::now(); trie_result search_ret = newtries[m].LPM1_search_rule(newGenKey); //uint64_t priority = tries[m].LPM1_search_rule(newGenKey); //cout << "Priority value: " << search_ret.priority << ", Action value: " << search_ret.action << endl; auto end4 = get_time::now(); auto diff4 = end4 - start4; // Insert all the priority value, including match and no_match //matchVector.push_back(priority); matchVector.push_back(search_ret.priority); // Store the priority value decisionVector.push_back(search_ret.action); //cout << "test value: " << search_ret.action << endl; // Has a bug here....... action should not be 0 // Find the bug, the expand function did not insert the action attribute value newsum_key_search_time += chrono::duration_cast<ns>(diff4).count(); } //cout << "matchVector size: " << matchVector.size() << endl; //cout << "decisionVector size: " << decisionVector.size() << endl; // should be the same vector<uint64_t> test1; // Store the priority value vector<uint32_t> test2; // Store the action value for (int v = 0; v < matchVector.size(); v++) { if (matchVector[v] == 0) { continue; } else { uint64_t test = matchVector[v]; uint32_t action2 = decisionVector[v]; test1.push_back(test); test2.push_back(action2); continue; } } // Choose the smallest one, which means the highest priority if (test1.size() > 0) { uint64_t match_final = *min_element(test1.begin(), test1.end()); checksum += match_final; match++; vector<uint64_t>::iterator it; it = find(test1.begin(), test1.end(),match_final); int position1 = distance(test1.begin(), it); //cout << "action size: " << test2.size() << endl; /* for (int q = 0; q < test2.size(); q++) { cout << "action set===" << q << " " << test2[q] << endl; } */ actionSum += test2.at(position1); //cout << "i index:" << j << ", action=:" << decision << endl; //cout << "i index:" << i << ", action=" << test2.at(position1) << endl; //cout << "i index:" << i << " " << "priority=:" << match_final << ", action=" << test2.at(position1) << endl; } } //get time2 //auto end = get_time::now(); //auto diff = end - start; cout << "Total rules rearrange configure time is:" << newsum_rule_rearrange_time << endl; cout << "Total rules insertion configure time is:" << newsum_rule_insertion_time << endl; cout << "Total keys rearrange configure time is:" << newsum_key_rearrange_time << endl; cout << "Total keys search time is:" << newsum_key_search_time << endl; cout << "Total expanded count is:" << " " << newsum_trie_expand_count << endl; cout << "Expand rule num is:" << " " << newexpandRule_num << endl; cout << "Insert rule num is:" << " " << newinsertRule_num << endl; cout << "Total insert rule num is:" << " " << newsum_trie_count << endl; cout << "Total insert trie_node count is:" << " " << newsum_trie_node_count << endl; cout << "Checksum: " << checksum << endl; cout << "ActionSum: " << actionSum << endl; cout << "Total matches: " << match << endl; cout << "==================================================" << endl; return 0; } update // Copyright (c) 2015 Flowgrammable.org // All rights reserved #include "../libmatch/basic_trie.cpp" #include <iostream> #include <vector> #include <string> #include <stdio.h> #include <fstream> #include <cstdint> #include <sstream> #include <iomanip> #include <math.h> #include <chrono> #include <algorithm> #include <functional> using namespace std; using ns = chrono::nanoseconds; using ms = chrono::microseconds; using get_time = chrono::steady_clock ; struct Result { // define the result struct for merging algorithm int flag = -1; // show the different bit position int dif = 0; // the number bit of difference }; // Matches integer type Rule strTint(string rulestr) { Rule rule; rule.mask = 0; rule.value = 0; // Find the position of ".", which spilit IP address to 4 parts size_t p1 = rulestr.find_first_of(" "); string substr1 = rulestr.substr(0,p1); string substr2 = rulestr.substr((p1 + 1)); rule.value = stoull(substr1); // unsigned long long 64bit rule.mask = stoull(substr2); return rule; } /* * Check the mask part relation * whether is subset * the "1" bit position */ bool is_subset(Rule a, Rule b) { vector<int> vec_a; vector<int> vec_b; // Get the "1" bit position for the mask part of two rules for (int i = 0; i < 64; i++) { if ((a.mask & (uint64_t(1) << i)) == 1) { vec_a.push_back(i); } if ((b.mask & (uint64_t(1) << i)) == 1) { vec_b.push_back(i); } } // Check the vec_a and vec_b is subset or not std::sort(vec_a.begin(),vec_a.end()); std::sort(vec_b.begin(),vec_b.end()); if (std::includes (vec_a.begin(), vec_a.end(), vec_b.begin(),vec_b.end()) || std::includes (vec_b.begin(), vec_b.end(), vec_a.begin(),vec_a.end())) { return true; } else { return false; } } /* * Merge the rules between the first rule and second rule * depends on the bits of every column * if in each column, it has "1" and "0" or "*" */ Result is_mergeable(Rule firstrule, Rule secondrule) { Result ret; Rule rule1; rule1.mask = firstrule.mask | secondrule.mask; //cout << "rule1.mask = " << rule1.mask << endl; if (rule1.mask == 0) { // Check the value part is the same or not, because there is no "*" for (int q = 0; q < 64; q++) { // Check every bit position on the value part if ((firstrule.value & (uint64_t(1) << q)) != (secondrule.value & (uint64_t(1) << q)) ) { // If the bit position are not the same, flag and dif value changes ret.flag = q; // show the bit position ret.dif++; } else { continue; } } // Get all the difference bit position between two rules (mask value = 0) } else { // If the mask value is not 0, which means the mask value part has the "*", wildcard for (int k = 0; k < 64; k++) { // Get all the bit positions of "0" in mask value part if ((rule1.mask & (uint64_t(1) << k)) == 0) { // check the value part, the hamming distance // Check the hamming distance between the value part in the "0" positions if ((firstrule.value & (uint64_t(1) << k)) != (secondrule.value & (uint64_t(1) << k)) ) { ret.flag = k; // show the bit position ret.dif++; } else { continue; } } else { continue; } } } return ret; // The condition for merging, hamming distance smaller than 1 } vector<Rule> merge_rules(vector<Rule>& ruleList) { // Copy into a new vector vector<Rule> new_rule_list(ruleList); Rule newRule7; for (int i = 0; i < new_rule_list.size() - 1; i++) { for (int j = i+1; j < new_rule_list.size(); j++) { // The condition for able to merging // If the two rules' mask value part is the same if (new_rule_list.at(i).action == new_rule_list.at(j).action) { if (new_rule_list.at(i).mask == new_rule_list.at(j).mask) { // Just compare the value part when the mask part is "0", ignor the "1" part Result ret2 = is_mergeable(new_rule_list.at(i), new_rule_list.at(j)); // Get the ret2 value, to see the bit position difference and the flag value //cout << "i =" << i << " " << "j =" << j << " " << "dif =" << ret2.dif << " " << "flag =" << ret2.flag << endl; if (ret2.dif == 0) { // the value part is the same on the "0" positions at mask part //cout << "Merge rules" << endl; newRule7.mask = (new_rule_list.at(i).mask | new_rule_list.at(j).mask); newRule7.value = new_rule_list.at(i).value & new_rule_list.at(j).value; // The merged rule's priority should equal to the highest priority newRule7.priority = min( new_rule_list.at(i).priority, new_rule_list.at(j).priority ); newRule7.action = new_rule_list.at(i).action; //newRule7.priority = new_rule_list.size() - 1; //cout << "value = " << newRule7.value << " " << "mask = " << newRule7.mask << " " << "priority = " << newRule7.priority << endl; new_rule_list.erase(new_rule_list.begin() + i); new_rule_list.erase(new_rule_list.begin() + (j-1)); // Insert the new merged rule into the beginning of the vector new_rule_list.push_back(newRule7); i = -1; break; } if (ret2.dif == 1) { // There is just one bit position different //cout << "Merge rules" << endl; newRule7.mask = (new_rule_list.at(i).mask | new_rule_list.at(j).mask) + (uint64_t(1) << ret2.flag); newRule7.value = new_rule_list.at(i).value & new_rule_list.at(j).value; newRule7.priority = min( new_rule_list.at(i).priority, new_rule_list.at(j).priority ); newRule7.action = new_rule_list.at(i).action; //newRule7.priority = new_rule_list.size() - 1; //cout << "value = " << newRule7.value << " " << "mask = " << newRule7.mask << " " << "priority = " << newRule7.priority << endl; new_rule_list.erase(new_rule_list.begin() + i); new_rule_list.erase(new_rule_list.begin() + (j-1)); // Insert the new merged rule into the beginning of the vector new_rule_list.push_back(newRule7); i = -1; break; } else { continue; } } else { continue; } } else { continue; } } } /* for (int k = 0; k < new_rule_list.size(); k++) { cout << "value part:" << new_rule_list.at(k).value << " " << "mask part:" << new_rule_list.at(k).mask << endl; } */ return new_rule_list; } /* * Check whether the new rule is a prefix rule * if yes, do the LPM insertion * if not, do the expand rule function */ bool is_prefix(Rule& rule) { // Store the wildcard postion into vector maskPosion vector<uint32_t> maskPosition; // Check the mask field from the lower bit for(int i = 0; i < 64; i++) { // if this: get the position whose bit is 1 (have wildcard) if((rule.mask >> i) & uint64_t(1) == 1) { maskPosition.push_back(i); } } uint32_t num = maskPosition.size(); // num is the number of wildcard if (rule.mask == (uint64_t(1) << num)-1) { return true; } else { return false; } } // Sorting the rules in an asscending order bool wayToSort(Rule aa, Rule bb) { return (aa.mask < bb.mask); } bool wayToSort1(Rule aaa, Rule bbb) { return (aaa.value < bbb.value); } /* * Sorting the prefix format rules into asscending order, denpending on the prefix length * using the std::sort function */ vector<Rule> sort_rules(vector<Rule>& ruleList) { std::sort(ruleList.begin(), ruleList.end(), wayToSort); /* cout << "mark" << "===============" << endl; for (int k = 0; k < ruleList.size(); k ++) { cout << ruleList[k].value << ", " << ruleList[k].mask << endl; } */ vector<Rule> sortTable; vector<Rule> sortTotalTable; // Determine the size of combined table sortTotalTable.reserve(ruleList.size()); for (int i = 0; i < ruleList.size(); i ++) { if (i != ruleList.size() - 1) { if (ruleList.at(i).mask == ruleList.at(i+1).mask) { // if the mask value is the same, push into the same vector //cout << "test" << endl; sortTable.push_back(ruleList.at(i)); continue; } else { sortTable.push_back(ruleList.at(i)); //cout << "i = " << i << endl; std::sort(sortTable.begin(), sortTable.end(), wayToSort1); sortTotalTable.insert( sortTotalTable.end(), sortTable.begin(), sortTable.end() ); /* for (int k = 0; k < sortTotalTable.size(); k ++) { cout << sortTotalTable[k].value << ", " << sortTotalTable[k].mask << endl; } cout << "sortTotalTable size = " << sortTotalTable.size() << endl; */ // Delete the current contents, clear the memory sortTable.clear(); //cout << "sortTable size = " << sortTable.size() << endl; continue; } } else { // for the last element in the vector // for avoiding the over-range of the vector if (ruleList.at(i).mask == ruleList.at(i-1).mask) { sortTable.push_back(ruleList.at(i)); //cout << "i = " << i << endl; std::sort(sortTable.begin(), sortTable.end(), wayToSort1); sortTotalTable.insert( sortTotalTable.end(), sortTable.begin(), sortTable.end() ); } else { std::sort(sortTable.begin(), sortTable.end(), wayToSort1); sortTotalTable.insert( sortTotalTable.end(), sortTable.begin(), sortTable.end() ); sortTable.clear(); sortTable.push_back(ruleList.at(i)); sortTotalTable.insert( sortTotalTable.end(), sortTable.begin(), sortTable.end() ); } } } return sortTotalTable; } /* * Generate the two dimensional array (generate delta array) from the pingRulesTable array * With all the bits in each rule, including "0" and "1" * Caculate the score--the sum of column */ vector<int> generate_delta(vector<Rule>& ruleList) { vector<uint64_t> sumColumn; for (int j = 0; j < 64; j++) { uint32_t score = 0; for (int i = 0; i < ruleList.size(); i++) { score += ((((ruleList.at(i)).mask) >> j) & uint64_t(1)); } sumColumn.push_back(score); } // Copy the sumColumn vector to a new vector vector<uint64_t> newSumColumn(sumColumn); /* * Checked the newSumColumn vector is the same with the sumColumn vector cout << newSumColumn.size() << endl; for (i = 0; i < newSumColumn.size(); i++) { cout << newSumColumn[i] << endl; } */ // Sort the newSumColumn vector in descending order std::sort(newSumColumn.begin(), newSumColumn.end(), std::greater<uint64_t>()); /* * Checked the descending order is correct or not for (i = 0; i < newSumColumn.size(); i++) { cout << newSumColumn[i] << endl; } */ // Construct the delta(): the rearrangement operation {left shift, right shift, and no change} // the element in delta vector, can be negative, positive and "0" vector<int> delta; // checkpoint is the index/subscript of the newSumColumn has the same value with the sumColumn uint32_t checkpoint = 0; int gap = 0; // Gap is the difference between the original and new sumcolumn vectors for (int i = 0; i < sumColumn.size(); i++) { //cout << "mark1" << " " << sumColumn[i] << endl; for (int j = 0; j < newSumColumn.size(); j++) { //cout << newSumColumn[j] << endl; // Check the first equal element, if it is true, then return the checkpoint if (newSumColumn[j] != sumColumn[i]) { continue; } else if (newSumColumn[j] == sumColumn[i]) { checkpoint = j; newSumColumn[j] = 132; // make the matched column invalid break; } else { // Search all the 64 values, still didn't find the same value cout << "Error occurs" << endl; } } // Get the difference between the original vector data and the sorted vector data // Create the rearrangement operation gap = i - checkpoint; delta.push_back(gap); } return delta; } /* * Generate the new rule after the delta operations * if the element value of delta vector is negative, which means left shift * if the element value of delta vector is positive, which means right shift * if the element value of delta vector is "0", which means no change */ // Create a new pingRulesTable for the new rearrangement rules //vector<Rule> newPingRulesTable; // for each bit of each rule vector<Rule> rules_rearrange(vector<Rule>& oldRuleList, vector<int> delta_array) { vector<Rule> sumRulesTable; // for a new rule for (int i = 0; i < oldRuleList.size(); i++) { Rule newRule; for (int j = 0; j < 64; j++) { Rule subRule; if (delta_array[j] < 0) { // if it is negative, do the left shift // from the lsb position, do the correct operations // Note: because here is 64 bit, if we just use 1 to do left shift, it will occur overflow // since "1" is 32bit by default subRule.value = ( (( (oldRuleList[i].value) & (uint64_t(1) << j) ) ) << (abs(delta_array[j])) ); subRule.mask = ( (( (oldRuleList[i].mask) & (uint64_t(1) << j) ) ) << (abs(delta_array[j])) ); } else if (delta_array[j] > 0) { // if it is positive, do the right shift subRule.value = ( (( (oldRuleList[i].value) & (uint64_t(1) << j) ) ) >> (abs(delta_array[j])) ); subRule.mask = ( (( (oldRuleList[i].mask) & (uint64_t(1) << j) ) ) >> (abs(delta_array[j])) ); } else if (delta_array[j] == 0) { // if it is "0", no change subRule.value = (( (oldRuleList[i].value) & (uint64_t(1) << j) ) ); subRule.mask = (( (oldRuleList[i].mask) & (uint64_t(1) << j) ) ); } newRule.value |= subRule.value; newRule.mask |= subRule.mask; //cout << j << " " << newRule.mask << endl; newRule.priority = oldRuleList[i].priority; newRule.action = oldRuleList[i].action; } sumRulesTable.push_back(newRule); } return sumRulesTable; } /* * Rearrange each key in the keyTable according to the delta vector * because the rules are being reordered by the delta vector */ uint64_t keys_rearrange(uint64_t key, vector<int> delta_array) { // Calculate the key rearrangement configure time basing on the delta vector uint64_t newKey = 0; // new key after reordering for (int j = 0; j < 64; j++) { uint64_t subKey = 0; // subKey is the single bit value of each key if (delta_array[j] < 0) { subKey = ( (( key & (uint64_t(1) << j) ) ) << (abs(delta_array[j])) ); } else if (delta_array[j] > 0) { // if it is positive, do the right shift subKey = ( (( key & (uint64_t(1) << j) ) ) >> (abs(delta_array[j])) ); } else if (delta_array[j] == 0) { // if it is "0", no change subKey = (( key & (uint64_t(1) << j) ) ); } newKey |= subKey; } return newKey; //cout << newKey << endl; } /* *Create a function called construct the data structure *Insert rules */ /* *Create a function called the whole search process *search rules */ static int threshold; // Set the wildcard num as a variable int main(int argc, char* argv[]) { // Input the action file vector<int> actions; string line1; uint32_t action1; ifstream file2 (argv[3]); // Read action from the txt file if (file2.is_open()) { while (!file2.eof()) { getline(file2, line1); if (!line1.empty()) { action1 = stoull(line1); actions.push_back(action1); } } } file2.close(); // Set the hard line for the memory cost == number of trie node threshold = stoull(argv[4]); ifstream file (argv[1]); // Read the rules from txt file vector<Rule> oldpingRulesTable; int i = 0; if (file.is_open()) { while (!file.eof()) { // Read lines as long as the file is string line; getline(file,line); if(!line.empty()) { Rule rule = strTint(line); // Add the priority feature when generating rules // Priority is in-order of generating rule.action = actions[i]; i = i + 1; rule.priority = i; //rule.priority = ++i; // Push the input file into ruleArray oldpingRulesTable.push_back(rule); } } } file.close(); // Need to check the priority preserve the same after sorting vector<Rule> pingRulesTable = sort_rules(oldpingRulesTable); //cout << "Sorted total size = " << pingRulesTable.size() << endl; //vector<Rule> pingRulesTable = merge_rules(oldpingRulesTable); //cout << "Merged total size = " << pingRulesTable.size() << endl; /* for (int k = 0; k < pingRulesTable.size(); k++) { cout << pingRulesTable[k].priority << " " << pingRulesTable[k].action << " " << pingRulesTable[k].value << " " << pingRulesTable[k].mask << endl; } */ // Read in keys from file: ifstream file1 (argv[2]); vector<uint64_t> keyTable; if (file1.is_open()) { while (!file1.eof()) { // Read lines as long as the file is string packet; getline(file1,packet); if(!packet.empty()) { uint64_t key = stoull(packet); // Push the input file into ruleArray keyTable.push_back(key); } } } file1.close(); cout << "The num of keys: " << keyTable.size() << endl; // Genearte the different size of key nums /* vector<uint64_t> keyTable; for (int i = 0; i < 17642000; i++) { keyTable.push_back(keyTable1[i]); } */ /* * Grouping algorithm * Use the is_cross_pattern function to check the grouping number * Avoid the expanding number is too large * how to improve the grouping algorithm?? * add the threshold, to adjust the grouping seperation */ // For the grouped rule table vector<uint32_t> groupVector; vector<Rule> newList; // avoid the bad allocation memory // The grouping algorithm is to create the most number of // groups without expansion /* * Noexpand group algorithm */ for ( int i = 0; i < pingRulesTable.size(); i++ ) { if (i < (pingRulesTable.size()-1)) { newList.push_back(pingRulesTable[i]); vector<int> new_generated_delta = generate_delta(newList); // Create the rearranged rule set vector<Rule> new_table_list = rules_rearrange( newList, new_generated_delta ); for ( int k = 0; k < new_table_list.size(); k++ ) { //Trie trie1; // for caculating the trie1.new_num // for guarantee avoding the bad memory alloc if ( is_prefix(new_table_list.at (k)) ) { // if this is prefix rules, don't need to expand //trie1.insert_prefix_rule_priority(new_table_list.at(k)); continue; } else { groupVector.push_back(i-1); // clear the newList vector, becasue this is a seperated group newList.clear(); i = i -1; break; } } } else { groupVector.push_back(i); } } //========================================== // Copy the groupVector, in order to recover the deleted element later vector<uint32_t> original_groupVector(groupVector); cout << "(No expand) Num of Original groups is:" << " " << original_groupVector.size() << endl; /* for (i = 0; i < original_groupVector.size(); i++) { cout << "Original Group index: " << i << "," << original_groupVector[i] << endl; } */ /* Create all the subgroups * The big array is called bigArray * insert the whole rule set into the separate groups */ int test_flag = 0; // This variable is used to break the nested loop for (int v = 0; v < original_groupVector.size(); v++) { vector< vector<Rule> > bigArray; // it's a intermediate variable, two-dimensional array // Create a new sub group by copying the related rules for (int m = 0; m < groupVector.size(); m++) { bigArray.push_back(vector<Rule> ()); } for (int j = 0; j < groupVector.size(); j++) { if (j == 0) { for (int i = 0; i < (groupVector[j] + 1); i++) { bigArray[j].push_back(pingRulesTable.at(i)); } continue; } else { for (int k = (groupVector[j-1] + 1); k < (groupVector[j] + 1); k++) { bigArray[j].push_back(pingRulesTable.at(k)); } continue; } } //================================================ /* * Start to build the newRules in each group * We get the new rearrangement rules table here, named sumRulesTabel * Next, we will do the rules insertion * Here, we just insert prefix rules, follow the LPM insertion function * So we need to check whether each new rules is prefix rule * If it is, then do the insertion * if not, do the expansion algorithm to make it is prefix rule */ int expandRule_num = 0; int insertRule_num = 0; uint64_t sum_trie_expand_count = 0; uint64_t sum_trie_count = 0; uint64_t sum_trie_node_count = 0; int ping_test = 0; //get time1 //auto start = get_time::now(); // use auto keyword to minimize typing strokes :) // Define a 2D vector for storing delta vector vector< vector<int> > delta_vector; // Allocate an array to hold my class objects vector<Trie> tries(groupVector.size()); // Start to construct the trie data structure here for (int j = 0; j < groupVector.size(); j++) { // Initilize a trie // Each group is a seperate trie // Initialize each trie vector<int> delta_need = generate_delta(bigArray[j]); // Push each delta vector into the 2D vector delta_vector.push_back(delta_need); vector<Rule> newnewTable = rules_rearrange(bigArray[j], delta_need); // Doing the rule insertion for (int k = 0; k < newnewTable.size(); k++) { if ( is_prefix(newnewTable.at(k)) ) { tries[j].insert_prefix_rule_priority(newnewTable.at(k)); insertRule_num ++; } else { // Avoid the memory overflow, expand too much // Set the threshold to "20" if ( tries[j].get_new_num( newnewTable.at (k)) < 20 ) { // becasue we control the number of expanding wildcard // so don't need to delete rules manually tries[j].expand_rule(newnewTable.at(k)); expandRule_num ++; } else { test_flag = 100; // make sure to break out of the loop cout << "test test==expand too much" << endl; // If expand too much cout << "ping test....." << endl; break; } } } cout << "j=" << j << ", " << "trie node num: " << tries[j].node_count << endl; sum_trie_expand_count += tries[j].expand_count; // correct sum_trie_count += tries[j].count; sum_trie_node_count += tries[j].node_count; } cout << "ping ping test...." << endl; cout << "test_flag: " << test_flag << endl; cout << "Num of trie node: " << sum_trie_node_count << endl; // Check the memory cost, compared with the hard threshold==200,000 trie node // If the total cost of trie node is smaller than the threshold, // do the merge group operation if ( test_flag == 100 ){ cout << "Index of v: " << v-1 << "," << original_groupVector[v-1] << endl; // Insert the element to the beginning of the vector, "0" position groupVector.insert(groupVector.begin(), original_groupVector[v-1]); break; } if ( original_groupVector.size() == 1 ) { // The original group is 1, cannot merge anymore, would be "-1" break; } if ( groupVector.size() == 1 ) { break; } else { if ( sum_trie_node_count < threshold ) { // do the grouping merge, which means change the groupVector // show the original group vector without expansion // erase the first element in the groupVector vector<uint32_t> flag_groupVector(groupVector); groupVector.erase(groupVector.begin()); /* if ( groupVector.size() == 1 ) { break; } */ //else { vector< vector<Rule> > newbigArray; // Create a new sub group by copying the related rules for (int m = 0; m < groupVector.size(); m++) { newbigArray.push_back(vector<Rule> ()); } for (int j = 0; j < groupVector.size(); j++) { if (j == 0) { for (int i = 0; i < (groupVector[j] + 1); i++) { newbigArray[j].push_back(pingRulesTable.at(i)); } continue; } else { for (int k = (groupVector[j-1] + 1); k < (groupVector[j] + 1); k++) { newbigArray[j].push_back(pingRulesTable.at(k)); } continue; } } // Start to build the newRules in each group /* * We get the new rearrangement rules table here, named sumRulesTabel * Next, we will do the rules insertion * Here, we just insert prefix rules, follow the LPM insertion function * So we need to check whether each new rules is prefix rule * If it is, then do the insertion * if not, do the expansion algorithm to make it is prefix rule */ int newexpandRule_num = 0; int newinsertRule_num = 0; uint64_t newsum_trie_expand_count = 0; uint64_t newsum_trie_count = 0; uint64_t newsum_trie_node_count = 0; auto newsum_rule_rearrange_time = 0; auto newsum_rule_insertion_time = 0; //get time1 //auto start = get_time::now(); // use auto keyword to minimize typing strokes :) // Define a 2D vector for storing delta vector vector< vector<int> > newdelta_vector; // Allocate an array to hold my class objects vector<Trie> newtries(groupVector.size()); //Trie* trie = new Trie[groupVector.size()]; // Start to construct the trie data structure here for (int j = 0; j < groupVector.size(); j++) { // Initilize a trie // Each group is a seperate trie // Initialize each trie auto start1 = get_time::now(); vector<int> delta_need = generate_delta(newbigArray[j]); // Push each delta vector into the 2D vector newdelta_vector.push_back(delta_need); vector<Rule> newnewnewTable = rules_rearrange(newbigArray[j], delta_need); // Sorting the rules in each group into asscending order // prepare for the merging next //vector<Rule> newnewTable = merge_rules(newSumRuleTable); auto end1 = get_time::now(); auto diff1 = end1 - start1; newsum_rule_rearrange_time += chrono::duration_cast<ms>(diff1).count(); // Doing the rule insertion auto start2 = get_time::now(); for (int k = 0; k < newnewnewTable.size(); k++) { if ( is_prefix(newnewnewTable.at(k)) ) { newtries[j].insert_prefix_rule_priority(newnewnewTable.at(k)); newinsertRule_num ++; } else { // becasue we control the number of expanding wildcard // so don't need to delete rules manually //cout << "group index=" << j << ", index num: " << k << "," << "value: "<< newnewnewTable[k].value << "," << "mask: " //<< newnewnewTable[k].mask << endl; if ( newtries[j].get_new_num( newnewnewTable.at (k)) < 23 ) { // becasue we control the number of expanding wildcard // so don't need to delete rules manually newtries[j].expand_rule(newnewnewTable.at(k)); expandRule_num ++; } else { cout << "888888888888888888888" << endl; cout << "test test==expand too much" << endl; // If expand too much ping_test = 100; // make sure to break out of the loop break; } } } //cout << "j=" << j << ", " << "count number: " << tries[j].count << endl; cout << "j=" << j << ", " << "trie node num: " << newtries[j].node_count << endl; auto end2 = get_time::now(); auto diff2 = end2 - start2; newsum_rule_insertion_time += chrono::duration_cast<ms>(diff2).count(); newsum_trie_expand_count += newtries[j].expand_count; // correct newsum_trie_count += newtries[j].count; newsum_trie_node_count += newtries[j].node_count; } if ( ping_test == 100 ) { cout << "break the j" << endl; groupVector.insert(groupVector.begin(), flag_groupVector[0]); break; // break the j loop, uppter layer } cout << "Num of groups is:" << " " << groupVector.size() << endl; // Finished the rearranged rule insertion for each subtrie // Doing the rule searching char output[][32] = {"Not present in rulesTable", "Present in rulesTable"}; uint64_t actionSum = 0; uint64_t checksum = 0; // show the sum of matching priority uint64_t match = 0; // how many keys are being matched in these new rules auto newsum_key_rearrange_time = 0; auto newsum_key_search_time = 0; for (int i = 0; i < keyTable.size(); i++) { // Check each key auto start3 = get_time::now(); vector<uint64_t> matchVector; vector<uint32_t> decisionVector; for (int m = 0; m < groupVector.size(); m++) { uint64_t newGenKey = keys_rearrange(keyTable[i], newdelta_vector[m]); auto end3 = get_time::now(); auto diff3 = end3 - start3; newsum_key_rearrange_time += chrono::duration_cast<ms>(diff3).count(); auto start4 = get_time::now(); trie_result search_ret = newtries[m].LPM1_search_rule(newGenKey); //uint64_t priority = tries[m].LPM1_search_rule(newGenKey); //cout << "Priority value: " << search_ret.priority << ", Action value: " << search_ret.action << endl; auto end4 = get_time::now(); auto diff4 = end4 - start4; // Insert all the priority value, including match and no_match //matchVector.push_back(priority); matchVector.push_back(search_ret.priority); // Store the priority value decisionVector.push_back(search_ret.action); //cout << "test value: " << search_ret.action << endl; // Has a bug here....... action should not be 0 // Find the bug, the expand function did not insert the action attribute value newsum_key_search_time += chrono::duration_cast<ns>(diff4).count(); } //cout << "matchVector size: " << matchVector.size() << endl; //cout << "decisionVector size: " << decisionVector.size() << endl; // should be the same vector<uint64_t> test1; // Store the priority value vector<uint32_t> test2; // Store the action value for (int v = 0; v < matchVector.size(); v++) { if (matchVector[v] == 0) { continue; } else { uint64_t test = matchVector[v]; uint32_t action2 = decisionVector[v]; test1.push_back(test); test2.push_back(action2); continue; } } // Choose the smallest one, which means the highest priority if (test1.size() > 0) { uint64_t match_final = *min_element(test1.begin(), test1.end()); checksum += match_final; match++; vector<uint64_t>::iterator it; it = find(test1.begin(), test1.end(),match_final); int position1 = distance(test1.begin(), it); //cout << "action size: " << test2.size() << endl; /* for (int q = 0; q < test2.size(); q++) { cout << "action set===" << q << " " << test2[q] << endl; } */ actionSum += test2.at(position1); //cout << "i index:" << j << ", action=:" << decision << endl; //cout << "i index:" << i << ", action=" << test2.at(position1) << endl; //cout << "i index:" << i << " " << "priority=:" << match_final << ", action=" << test2.at(position1) << endl; } } //get time2 //auto end = get_time::now(); //auto diff = end - start; cout << "Total rules rearrange configure time is:" << newsum_rule_rearrange_time << endl; cout << "Total rules insertion configure time is:" << newsum_rule_insertion_time << endl; cout << "Total keys rearrange configure time is:" << newsum_key_rearrange_time << endl; cout << "Total keys search time is:" << newsum_key_search_time << endl; cout << "Total expanded count is:" << " " << newsum_trie_expand_count << endl; cout << "Expand rule num is:" << " " << newexpandRule_num << endl; cout << "Insert rule num is:" << " " << newinsertRule_num << endl; cout << "Total insert rule num is:" << " " << newsum_trie_count << endl; cout << "Total insert trie_node count is:" << " " << newsum_trie_node_count << endl; cout << "Checksum: " << checksum << endl; cout << "ActionSum: " << actionSum << endl; cout << "Total matches: " << match << endl; cout << "==================================================" << endl; //} continue; } // If the trie node > 200000, break the for loop else { cout << "trie node num threshold ==> Index of v: " << v-1 << "," << original_groupVector[v-1] << endl; // Insert the element to the beginning of the vector, "0" position groupVector.insert(groupVector.begin(), original_groupVector[v-1]); break; } } // return groupVector, in order to build the final groups } cout << "Num of groups is:" << " " << groupVector.size() << endl; /* for (i = 0; i < groupVector.size(); i++) { cout << "Group index: " << i << "," << groupVector[i] << endl; } */ vector< vector<Rule> > newbigArray; // Create a new sub group by copying the related rules for (int m = 0; m < groupVector.size(); m++) { newbigArray.push_back(vector<Rule> ()); } for (int j = 0; j < groupVector.size(); j++) { if (j == 0) { for (int i = 0; i < (groupVector[j] + 1); i++) { newbigArray[j].push_back(pingRulesTable.at(i)); } continue; } else { for (int k = (groupVector[j-1] + 1); k < (groupVector[j] + 1); k++) { newbigArray[j].push_back(pingRulesTable.at(k)); } continue; } } // Start to build the newRules in each group /* * We get the new rearrangement rules table here, named sumRulesTabel * Next, we will do the rules insertion * Here, we just insert prefix rules, follow the LPM insertion function * So we need to check whether each new rules is prefix rule * If it is, then do the insertion * if not, do the expansion algorithm to make it is prefix rule */ int newexpandRule_num = 0; int newinsertRule_num = 0; uint64_t newsum_trie_expand_count = 0; uint64_t newsum_trie_count = 0; uint64_t newsum_trie_node_count = 0; auto newsum_rule_rearrange_time = 0; auto newsum_rule_insertion_time = 0; //get time1 //auto start = get_time::now(); // use auto keyword to minimize typing strokes :) // Define a 2D vector for storing delta vector vector< vector<int> > newdelta_vector; // Allocate an array to hold my class objects vector<Trie> newtries(groupVector.size()); //Trie* trie = new Trie[groupVector.size()]; // Start to construct the trie data structure here for (int j = 0; j < groupVector.size(); j++) { // Initilize a trie // Each group is a seperate trie // Initialize each trie auto start1 = get_time::now(); vector<int> delta_need = generate_delta(newbigArray[j]); // Push each delta vector into the 2D vector newdelta_vector.push_back(delta_need); vector<Rule> newnewnewTable = rules_rearrange(newbigArray[j], delta_need); // Sorting the rules in each group into asscending order // prepare for the merging next //vector<Rule> newnewTable = merge_rules(newSumRuleTable); auto end1 = get_time::now(); auto diff1 = end1 - start1; newsum_rule_rearrange_time += chrono::duration_cast<ms>(diff1).count(); // Doing the rule insertion auto start2 = get_time::now(); for (int k = 0; k < newnewnewTable.size(); k++) { if ( is_prefix(newnewnewTable.at(k)) ) { newtries[j].insert_prefix_rule_priority(newnewnewTable.at(k)); newinsertRule_num ++; } else { // becasue we control the number of expanding wildcard // so don't need to delete rules manually //cout << "group index=" << j << ", index num: " << k << "," << "value: "<< newnewnewTable[k].value << "," << "mask: " //<< newnewnewTable[k].mask << endl; newtries[j].expand_rule(newnewnewTable.at(k)); newexpandRule_num ++; } } //cout << "j=" << j << ", " << "count number: " << tries[j].count << endl; cout << "j=" << j << ", " << "trie node num: " << newtries[j].node_count << endl; auto end2 = get_time::now(); auto diff2 = end2 - start2; newsum_rule_insertion_time += chrono::duration_cast<ms>(diff2).count(); newsum_trie_expand_count += newtries[j].expand_count; // correct newsum_trie_count += newtries[j].count; newsum_trie_node_count += newtries[j].node_count; } // Finished the rearranged rule insertion for each subtrie // Doing the rule searching char output[][32] = {"Not present in rulesTable", "Present in rulesTable"}; uint64_t actionSum = 0; uint64_t checksum = 0; // show the sum of matching priority uint64_t match = 0; // how many keys are being matched in these new rules auto newsum_key_rearrange_time = 0; auto newsum_key_search_time = 0; for (int i = 0; i < keyTable.size(); i++) { // Check each key auto start3 = get_time::now(); vector<uint64_t> matchVector; vector<uint32_t> decisionVector; for (int m = 0; m < groupVector.size(); m++) { uint64_t newGenKey = keys_rearrange(keyTable[i], newdelta_vector[m]); auto end3 = get_time::now(); auto diff3 = end3 - start3; newsum_key_rearrange_time += chrono::duration_cast<ms>(diff3).count(); auto start4 = get_time::now(); trie_result search_ret = newtries[m].LPM1_search_rule(newGenKey); //uint64_t priority = tries[m].LPM1_search_rule(newGenKey); //cout << "Priority value: " << search_ret.priority << ", Action value: " << search_ret.action << endl; auto end4 = get_time::now(); auto diff4 = end4 - start4; // Insert all the priority value, including match and no_match //matchVector.push_back(priority); matchVector.push_back(search_ret.priority); // Store the priority value decisionVector.push_back(search_ret.action); //cout << "test value: " << search_ret.action << endl; // Has a bug here....... action should not be 0 // Find the bug, the expand function did not insert the action attribute value newsum_key_search_time += chrono::duration_cast<ns>(diff4).count(); } //cout << "matchVector size: " << matchVector.size() << endl; //cout << "decisionVector size: " << decisionVector.size() << endl; // should be the same vector<uint64_t> test1; // Store the priority value vector<uint32_t> test2; // Store the action value for (int v = 0; v < matchVector.size(); v++) { if (matchVector[v] == 0) { continue; } else { uint64_t test = matchVector[v]; uint32_t action2 = decisionVector[v]; test1.push_back(test); test2.push_back(action2); continue; } } // Choose the smallest one, which means the highest priority if (test1.size() > 0) { uint64_t match_final = *min_element(test1.begin(), test1.end()); checksum += match_final; match++; vector<uint64_t>::iterator it; it = find(test1.begin(), test1.end(),match_final); int position1 = distance(test1.begin(), it); //cout << "action size: " << test2.size() << endl; /* for (int q = 0; q < test2.size(); q++) { cout << "action set===" << q << " " << test2[q] << endl; } */ actionSum += test2.at(position1); //cout << "i index:" << j << ", action=:" << decision << endl; //cout << "i index:" << i << ", action=" << test2.at(position1) << endl; //cout << "i index:" << i << " " << "priority=:" << match_final << ", action=" << test2.at(position1) << endl; } } //get time2 //auto end = get_time::now(); //auto diff = end - start; cout << "Total rules rearrange configure time is:" << newsum_rule_rearrange_time << endl; cout << "Total rules insertion configure time is:" << newsum_rule_insertion_time << endl; cout << "Total keys rearrange configure time is:" << newsum_key_rearrange_time << endl; cout << "Total keys search time is:" << newsum_key_search_time << endl; cout << "Total expanded count is:" << " " << newsum_trie_expand_count << endl; cout << "Expand rule num is:" << " " << newexpandRule_num << endl; cout << "Insert rule num is:" << " " << newinsertRule_num << endl; cout << "Total insert rule num is:" << " " << newsum_trie_count << endl; cout << "Total insert trie_node count is:" << " " << newsum_trie_node_count << endl; cout << "Checksum: " << checksum << endl; cout << "ActionSum: " << actionSum << endl; cout << "Total matches: " << match << endl; cout << "==================================================" << endl; return 0; }
/* Copyright 2015 The Trustees of Princeton University Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "fs.h" #include "consistency.h" #include "read.h" #include "write.h" #include "client.h" #include "replication.h" #include "inode.h" #include "sync.h" #include "vacuumer.h" // export an fskit_entry to an md_entry, i.e. to create it on the MS. Use the given gateway to get the coordinator, volume, and read/write freshness values. // only set fields in dest that can be filled in from src // return 0 on success // return -ENOMEM on OOM // return -EINVAL on invalid inode type // NOTE: src must be read-locked static int UG_fs_export( struct md_entry* dest, char const* name, struct fskit_entry* src, uint64_t parent_id, struct SG_gateway* gateway ) { struct ms_client* ms = SG_gateway_ms( gateway ); struct md_syndicate_conf* conf = SG_gateway_conf( gateway ); struct UG_inode* inode = NULL; memset( dest, 0, sizeof( struct md_entry ) ); // get type int type = fskit_entry_get_type( src ); if( type == FSKIT_ENTRY_TYPE_FILE ) { dest->type = MD_ENTRY_FILE; dest->size = fskit_entry_get_size( src ); } else if( type == FSKIT_ENTRY_TYPE_DIR ) { dest->type = MD_ENTRY_DIR; dest->size = 4096; } else { // invalid return -EINVAL; } char* name_dup = strdup( name ); if( name_dup == NULL ) { return -ENOMEM; } inode = (struct UG_inode*)fskit_entry_get_user_data( src ); dest->type = type; dest->name = name_dup; dest->file_id = fskit_entry_get_file_id( src ); fskit_entry_get_ctime( src, &dest->ctime_sec, &dest->ctime_nsec ); fskit_entry_get_mtime( src, &dest->mtime_sec, &dest->mtime_nsec ); if( type == FSKIT_ENTRY_TYPE_FILE ) { if( inode != NULL && UG_inode_manifest( inode ) != NULL ) { // file already exists SG_manifest_get_modtime( UG_inode_manifest( inode ), &dest->manifest_mtime_sec, &dest->manifest_mtime_nsec ); } else { // new file dest->manifest_mtime_sec = dest->mtime_sec; dest->manifest_mtime_nsec = dest->mtime_nsec; } } dest->owner = SG_gateway_user_id( gateway ); dest->mode = fskit_entry_get_mode( src ); dest->parent_id = parent_id; dest->max_read_freshness = conf->default_read_freshness; dest->max_write_freshness = conf->default_write_freshness; dest->coordinator = SG_gateway_id( gateway ); dest->volume = ms_client_get_volume_id( ms ); return 0; } // create or make a directory // generate metadata for the inode, and send it off to the MS. // obtain the metadata from either caller_inode_data (in which case, mode will be ignored), or generate data consistent with an empty file (using mode). // * if the caller supplies caller_inode_data, then the following fields will be filled in automatically: // -- file_id // -- parent_id // -- version // -- write_nonce // -- xattr_nonce // -- xattr_hash // -- capacity // -- generation // -- num_children // -- ent_sig // -- ent_sig_len // return -errno on failure (i.e. it exists, we don't have permission, we get a network error, etc.) // NOTE: fent will be write-locked by fskit // NOTE: for files, this will disable truncate (so the subsequent trunc(2) that follows a creat(2) does not incur an extra round-trip) static int UG_fs_create_or_mkdir( struct fskit_core* fs, struct fskit_route_metadata* route_metadata, struct fskit_entry* fent, mode_t mode, struct md_entry* caller_inode_data, struct UG_inode** ret_inode_data ) { struct md_entry inode_data; struct md_entry* inode_data_ptr = NULL; int rc = 0; struct SG_gateway* gateway = (struct SG_gateway*)fskit_core_get_user_data( fs ); struct fskit_entry* parent = fskit_route_metadata_get_parent( route_metadata ); char* name = fskit_route_metadata_get_name( route_metadata ); uint64_t old_size = 0; bool is_mkdir = false; // do nothing if anonymous if( SG_gateway_user_id(gateway) == SG_USER_ANON ) { return -EPERM; } if( caller_inode_data == NULL ) { // generate inode data memset( &inode_data, 0, sizeof(struct md_entry) ); // generate the request rc = UG_fs_export( &inode_data, name, fent, fskit_entry_get_file_id( parent ), gateway ); if( rc != 0 ) { return rc; } // propagate the caller and Syndicate-specific fields... inode_data.mode = mode; inode_data_ptr = &inode_data; } else { inode_data_ptr = caller_inode_data; inode_data_ptr->parent_id = fskit_entry_get_file_id( parent ); // make sure fskit_entry matches timestamps and size UG_inode_fskit_common_init( fent, caller_inode_data ); } old_size = inode_data_ptr->size; if( inode_data_ptr->type == MD_ENTRY_DIR ) { // directories are *always* 4096 bytes inode_data_ptr->size = 4096; is_mkdir = true; } rc = UG_inode_publish( gateway, fent, inode_data_ptr, ret_inode_data ); inode_data_ptr->size = old_size; if( inode_data_ptr == &inode_data ) { md_entry_free( &inode_data ); } if( rc != 0 ) { SG_error("UG_inode_publish rc = %d\n", rc ); } else { // if this is a directory, preserve the size if( is_mkdir ) { SG_debug("mkdir rc = %d\n", rc); UG_inode_set_size( *ret_inode_data, 4096 ); fskit_entry_set_size( fent, 4096 ); } } return rc; } // fskit create callback: try to create the entry on the MS. // return 0 on success, and create the file on the MS // return negative on failure (i.e. it exists, we don't have permission, we get a network error, etc.) // NOTE: fent will be write-locked by fskit static int UG_fs_create( struct fskit_core* fs, struct fskit_route_metadata* route_metadata, struct fskit_entry* fent, mode_t mode, void** ret_inode_data, void** ret_handle_data ) { int rc = 0; // inode data struct UG_inode* inode = NULL; // caller-given inode data struct md_entry* caller_inode_data = (struct md_entry*)fskit_route_metadata_get_cls( route_metadata ); // handle data struct UG_file_handle* handle = NULL; rc = UG_fs_create_or_mkdir( fs, route_metadata, fent, mode, caller_inode_data, &inode ); if( rc != 0 ) { return rc; } // success! // create the handle handle = SG_CALLOC( struct UG_file_handle, 1 ); if( handle == NULL ) { UG_inode_free( inode ); SG_safe_free( inode ); return -ENOMEM; } rc = UG_file_handle_init( handle, inode, O_CREAT | O_WRONLY | O_TRUNC ); if( rc != 0 ) { SG_safe_free( handle ); UG_inode_free( inode ); SG_safe_free( inode ); return -ENOMEM; } // success! *ret_inode_data = inode; *ret_handle_data = handle; return 0; } // fskit mkdir callback // return 0 on success, and create the dir on the MS // return negative on failure (i.e. it exists, we don't have permission, we got a network error, etc.) // NOTE: fent will be write-locked by fskit static int UG_fs_mkdir( struct fskit_core* fs, struct fskit_route_metadata* route_metadata, struct fskit_entry* fent, mode_t mode, void** ret_inode_data ) { int rc = 0; // inode data struct UG_inode* inode = NULL; // caller-given inode data struct md_entry* caller_inode_data = (struct md_entry*)fskit_route_metadata_get_cls( route_metadata ); rc = UG_fs_create_or_mkdir( fs, route_metadata, fent, mode, caller_inode_data, &inode ); if( rc != 0 ) { return rc; } // success! *ret_inode_data = inode; return 0; } // fskit open/opendir callback // refresh path information for the fent // return 0 on success // return negative on failure (i.e. network error, OOM) // NOTE: fent must *not* be locked (the consistency discipline must not alter its lock state) static int UG_fs_open( struct fskit_core* fs, struct fskit_route_metadata* route_metadata, struct fskit_entry* fent, int flags, void** handle_data ) { int rc = 0; struct UG_file_handle* handle = NULL; struct SG_gateway* gateway = (struct SG_gateway*)fskit_core_get_user_data( fs ); struct UG_inode* inode = NULL; // refresh path rc = UG_consistency_path_ensure_fresh( gateway, fskit_route_metadata_get_path( route_metadata ) ); if( rc != 0 ) { SG_error( "UG_consistency_path_ensure_fresh('%s') rc = %d\n", fskit_route_metadata_get_path( route_metadata ), rc ); return rc; } // if this is a directory, go reload the children if( fskit_entry_get_type( fent ) == FSKIT_ENTRY_TYPE_DIR ) { // ensure the listing is fresh rc = UG_consistency_dir_ensure_fresh( gateway, fskit_route_metadata_get_path( route_metadata ) ); if( rc != 0 ) { SG_error("UG_consistency_dir_ensure_fresh('%s') rc = %d\n", fskit_route_metadata_get_path( route_metadata ), rc ); return rc; } // no handle structure is necessary } else { // generate a file handle handle = SG_CALLOC( struct UG_file_handle, 1 ); if( handle == NULL ) { // OOM return -ENOMEM; } // get inode fskit_entry_rlock( fent ); inode = (struct UG_inode*)fskit_entry_get_user_data( fent ); if( UG_inode_deleting( inode ) ) { rc = -ENOENT; } else { rc = UG_file_handle_init( handle, inode, flags ); } fskit_entry_unlock( fent ); if( rc != 0 ) { // OOM SG_safe_free( handle ); return rc; } *handle_data = handle; } return rc; } // fskit close callback (i.e. FUSE release)--free up the handle // if it's a file handle, then try to fsync it for good measure. ERRORS WILL BE MASKED // NOTE: it is incorrect for a program to rely on close or flush to synchronize data to the RGs. // correct programs should call fsync(). Calling fsync() here does *not* guarantee that data will // be persistent, since there is no way to re-try a close(). static int UG_fs_close( struct fskit_core* fs, struct fskit_route_metadata* route_metadata, struct fskit_entry* fent, void* handle_data ) { struct UG_file_handle* handle = (struct UG_file_handle*)handle_data; char const* path = fskit_route_metadata_get_path(route_metadata); // to be safe, try to fsync it. int rc = UG_sync_fsync_ex( fs, path, fent ); if( rc != 0 ) { SG_error("Failed to fsync '%s', rc = %d\n", path, rc); } // free up if( handle != NULL ) { UG_file_handle_free( handle ); SG_safe_free( handle ); } return rc; } // fskit stat callback. // go refresh the path, and pull in any immediate children if it's a directory. // NOTE: fent must *not* be locked (the consistency discipline must not alter its lock state) static int UG_fs_stat( struct fskit_core* fs, struct fskit_route_metadata* route_metadata, struct fskit_entry* fent, struct stat* sb ) { int rc = 0; struct SG_gateway* gateway = (struct SG_gateway*)fskit_core_get_user_data( fs ); struct UG_inode* inode = NULL; struct fskit_entry* new_fent = NULL; // refresh path rc = UG_consistency_path_ensure_fresh( gateway, fskit_route_metadata_get_path( route_metadata ) ); if( rc != 0 ) { SG_error( "UG_consistency_path_ensure_fresh('%s') rc = %d\n", fskit_route_metadata_get_path( route_metadata ), rc ); return rc; } if( fent != NULL ) { fskit_entry_rlock( fent ); // check deleting... inode = (struct UG_inode*)fskit_entry_get_user_data( fent ); if( UG_inode_deleting( inode ) ) { rc = -ENOENT; } fskit_entry_unlock( fent ); } else { // we just discovered this inode and grafted it into our tree. // stat it new_fent = fskit_entry_resolve_path( fs, fskit_route_metadata_get_path( route_metadata ), 0, 0, false, &rc ); if( rc != 0 ) { return rc; } rc = fskit_entry_fstat( new_fent, sb ); fskit_entry_unlock( new_fent ); } return rc; } // truncate locally--ask the MS to update the size and version, vacuum now-removed blocks, and replicate the new manifest. // return 0 on success // return -ENOMEM on OOM // return -EISDIR if the inode is a directory // return -errno on network error // NOTE: inode->entry must be write-locked // NOTE: this method will do nothing if it is on the creat(2) I/O path, since it doesn't make much sense for Syndicate to truncate immediately after creating. static int UG_fs_trunc_local( struct SG_gateway* gateway, char const* fs_path, struct UG_inode* inode, off_t new_size ) { int rc = 0; struct md_entry inode_data; struct UG_state* ug = (struct UG_state*)SG_gateway_cls( gateway ); struct ms_client* ms = SG_gateway_ms( gateway ); struct UG_vacuumer* vacuumer = UG_state_vacuumer( ug ); struct fskit_core* fs = UG_state_fs( ug ); struct md_entry inode_data_out; memset( &inode_data_out, 0, sizeof(struct md_entry) ); struct SG_manifest new_manifest; // manifest after truncate struct SG_manifest removed; struct UG_replica_context* rctx = NULL; struct UG_vacuum_context* vctx = NULL; struct timespec new_manifest_modtime; struct timespec old_manifest_modtime; uint64_t volume_blocksize = ms_client_get_volume_blocksize( ms ); uint64_t new_max_block = new_size / volume_blocksize; unsigned char xattr_hash[SHA256_DIGEST_LENGTH]; memset( xattr_hash, 0, SHA256_DIGEST_LENGTH ); if( new_size % volume_blocksize > 0 ) { new_max_block++; } // if deleting, deny further I/O if( UG_inode_deleting( inode ) ) { return -ENOENT; } // if creating, then this trunc(2) is part of a creat(2). // allow subsequent trunc(2), but claim that this one succeeded. if( UG_inode_creating( inode ) ) { SG_debug("Skip truncate on %" PRIX64 ", since it is being created\n", UG_inode_file_id( inode )); UG_inode_set_creating( inode, false ); return 0; } // can't truncate a directory if( fskit_entry_get_type( UG_inode_fskit_entry( inode ) ) == FSKIT_ENTRY_TYPE_DIR ) { return -EISDIR; } SG_debug("Truncate '%s' to %jd\n", fs_path, new_size ); // get inode data... rc = UG_inode_export( &inode_data, inode, 0 ); if( rc != 0 ) { return rc; } // get xattr hash... rc = UG_inode_export_xattr_hash( fs, SG_gateway_id( gateway ), inode, xattr_hash ); if( rc != 0 ) { md_entry_free( &inode_data ); return rc; } rc = SG_manifest_init( &removed, ms_client_get_volume_id( ms ), SG_gateway_id( gateway ), UG_inode_file_id( inode ), UG_inode_file_version( inode ) ); if( rc != 0 ) { md_entry_free( &inode_data ); return rc; } rc = SG_manifest_dup( &new_manifest, UG_inode_manifest( inode ) ); if( rc != 0 ) { // OOM md_entry_free( &inode_data ); SG_manifest_free( &removed ); return rc; } // find removed blocks rc = UG_inode_truncate_find_removed( gateway, inode, new_size, &removed ); if( rc != 0 ) { // OOM SG_manifest_free( &removed ); SG_manifest_free( &new_manifest ); md_entry_free( &inode_data ); return rc; } // prepare the vacuum request vctx = UG_vacuum_context_new(); if( vctx == NULL ) { // OOM SG_manifest_free( &removed ); SG_manifest_free( &new_manifest ); md_entry_free( &inode_data ); return -ENOMEM; } rc = UG_vacuum_context_init( vctx, ug, fs_path, inode, &removed ); SG_manifest_free( &removed ); if( rc != 0 ) { // OOM SG_manifest_free( &new_manifest ); md_entry_free( &inode_data ); SG_safe_free( vctx ); return rc; } // prepare the replication request rctx = UG_replica_context_new(); if( rctx == NULL ) { // OOM SG_manifest_free( &new_manifest ); md_entry_free( &inode_data ); UG_vacuum_context_free( vctx ); return -ENOMEM; } SG_debug("Remove all blocks beyond %" PRIu64 "\n", new_max_block ); SG_manifest_truncate( &new_manifest, new_max_block ); // advance manifest timestamp, size, nonce, version clock_gettime( CLOCK_REALTIME, &new_manifest_modtime ); SG_manifest_set_modtime( &new_manifest, new_manifest_modtime.tv_sec, new_manifest_modtime.tv_nsec ); SG_manifest_set_size( &new_manifest, new_size ); SG_manifest_set_file_version( &new_manifest, inode_data.version + 1 ); rc = UG_replica_context_init( rctx, ug, fs_path, inode, &new_manifest, NULL ); if( rc != 0 ) { // OOM SG_manifest_free( &new_manifest ); UG_vacuum_context_free( vctx ); md_entry_free( &inode_data ); SG_safe_free( rctx ); return rc; } SG_manifest_free( &new_manifest ); if( rc != 0 ) { UG_vacuum_context_free( vctx ); UG_replica_context_free( rctx ); SG_safe_free( rctx ); md_entry_free( &inode_data ); return rc; } // replicate truncated manifest to all RGs, but don't tell the MS. We'll do that ourselves UG_replica_context_hint( rctx, UG_REPLICA_HINT_NO_MS_UPDATE ); rc = UG_replicate( gateway, rctx ); if( rc != 0 ) { // replication error... SG_error("UG_replicate('%s') rc = %d\n", fs_path, rc ); UG_vacuum_context_free( vctx ); UG_replica_context_free( rctx ); SG_safe_free( rctx ); md_entry_free( &inode_data ); return rc; } // update on the MS inode_data.size = new_size; inode_data.version += 1; // next version inode_data.write_nonce += 1; inode_data.manifest_mtime_sec = new_manifest_modtime.tv_sec; // preserve modtime of manifest we replicated inode_data.manifest_mtime_nsec = new_manifest_modtime.tv_nsec; inode_data.xattr_hash = xattr_hash; SG_debug("'%s' (%" PRIX64 ") version %" PRId64 " --> %" PRId64 ", write_nonce %" PRId64 " --> %" PRId64 "\n", fs_path, inode_data.file_id, inode_data.version - 1, inode_data.version, inode_data.write_nonce - 1, inode_data.write_nonce); // update size and version remotely rc = ms_client_update( ms, &inode_data_out, &inode_data ); if( rc != 0 ) { SG_error("ms_client_update('%s', %jd) rc = %d\n", fs_path, new_size, rc ); UG_vacuum_context_free( vctx ); UG_replica_context_free( rctx ); SG_safe_free( rctx ); md_entry_free( &inode_data ); return rc; } inode_data.xattr_hash = NULL; md_entry_free( &inode_data ); UG_inode_set_write_nonce( inode, inode_data_out.write_nonce ); md_entry_free( &inode_data_out ); // truncate locally, and apply MS-hosted changes UG_inode_preserve_old_manifest_modtime( inode ); UG_inode_truncate( gateway, inode, new_size, inode_data_out.version, inode_data_out.write_nonce, &new_manifest_modtime ); old_manifest_modtime = UG_inode_old_manifest_modtime( inode ); UG_vacuum_context_set_manifest_modtime( vctx, old_manifest_modtime.tv_sec, old_manifest_modtime.tv_nsec ); // garbate-collect while( 1 ) { rc = UG_vacuum_run( vacuumer, vctx ); if( rc != 0 ) { SG_error("UG_vacuum_run('%s') rc = %d, retrying...\n", fs_path, rc ); continue; } break; } UG_vacuum_context_free( vctx ); UG_replica_context_free( rctx ); SG_safe_free( rctx ); SG_safe_free( vctx ); return rc; } // ask another gateway to truncate a file for us. // return 0 on success // return -ENOMEM on OOM // return -EISDIR if the entry is a directory. // return -EREMOTEIO on failed network I/O // return the non-zero error code from the remote truncate if the remote truncate failed // NOTE: inode->entry should be write-locked static int UG_fs_trunc_remote( struct SG_gateway* gateway, char const* fs_path, struct UG_inode* inode, off_t new_size ) { int rc = 0; SG_messages::Request req; SG_messages::Reply reply; struct SG_request_data reqdat; int64_t manifest_mtime_sec = 0; int32_t manifest_mtime_nsec = 0; // if deleting, deny further I/O if( UG_inode_deleting( inode ) ) { return -ENOENT; } if( fskit_entry_get_type( UG_inode_fskit_entry( inode ) ) != FSKIT_ENTRY_TYPE_DIR ) { return -EISDIR; } SG_manifest_get_modtime( UG_inode_manifest( inode ), &manifest_mtime_sec, &manifest_mtime_nsec ); rc = SG_request_data_init_manifest( gateway, fs_path, UG_inode_file_id( inode ), UG_inode_file_version( inode ), manifest_mtime_sec, manifest_mtime_nsec, &reqdat ); if( rc != 0 ) { // OOM return rc; } rc = SG_client_request_TRUNCATE_setup( gateway, &req, &reqdat, UG_inode_coordinator_id( inode ), new_size ); if( rc != 0 ) { // OOM SG_error("SG_client_request_TRUNCATE_setup('%s') rc = %d\n", fs_path, rc ); SG_request_data_free( &reqdat ); return rc; } SG_request_data_free( &reqdat ); rc = SG_client_request_send( gateway, UG_inode_coordinator_id( inode ), &req, NULL, &reply ); if( rc != 0 ) { // network error SG_error("SG_client_request_send(TRUNC '%s' %jd) rc = %d\n", fs_path, new_size, rc ); // timed out? retry if( rc == -ETIMEDOUT ) { rc = -EAGAIN; } // propagate retries; everything else is remote I/O error if( rc != -EAGAIN ) { rc = -EREMOTEIO; } return rc; } if( reply.error_code() != 0 ) { // failed to process SG_error("SG_client_request_send(TRUNC '%s' %jd) reply error = %d\n", fs_path, new_size, rc ); return reply.error_code(); } // truncate locally, // TODO: have server fill in reply.ent_out, and plumb it through here UG_inode_truncate( gateway, inode, new_size, 0, 0, NULL ); // reload inode on next access UG_inode_set_read_stale( inode, true ); return rc; } // fskit route for truncating files. // In the UG, this simply tells the MS that the size has changed. // return 0 on success // return -EPERM if the gateway is anonymous // return -ENOMEM on OOM // return -errno on failure to connect to the MS // NOTE: fent will be write-locked by fskit static int UG_fs_trunc( struct fskit_core* fs, struct fskit_route_metadata* route_metadata, struct fskit_entry* fent, off_t new_size, void* inode_cls ) { int rc = 0; char* path = fskit_route_metadata_get_path( route_metadata ); struct UG_inode* inode = (struct UG_inode*)fskit_entry_get_user_data( fent ); struct SG_gateway* gateway = (struct SG_gateway*)fskit_core_get_user_data( fs ); // cannot proceed if anonymous if( SG_gateway_user_id(gateway) == SG_USER_ANON ) { return -EPERM; } UG_try_or_coordinate( gateway, path, UG_inode_coordinator_id( inode ), UG_fs_trunc_local( gateway, path, inode, new_size ), UG_fs_trunc_remote( gateway, path, inode, new_size ), &rc ); return rc; } // ask the MS to detach a file or directory. If we succeed, clear any cached state. // return 0 on success // return -ENOMEM on OOM // return -ENOENT if this inode is already being deleted // return -EAGAIN if we should try again // return -EREMOTEIO on remote error (e.g. on the MS or RGs) // return -errno on network error // NOTE: inode->entry must be write-locked static int UG_fs_detach_local( struct SG_gateway* gateway, char const* fs_path, bool renamed, struct UG_inode* inode ) { int rc = 0; struct ms_client* ms = SG_gateway_ms( gateway ); struct md_syndicate_cache* cache = SG_gateway_cache( gateway ); struct UG_state* ug = (struct UG_state*)SG_gateway_cls( gateway ); struct md_entry inode_data; struct UG_vacuum_context* vctx = NULL; bool vacuum_again = true; if( UG_inode_deleting( inode ) ) { return -ENOENT; } if( renamed ) { // nothing to do return 0; } // deny subsequent I/O operations UG_inode_set_deleting( inode, true ); // export... rc = UG_inode_export( &inode_data, inode, 0 ); if( rc != 0 ) { UG_inode_set_deleting( inode, false ); return rc; } // if this is a file, and we're the coordinator, vacuum it if( UG_inode_coordinator_id( inode ) == SG_gateway_id( gateway ) && fskit_entry_get_type( UG_inode_fskit_entry( inode ) ) == FSKIT_ENTRY_TYPE_FILE ) { while( vacuum_again ) { vctx = UG_vacuum_context_new(); if( vctx == NULL ) { rc = -ENOMEM; md_entry_free( &inode_data ); UG_inode_set_deleting( inode, false ); return rc; } rc = UG_vacuum_context_init( vctx, ug, fs_path, inode, NULL ); if( rc != 0 ) { SG_error("UG_vacuum_context_init('%s') rc = %d\n", fs_path, rc ); md_entry_free( &inode_data ); SG_safe_free( vctx ); UG_inode_set_deleting( inode, false ); return rc; } // allow deleting the current manifest UG_vacuum_context_set_unlinking( vctx, true ); while( 1 ) { // vacuum until we succeed rc = UG_vacuum_run( UG_state_vacuumer( ug ), vctx ); if( rc != 0 ) { SG_error("UG_vacuum_run('%s') rc = %d; retrying...\n", fs_path, rc ); continue; } break; } // try again until we've vacuumed everything vacuum_again = !UG_vacuum_context_is_clean( vctx ); UG_vacuum_context_free( vctx ); SG_safe_free( vctx ); } } // delete on the MS rc = ms_client_delete( ms, &inode_data ); md_entry_free( &inode_data ); if( rc != 0 ) { UG_inode_set_deleting( inode, false ); SG_error("ms_client_delete('%s') rc = %d\n", fs_path, rc ); return rc; } // blow away local cached state, if this is a file if( fskit_entry_get_file_id( UG_inode_fskit_entry( inode ) ) == FSKIT_ENTRY_TYPE_FILE ) { md_cache_evict_file( cache, UG_inode_file_id( inode ), UG_inode_file_version( inode ), 0 ); } return rc; } // ask a remote gateway to detach an inode for us, if the inode is a file. // if the inode is a directory, ask the MS directly. // return 0 on success // return -ENOMEM on OOM // return -EAGAIN if we timed out // return -EREMOTEIO on network error // return non-zero error code from the remote unlink if it failed remotely static int UG_fs_detach_remote( struct SG_gateway* gateway, char const* fs_path, bool renamed, struct UG_inode* inode ) { int rc = 0; struct md_syndicate_cache* cache = SG_gateway_cache( gateway ); SG_messages::Request req; SG_messages::Reply reply; struct SG_request_data reqdat; int64_t manifest_mtime_sec = 0; int32_t manifest_mtime_nsec = 0; if( renamed ) { // nothing to do return 0; } SG_manifest_get_modtime( UG_inode_manifest( inode ), &manifest_mtime_sec, &manifest_mtime_nsec ); rc = SG_request_data_init_manifest( gateway, fs_path, UG_inode_file_id( inode ), UG_inode_file_version( inode ), manifest_mtime_sec, manifest_mtime_nsec, &reqdat ); if( rc != 0 ) { // OOM return rc; } // NOTE: no vacuum ticket; the receiving gateway can verify the write-permission with the certificate rc = SG_client_request_DETACH_setup( gateway, &req, &reqdat, UG_inode_coordinator_id( inode ) ); if( rc != 0 ) { // OOM SG_error("SG_client_request_DETACH_setup('%s') rc = %d\n", fs_path, rc ); SG_request_data_free( &reqdat ); return rc; } SG_request_data_free( &reqdat ); rc = SG_client_request_send( gateway, UG_inode_coordinator_id( inode ), &req, NULL, &reply ); if( rc != 0 ) { // network error SG_error("SG_client_request_send(DETACH '%s') rc = %d\n", fs_path, rc ); // timed out? retry if( rc == -ETIMEDOUT ) { rc = -EAGAIN; } // propagate retries; everything else is remote I/O error if( rc != -EAGAIN ) { rc = -EREMOTEIO; } return rc; } if( reply.error_code() != 0 ) { // failed to process SG_error("SG_client_request_send(DETACH '%s') reply error = %d\n", fs_path, rc ); return reply.error_code(); } // blow away local cached state md_cache_evict_file( cache, UG_inode_file_id( inode ), UG_inode_file_version( inode ), 0 ); return rc; } // fskit route for detaching a file or directory. // In the UG, this simply tells the MS to delete the entry. // if we're the coordinator, and this is a file, then garbage-collect all of its blocks. // This method is used when the gateway is in operation, since because Syndicate does not // support hard links, this method will get called only when the user unlinks or rmdirs and inode. // We switch over to UG_fs_destroy when cleaning up on exit. // return 0 on success // return -EPERM if the gateway is anonymous // return -ENOMEM on OOM // return -EAGAIN if the caller should try detaching again // return -errno on failure to connect to the MS // NOTE: fent should not be locked at all (it will be unreferenceable) static int UG_fs_detach_and_destroy( struct fskit_core* fs, struct fskit_route_metadata* route_metadata, struct fskit_entry* fent, void* inode_cls ) { int rc = 0; struct UG_inode* inode = (struct UG_inode*)inode_cls; struct SG_gateway* gateway = (struct SG_gateway*)fskit_core_get_user_data( fs ); char* path = fskit_route_metadata_get_path( route_metadata ); bool renamed = fskit_route_metadata_renamed( route_metadata ); // cannot proceed if anonymous if( SG_gateway_user_id(gateway) == SG_USER_ANON ) { return -EPERM; } fskit_entry_rlock( fent ); int type = fskit_entry_get_type( fent ); uint64_t file_id = fskit_entry_get_file_id( fent ); fskit_entry_unlock( fent ); SG_debug("Detach/destroy %" PRIX64 "\n", file_id ); if( type == FSKIT_ENTRY_TYPE_FILE ) { // route request to coordinator UG_try_or_coordinate( gateway, path, UG_inode_coordinator_id( inode ), UG_fs_detach_local( gateway, fskit_route_metadata_get_path( route_metadata ), renamed, inode ), UG_fs_detach_remote( gateway, fskit_route_metadata_get_path( route_metadata ), renamed, inode ), &rc ); if( rc != 0 ) { SG_error("UG_try_or_coordinate( DETACH '%s' ) rc = %d\n", fskit_route_metadata_get_path( route_metadata ), rc ); } } else { // send directly to the MS rc = UG_fs_detach_local( gateway, fskit_route_metadata_get_path( route_metadata ), renamed, inode ); if( rc != 0 ) { SG_error("UG_fs_detach_local('%s') rc = %d\n", fskit_route_metadata_get_path( route_metadata ), rc ); } } if( rc == 0 ) { // success! UG_inode_free( inode ); SG_safe_free( inode ); } return rc; } // fskit route for destroying a file or directory inode data // This is used only for shutting down the gateway and freeing memory. // return 0 on success static int UG_fs_destroy( struct fskit_core* fs, struct fskit_route_metadata* route_metadata, struct fskit_entry* fent, void* inode_cls ) { struct UG_inode* inode = (struct UG_inode*)inode_cls; uint64_t file_id = 0; if( inode != NULL ) { file_id = UG_inode_file_id( inode ); SG_debug("Destroy %" PRIX64 "\n", file_id ); UG_inode_free( inode ); SG_safe_free( inode ); fskit_entry_set_user_data( fent, NULL ); } else { fskit_entry_rlock( fent ); SG_warn("%" PRIX64 ": inode already freed\n", fskit_entry_get_file_id( fent) ); fskit_entry_unlock( fent ); } return 0; } // get the xattr hashes and inode metadata for the old and new inodes on rename // return 0 on success // reutrn -ENOMEM on OOM static int UG_fs_rename_inode_export( struct fskit_core* fs, char const* old_path, struct fskit_entry* old_parent, struct UG_inode* old_inode, struct md_entry* old_fent_metadata, char const* new_path, struct fskit_entry* new_parent, struct UG_inode* new_inode, struct md_entry* new_fent_metadata ) { int rc = 0; struct SG_gateway* gateway = (struct SG_gateway*)fskit_core_get_user_data( fs ); uint64_t old_parent_id = fskit_entry_get_file_id( old_parent ); uint64_t new_parent_id = fskit_entry_get_file_id( new_parent ); unsigned char* old_xattr_hash = SG_CALLOC( unsigned char, SHA256_DIGEST_LENGTH ); unsigned char* new_xattr_hash = SG_CALLOC( unsigned char, SHA256_DIGEST_LENGTH ); if( SG_gateway_user_id(gateway) == SG_USER_ANON ) { return -EPERM; } if( old_xattr_hash == NULL || new_xattr_hash == NULL ) { SG_safe_free( new_xattr_hash ); SG_safe_free( old_xattr_hash ); return -ENOMEM; } rc = UG_inode_export( old_fent_metadata, old_inode, old_parent_id ); if( rc != 0 ) { SG_safe_free( new_xattr_hash ); SG_safe_free( old_xattr_hash ); SG_error("UG_inode_export(%s) rc = %d\n", old_path, rc ); return rc; } // set new name in old inode data SG_safe_free( old_fent_metadata->name ); old_fent_metadata->name = md_basename( new_path, NULL ); if( old_fent_metadata->name == NULL ) { md_entry_free( old_fent_metadata ); SG_safe_free( old_xattr_hash ); SG_safe_free( new_xattr_hash ); return -ENOMEM; } rc = UG_inode_export_xattr_hash( fs, SG_gateway_id( gateway ), old_inode, old_xattr_hash ); if( rc != 0 ) { SG_safe_free( new_xattr_hash ); SG_safe_free( old_xattr_hash ); md_entry_free( old_fent_metadata ); SG_error("UG_inode_export_xattr_hash(%s) rc = %d\n", old_path, rc ); return rc; } memcpy( new_xattr_hash, old_xattr_hash, SHA256_DIGEST_LENGTH ); if( new_inode != NULL ) { rc = UG_inode_export( new_fent_metadata, new_inode, new_parent_id ); if( rc != 0 ) { md_entry_free( old_fent_metadata ); SG_safe_free( old_xattr_hash ); SG_safe_free( new_xattr_hash ); SG_error("UG_inode_export(%s) rc = %d\n", new_path, rc ); return rc; } } else { // will rename into a new path entirely rc = md_entry_dup2( old_fent_metadata, new_fent_metadata ); if( rc != 0 ) { md_entry_free( old_fent_metadata ); SG_safe_free( old_xattr_hash ); SG_safe_free( new_xattr_hash ); SG_error("md_entry_dup2 rc = %d\n", rc ); return rc; } // switch parent new_fent_metadata->parent_id = new_parent_id; } old_fent_metadata->xattr_hash = old_xattr_hash; new_fent_metadata->xattr_hash = new_xattr_hash; // dest carries *old* name, but src carries the *new* name SG_safe_free( new_fent_metadata->name ); new_fent_metadata->name = md_basename( old_path, NULL ); if( new_fent_metadata->name == NULL ) { md_entry_free( old_fent_metadata ); md_entry_free( new_fent_metadata ); SG_safe_free( old_xattr_hash ); SG_safe_free( new_xattr_hash ); return -ENOMEM; } // preserve a few key details new_fent_metadata->manifest_mtime_sec = old_fent_metadata->manifest_mtime_sec; new_fent_metadata->manifest_mtime_nsec = old_fent_metadata->manifest_mtime_nsec; new_fent_metadata->xattr_nonce = old_fent_metadata->xattr_nonce; return 0; } // ask the MS to rename an inode for us. // old_parent and new_parent must be at least read-locked // we must be the coordinator of old_inode // return 0 on success // return -ENOMEM on OOM // return negative on network error // NOTE: old_inode->entry should be write-locked by fskit static int UG_fs_rename_local( struct fskit_core* fs, struct fskit_entry* old_parent, char const* old_path, struct UG_inode* old_inode, struct fskit_entry* new_parent, char const* new_path, struct UG_inode* new_inode ) { int rc = 0; struct SG_gateway* gateway = (struct SG_gateway*)fskit_core_get_user_data( fs ); struct ms_client* ms = SG_gateway_ms( gateway ); struct UG_state* ug = (struct UG_state*)SG_gateway_cls( gateway ); struct UG_replica_context* rctx = NULL; struct UG_vacuum_context* vctx_old = NULL; struct UG_vacuum_context* vctx_new = NULL; struct UG_vacuumer* vacuumer = UG_state_vacuumer( ug ); struct md_entry old_fent_metadata; struct md_entry new_fent_metadata; struct SG_manifest new_manifest; struct timespec old_manifest_modtime; struct timespec new_manifest_modtime; memset( &old_fent_metadata, 0, sizeof(struct md_entry) ); memset( &new_fent_metadata, 0, sizeof(struct md_entry) ); memset( &new_manifest, 0, sizeof(struct SG_manifest) ); memset( &old_manifest_modtime, 0, sizeof(struct timespec) ); memset( &new_manifest_modtime, 0, sizeof(struct timespec) ); // gather inode data rc = UG_fs_rename_inode_export( fs, old_path, old_parent, old_inode, &old_fent_metadata, new_path, new_parent, new_inode, &new_fent_metadata ); if( rc != 0 ) { // OOM return rc; } // make a new manifest for the old inode rc = SG_manifest_dup( &new_manifest, UG_inode_manifest( old_inode ) ); if( rc != 0 ) { // OOM md_entry_free( &old_fent_metadata ); md_entry_free( &new_fent_metadata ); return rc; } // prepare the vacuum requests vctx_old = UG_vacuum_context_new(); vctx_new = UG_vacuum_context_new(); if( vctx_old == NULL || vctx_new == NULL ) { // OOM SG_safe_free( vctx_old ); SG_safe_free( vctx_new ); md_entry_free( &old_fent_metadata ); md_entry_free( &new_fent_metadata ); SG_manifest_free( &new_manifest ); return -ENOMEM; } // will vacuum the old inode, removing its old manifest if( old_fent_metadata.type == MD_ENTRY_FILE ) { rc = UG_vacuum_context_init( vctx_old, ug, old_path, old_inode, NULL ); if( rc != 0 ) { // OOM md_entry_free( &old_fent_metadata ); md_entry_free( &new_fent_metadata ); SG_manifest_free( &new_manifest ); SG_safe_free( vctx_old ); SG_safe_free( vctx_new ); return rc; } } // will vacuum the new inode (if it exists), removing its old blocks and manifests if( new_inode != NULL ) { if( new_fent_metadata.type == MD_ENTRY_FILE ) { rc = UG_vacuum_context_init( vctx_new, ug, new_path, new_inode, NULL ); if( rc != 0 ) { // OOM md_entry_free( &old_fent_metadata ); md_entry_free( &new_fent_metadata ); SG_manifest_free( &new_manifest ); UG_vacuum_context_free( vctx_old ); SG_safe_free( vctx_old ); SG_safe_free( vctx_new ); return -ENOMEM; } } else { // directory must not be empty if( new_fent_metadata.num_children > 0 ) { SG_error("Directory %s not empty\n", new_path); md_entry_free( &old_fent_metadata ); md_entry_free( &new_fent_metadata ); SG_manifest_free( &new_manifest ); UG_vacuum_context_free( vctx_old ); SG_safe_free( vctx_old ); SG_safe_free( vctx_new ); return -ENOTEMPTY; } } } // prepare the replication request for the new manifest rctx = UG_replica_context_new(); if( rctx == NULL ) { // OOM md_entry_free( &old_fent_metadata ); md_entry_free( &new_fent_metadata ); SG_manifest_free( &new_manifest ); UG_vacuum_context_free( vctx_old ); SG_safe_free( vctx_old ); if( new_inode != NULL ) { UG_vacuum_context_free( vctx_new ); } SG_safe_free( vctx_new ); return -ENOMEM; } // advance manifest timestamp, nonce, version new_fent_metadata.version = old_fent_metadata.version + 1; clock_gettime( CLOCK_REALTIME, &new_manifest_modtime ); SG_manifest_set_modtime( &new_manifest, new_manifest_modtime.tv_sec, new_manifest_modtime.tv_nsec ); SG_manifest_set_file_version( &new_manifest, old_fent_metadata.version + 1 ); new_fent_metadata.manifest_mtime_sec = new_manifest_modtime.tv_sec; new_fent_metadata.manifest_mtime_nsec = new_manifest_modtime.tv_nsec; new_fent_metadata.version = old_fent_metadata.version + 1; // (this will become the new entry's manifest modtime) old_fent_metadata.manifest_mtime_sec = new_manifest_modtime.tv_sec; old_fent_metadata.manifest_mtime_nsec = new_manifest_modtime.tv_nsec; SG_debug("Duplicated manifest '%s': %zu blocks, ts=%ld.%ld (version %" PRId64 ")\n", old_path, SG_manifest_get_block_count( &new_manifest ), new_manifest_modtime.tv_sec, new_manifest_modtime.tv_nsec, SG_manifest_get_file_version(&new_manifest) ); // has to be the later version to prove that we have the latest old_fent_metadata.version += 1; // make the request to rename this inode rc = UG_replica_context_init_rename_hint( rctx, ug, old_path, new_path, old_inode, &new_manifest ); if( rc != 0 ) { // OOM md_entry_free( &old_fent_metadata ); md_entry_free( &new_fent_metadata ); SG_manifest_free( &new_manifest ); UG_vacuum_context_free( vctx_old ); SG_safe_free( vctx_old ); if( new_inode != NULL ) { UG_vacuum_context_free( vctx_new ); } SG_safe_free( vctx_new ); SG_safe_free( rctx ); return rc; } SG_manifest_free( &new_manifest ); // replicate rename hint (with manifest) to all RGs, but don't tell the MS. We'll do that ourselves UG_replica_context_hint( rctx, UG_REPLICA_HINT_NO_MS_UPDATE ); rc = UG_replicate( gateway, rctx ); if( rc != 0 ) { // replication error... SG_error("UG_replicate('%s') rc = %d\n", new_path, rc ); md_entry_free( &old_fent_metadata ); md_entry_free( &new_fent_metadata ); UG_vacuum_context_free( vctx_old ); SG_safe_free( vctx_old ); if( new_inode != NULL ) { UG_vacuum_context_free( vctx_new ); } SG_safe_free( vctx_new ); UG_replica_context_free( rctx ); SG_safe_free( rctx ); return rc; } // do the rename on the MS rc = ms_client_rename( ms, &old_fent_metadata, &new_fent_metadata ); md_entry_free( &old_fent_metadata ); md_entry_free( &new_fent_metadata ); UG_replica_context_free( rctx ); SG_safe_free( rctx ); if( rc != 0 ) { // failed to rename on the MS SG_error("ms_client_rename( '%s', '%s' ) rc = %d\n", old_path, new_path, rc ); UG_vacuum_context_free( vctx_old ); SG_safe_free( vctx_old ); if( new_inode != NULL ) { UG_vacuum_context_free( vctx_new ); } SG_safe_free( vctx_new ); return rc; } // remove the old manifest, if the old inode is a file if( old_fent_metadata.type == MD_ENTRY_FILE ) { old_manifest_modtime = UG_inode_old_manifest_modtime( old_inode ); UG_vacuum_context_set_manifest_modtime( vctx_old, old_manifest_modtime.tv_sec, old_manifest_modtime.tv_nsec ); } // garbate-collect SG_debug("Vacuum '%s'\n", old_path); while( old_fent_metadata.type == MD_ENTRY_FILE ) { rc = UG_vacuum_run( vacuumer, vctx_old ); if( rc != 0 ) { SG_error("UG_vacuum_run('%s') rc = %d, retrying...\n", old_path, rc ); continue; } break; } // vacuum the new inode (if it exists) if( new_inode != NULL ) { SG_debug("Vacuum '%s'\n", new_path); while( new_fent_metadata.type == MD_ENTRY_FILE ) { rc = UG_vacuum_run( vacuumer, vctx_new ); if( rc != 0 ) { SG_error("UG_vacuum_run('%s') rc = %d, retrying...\n", new_path, rc ); continue; } break; } UG_vacuum_context_free( vctx_new ); } SG_safe_free( vctx_new ); UG_vacuum_context_free( vctx_old ); SG_safe_free( vctx_old ); // force refresh on the destination on next access UG_inode_set_read_stale( old_inode, true ); return rc; } // ask another gateway to rename an inode, if the inode is a file. // if the inode is a directory, just ask the MS directly. // return 0 on success // return -ENOMEM on OOM // return -EREMOTEIO on failed network I/O // return -EAGAIN if the request timed out, or should be retried // return the non-zero error code if the rename failed on the remote gateway // NOTE: inode->entry should be write-locked by fskit static int UG_fs_rename_remote( struct fskit_core* fs, struct fskit_entry* old_parent, char const* fs_path, struct UG_inode* inode, struct fskit_entry* new_parent, char const* new_path, struct UG_inode* new_inode ) { int rc = 0; struct SG_gateway* gateway = (struct SG_gateway*)fskit_core_get_user_data( fs ); SG_messages::Request req; SG_messages::Reply reply; struct SG_request_data reqdat; int64_t manifest_mtime_sec = 0; int32_t manifest_mtime_nsec = 0; // if this is a directory, then this is a "local" rename--i.e. we have the ability to ask the MS directly, since the MS is the coordinator of all directories. if( fskit_entry_get_type( UG_inode_fskit_entry( inode ) ) == FSKIT_ENTRY_TYPE_DIR ) { return UG_fs_rename_local( fs, old_parent, fs_path, inode, new_parent, new_path, new_inode ); } SG_manifest_get_modtime( UG_inode_manifest( inode ), &manifest_mtime_sec, &manifest_mtime_nsec ); rc = SG_request_data_init_manifest( gateway, fs_path, UG_inode_file_id( inode ), UG_inode_file_version( inode ), manifest_mtime_sec, manifest_mtime_nsec, &reqdat ); if( rc != 0 ) { // OOM return rc; } rc = SG_client_request_RENAME_setup( gateway, &req, &reqdat, UG_inode_coordinator_id( inode ), new_path ); if( rc != 0 ) { // OOM SG_error("SG_client_request_RENAME_setup('%s') rc = %d\n", fs_path, rc ); SG_request_data_free( &reqdat ); return rc; } SG_request_data_free( &reqdat ); rc = SG_client_request_send( gateway, UG_inode_coordinator_id( inode ), &req, NULL, &reply ); if( rc != 0 ) { // network error SG_error("SG_client_request_send(RENAME '%s' to '%s') rc = %d\n", fs_path, new_path, rc ); // timed out? retry if( rc == -ETIMEDOUT ) { rc = -EAGAIN; } // propagate retries; everything else is remote I/O error if( rc != -EAGAIN ) { rc = -EREMOTEIO; } return rc; } if( reply.error_code() != 0 ) { // failed to process SG_error("SG_client_request_send(DETACH '%s' to '%s') reply error = %d\n", fs_path, new_path, rc ); return reply.error_code(); } return rc; } // fskit route for renaming a file or directory. // In the UG, this simply tells the MS to rename the entry if we're the coordinator, or tell the coordinator to do so if we're not. // return 0 on success // return -ENOMEM on OOM // return -errno if we had a network error // fent and dest will both be write-locked static int UG_fs_rename( struct fskit_core* fs, struct fskit_route_metadata* route_metadata, struct fskit_entry* fent, char const* new_path, struct fskit_entry* dest ) { int rc = 0; struct UG_inode* inode = (struct UG_inode*)fskit_entry_get_user_data( fent ); struct UG_inode* new_inode = NULL; struct SG_gateway* gateway = (struct SG_gateway*)fskit_core_get_user_data( fs ); char* path = fskit_route_metadata_get_path( route_metadata ); if( dest != NULL ) { new_inode = (struct UG_inode*)fskit_entry_get_user_data( dest ); } UG_try_or_coordinate( gateway, path, UG_inode_coordinator_id( inode ), UG_fs_rename_local( fs, fskit_route_metadata_get_parent( route_metadata ), path, inode, fskit_route_metadata_get_new_parent( route_metadata ), new_path, new_inode ), UG_fs_rename_remote( fs, fskit_route_metadata_get_parent( route_metadata ), path, inode, fskit_route_metadata_get_new_parent( route_metadata ), new_path, new_inode ), &rc ); return rc; } // fskit route for handling getxattr // return > 0 on success // return 0 if not built-in // return negative on error (see xattr.cpp) // fent must be read-locked static int UG_fs_fgetxattr( struct fskit_core* fs, struct fskit_route_metadata* route_metadata, struct fskit_entry* fent, char const* name, char* value, size_t value_len ) { int rc = 0; struct SG_gateway* gateway = (struct SG_gateway*)fskit_core_get_user_data( fs ); char const* path = fskit_route_metadata_get_path( route_metadata ); rc = UG_xattr_fgetxattr( gateway, path, fent, name, value, value_len ); return rc; } // fskit route for handling listxattr // merges "normal" fskit xattrs with builtins // return > 0 on success // return -ERANGE if not big enough // fent must be read-locked static int UG_fs_flistxattr( struct fskit_core* fs, struct fskit_route_metadata* route_metadata, struct fskit_entry* fent, char* buf, size_t buf_len ) { int rc = 0; struct SG_gateway* gateway = (struct SG_gateway*)fskit_core_get_user_data( fs ); char const* path = fskit_route_metadata_get_path( route_metadata ); rc = UG_xattr_flistxattr( gateway, path, fent, buf, buf_len ); return rc; } // fskit route for handling setxattr // handles built-in xattrs, and forwards the rest to local fskit // calls the MS to replicate xattrs. // return 0 on success // return -ERANGE if buffer is not big enough // fent must be write-locked static int UG_fs_fsetxattr( struct fskit_core* fs, struct fskit_route_metadata* route_metadata, struct fskit_entry* fent, char const* name, char const* value, size_t value_len, int flags ) { int rc = 0; struct SG_gateway* gateway = (struct SG_gateway*)fskit_core_get_user_data( fs ); char const* path = fskit_route_metadata_get_path( route_metadata ); rc = UG_xattr_fsetxattr( gateway, path, fent, name, value, value_len, flags ); return rc; } // fskit route for removexattr // return 0 if handled // return 1 if not handled // return negative on error static int UG_fs_fremovexattr( struct fskit_core* fs, struct fskit_route_metadata* route_metadata, struct fskit_entry* fent, char const* name ) { int rc = 0; struct SG_gateway* gateway = (struct SG_gateway*)fskit_core_get_user_data( fs ); char const* path = fskit_route_metadata_get_path( route_metadata ); rc = UG_xattr_fremovexattr( gateway, path, fent, name ); return rc; } // insert fskit entries into the fskit core // return 0 on success. // return -ENOMEM on OOM int UG_fs_install_methods( struct fskit_core* core, struct UG_state* state ) { int rh = 0; rh = fskit_route_stat( core, FSKIT_ROUTE_ANY, UG_fs_stat, FSKIT_CONCURRENT ); if( rh < 0 ) { SG_error("fskit_route_stat(%s) rc = %d\n", FSKIT_ROUTE_ANY, rh ); return rh; } UG_state_set_stat_rh( state, rh ); rh = fskit_route_mkdir( core, FSKIT_ROUTE_ANY, UG_fs_mkdir, FSKIT_INODE_SEQUENTIAL ); if( rh < 0 ) { SG_error("fskit_route_mkdir(%s) rc = %d\n", FSKIT_ROUTE_ANY, rh ); return rh; } UG_state_set_mkdir_rh( state, rh ); rh = fskit_route_create( core, FSKIT_ROUTE_ANY, UG_fs_create, FSKIT_INODE_SEQUENTIAL ); if( rh < 0 ) { SG_error("fskit_route_create(%s) rc = %d\n", FSKIT_ROUTE_ANY, rh ); return rh; } UG_state_set_creat_rh( state, rh ); rh = fskit_route_open( core, FSKIT_ROUTE_ANY, UG_fs_open, FSKIT_CONCURRENT ); if( rh < 0 ) { SG_error("fskit_route_open(%s) rc = %d\n", FSKIT_ROUTE_ANY, rh ); return rh; } UG_state_set_open_rh( state, rh ); rh = fskit_route_read( core, FSKIT_ROUTE_ANY, UG_read_impl, FSKIT_CONCURRENT ); if( rh < 0 ) { SG_error("fskit_route_read(%s) rc = %d\n", FSKIT_ROUTE_ANY, rh ); return rh; } UG_state_set_read_rh( state, rh ); rh = fskit_route_write( core, FSKIT_ROUTE_ANY, UG_write_impl, FSKIT_CONCURRENT ); if( rh < 0 ) { SG_error("fskit_route_write(%s) rc = %d\n", FSKIT_ROUTE_ANY, rh ); return rh; } UG_state_set_write_rh( state, rh ); rh = fskit_route_trunc( core, FSKIT_ROUTE_ANY, UG_fs_trunc, FSKIT_INODE_SEQUENTIAL ); if( rh < 0 ) { SG_error("fskit_route_trunc(%s) rc = %d\n", FSKIT_ROUTE_ANY, rh ); return rh; } UG_state_set_trunc_rh( state, rh ); rh = fskit_route_close( core, FSKIT_ROUTE_ANY, UG_fs_close, FSKIT_CONCURRENT ); if( rh < 0 ) { SG_error("fskit_route_close(%s) rc = %d\n", FSKIT_ROUTE_ANY, rh ); return rh; } UG_state_set_close_rh( state, rh ); rh = fskit_route_sync( core, FSKIT_ROUTE_ANY, UG_sync_fsync, FSKIT_CONCURRENT ); if( rh < 0 ) { SG_error("fskit_route_sync(%s) rc = %d\n", FSKIT_ROUTE_ANY, rh ); return rh; } UG_state_set_sync_rh( state, rh ); rh = fskit_route_destroy( core, FSKIT_ROUTE_ANY, UG_fs_detach_and_destroy, FSKIT_CONCURRENT ); if( rh < 0 ) { SG_error("fskit_route_destroy(%s) rc = %d\n", FSKIT_ROUTE_ANY, rh ); return rh; } UG_state_set_detach_rh( state, rh ); rh = fskit_route_rename( core, FSKIT_ROUTE_ANY, UG_fs_rename, FSKIT_CONCURRENT ); if( rh < 0 ) { SG_error("fskit_route_rename(%s) rc = %d\n", FSKIT_ROUTE_ANY, rh ); return rh; } UG_state_set_rename_rh( state, rh ); rh = fskit_route_getxattr( core, FSKIT_ROUTE_ANY, UG_fs_fgetxattr, FSKIT_CONCURRENT ); if( rh < 0 ) { SG_error("fskit_route_getxattr(%s) rc = %d\n", FSKIT_ROUTE_ANY, rh ); return rh; } UG_state_set_getxattr_rh( state, rh ); rh = fskit_route_setxattr( core, FSKIT_ROUTE_ANY, UG_fs_fsetxattr, FSKIT_INODE_SEQUENTIAL ); if( rh < 0 ) { SG_error("fskit_route_setxattr(%s) rc = %d\n", FSKIT_ROUTE_ANY, rh ); return rh; } UG_state_set_setxattr_rh( state, rh ); rh = fskit_route_listxattr( core, FSKIT_ROUTE_ANY, UG_fs_flistxattr, FSKIT_CONCURRENT ); if( rh < 0 ) { SG_error("fskit_route_listxattr(%s) rc = %d\n", FSKIT_ROUTE_ANY, rh ); return rh; } UG_state_set_listxattr_rh( state, rh ); rh = fskit_route_removexattr( core, FSKIT_ROUTE_ANY, UG_fs_fremovexattr, FSKIT_INODE_SEQUENTIAL ); if( rh < 0 ) { SG_error("fskit_route_removexattr(%s) rc = %d\n", FSKIT_ROUTE_ANY, rh ); return rh; } UG_state_set_removexattr_rh( state, rh ); return 0; } // remove all fskit methods, but install a detach method that simply frees the inode // return 0 on success // return -errno on failure int UG_fs_install_shutdown_methods( struct fskit_core* fs ) { // stop all fs calls int rc = fskit_unroute_all( fs ); if( rc != 0 ) { SG_error("fskit_unroute_all rc = %d\n", rc ); return rc; } // insert a memory-freeing call int rh = fskit_route_destroy( fs, FSKIT_ROUTE_ANY, UG_fs_destroy, FSKIT_CONCURRENT ); if( rh < 0 ) { SG_error("fskit_route_destroy(%s) rc = %d\n", FSKIT_ROUTE_ANY, rh ); return rh; } SG_debug("Destroy route inserted at %d\n", rh ); return 0; } // remove all fskit methods int UG_fs_uninstall_methods( struct fskit_core* fs ) { return fskit_unroute_all( fs ); } don't accidentally free xattr_hash on the stack on the ms_client_update error path /* Copyright 2015 The Trustees of Princeton University Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "fs.h" #include "consistency.h" #include "read.h" #include "write.h" #include "client.h" #include "replication.h" #include "inode.h" #include "sync.h" #include "vacuumer.h" // export an fskit_entry to an md_entry, i.e. to create it on the MS. Use the given gateway to get the coordinator, volume, and read/write freshness values. // only set fields in dest that can be filled in from src // return 0 on success // return -ENOMEM on OOM // return -EINVAL on invalid inode type // NOTE: src must be read-locked static int UG_fs_export( struct md_entry* dest, char const* name, struct fskit_entry* src, uint64_t parent_id, struct SG_gateway* gateway ) { struct ms_client* ms = SG_gateway_ms( gateway ); struct md_syndicate_conf* conf = SG_gateway_conf( gateway ); struct UG_inode* inode = NULL; memset( dest, 0, sizeof( struct md_entry ) ); // get type int type = fskit_entry_get_type( src ); if( type == FSKIT_ENTRY_TYPE_FILE ) { dest->type = MD_ENTRY_FILE; dest->size = fskit_entry_get_size( src ); } else if( type == FSKIT_ENTRY_TYPE_DIR ) { dest->type = MD_ENTRY_DIR; dest->size = 4096; } else { // invalid return -EINVAL; } char* name_dup = strdup( name ); if( name_dup == NULL ) { return -ENOMEM; } inode = (struct UG_inode*)fskit_entry_get_user_data( src ); dest->type = type; dest->name = name_dup; dest->file_id = fskit_entry_get_file_id( src ); fskit_entry_get_ctime( src, &dest->ctime_sec, &dest->ctime_nsec ); fskit_entry_get_mtime( src, &dest->mtime_sec, &dest->mtime_nsec ); if( type == FSKIT_ENTRY_TYPE_FILE ) { if( inode != NULL && UG_inode_manifest( inode ) != NULL ) { // file already exists SG_manifest_get_modtime( UG_inode_manifest( inode ), &dest->manifest_mtime_sec, &dest->manifest_mtime_nsec ); } else { // new file dest->manifest_mtime_sec = dest->mtime_sec; dest->manifest_mtime_nsec = dest->mtime_nsec; } } dest->owner = SG_gateway_user_id( gateway ); dest->mode = fskit_entry_get_mode( src ); dest->parent_id = parent_id; dest->max_read_freshness = conf->default_read_freshness; dest->max_write_freshness = conf->default_write_freshness; dest->coordinator = SG_gateway_id( gateway ); dest->volume = ms_client_get_volume_id( ms ); return 0; } // create or make a directory // generate metadata for the inode, and send it off to the MS. // obtain the metadata from either caller_inode_data (in which case, mode will be ignored), or generate data consistent with an empty file (using mode). // * if the caller supplies caller_inode_data, then the following fields will be filled in automatically: // -- file_id // -- parent_id // -- version // -- write_nonce // -- xattr_nonce // -- xattr_hash // -- capacity // -- generation // -- num_children // -- ent_sig // -- ent_sig_len // return -errno on failure (i.e. it exists, we don't have permission, we get a network error, etc.) // NOTE: fent will be write-locked by fskit // NOTE: for files, this will disable truncate (so the subsequent trunc(2) that follows a creat(2) does not incur an extra round-trip) static int UG_fs_create_or_mkdir( struct fskit_core* fs, struct fskit_route_metadata* route_metadata, struct fskit_entry* fent, mode_t mode, struct md_entry* caller_inode_data, struct UG_inode** ret_inode_data ) { struct md_entry inode_data; struct md_entry* inode_data_ptr = NULL; int rc = 0; struct SG_gateway* gateway = (struct SG_gateway*)fskit_core_get_user_data( fs ); struct fskit_entry* parent = fskit_route_metadata_get_parent( route_metadata ); char* name = fskit_route_metadata_get_name( route_metadata ); uint64_t old_size = 0; bool is_mkdir = false; // do nothing if anonymous if( SG_gateway_user_id(gateway) == SG_USER_ANON ) { return -EPERM; } if( caller_inode_data == NULL ) { // generate inode data memset( &inode_data, 0, sizeof(struct md_entry) ); // generate the request rc = UG_fs_export( &inode_data, name, fent, fskit_entry_get_file_id( parent ), gateway ); if( rc != 0 ) { return rc; } // propagate the caller and Syndicate-specific fields... inode_data.mode = mode; inode_data_ptr = &inode_data; } else { inode_data_ptr = caller_inode_data; inode_data_ptr->parent_id = fskit_entry_get_file_id( parent ); // make sure fskit_entry matches timestamps and size UG_inode_fskit_common_init( fent, caller_inode_data ); } old_size = inode_data_ptr->size; if( inode_data_ptr->type == MD_ENTRY_DIR ) { // directories are *always* 4096 bytes inode_data_ptr->size = 4096; is_mkdir = true; } rc = UG_inode_publish( gateway, fent, inode_data_ptr, ret_inode_data ); inode_data_ptr->size = old_size; if( inode_data_ptr == &inode_data ) { md_entry_free( &inode_data ); } if( rc != 0 ) { SG_error("UG_inode_publish rc = %d\n", rc ); } else { // if this is a directory, preserve the size if( is_mkdir ) { SG_debug("mkdir rc = %d\n", rc); UG_inode_set_size( *ret_inode_data, 4096 ); fskit_entry_set_size( fent, 4096 ); } } return rc; } // fskit create callback: try to create the entry on the MS. // return 0 on success, and create the file on the MS // return negative on failure (i.e. it exists, we don't have permission, we get a network error, etc.) // NOTE: fent will be write-locked by fskit static int UG_fs_create( struct fskit_core* fs, struct fskit_route_metadata* route_metadata, struct fskit_entry* fent, mode_t mode, void** ret_inode_data, void** ret_handle_data ) { int rc = 0; // inode data struct UG_inode* inode = NULL; // caller-given inode data struct md_entry* caller_inode_data = (struct md_entry*)fskit_route_metadata_get_cls( route_metadata ); // handle data struct UG_file_handle* handle = NULL; rc = UG_fs_create_or_mkdir( fs, route_metadata, fent, mode, caller_inode_data, &inode ); if( rc != 0 ) { return rc; } // success! // create the handle handle = SG_CALLOC( struct UG_file_handle, 1 ); if( handle == NULL ) { UG_inode_free( inode ); SG_safe_free( inode ); return -ENOMEM; } rc = UG_file_handle_init( handle, inode, O_CREAT | O_WRONLY | O_TRUNC ); if( rc != 0 ) { SG_safe_free( handle ); UG_inode_free( inode ); SG_safe_free( inode ); return -ENOMEM; } // success! *ret_inode_data = inode; *ret_handle_data = handle; return 0; } // fskit mkdir callback // return 0 on success, and create the dir on the MS // return negative on failure (i.e. it exists, we don't have permission, we got a network error, etc.) // NOTE: fent will be write-locked by fskit static int UG_fs_mkdir( struct fskit_core* fs, struct fskit_route_metadata* route_metadata, struct fskit_entry* fent, mode_t mode, void** ret_inode_data ) { int rc = 0; // inode data struct UG_inode* inode = NULL; // caller-given inode data struct md_entry* caller_inode_data = (struct md_entry*)fskit_route_metadata_get_cls( route_metadata ); rc = UG_fs_create_or_mkdir( fs, route_metadata, fent, mode, caller_inode_data, &inode ); if( rc != 0 ) { return rc; } // success! *ret_inode_data = inode; return 0; } // fskit open/opendir callback // refresh path information for the fent // return 0 on success // return negative on failure (i.e. network error, OOM) // NOTE: fent must *not* be locked (the consistency discipline must not alter its lock state) static int UG_fs_open( struct fskit_core* fs, struct fskit_route_metadata* route_metadata, struct fskit_entry* fent, int flags, void** handle_data ) { int rc = 0; struct UG_file_handle* handle = NULL; struct SG_gateway* gateway = (struct SG_gateway*)fskit_core_get_user_data( fs ); struct UG_inode* inode = NULL; // refresh path rc = UG_consistency_path_ensure_fresh( gateway, fskit_route_metadata_get_path( route_metadata ) ); if( rc != 0 ) { SG_error( "UG_consistency_path_ensure_fresh('%s') rc = %d\n", fskit_route_metadata_get_path( route_metadata ), rc ); return rc; } // if this is a directory, go reload the children if( fskit_entry_get_type( fent ) == FSKIT_ENTRY_TYPE_DIR ) { // ensure the listing is fresh rc = UG_consistency_dir_ensure_fresh( gateway, fskit_route_metadata_get_path( route_metadata ) ); if( rc != 0 ) { SG_error("UG_consistency_dir_ensure_fresh('%s') rc = %d\n", fskit_route_metadata_get_path( route_metadata ), rc ); return rc; } // no handle structure is necessary } else { // generate a file handle handle = SG_CALLOC( struct UG_file_handle, 1 ); if( handle == NULL ) { // OOM return -ENOMEM; } // get inode fskit_entry_rlock( fent ); inode = (struct UG_inode*)fskit_entry_get_user_data( fent ); if( UG_inode_deleting( inode ) ) { rc = -ENOENT; } else { rc = UG_file_handle_init( handle, inode, flags ); } fskit_entry_unlock( fent ); if( rc != 0 ) { // OOM SG_safe_free( handle ); return rc; } *handle_data = handle; } return rc; } // fskit close callback (i.e. FUSE release)--free up the handle // if it's a file handle, then try to fsync it for good measure. ERRORS WILL BE MASKED // NOTE: it is incorrect for a program to rely on close or flush to synchronize data to the RGs. // correct programs should call fsync(). Calling fsync() here does *not* guarantee that data will // be persistent, since there is no way to re-try a close(). static int UG_fs_close( struct fskit_core* fs, struct fskit_route_metadata* route_metadata, struct fskit_entry* fent, void* handle_data ) { struct UG_file_handle* handle = (struct UG_file_handle*)handle_data; char const* path = fskit_route_metadata_get_path(route_metadata); // to be safe, try to fsync it. int rc = UG_sync_fsync_ex( fs, path, fent ); if( rc != 0 ) { SG_error("Failed to fsync '%s', rc = %d\n", path, rc); } // free up if( handle != NULL ) { UG_file_handle_free( handle ); SG_safe_free( handle ); } return rc; } // fskit stat callback. // go refresh the path, and pull in any immediate children if it's a directory. // NOTE: fent must *not* be locked (the consistency discipline must not alter its lock state) static int UG_fs_stat( struct fskit_core* fs, struct fskit_route_metadata* route_metadata, struct fskit_entry* fent, struct stat* sb ) { int rc = 0; struct SG_gateway* gateway = (struct SG_gateway*)fskit_core_get_user_data( fs ); struct UG_inode* inode = NULL; struct fskit_entry* new_fent = NULL; // refresh path rc = UG_consistency_path_ensure_fresh( gateway, fskit_route_metadata_get_path( route_metadata ) ); if( rc != 0 ) { SG_error( "UG_consistency_path_ensure_fresh('%s') rc = %d\n", fskit_route_metadata_get_path( route_metadata ), rc ); return rc; } if( fent != NULL ) { fskit_entry_rlock( fent ); // check deleting... inode = (struct UG_inode*)fskit_entry_get_user_data( fent ); if( UG_inode_deleting( inode ) ) { rc = -ENOENT; } fskit_entry_unlock( fent ); } else { // we just discovered this inode and grafted it into our tree. // stat it new_fent = fskit_entry_resolve_path( fs, fskit_route_metadata_get_path( route_metadata ), 0, 0, false, &rc ); if( rc != 0 ) { return rc; } rc = fskit_entry_fstat( new_fent, sb ); fskit_entry_unlock( new_fent ); } return rc; } // truncate locally--ask the MS to update the size and version, vacuum now-removed blocks, and replicate the new manifest. // return 0 on success // return -ENOMEM on OOM // return -EISDIR if the inode is a directory // return -errno on network error // NOTE: inode->entry must be write-locked // NOTE: this method will do nothing if it is on the creat(2) I/O path, since it doesn't make much sense for Syndicate to truncate immediately after creating. static int UG_fs_trunc_local( struct SG_gateway* gateway, char const* fs_path, struct UG_inode* inode, off_t new_size ) { int rc = 0; struct md_entry inode_data; struct UG_state* ug = (struct UG_state*)SG_gateway_cls( gateway ); struct ms_client* ms = SG_gateway_ms( gateway ); struct UG_vacuumer* vacuumer = UG_state_vacuumer( ug ); struct fskit_core* fs = UG_state_fs( ug ); struct md_entry inode_data_out; memset( &inode_data_out, 0, sizeof(struct md_entry) ); struct SG_manifest new_manifest; // manifest after truncate struct SG_manifest removed; struct UG_replica_context* rctx = NULL; struct UG_vacuum_context* vctx = NULL; struct timespec new_manifest_modtime; struct timespec old_manifest_modtime; uint64_t volume_blocksize = ms_client_get_volume_blocksize( ms ); uint64_t new_max_block = new_size / volume_blocksize; unsigned char xattr_hash[SHA256_DIGEST_LENGTH]; memset( xattr_hash, 0, SHA256_DIGEST_LENGTH ); if( new_size % volume_blocksize > 0 ) { new_max_block++; } // if deleting, deny further I/O if( UG_inode_deleting( inode ) ) { return -ENOENT; } // if creating, then this trunc(2) is part of a creat(2). // allow subsequent trunc(2), but claim that this one succeeded. if( UG_inode_creating( inode ) ) { SG_debug("Skip truncate on %" PRIX64 ", since it is being created\n", UG_inode_file_id( inode )); UG_inode_set_creating( inode, false ); return 0; } // can't truncate a directory if( fskit_entry_get_type( UG_inode_fskit_entry( inode ) ) == FSKIT_ENTRY_TYPE_DIR ) { return -EISDIR; } SG_debug("Truncate '%s' to %jd\n", fs_path, new_size ); // get inode data... rc = UG_inode_export( &inode_data, inode, 0 ); if( rc != 0 ) { return rc; } // get xattr hash... rc = UG_inode_export_xattr_hash( fs, SG_gateway_id( gateway ), inode, xattr_hash ); if( rc != 0 ) { md_entry_free( &inode_data ); return rc; } rc = SG_manifest_init( &removed, ms_client_get_volume_id( ms ), SG_gateway_id( gateway ), UG_inode_file_id( inode ), UG_inode_file_version( inode ) ); if( rc != 0 ) { md_entry_free( &inode_data ); return rc; } rc = SG_manifest_dup( &new_manifest, UG_inode_manifest( inode ) ); if( rc != 0 ) { // OOM md_entry_free( &inode_data ); SG_manifest_free( &removed ); return rc; } // find removed blocks rc = UG_inode_truncate_find_removed( gateway, inode, new_size, &removed ); if( rc != 0 ) { // OOM SG_manifest_free( &removed ); SG_manifest_free( &new_manifest ); md_entry_free( &inode_data ); return rc; } // prepare the vacuum request vctx = UG_vacuum_context_new(); if( vctx == NULL ) { // OOM SG_manifest_free( &removed ); SG_manifest_free( &new_manifest ); md_entry_free( &inode_data ); return -ENOMEM; } rc = UG_vacuum_context_init( vctx, ug, fs_path, inode, &removed ); SG_manifest_free( &removed ); if( rc != 0 ) { // OOM SG_manifest_free( &new_manifest ); md_entry_free( &inode_data ); SG_safe_free( vctx ); return rc; } // prepare the replication request rctx = UG_replica_context_new(); if( rctx == NULL ) { // OOM SG_manifest_free( &new_manifest ); md_entry_free( &inode_data ); UG_vacuum_context_free( vctx ); return -ENOMEM; } SG_debug("Remove all blocks beyond %" PRIu64 "\n", new_max_block ); SG_manifest_truncate( &new_manifest, new_max_block ); // advance manifest timestamp, size, nonce, version clock_gettime( CLOCK_REALTIME, &new_manifest_modtime ); SG_manifest_set_modtime( &new_manifest, new_manifest_modtime.tv_sec, new_manifest_modtime.tv_nsec ); SG_manifest_set_size( &new_manifest, new_size ); SG_manifest_set_file_version( &new_manifest, inode_data.version + 1 ); rc = UG_replica_context_init( rctx, ug, fs_path, inode, &new_manifest, NULL ); if( rc != 0 ) { // OOM SG_manifest_free( &new_manifest ); UG_vacuum_context_free( vctx ); md_entry_free( &inode_data ); SG_safe_free( rctx ); return rc; } SG_manifest_free( &new_manifest ); if( rc != 0 ) { UG_vacuum_context_free( vctx ); UG_replica_context_free( rctx ); SG_safe_free( rctx ); md_entry_free( &inode_data ); return rc; } // replicate truncated manifest to all RGs, but don't tell the MS. We'll do that ourselves UG_replica_context_hint( rctx, UG_REPLICA_HINT_NO_MS_UPDATE ); rc = UG_replicate( gateway, rctx ); if( rc != 0 ) { // replication error... SG_error("UG_replicate('%s') rc = %d\n", fs_path, rc ); UG_vacuum_context_free( vctx ); UG_replica_context_free( rctx ); SG_safe_free( rctx ); md_entry_free( &inode_data ); return rc; } // update on the MS inode_data.size = new_size; inode_data.version += 1; // next version inode_data.write_nonce += 1; inode_data.manifest_mtime_sec = new_manifest_modtime.tv_sec; // preserve modtime of manifest we replicated inode_data.manifest_mtime_nsec = new_manifest_modtime.tv_nsec; inode_data.xattr_hash = xattr_hash; // careful...this is on the stack SG_debug("'%s' (%" PRIX64 ") version %" PRId64 " --> %" PRId64 ", write_nonce %" PRId64 " --> %" PRId64 "\n", fs_path, inode_data.file_id, inode_data.version - 1, inode_data.version, inode_data.write_nonce - 1, inode_data.write_nonce); // update size and version remotely rc = ms_client_update( ms, &inode_data_out, &inode_data ); inode_data.xattr_hash = NULL; // do NOT free this, since it's on the stack if( rc != 0 ) { SG_error("ms_client_update('%s', %jd) rc = %d\n", fs_path, new_size, rc ); UG_vacuum_context_free( vctx ); UG_replica_context_free( rctx ); SG_safe_free( rctx ); md_entry_free( &inode_data ); return rc; } md_entry_free( &inode_data ); UG_inode_set_write_nonce( inode, inode_data_out.write_nonce ); md_entry_free( &inode_data_out ); // truncate locally, and apply MS-hosted changes UG_inode_preserve_old_manifest_modtime( inode ); UG_inode_truncate( gateway, inode, new_size, inode_data_out.version, inode_data_out.write_nonce, &new_manifest_modtime ); old_manifest_modtime = UG_inode_old_manifest_modtime( inode ); UG_vacuum_context_set_manifest_modtime( vctx, old_manifest_modtime.tv_sec, old_manifest_modtime.tv_nsec ); // garbate-collect while( 1 ) { rc = UG_vacuum_run( vacuumer, vctx ); if( rc != 0 ) { SG_error("UG_vacuum_run('%s') rc = %d, retrying...\n", fs_path, rc ); continue; } break; } UG_vacuum_context_free( vctx ); UG_replica_context_free( rctx ); SG_safe_free( rctx ); SG_safe_free( vctx ); return rc; } // ask another gateway to truncate a file for us. // return 0 on success // return -ENOMEM on OOM // return -EISDIR if the entry is a directory. // return -EREMOTEIO on failed network I/O // return the non-zero error code from the remote truncate if the remote truncate failed // NOTE: inode->entry should be write-locked static int UG_fs_trunc_remote( struct SG_gateway* gateway, char const* fs_path, struct UG_inode* inode, off_t new_size ) { int rc = 0; SG_messages::Request req; SG_messages::Reply reply; struct SG_request_data reqdat; int64_t manifest_mtime_sec = 0; int32_t manifest_mtime_nsec = 0; // if deleting, deny further I/O if( UG_inode_deleting( inode ) ) { return -ENOENT; } if( fskit_entry_get_type( UG_inode_fskit_entry( inode ) ) != FSKIT_ENTRY_TYPE_DIR ) { return -EISDIR; } SG_manifest_get_modtime( UG_inode_manifest( inode ), &manifest_mtime_sec, &manifest_mtime_nsec ); rc = SG_request_data_init_manifest( gateway, fs_path, UG_inode_file_id( inode ), UG_inode_file_version( inode ), manifest_mtime_sec, manifest_mtime_nsec, &reqdat ); if( rc != 0 ) { // OOM return rc; } rc = SG_client_request_TRUNCATE_setup( gateway, &req, &reqdat, UG_inode_coordinator_id( inode ), new_size ); if( rc != 0 ) { // OOM SG_error("SG_client_request_TRUNCATE_setup('%s') rc = %d\n", fs_path, rc ); SG_request_data_free( &reqdat ); return rc; } SG_request_data_free( &reqdat ); rc = SG_client_request_send( gateway, UG_inode_coordinator_id( inode ), &req, NULL, &reply ); if( rc != 0 ) { // network error SG_error("SG_client_request_send(TRUNC '%s' %jd) rc = %d\n", fs_path, new_size, rc ); // timed out? retry if( rc == -ETIMEDOUT ) { rc = -EAGAIN; } // propagate retries; everything else is remote I/O error if( rc != -EAGAIN ) { rc = -EREMOTEIO; } return rc; } if( reply.error_code() != 0 ) { // failed to process SG_error("SG_client_request_send(TRUNC '%s' %jd) reply error = %d\n", fs_path, new_size, rc ); return reply.error_code(); } // truncate locally, // TODO: have server fill in reply.ent_out, and plumb it through here UG_inode_truncate( gateway, inode, new_size, 0, 0, NULL ); // reload inode on next access UG_inode_set_read_stale( inode, true ); return rc; } // fskit route for truncating files. // In the UG, this simply tells the MS that the size has changed. // return 0 on success // return -EPERM if the gateway is anonymous // return -ENOMEM on OOM // return -errno on failure to connect to the MS // NOTE: fent will be write-locked by fskit static int UG_fs_trunc( struct fskit_core* fs, struct fskit_route_metadata* route_metadata, struct fskit_entry* fent, off_t new_size, void* inode_cls ) { int rc = 0; char* path = fskit_route_metadata_get_path( route_metadata ); struct UG_inode* inode = (struct UG_inode*)fskit_entry_get_user_data( fent ); struct SG_gateway* gateway = (struct SG_gateway*)fskit_core_get_user_data( fs ); // cannot proceed if anonymous if( SG_gateway_user_id(gateway) == SG_USER_ANON ) { return -EPERM; } UG_try_or_coordinate( gateway, path, UG_inode_coordinator_id( inode ), UG_fs_trunc_local( gateway, path, inode, new_size ), UG_fs_trunc_remote( gateway, path, inode, new_size ), &rc ); return rc; } // ask the MS to detach a file or directory. If we succeed, clear any cached state. // return 0 on success // return -ENOMEM on OOM // return -ENOENT if this inode is already being deleted // return -EAGAIN if we should try again // return -EREMOTEIO on remote error (e.g. on the MS or RGs) // return -errno on network error // NOTE: inode->entry must be write-locked static int UG_fs_detach_local( struct SG_gateway* gateway, char const* fs_path, bool renamed, struct UG_inode* inode ) { int rc = 0; struct ms_client* ms = SG_gateway_ms( gateway ); struct md_syndicate_cache* cache = SG_gateway_cache( gateway ); struct UG_state* ug = (struct UG_state*)SG_gateway_cls( gateway ); struct md_entry inode_data; struct UG_vacuum_context* vctx = NULL; bool vacuum_again = true; if( UG_inode_deleting( inode ) ) { return -ENOENT; } if( renamed ) { // nothing to do return 0; } // deny subsequent I/O operations UG_inode_set_deleting( inode, true ); // export... rc = UG_inode_export( &inode_data, inode, 0 ); if( rc != 0 ) { UG_inode_set_deleting( inode, false ); return rc; } // if this is a file, and we're the coordinator, vacuum it if( UG_inode_coordinator_id( inode ) == SG_gateway_id( gateway ) && fskit_entry_get_type( UG_inode_fskit_entry( inode ) ) == FSKIT_ENTRY_TYPE_FILE ) { while( vacuum_again ) { vctx = UG_vacuum_context_new(); if( vctx == NULL ) { rc = -ENOMEM; md_entry_free( &inode_data ); UG_inode_set_deleting( inode, false ); return rc; } rc = UG_vacuum_context_init( vctx, ug, fs_path, inode, NULL ); if( rc != 0 ) { SG_error("UG_vacuum_context_init('%s') rc = %d\n", fs_path, rc ); md_entry_free( &inode_data ); SG_safe_free( vctx ); UG_inode_set_deleting( inode, false ); return rc; } // allow deleting the current manifest UG_vacuum_context_set_unlinking( vctx, true ); while( 1 ) { // vacuum until we succeed rc = UG_vacuum_run( UG_state_vacuumer( ug ), vctx ); if( rc != 0 ) { SG_error("UG_vacuum_run('%s') rc = %d; retrying...\n", fs_path, rc ); continue; } break; } // try again until we've vacuumed everything vacuum_again = !UG_vacuum_context_is_clean( vctx ); UG_vacuum_context_free( vctx ); SG_safe_free( vctx ); } } // delete on the MS rc = ms_client_delete( ms, &inode_data ); md_entry_free( &inode_data ); if( rc != 0 ) { UG_inode_set_deleting( inode, false ); SG_error("ms_client_delete('%s') rc = %d\n", fs_path, rc ); return rc; } // blow away local cached state, if this is a file if( fskit_entry_get_file_id( UG_inode_fskit_entry( inode ) ) == FSKIT_ENTRY_TYPE_FILE ) { md_cache_evict_file( cache, UG_inode_file_id( inode ), UG_inode_file_version( inode ), 0 ); } return rc; } // ask a remote gateway to detach an inode for us, if the inode is a file. // if the inode is a directory, ask the MS directly. // return 0 on success // return -ENOMEM on OOM // return -EAGAIN if we timed out // return -EREMOTEIO on network error // return non-zero error code from the remote unlink if it failed remotely static int UG_fs_detach_remote( struct SG_gateway* gateway, char const* fs_path, bool renamed, struct UG_inode* inode ) { int rc = 0; struct md_syndicate_cache* cache = SG_gateway_cache( gateway ); SG_messages::Request req; SG_messages::Reply reply; struct SG_request_data reqdat; int64_t manifest_mtime_sec = 0; int32_t manifest_mtime_nsec = 0; if( renamed ) { // nothing to do return 0; } SG_manifest_get_modtime( UG_inode_manifest( inode ), &manifest_mtime_sec, &manifest_mtime_nsec ); rc = SG_request_data_init_manifest( gateway, fs_path, UG_inode_file_id( inode ), UG_inode_file_version( inode ), manifest_mtime_sec, manifest_mtime_nsec, &reqdat ); if( rc != 0 ) { // OOM return rc; } // NOTE: no vacuum ticket; the receiving gateway can verify the write-permission with the certificate rc = SG_client_request_DETACH_setup( gateway, &req, &reqdat, UG_inode_coordinator_id( inode ) ); if( rc != 0 ) { // OOM SG_error("SG_client_request_DETACH_setup('%s') rc = %d\n", fs_path, rc ); SG_request_data_free( &reqdat ); return rc; } SG_request_data_free( &reqdat ); rc = SG_client_request_send( gateway, UG_inode_coordinator_id( inode ), &req, NULL, &reply ); if( rc != 0 ) { // network error SG_error("SG_client_request_send(DETACH '%s') rc = %d\n", fs_path, rc ); // timed out? retry if( rc == -ETIMEDOUT ) { rc = -EAGAIN; } // propagate retries; everything else is remote I/O error if( rc != -EAGAIN ) { rc = -EREMOTEIO; } return rc; } if( reply.error_code() != 0 ) { // failed to process SG_error("SG_client_request_send(DETACH '%s') reply error = %d\n", fs_path, rc ); return reply.error_code(); } // blow away local cached state md_cache_evict_file( cache, UG_inode_file_id( inode ), UG_inode_file_version( inode ), 0 ); return rc; } // fskit route for detaching a file or directory. // In the UG, this simply tells the MS to delete the entry. // if we're the coordinator, and this is a file, then garbage-collect all of its blocks. // This method is used when the gateway is in operation, since because Syndicate does not // support hard links, this method will get called only when the user unlinks or rmdirs and inode. // We switch over to UG_fs_destroy when cleaning up on exit. // return 0 on success // return -EPERM if the gateway is anonymous // return -ENOMEM on OOM // return -EAGAIN if the caller should try detaching again // return -errno on failure to connect to the MS // NOTE: fent should not be locked at all (it will be unreferenceable) static int UG_fs_detach_and_destroy( struct fskit_core* fs, struct fskit_route_metadata* route_metadata, struct fskit_entry* fent, void* inode_cls ) { int rc = 0; struct UG_inode* inode = (struct UG_inode*)inode_cls; struct SG_gateway* gateway = (struct SG_gateway*)fskit_core_get_user_data( fs ); char* path = fskit_route_metadata_get_path( route_metadata ); bool renamed = fskit_route_metadata_renamed( route_metadata ); // cannot proceed if anonymous if( SG_gateway_user_id(gateway) == SG_USER_ANON ) { return -EPERM; } fskit_entry_rlock( fent ); int type = fskit_entry_get_type( fent ); uint64_t file_id = fskit_entry_get_file_id( fent ); fskit_entry_unlock( fent ); SG_debug("Detach/destroy %" PRIX64 "\n", file_id ); if( type == FSKIT_ENTRY_TYPE_FILE ) { // route request to coordinator UG_try_or_coordinate( gateway, path, UG_inode_coordinator_id( inode ), UG_fs_detach_local( gateway, fskit_route_metadata_get_path( route_metadata ), renamed, inode ), UG_fs_detach_remote( gateway, fskit_route_metadata_get_path( route_metadata ), renamed, inode ), &rc ); if( rc != 0 ) { SG_error("UG_try_or_coordinate( DETACH '%s' ) rc = %d\n", fskit_route_metadata_get_path( route_metadata ), rc ); } } else { // send directly to the MS rc = UG_fs_detach_local( gateway, fskit_route_metadata_get_path( route_metadata ), renamed, inode ); if( rc != 0 ) { SG_error("UG_fs_detach_local('%s') rc = %d\n", fskit_route_metadata_get_path( route_metadata ), rc ); } } if( rc == 0 ) { // success! UG_inode_free( inode ); SG_safe_free( inode ); } return rc; } // fskit route for destroying a file or directory inode data // This is used only for shutting down the gateway and freeing memory. // return 0 on success static int UG_fs_destroy( struct fskit_core* fs, struct fskit_route_metadata* route_metadata, struct fskit_entry* fent, void* inode_cls ) { struct UG_inode* inode = (struct UG_inode*)inode_cls; uint64_t file_id = 0; if( inode != NULL ) { file_id = UG_inode_file_id( inode ); SG_debug("Destroy %" PRIX64 "\n", file_id ); UG_inode_free( inode ); SG_safe_free( inode ); fskit_entry_set_user_data( fent, NULL ); } else { fskit_entry_rlock( fent ); SG_warn("%" PRIX64 ": inode already freed\n", fskit_entry_get_file_id( fent) ); fskit_entry_unlock( fent ); } return 0; } // get the xattr hashes and inode metadata for the old and new inodes on rename // return 0 on success // reutrn -ENOMEM on OOM static int UG_fs_rename_inode_export( struct fskit_core* fs, char const* old_path, struct fskit_entry* old_parent, struct UG_inode* old_inode, struct md_entry* old_fent_metadata, char const* new_path, struct fskit_entry* new_parent, struct UG_inode* new_inode, struct md_entry* new_fent_metadata ) { int rc = 0; struct SG_gateway* gateway = (struct SG_gateway*)fskit_core_get_user_data( fs ); uint64_t old_parent_id = fskit_entry_get_file_id( old_parent ); uint64_t new_parent_id = fskit_entry_get_file_id( new_parent ); unsigned char* old_xattr_hash = SG_CALLOC( unsigned char, SHA256_DIGEST_LENGTH ); unsigned char* new_xattr_hash = SG_CALLOC( unsigned char, SHA256_DIGEST_LENGTH ); if( SG_gateway_user_id(gateway) == SG_USER_ANON ) { return -EPERM; } if( old_xattr_hash == NULL || new_xattr_hash == NULL ) { SG_safe_free( new_xattr_hash ); SG_safe_free( old_xattr_hash ); return -ENOMEM; } rc = UG_inode_export( old_fent_metadata, old_inode, old_parent_id ); if( rc != 0 ) { SG_safe_free( new_xattr_hash ); SG_safe_free( old_xattr_hash ); SG_error("UG_inode_export(%s) rc = %d\n", old_path, rc ); return rc; } // set new name in old inode data SG_safe_free( old_fent_metadata->name ); old_fent_metadata->name = md_basename( new_path, NULL ); if( old_fent_metadata->name == NULL ) { md_entry_free( old_fent_metadata ); SG_safe_free( old_xattr_hash ); SG_safe_free( new_xattr_hash ); return -ENOMEM; } rc = UG_inode_export_xattr_hash( fs, SG_gateway_id( gateway ), old_inode, old_xattr_hash ); if( rc != 0 ) { SG_safe_free( new_xattr_hash ); SG_safe_free( old_xattr_hash ); md_entry_free( old_fent_metadata ); SG_error("UG_inode_export_xattr_hash(%s) rc = %d\n", old_path, rc ); return rc; } memcpy( new_xattr_hash, old_xattr_hash, SHA256_DIGEST_LENGTH ); if( new_inode != NULL ) { rc = UG_inode_export( new_fent_metadata, new_inode, new_parent_id ); if( rc != 0 ) { md_entry_free( old_fent_metadata ); SG_safe_free( old_xattr_hash ); SG_safe_free( new_xattr_hash ); SG_error("UG_inode_export(%s) rc = %d\n", new_path, rc ); return rc; } } else { // will rename into a new path entirely rc = md_entry_dup2( old_fent_metadata, new_fent_metadata ); if( rc != 0 ) { md_entry_free( old_fent_metadata ); SG_safe_free( old_xattr_hash ); SG_safe_free( new_xattr_hash ); SG_error("md_entry_dup2 rc = %d\n", rc ); return rc; } // switch parent new_fent_metadata->parent_id = new_parent_id; } old_fent_metadata->xattr_hash = old_xattr_hash; new_fent_metadata->xattr_hash = new_xattr_hash; // dest carries *old* name, but src carries the *new* name SG_safe_free( new_fent_metadata->name ); new_fent_metadata->name = md_basename( old_path, NULL ); if( new_fent_metadata->name == NULL ) { md_entry_free( old_fent_metadata ); md_entry_free( new_fent_metadata ); SG_safe_free( old_xattr_hash ); SG_safe_free( new_xattr_hash ); return -ENOMEM; } // preserve a few key details new_fent_metadata->manifest_mtime_sec = old_fent_metadata->manifest_mtime_sec; new_fent_metadata->manifest_mtime_nsec = old_fent_metadata->manifest_mtime_nsec; new_fent_metadata->xattr_nonce = old_fent_metadata->xattr_nonce; return 0; } // ask the MS to rename an inode for us. // old_parent and new_parent must be at least read-locked // we must be the coordinator of old_inode // return 0 on success // return -ENOMEM on OOM // return negative on network error // NOTE: old_inode->entry should be write-locked by fskit static int UG_fs_rename_local( struct fskit_core* fs, struct fskit_entry* old_parent, char const* old_path, struct UG_inode* old_inode, struct fskit_entry* new_parent, char const* new_path, struct UG_inode* new_inode ) { int rc = 0; struct SG_gateway* gateway = (struct SG_gateway*)fskit_core_get_user_data( fs ); struct ms_client* ms = SG_gateway_ms( gateway ); struct UG_state* ug = (struct UG_state*)SG_gateway_cls( gateway ); struct UG_replica_context* rctx = NULL; struct UG_vacuum_context* vctx_old = NULL; struct UG_vacuum_context* vctx_new = NULL; struct UG_vacuumer* vacuumer = UG_state_vacuumer( ug ); struct md_entry old_fent_metadata; struct md_entry new_fent_metadata; struct SG_manifest new_manifest; struct timespec old_manifest_modtime; struct timespec new_manifest_modtime; memset( &old_fent_metadata, 0, sizeof(struct md_entry) ); memset( &new_fent_metadata, 0, sizeof(struct md_entry) ); memset( &new_manifest, 0, sizeof(struct SG_manifest) ); memset( &old_manifest_modtime, 0, sizeof(struct timespec) ); memset( &new_manifest_modtime, 0, sizeof(struct timespec) ); // gather inode data rc = UG_fs_rename_inode_export( fs, old_path, old_parent, old_inode, &old_fent_metadata, new_path, new_parent, new_inode, &new_fent_metadata ); if( rc != 0 ) { // OOM return rc; } // make a new manifest for the old inode rc = SG_manifest_dup( &new_manifest, UG_inode_manifest( old_inode ) ); if( rc != 0 ) { // OOM md_entry_free( &old_fent_metadata ); md_entry_free( &new_fent_metadata ); return rc; } // prepare the vacuum requests vctx_old = UG_vacuum_context_new(); vctx_new = UG_vacuum_context_new(); if( vctx_old == NULL || vctx_new == NULL ) { // OOM SG_safe_free( vctx_old ); SG_safe_free( vctx_new ); md_entry_free( &old_fent_metadata ); md_entry_free( &new_fent_metadata ); SG_manifest_free( &new_manifest ); return -ENOMEM; } // will vacuum the old inode, removing its old manifest if( old_fent_metadata.type == MD_ENTRY_FILE ) { rc = UG_vacuum_context_init( vctx_old, ug, old_path, old_inode, NULL ); if( rc != 0 ) { // OOM md_entry_free( &old_fent_metadata ); md_entry_free( &new_fent_metadata ); SG_manifest_free( &new_manifest ); SG_safe_free( vctx_old ); SG_safe_free( vctx_new ); return rc; } } // will vacuum the new inode (if it exists), removing its old blocks and manifests if( new_inode != NULL ) { if( new_fent_metadata.type == MD_ENTRY_FILE ) { rc = UG_vacuum_context_init( vctx_new, ug, new_path, new_inode, NULL ); if( rc != 0 ) { // OOM md_entry_free( &old_fent_metadata ); md_entry_free( &new_fent_metadata ); SG_manifest_free( &new_manifest ); UG_vacuum_context_free( vctx_old ); SG_safe_free( vctx_old ); SG_safe_free( vctx_new ); return -ENOMEM; } } else { // directory must not be empty if( new_fent_metadata.num_children > 0 ) { SG_error("Directory %s not empty\n", new_path); md_entry_free( &old_fent_metadata ); md_entry_free( &new_fent_metadata ); SG_manifest_free( &new_manifest ); UG_vacuum_context_free( vctx_old ); SG_safe_free( vctx_old ); SG_safe_free( vctx_new ); return -ENOTEMPTY; } } } // prepare the replication request for the new manifest rctx = UG_replica_context_new(); if( rctx == NULL ) { // OOM md_entry_free( &old_fent_metadata ); md_entry_free( &new_fent_metadata ); SG_manifest_free( &new_manifest ); UG_vacuum_context_free( vctx_old ); SG_safe_free( vctx_old ); if( new_inode != NULL ) { UG_vacuum_context_free( vctx_new ); } SG_safe_free( vctx_new ); return -ENOMEM; } // advance manifest timestamp, nonce, version new_fent_metadata.version = old_fent_metadata.version + 1; clock_gettime( CLOCK_REALTIME, &new_manifest_modtime ); SG_manifest_set_modtime( &new_manifest, new_manifest_modtime.tv_sec, new_manifest_modtime.tv_nsec ); SG_manifest_set_file_version( &new_manifest, old_fent_metadata.version + 1 ); new_fent_metadata.manifest_mtime_sec = new_manifest_modtime.tv_sec; new_fent_metadata.manifest_mtime_nsec = new_manifest_modtime.tv_nsec; new_fent_metadata.version = old_fent_metadata.version + 1; // (this will become the new entry's manifest modtime) old_fent_metadata.manifest_mtime_sec = new_manifest_modtime.tv_sec; old_fent_metadata.manifest_mtime_nsec = new_manifest_modtime.tv_nsec; SG_debug("Duplicated manifest '%s': %zu blocks, ts=%ld.%ld (version %" PRId64 ")\n", old_path, SG_manifest_get_block_count( &new_manifest ), new_manifest_modtime.tv_sec, new_manifest_modtime.tv_nsec, SG_manifest_get_file_version(&new_manifest) ); // has to be the later version to prove that we have the latest old_fent_metadata.version += 1; // make the request to rename this inode rc = UG_replica_context_init_rename_hint( rctx, ug, old_path, new_path, old_inode, &new_manifest ); if( rc != 0 ) { // OOM md_entry_free( &old_fent_metadata ); md_entry_free( &new_fent_metadata ); SG_manifest_free( &new_manifest ); UG_vacuum_context_free( vctx_old ); SG_safe_free( vctx_old ); if( new_inode != NULL ) { UG_vacuum_context_free( vctx_new ); } SG_safe_free( vctx_new ); SG_safe_free( rctx ); return rc; } SG_manifest_free( &new_manifest ); // replicate rename hint (with manifest) to all RGs, but don't tell the MS. We'll do that ourselves UG_replica_context_hint( rctx, UG_REPLICA_HINT_NO_MS_UPDATE ); rc = UG_replicate( gateway, rctx ); if( rc != 0 ) { // replication error... SG_error("UG_replicate('%s') rc = %d\n", new_path, rc ); md_entry_free( &old_fent_metadata ); md_entry_free( &new_fent_metadata ); UG_vacuum_context_free( vctx_old ); SG_safe_free( vctx_old ); if( new_inode != NULL ) { UG_vacuum_context_free( vctx_new ); } SG_safe_free( vctx_new ); UG_replica_context_free( rctx ); SG_safe_free( rctx ); return rc; } // do the rename on the MS rc = ms_client_rename( ms, &old_fent_metadata, &new_fent_metadata ); md_entry_free( &old_fent_metadata ); md_entry_free( &new_fent_metadata ); UG_replica_context_free( rctx ); SG_safe_free( rctx ); if( rc != 0 ) { // failed to rename on the MS SG_error("ms_client_rename( '%s', '%s' ) rc = %d\n", old_path, new_path, rc ); UG_vacuum_context_free( vctx_old ); SG_safe_free( vctx_old ); if( new_inode != NULL ) { UG_vacuum_context_free( vctx_new ); } SG_safe_free( vctx_new ); return rc; } // remove the old manifest, if the old inode is a file if( old_fent_metadata.type == MD_ENTRY_FILE ) { old_manifest_modtime = UG_inode_old_manifest_modtime( old_inode ); UG_vacuum_context_set_manifest_modtime( vctx_old, old_manifest_modtime.tv_sec, old_manifest_modtime.tv_nsec ); } // garbate-collect SG_debug("Vacuum '%s'\n", old_path); while( old_fent_metadata.type == MD_ENTRY_FILE ) { rc = UG_vacuum_run( vacuumer, vctx_old ); if( rc != 0 ) { SG_error("UG_vacuum_run('%s') rc = %d, retrying...\n", old_path, rc ); continue; } break; } // vacuum the new inode (if it exists) if( new_inode != NULL ) { SG_debug("Vacuum '%s'\n", new_path); while( new_fent_metadata.type == MD_ENTRY_FILE ) { rc = UG_vacuum_run( vacuumer, vctx_new ); if( rc != 0 ) { SG_error("UG_vacuum_run('%s') rc = %d, retrying...\n", new_path, rc ); continue; } break; } UG_vacuum_context_free( vctx_new ); } SG_safe_free( vctx_new ); UG_vacuum_context_free( vctx_old ); SG_safe_free( vctx_old ); // force refresh on the destination on next access UG_inode_set_read_stale( old_inode, true ); return rc; } // ask another gateway to rename an inode, if the inode is a file. // if the inode is a directory, just ask the MS directly. // return 0 on success // return -ENOMEM on OOM // return -EREMOTEIO on failed network I/O // return -EAGAIN if the request timed out, or should be retried // return the non-zero error code if the rename failed on the remote gateway // NOTE: inode->entry should be write-locked by fskit static int UG_fs_rename_remote( struct fskit_core* fs, struct fskit_entry* old_parent, char const* fs_path, struct UG_inode* inode, struct fskit_entry* new_parent, char const* new_path, struct UG_inode* new_inode ) { int rc = 0; struct SG_gateway* gateway = (struct SG_gateway*)fskit_core_get_user_data( fs ); SG_messages::Request req; SG_messages::Reply reply; struct SG_request_data reqdat; int64_t manifest_mtime_sec = 0; int32_t manifest_mtime_nsec = 0; // if this is a directory, then this is a "local" rename--i.e. we have the ability to ask the MS directly, since the MS is the coordinator of all directories. if( fskit_entry_get_type( UG_inode_fskit_entry( inode ) ) == FSKIT_ENTRY_TYPE_DIR ) { return UG_fs_rename_local( fs, old_parent, fs_path, inode, new_parent, new_path, new_inode ); } SG_manifest_get_modtime( UG_inode_manifest( inode ), &manifest_mtime_sec, &manifest_mtime_nsec ); rc = SG_request_data_init_manifest( gateway, fs_path, UG_inode_file_id( inode ), UG_inode_file_version( inode ), manifest_mtime_sec, manifest_mtime_nsec, &reqdat ); if( rc != 0 ) { // OOM return rc; } rc = SG_client_request_RENAME_setup( gateway, &req, &reqdat, UG_inode_coordinator_id( inode ), new_path ); if( rc != 0 ) { // OOM SG_error("SG_client_request_RENAME_setup('%s') rc = %d\n", fs_path, rc ); SG_request_data_free( &reqdat ); return rc; } SG_request_data_free( &reqdat ); rc = SG_client_request_send( gateway, UG_inode_coordinator_id( inode ), &req, NULL, &reply ); if( rc != 0 ) { // network error SG_error("SG_client_request_send(RENAME '%s' to '%s') rc = %d\n", fs_path, new_path, rc ); // timed out? retry if( rc == -ETIMEDOUT ) { rc = -EAGAIN; } // propagate retries; everything else is remote I/O error if( rc != -EAGAIN ) { rc = -EREMOTEIO; } return rc; } if( reply.error_code() != 0 ) { // failed to process SG_error("SG_client_request_send(DETACH '%s' to '%s') reply error = %d\n", fs_path, new_path, rc ); return reply.error_code(); } return rc; } // fskit route for renaming a file or directory. // In the UG, this simply tells the MS to rename the entry if we're the coordinator, or tell the coordinator to do so if we're not. // return 0 on success // return -ENOMEM on OOM // return -errno if we had a network error // fent and dest will both be write-locked static int UG_fs_rename( struct fskit_core* fs, struct fskit_route_metadata* route_metadata, struct fskit_entry* fent, char const* new_path, struct fskit_entry* dest ) { int rc = 0; struct UG_inode* inode = (struct UG_inode*)fskit_entry_get_user_data( fent ); struct UG_inode* new_inode = NULL; struct SG_gateway* gateway = (struct SG_gateway*)fskit_core_get_user_data( fs ); char* path = fskit_route_metadata_get_path( route_metadata ); if( dest != NULL ) { new_inode = (struct UG_inode*)fskit_entry_get_user_data( dest ); } UG_try_or_coordinate( gateway, path, UG_inode_coordinator_id( inode ), UG_fs_rename_local( fs, fskit_route_metadata_get_parent( route_metadata ), path, inode, fskit_route_metadata_get_new_parent( route_metadata ), new_path, new_inode ), UG_fs_rename_remote( fs, fskit_route_metadata_get_parent( route_metadata ), path, inode, fskit_route_metadata_get_new_parent( route_metadata ), new_path, new_inode ), &rc ); return rc; } // fskit route for handling getxattr // return > 0 on success // return 0 if not built-in // return negative on error (see xattr.cpp) // fent must be read-locked static int UG_fs_fgetxattr( struct fskit_core* fs, struct fskit_route_metadata* route_metadata, struct fskit_entry* fent, char const* name, char* value, size_t value_len ) { int rc = 0; struct SG_gateway* gateway = (struct SG_gateway*)fskit_core_get_user_data( fs ); char const* path = fskit_route_metadata_get_path( route_metadata ); rc = UG_xattr_fgetxattr( gateway, path, fent, name, value, value_len ); return rc; } // fskit route for handling listxattr // merges "normal" fskit xattrs with builtins // return > 0 on success // return -ERANGE if not big enough // fent must be read-locked static int UG_fs_flistxattr( struct fskit_core* fs, struct fskit_route_metadata* route_metadata, struct fskit_entry* fent, char* buf, size_t buf_len ) { int rc = 0; struct SG_gateway* gateway = (struct SG_gateway*)fskit_core_get_user_data( fs ); char const* path = fskit_route_metadata_get_path( route_metadata ); rc = UG_xattr_flistxattr( gateway, path, fent, buf, buf_len ); return rc; } // fskit route for handling setxattr // handles built-in xattrs, and forwards the rest to local fskit // calls the MS to replicate xattrs. // return 0 on success // return -ERANGE if buffer is not big enough // fent must be write-locked static int UG_fs_fsetxattr( struct fskit_core* fs, struct fskit_route_metadata* route_metadata, struct fskit_entry* fent, char const* name, char const* value, size_t value_len, int flags ) { int rc = 0; struct SG_gateway* gateway = (struct SG_gateway*)fskit_core_get_user_data( fs ); char const* path = fskit_route_metadata_get_path( route_metadata ); rc = UG_xattr_fsetxattr( gateway, path, fent, name, value, value_len, flags ); return rc; } // fskit route for removexattr // return 0 if handled // return 1 if not handled // return negative on error static int UG_fs_fremovexattr( struct fskit_core* fs, struct fskit_route_metadata* route_metadata, struct fskit_entry* fent, char const* name ) { int rc = 0; struct SG_gateway* gateway = (struct SG_gateway*)fskit_core_get_user_data( fs ); char const* path = fskit_route_metadata_get_path( route_metadata ); rc = UG_xattr_fremovexattr( gateway, path, fent, name ); return rc; } // insert fskit entries into the fskit core // return 0 on success. // return -ENOMEM on OOM int UG_fs_install_methods( struct fskit_core* core, struct UG_state* state ) { int rh = 0; rh = fskit_route_stat( core, FSKIT_ROUTE_ANY, UG_fs_stat, FSKIT_CONCURRENT ); if( rh < 0 ) { SG_error("fskit_route_stat(%s) rc = %d\n", FSKIT_ROUTE_ANY, rh ); return rh; } UG_state_set_stat_rh( state, rh ); rh = fskit_route_mkdir( core, FSKIT_ROUTE_ANY, UG_fs_mkdir, FSKIT_INODE_SEQUENTIAL ); if( rh < 0 ) { SG_error("fskit_route_mkdir(%s) rc = %d\n", FSKIT_ROUTE_ANY, rh ); return rh; } UG_state_set_mkdir_rh( state, rh ); rh = fskit_route_create( core, FSKIT_ROUTE_ANY, UG_fs_create, FSKIT_INODE_SEQUENTIAL ); if( rh < 0 ) { SG_error("fskit_route_create(%s) rc = %d\n", FSKIT_ROUTE_ANY, rh ); return rh; } UG_state_set_creat_rh( state, rh ); rh = fskit_route_open( core, FSKIT_ROUTE_ANY, UG_fs_open, FSKIT_CONCURRENT ); if( rh < 0 ) { SG_error("fskit_route_open(%s) rc = %d\n", FSKIT_ROUTE_ANY, rh ); return rh; } UG_state_set_open_rh( state, rh ); rh = fskit_route_read( core, FSKIT_ROUTE_ANY, UG_read_impl, FSKIT_CONCURRENT ); if( rh < 0 ) { SG_error("fskit_route_read(%s) rc = %d\n", FSKIT_ROUTE_ANY, rh ); return rh; } UG_state_set_read_rh( state, rh ); rh = fskit_route_write( core, FSKIT_ROUTE_ANY, UG_write_impl, FSKIT_CONCURRENT ); if( rh < 0 ) { SG_error("fskit_route_write(%s) rc = %d\n", FSKIT_ROUTE_ANY, rh ); return rh; } UG_state_set_write_rh( state, rh ); rh = fskit_route_trunc( core, FSKIT_ROUTE_ANY, UG_fs_trunc, FSKIT_INODE_SEQUENTIAL ); if( rh < 0 ) { SG_error("fskit_route_trunc(%s) rc = %d\n", FSKIT_ROUTE_ANY, rh ); return rh; } UG_state_set_trunc_rh( state, rh ); rh = fskit_route_close( core, FSKIT_ROUTE_ANY, UG_fs_close, FSKIT_CONCURRENT ); if( rh < 0 ) { SG_error("fskit_route_close(%s) rc = %d\n", FSKIT_ROUTE_ANY, rh ); return rh; } UG_state_set_close_rh( state, rh ); rh = fskit_route_sync( core, FSKIT_ROUTE_ANY, UG_sync_fsync, FSKIT_CONCURRENT ); if( rh < 0 ) { SG_error("fskit_route_sync(%s) rc = %d\n", FSKIT_ROUTE_ANY, rh ); return rh; } UG_state_set_sync_rh( state, rh ); rh = fskit_route_destroy( core, FSKIT_ROUTE_ANY, UG_fs_detach_and_destroy, FSKIT_CONCURRENT ); if( rh < 0 ) { SG_error("fskit_route_destroy(%s) rc = %d\n", FSKIT_ROUTE_ANY, rh ); return rh; } UG_state_set_detach_rh( state, rh ); rh = fskit_route_rename( core, FSKIT_ROUTE_ANY, UG_fs_rename, FSKIT_CONCURRENT ); if( rh < 0 ) { SG_error("fskit_route_rename(%s) rc = %d\n", FSKIT_ROUTE_ANY, rh ); return rh; } UG_state_set_rename_rh( state, rh ); rh = fskit_route_getxattr( core, FSKIT_ROUTE_ANY, UG_fs_fgetxattr, FSKIT_CONCURRENT ); if( rh < 0 ) { SG_error("fskit_route_getxattr(%s) rc = %d\n", FSKIT_ROUTE_ANY, rh ); return rh; } UG_state_set_getxattr_rh( state, rh ); rh = fskit_route_setxattr( core, FSKIT_ROUTE_ANY, UG_fs_fsetxattr, FSKIT_INODE_SEQUENTIAL ); if( rh < 0 ) { SG_error("fskit_route_setxattr(%s) rc = %d\n", FSKIT_ROUTE_ANY, rh ); return rh; } UG_state_set_setxattr_rh( state, rh ); rh = fskit_route_listxattr( core, FSKIT_ROUTE_ANY, UG_fs_flistxattr, FSKIT_CONCURRENT ); if( rh < 0 ) { SG_error("fskit_route_listxattr(%s) rc = %d\n", FSKIT_ROUTE_ANY, rh ); return rh; } UG_state_set_listxattr_rh( state, rh ); rh = fskit_route_removexattr( core, FSKIT_ROUTE_ANY, UG_fs_fremovexattr, FSKIT_INODE_SEQUENTIAL ); if( rh < 0 ) { SG_error("fskit_route_removexattr(%s) rc = %d\n", FSKIT_ROUTE_ANY, rh ); return rh; } UG_state_set_removexattr_rh( state, rh ); return 0; } // remove all fskit methods, but install a detach method that simply frees the inode // return 0 on success // return -errno on failure int UG_fs_install_shutdown_methods( struct fskit_core* fs ) { // stop all fs calls int rc = fskit_unroute_all( fs ); if( rc != 0 ) { SG_error("fskit_unroute_all rc = %d\n", rc ); return rc; } // insert a memory-freeing call int rh = fskit_route_destroy( fs, FSKIT_ROUTE_ANY, UG_fs_destroy, FSKIT_CONCURRENT ); if( rh < 0 ) { SG_error("fskit_route_destroy(%s) rc = %d\n", FSKIT_ROUTE_ANY, rh ); return rh; } SG_debug("Destroy route inserted at %d\n", rh ); return 0; } // remove all fskit methods int UG_fs_uninstall_methods( struct fskit_core* fs ) { return fskit_unroute_all( fs ); }
/************************************************************************* * * $RCSfile: xmldrani.cxx,v $ * * $Revision: 1.22 $ * * last change: $Author: obo $ $Date: 2004-06-04 11:12:54 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifdef PCH #include "filt_pch.hxx" #endif #pragma hdrstop // INCLUDE --------------------------------------------------------------- #include "xmldrani.hxx" #include "xmlimprt.hxx" #include "xmlfilti.hxx" #include "xmlsorti.hxx" #include "document.hxx" #include "globstr.hrc" #include "docuno.hxx" #include "dbcolect.hxx" #include "datauno.hxx" #ifndef SC_SCATTR_HXX #include "attrib.hxx" #endif #ifndef SC_UNONAMES_HXX #include "unonames.hxx" #endif #ifndef SC_CONVUNO_HXX #include "convuno.hxx" #endif #ifndef _SC_XMLCONVERTER_HXX #include "XMLConverter.hxx" #endif #include <xmloff/xmltkmap.hxx> #include <xmloff/nmspmap.hxx> #ifndef _XMLOFF_XMLTOKEN_HXX #include <xmloff/xmltoken.hxx> #endif #ifndef _XMLOFF_XMLUCONV_HXX #include <xmloff/xmluconv.hxx> #endif #ifndef _XMLOFF_XMLERROR_HXX #include <xmloff/xmlerror.hxx> #endif #include <com/sun/star/sheet/XSpreadsheetDocument.hpp> #include <com/sun/star/sheet/XDatabaseRanges.hpp> #include <com/sun/star/sheet/XDatabaseRange.hpp> #include <com/sun/star/table/CellRangeAddress.hpp> #ifndef _COMPHELPER_EXTRACT_HXX_ #include <comphelper/extract.hxx> #endif #ifndef _COM_SUN_STAR_UNO_RUNTIMEEXCEPTION_HPP_ #include <com/sun/star/uno/RuntimeException.hpp> #endif #ifndef _COM_SUN_STAR_XML_SAX_XLOCATOR_HPP_ #include <com/sun/star/xml/sax/XLocator.hpp> #endif #define SC_ENABLEUSERSORTLIST "EnableUserSortList" #define SC_USERSORTLISTINDEX "UserSortListIndex" #define SC_USERLIST "UserList" using namespace com::sun::star; using namespace xmloff::token; //------------------------------------------------------------------ ScXMLDatabaseRangesContext::ScXMLDatabaseRangesContext( ScXMLImport& rImport, USHORT nPrfx, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList) : SvXMLImportContext( rImport, nPrfx, rLName ) { // has no attributes rImport.LockSolarMutex(); } ScXMLDatabaseRangesContext::~ScXMLDatabaseRangesContext() { GetScImport().UnlockSolarMutex(); } SvXMLImportContext *ScXMLDatabaseRangesContext::CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList ) { SvXMLImportContext *pContext = 0; const SvXMLTokenMap& rTokenMap = GetScImport().GetDatabaseRangesElemTokenMap(); switch( rTokenMap.Get( nPrefix, rLName ) ) { case XML_TOK_DATABASE_RANGE : { pContext = new ScXMLDatabaseRangeContext( GetScImport(), nPrefix, rLName, xAttrList); } break; } if( !pContext ) pContext = new SvXMLImportContext( GetImport(), nPrefix, rLName ); return pContext; } void ScXMLDatabaseRangesContext::EndElement() { } ScXMLDatabaseRangeContext::ScXMLDatabaseRangeContext( ScXMLImport& rImport, USHORT nPrfx, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList) : SvXMLImportContext( rImport, nPrfx, rLName ), nRefresh(0), nSubTotalsUserListIndex(0), nSubTotalRuleGroupFieldNumber(0), bContainsSort(sal_False), bContainsSubTotal(sal_False), bIsSelection(sal_False), bKeepFormats(sal_False), bMoveCells(sal_False), bStripData(sal_False), eOrientation(table::TableOrientation_ROWS), bContainsHeader(sal_True), bAutoFilter(sal_False), bFilterCopyOutputData(sal_False), bFilterIsCaseSensitive(sal_False), bFilterSkipDuplicates(sal_False), bFilterUseRegularExpressions(sal_False), bFilterConditionSourceRange(sal_False), bSubTotalsBindFormatsToContent(sal_False), bSubTotalsIsCaseSensitive(sal_False), bSubTotalsInsertPageBreaks(sal_False), bSubTotalsSortGroups(sal_False), bSubTotalsEnabledUserList(sal_False), bSubTotalsAscending(sal_True), bNative(sal_True), aSubTotalColumns(), aSortSequence() { nSourceType = sheet::DataImportMode_NONE; String sUnbenannt = ScGlobal::GetRscString(STR_DB_NONAME); rtl::OUString sOUUnbenannt (sUnbenannt); sDatabaseRangeName = sOUUnbenannt; sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0; const SvXMLTokenMap& rAttrTokenMap = GetScImport().GetDatabaseRangeAttrTokenMap(); for( sal_Int16 i=0; i < nAttrCount; i++ ) { rtl::OUString sAttrName = xAttrList->getNameByIndex( i ); rtl::OUString aLocalName; USHORT nPrefix = GetScImport().GetNamespaceMap().GetKeyByAttrName( sAttrName, &aLocalName ); rtl::OUString sValue = xAttrList->getValueByIndex( i ); switch( rAttrTokenMap.Get( nPrefix, aLocalName ) ) { case XML_TOK_DATABASE_RANGE_ATTR_NAME : { sDatabaseRangeName = sValue; } break; case XML_TOK_DATABASE_RANGE_ATTR_IS_SELECTION : { bIsSelection = IsXMLToken(sValue, XML_TRUE); } break; case XML_TOK_DATABASE_RANGE_ATTR_ON_UPDATE_KEEP_STYLES : { bKeepFormats = IsXMLToken(sValue, XML_TRUE); } break; case XML_TOK_DATABASE_RANGE_ATTR_ON_UPDATE_KEEP_SIZE : { bMoveCells = !IsXMLToken(sValue, XML_TRUE); } break; case XML_TOK_DATABASE_RANGE_ATTR_HAS_PERSISTENT_DATA : { bStripData = !IsXMLToken(sValue, XML_TRUE); } break; case XML_TOK_DATABASE_RANGE_ATTR_ORIENTATION : { if (IsXMLToken(sValue, XML_COLUMN)) eOrientation = table::TableOrientation_COLUMNS; } break; case XML_TOK_DATABASE_RANGE_ATTR_CONTAINS_HEADER : { bContainsHeader = IsXMLToken(sValue, XML_TRUE); } break; case XML_TOK_DATABASE_RANGE_ATTR_DISPLAY_FILTER_BUTTONS : { bAutoFilter = IsXMLToken(sValue, XML_TRUE); } break; case XML_TOK_DATABASE_RANGE_ATTR_TARGET_RANGE_ADDRESS : { sRangeAddress = sValue; } break; case XML_TOK_DATABASE_RANGE_ATTR_REFRESH_DELAY : { double fTime; if( SvXMLUnitConverter::convertTime( fTime, sValue ) ) nRefresh = Max( (sal_Int32)(fTime * 86400.0), (sal_Int32)0 ); } break; } } } ScXMLDatabaseRangeContext::~ScXMLDatabaseRangeContext() { } SvXMLImportContext *ScXMLDatabaseRangeContext::CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList ) { SvXMLImportContext *pContext = 0; const SvXMLTokenMap& rTokenMap = GetScImport().GetDatabaseRangeElemTokenMap(); switch( rTokenMap.Get( nPrefix, rLName ) ) { case XML_TOK_DATABASE_RANGE_SOURCE_SQL : { pContext = new ScXMLSourceSQLContext( GetScImport(), nPrefix, rLName, xAttrList, this); } break; case XML_TOK_DATABASE_RANGE_SOURCE_TABLE : { pContext = new ScXMLSourceTableContext( GetScImport(), nPrefix, rLName, xAttrList, this); } break; case XML_TOK_DATABASE_RANGE_SOURCE_QUERY : { pContext = new ScXMLSourceQueryContext( GetScImport(), nPrefix, rLName, xAttrList, this); } break; case XML_TOK_FILTER : { pContext = new ScXMLFilterContext( GetScImport(), nPrefix, rLName, xAttrList, this); } break; case XML_TOK_SORT : { bContainsSort = sal_True; pContext = new ScXMLSortContext( GetScImport(), nPrefix, rLName, xAttrList, this); } break; case XML_TOK_DATABASE_RANGE_SUBTOTAL_RULES : { bContainsSubTotal = sal_True; pContext = new ScXMLSubTotalRulesContext( GetScImport(), nPrefix, rLName, xAttrList, this); } break; } if( !pContext ) pContext = new SvXMLImportContext( GetImport(), nPrefix, rLName ); return pContext; } void ScXMLDatabaseRangeContext::EndElement() { if (GetScImport().GetModel().is()) { uno::Reference <beans::XPropertySet> xPropertySet( GetScImport().GetModel(), uno::UNO_QUERY ); ScDocument* pDoc = GetScImport().GetDocument(); if (pDoc && xPropertySet.is()) { uno::Any aDatabaseRanges = xPropertySet->getPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNO_DATABASERNG))); uno::Reference <sheet::XDatabaseRanges> xDatabaseRanges; if (aDatabaseRanges >>= xDatabaseRanges) { table::CellRangeAddress aCellRangeAddress; sal_Int32 nOffset(0); if (ScXMLConverter::GetRangeFromString( aCellRangeAddress, sRangeAddress, pDoc, nOffset )) { sal_Bool bInsert(sal_True); try { xDatabaseRanges->addNewByName(sDatabaseRangeName, aCellRangeAddress); } catch ( uno::RuntimeException& rRuntimeException ) { bInsert = sal_False; rtl::OUString sErrorMessage(RTL_CONSTASCII_USTRINGPARAM("DatabaseRange ")); sErrorMessage += sDatabaseRangeName; sErrorMessage += rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(" could not be created with the range ")); sErrorMessage += sRangeAddress; uno::Sequence<rtl::OUString> aSeq(1); aSeq[0] = sErrorMessage; uno::Reference<xml::sax::XLocator> xLocator; GetScImport().SetError(XMLERROR_API | XMLERROR_FLAG_ERROR, aSeq, rRuntimeException.Message, xLocator); } if (bInsert) { uno::Any aDatabaseRange = xDatabaseRanges->getByName(sDatabaseRangeName); uno::Reference <sheet::XDatabaseRange> xDatabaseRange; if (aDatabaseRange >>= xDatabaseRange) { uno::Reference <beans::XPropertySet> xDatabaseRangePropertySet (xDatabaseRange, uno::UNO_QUERY); if (xDatabaseRangePropertySet.is()) { uno::Any aTempValue; aTempValue = ::cppu::bool2any(bKeepFormats); xDatabaseRangePropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_KEEPFORM)), aTempValue); aTempValue = ::cppu::bool2any(bMoveCells); xDatabaseRangePropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_MOVCELLS)), aTempValue); aTempValue = ::cppu::bool2any(bStripData); xDatabaseRangePropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_STRIPDAT)), aTempValue); } uno::Sequence <beans::PropertyValue> aImportDescriptor = xDatabaseRange->getImportDescriptor(); sal_Int32 nImportProperties = aImportDescriptor.getLength(); for (sal_Int16 i = 0; i < nImportProperties; i++) { if (aImportDescriptor[i].Name == rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_DBNAME))) { uno::Any aDatabaseName; aDatabaseName <<= sDatabaseName; aImportDescriptor[i].Value = aDatabaseName; } else if (aImportDescriptor[i].Name == rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_SRCOBJ))) { uno::Any aSourceObject; aSourceObject <<= sSourceObject; aImportDescriptor[i].Value = aSourceObject; } else if (aImportDescriptor[i].Name == rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_SRCTYPE))) { uno::Any aSourceType; aSourceType <<= nSourceType; aImportDescriptor[i].Value = aSourceType; } else if (aImportDescriptor[i].Name == rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_ISNATIVE))) { uno::Any aNative; aNative = ::cppu::bool2any(bNative); aImportDescriptor[i].Value = aNative; } } ScDBCollection* pDBCollection = pDoc->GetDBCollection(); sal_uInt16 nIndex; pDBCollection->SearchName(sDatabaseRangeName, nIndex); ScDBData* pDBData = (*pDBCollection)[nIndex]; pDBData->SetImportSelection(bIsSelection); pDBData->SetAutoFilter(bAutoFilter); if (bAutoFilter) pDoc->ApplyFlagsTab( static_cast<SCCOL>(aCellRangeAddress.StartColumn), static_cast<SCROW>(aCellRangeAddress.StartRow), static_cast<SCCOL>(aCellRangeAddress.EndColumn), static_cast<SCROW>(aCellRangeAddress.StartRow), aCellRangeAddress.Sheet, SC_MF_AUTO ); ScImportParam aImportParam; ScImportDescriptor::FillImportParam(aImportParam, aImportDescriptor); pDBData->SetImportParam(aImportParam); if (bContainsSort) { sal_uInt32 nOldSize(aSortSequence.getLength()); aSortSequence.realloc(nOldSize + 1); beans::PropertyValue aProperty; aProperty.Name = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_ORIENT)); aProperty.Value <<= eOrientation; aSortSequence[nOldSize] = aProperty; ScSortParam aSortParam; ScSortDescriptor::FillSortParam(aSortParam, aSortSequence); //#98317#; until now the Fields are relative to the left top edge of the range, but the // core wants to have the absolute position (column/row) SCCOLROW nFieldStart = aSortParam.bByRow ? static_cast<SCCOLROW>(aCellRangeAddress.StartColumn) : static_cast<SCCOLROW>(aCellRangeAddress.StartRow); for (sal_uInt16 i = 0; i < MAXSORT; ++i) { if (aSortParam.bDoSort[i]) aSortParam.nField[i] += nFieldStart; } pDBData->SetSortParam(aSortParam); } uno::Reference <sheet::XSheetFilterDescriptor> xSheetFilterDescriptor = xDatabaseRange->getFilterDescriptor(); if (xSheetFilterDescriptor.is()) { uno::Reference <beans::XPropertySet> xFilterPropertySet (xSheetFilterDescriptor, uno::UNO_QUERY); if (xFilterPropertySet.is()) { uno::Any aTemp; sal_Bool bOrientation(table::TableOrientation_COLUMNS == eOrientation); aTemp = ::cppu::bool2any(bOrientation); xFilterPropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_ORIENT)), aTemp); aTemp = ::cppu::bool2any(bContainsHeader); xFilterPropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_CONTHDR)), aTemp); aTemp = ::cppu::bool2any(bFilterCopyOutputData); xFilterPropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_COPYOUT)), aTemp); aTemp = ::cppu::bool2any(bFilterIsCaseSensitive); xFilterPropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_ISCASE)), aTemp); aTemp = ::cppu::bool2any(bFilterSkipDuplicates); xFilterPropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_SKIPDUP)), aTemp); aTemp = ::cppu::bool2any(bFilterUseRegularExpressions); xFilterPropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_USEREGEX)), aTemp); aTemp <<= aFilterOutputPosition; xFilterPropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_OUTPOS)), aTemp); } xSheetFilterDescriptor->setFilterFields(aFilterFields); if (bFilterConditionSourceRange) { ScRange aAdvSource; ScUnoConversion::FillScRange( aAdvSource, aFilterConditionSourceRangeAddress ); pDBData->SetAdvancedQuerySource(&aAdvSource); } } if (bContainsSubTotal) { uno::Reference <sheet::XSubTotalDescriptor> xSubTotalDescriptor = xDatabaseRange->getSubTotalDescriptor(); if (xSubTotalDescriptor.is()) { uno::Reference <beans::XPropertySet> xSubTotalPropertySet (xSubTotalDescriptor, uno::UNO_QUERY); if( xSubTotalPropertySet.is()) { uno::Any aTemp; aTemp = ::cppu::bool2any(bSubTotalsBindFormatsToContent); xSubTotalPropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_BINDFMT)), aTemp); aTemp = ::cppu::bool2any(bSubTotalsEnabledUserList); xSubTotalPropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_ENABLEUSERSORTLIST)), aTemp); aTemp <<= nSubTotalsUserListIndex; xSubTotalPropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_USERSORTLISTINDEX)), aTemp); aTemp = ::cppu::bool2any(bSubTotalsInsertPageBreaks); xSubTotalPropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_INSBRK)), aTemp); aTemp = ::cppu::bool2any(bSubTotalsIsCaseSensitive); xSubTotalPropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_ISCASE)), aTemp); } ScSubTotalParam aSubTotalParam; aSubTotalParam.bDoSort = bSubTotalsSortGroups; aSubTotalParam.bAscending = bSubTotalsAscending; aSubTotalParam.bUserDef = bSubTotalsEnabledUserList; aSubTotalParam.nUserIndex = nSubTotalsUserListIndex; pDBData->SetSubTotalParam(aSubTotalParam); xSubTotalDescriptor->addNew(aSubTotalColumns, nSubTotalRuleGroupFieldNumber); } } if ( pDBData->HasImportParam() && !pDBData->HasImportSelection() ) { pDBData->SetRefreshDelay( nRefresh ); pDBData->SetRefreshHandler( pDBCollection->GetRefreshHandler() ); pDBData->SetRefreshControl( pDoc->GetRefreshTimerControlAddress() ); } } } } } } } } ScXMLSourceSQLContext::ScXMLSourceSQLContext( ScXMLImport& rImport, USHORT nPrfx, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList, ScXMLDatabaseRangeContext* pTempDatabaseRangeContext) : SvXMLImportContext( rImport, nPrfx, rLName ) { pDatabaseRangeContext = pTempDatabaseRangeContext; sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0; const SvXMLTokenMap& rAttrTokenMap = GetScImport().GetDatabaseRangeSourceSQLAttrTokenMap(); for( sal_Int16 i=0; i < nAttrCount; i++ ) { rtl::OUString sAttrName = xAttrList->getNameByIndex( i ); rtl::OUString aLocalName; USHORT nPrefix = GetScImport().GetNamespaceMap().GetKeyByAttrName( sAttrName, &aLocalName ); rtl::OUString sValue = xAttrList->getValueByIndex( i ); switch( rAttrTokenMap.Get( nPrefix, aLocalName ) ) { case XML_TOK_SOURCE_SQL_ATTR_DATABASE_NAME : { pDatabaseRangeContext->SetDatabaseName(sValue); } break; case XML_TOK_SOURCE_SQL_ATTR_SQL_STATEMENT : { pDatabaseRangeContext->SetSourceObject(sValue); } break; case XML_TOK_SOURCE_SQL_ATTR_PARSE_SQL_STATEMENT : { pDatabaseRangeContext->SetNative(IsXMLToken(sValue, XML_TRUE)); } break; } } pDatabaseRangeContext->SetSourceType(sheet::DataImportMode_SQL); } ScXMLSourceSQLContext::~ScXMLSourceSQLContext() { } SvXMLImportContext *ScXMLSourceSQLContext::CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList ) { SvXMLImportContext *pContext = 0; if( !pContext ) pContext = new SvXMLImportContext( GetImport(), nPrefix, rLName ); return pContext; } void ScXMLSourceSQLContext::EndElement() { } ScXMLSourceTableContext::ScXMLSourceTableContext( ScXMLImport& rImport, USHORT nPrfx, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList, ScXMLDatabaseRangeContext* pTempDatabaseRangeContext) : SvXMLImportContext( rImport, nPrfx, rLName ) { pDatabaseRangeContext = pTempDatabaseRangeContext; sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0; const SvXMLTokenMap& rAttrTokenMap = GetScImport().GetDatabaseRangeSourceTableAttrTokenMap(); for( sal_Int16 i=0; i < nAttrCount; i++ ) { rtl::OUString sAttrName = xAttrList->getNameByIndex( i ); rtl::OUString aLocalName; USHORT nPrefix = GetScImport().GetNamespaceMap().GetKeyByAttrName( sAttrName, &aLocalName ); rtl::OUString sValue = xAttrList->getValueByIndex( i ); switch( rAttrTokenMap.Get( nPrefix, aLocalName ) ) { case XML_TOK_SOURCE_TABLE_ATTR_DATABASE_NAME : { pDatabaseRangeContext->SetDatabaseName(sValue); } break; case XML_TOK_SOURCE_TABLE_ATTR_TABLE_NAME : { pDatabaseRangeContext->SetSourceObject(sValue); } break; } } pDatabaseRangeContext->SetSourceType(sheet::DataImportMode_TABLE); } ScXMLSourceTableContext::~ScXMLSourceTableContext() { } SvXMLImportContext *ScXMLSourceTableContext::CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList ) { SvXMLImportContext *pContext = 0; if( !pContext ) pContext = new SvXMLImportContext( GetImport(), nPrefix, rLName ); return pContext; } void ScXMLSourceTableContext::EndElement() { } ScXMLSourceQueryContext::ScXMLSourceQueryContext( ScXMLImport& rImport, USHORT nPrfx, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList, ScXMLDatabaseRangeContext* pTempDatabaseRangeContext) : SvXMLImportContext( rImport, nPrfx, rLName ) { pDatabaseRangeContext = pTempDatabaseRangeContext; sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0; const SvXMLTokenMap& rAttrTokenMap = GetScImport().GetDatabaseRangeSourceQueryAttrTokenMap(); for( sal_Int16 i=0; i < nAttrCount; i++ ) { rtl::OUString sAttrName = xAttrList->getNameByIndex( i ); rtl::OUString aLocalName; USHORT nPrefix = GetScImport().GetNamespaceMap().GetKeyByAttrName( sAttrName, &aLocalName ); rtl::OUString sValue = xAttrList->getValueByIndex( i ); switch( rAttrTokenMap.Get( nPrefix, aLocalName ) ) { case XML_TOK_SOURCE_QUERY_ATTR_DATABASE_NAME : { pDatabaseRangeContext->SetDatabaseName(sValue); } break; case XML_TOK_SOURCE_QUERY_ATTR_QUERY_NAME : { pDatabaseRangeContext->SetSourceObject(sValue); } break; } } pDatabaseRangeContext->SetSourceType(sheet::DataImportMode_QUERY); } ScXMLSourceQueryContext::~ScXMLSourceQueryContext() { } SvXMLImportContext *ScXMLSourceQueryContext::CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList ) { SvXMLImportContext *pContext = 0; if( !pContext ) pContext = new SvXMLImportContext( GetImport(), nPrefix, rLName ); return pContext; } void ScXMLSourceQueryContext::EndElement() { } ScXMLSubTotalRulesContext::ScXMLSubTotalRulesContext( ScXMLImport& rImport, USHORT nPrfx, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList, ScXMLDatabaseRangeContext* pTempDatabaseRangeContext) : SvXMLImportContext( rImport, nPrfx, rLName ) { pDatabaseRangeContext = pTempDatabaseRangeContext; sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0; const SvXMLTokenMap& rAttrTokenMap = GetScImport().GetDatabaseRangeSubTotalRulesAttrTokenMap(); for( sal_Int16 i=0; i < nAttrCount; i++ ) { rtl::OUString sAttrName = xAttrList->getNameByIndex( i ); rtl::OUString aLocalName; USHORT nPrefix = GetScImport().GetNamespaceMap().GetKeyByAttrName( sAttrName, &aLocalName ); rtl::OUString sValue = xAttrList->getValueByIndex( i ); switch( rAttrTokenMap.Get( nPrefix, aLocalName ) ) { case XML_TOK_SUBTOTAL_RULES_ATTR_BIND_STYLES_TO_CONTENT : { pDatabaseRangeContext->SetSubTotalsBindFormatsToContent(IsXMLToken(sValue, XML_TRUE)); } break; case XML_TOK_SUBTOTAL_RULES_ATTR_CASE_SENSITIVE : { pDatabaseRangeContext->SetSubTotalsIsCaseSensitive(IsXMLToken(sValue, XML_TRUE)); } break; case XML_TOK_SUBTOTAL_RULES_ATTR_PAGE_BREAKS_ON_GROUP_CHANGE : { pDatabaseRangeContext->SetSubTotalsInsertPageBreaks(IsXMLToken(sValue, XML_TRUE)); } break; } } } ScXMLSubTotalRulesContext::~ScXMLSubTotalRulesContext() { } SvXMLImportContext *ScXMLSubTotalRulesContext::CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList ) { SvXMLImportContext *pContext = 0; const SvXMLTokenMap& rTokenMap = GetScImport().GetDatabaseRangeSubTotalRulesElemTokenMap(); switch( rTokenMap.Get( nPrefix, rLName ) ) { case XML_TOK_SUBTOTAL_RULES_SORT_GROUPS : { pContext = new ScXMLSortGroupsContext( GetScImport(), nPrefix, rLName, xAttrList, pDatabaseRangeContext); } break; case XML_TOK_SUBTOTAL_RULES_SUBTOTAL_RULE : { pContext = new ScXMLSubTotalRuleContext( GetScImport(), nPrefix, rLName, xAttrList, pDatabaseRangeContext); } break; } if( !pContext ) pContext = new SvXMLImportContext( GetImport(), nPrefix, rLName ); return pContext; } void ScXMLSubTotalRulesContext::EndElement() { } ScXMLSortGroupsContext::ScXMLSortGroupsContext( ScXMLImport& rImport, USHORT nPrfx, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList, ScXMLDatabaseRangeContext* pTempDatabaseRangeContext) : SvXMLImportContext( rImport, nPrfx, rLName ) { pDatabaseRangeContext = pTempDatabaseRangeContext; pDatabaseRangeContext->SetSubTotalsSortGroups(sal_True); sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0; const SvXMLTokenMap& rAttrTokenMap = GetScImport().GetSubTotalRulesSortGroupsAttrTokenMap(); for( sal_Int16 i=0; i < nAttrCount; i++ ) { rtl::OUString sAttrName = xAttrList->getNameByIndex( i ); rtl::OUString aLocalName; USHORT nPrefix = GetScImport().GetNamespaceMap().GetKeyByAttrName( sAttrName, &aLocalName ); rtl::OUString sValue = xAttrList->getValueByIndex( i ); switch( rAttrTokenMap.Get( nPrefix, aLocalName ) ) { case XML_TOK_SORT_GROUPS_ATTR_DATA_TYPE : { if (sValue.getLength() > 8) { rtl::OUString sTemp = sValue.copy(0, 8); if (sTemp.compareToAscii(SC_USERLIST) == 0) { pDatabaseRangeContext->SetSubTotalsEnabledUserList(sal_True); sTemp = sValue.copy(8); pDatabaseRangeContext->SetSubTotalsUserListIndex(static_cast<sal_Int16>(sTemp.toInt32())); } else { //if (IsXMLToken(sValue, XML_AUTOMATIC)) //aSortField.FieldType = util::SortFieldType_AUTOMATIC; // is not supported by StarOffice } } else { //if (IsXMLToken(sValue, XML_TEXT)) //aSortField.FieldType = util::SortFieldType_ALPHANUMERIC; // is not supported by StarOffice //else if (IsXMLToken(sValue, XML_NUMBER)) //aSortField.FieldType = util::SortFieldType_NUMERIC; // is not supported by StarOffice } } break; case XML_TOK_SORT_GROUPS_ATTR_ORDER : { if (IsXMLToken(sValue, XML_ASCENDING)) pDatabaseRangeContext->SetSubTotalsAscending(sal_True); else pDatabaseRangeContext->SetSubTotalsAscending(sal_False); } break; } } } ScXMLSortGroupsContext::~ScXMLSortGroupsContext() { } SvXMLImportContext *ScXMLSortGroupsContext::CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList ) { SvXMLImportContext *pContext = 0; if( !pContext ) pContext = new SvXMLImportContext( GetImport(), nPrefix, rLName ); return pContext; } void ScXMLSortGroupsContext::EndElement() { } ScXMLSubTotalRuleContext::ScXMLSubTotalRuleContext( ScXMLImport& rImport, USHORT nPrfx, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList, ScXMLDatabaseRangeContext* pTempDatabaseRangeContext) : SvXMLImportContext( rImport, nPrfx, rLName ) { pDatabaseRangeContext = pTempDatabaseRangeContext; sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0; const SvXMLTokenMap& rAttrTokenMap = GetScImport().GetSubTotalRulesSubTotalRuleAttrTokenMap(); for( sal_Int16 i=0; i < nAttrCount; i++ ) { rtl::OUString sAttrName = xAttrList->getNameByIndex( i ); rtl::OUString aLocalName; USHORT nPrefix = GetScImport().GetNamespaceMap().GetKeyByAttrName( sAttrName, &aLocalName ); rtl::OUString sValue = xAttrList->getValueByIndex( i ); switch( rAttrTokenMap.Get( nPrefix, aLocalName ) ) { case XML_TOK_SUBTOTAL_RULE_ATTR_GROUP_BY_FIELD_NUMBER : { pDatabaseRangeContext->SetSubTotalRuleGroupFieldNumber(static_cast<sal_Int16>(sValue.toInt32())); } break; } } } ScXMLSubTotalRuleContext::~ScXMLSubTotalRuleContext() { } SvXMLImportContext *ScXMLSubTotalRuleContext::CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList ) { SvXMLImportContext *pContext = 0; const SvXMLTokenMap& rTokenMap = GetScImport().GetSubTotalRulesSubTotalRuleElemTokenMap(); switch( rTokenMap.Get( nPrefix, rLName ) ) { case XML_TOK_SUBTOTAL_RULE_SUBTOTAL_FIELD : { pContext = new ScXMLSubTotalFieldContext( GetScImport(), nPrefix, rLName, xAttrList, pDatabaseRangeContext); } break; } if( !pContext ) pContext = new SvXMLImportContext( GetImport(), nPrefix, rLName ); return pContext; } void ScXMLSubTotalRuleContext::EndElement() { } ScXMLSubTotalFieldContext::ScXMLSubTotalFieldContext( ScXMLImport& rImport, USHORT nPrfx, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList, ScXMLDatabaseRangeContext* pTempDatabaseRangeContext) : SvXMLImportContext( rImport, nPrfx, rLName ) { pDatabaseRangeContext = pTempDatabaseRangeContext; sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0; const SvXMLTokenMap& rAttrTokenMap = GetScImport().GetSubTotalRuleSubTotalFieldAttrTokenMap(); for( sal_Int16 i=0; i < nAttrCount; i++ ) { rtl::OUString sAttrName = xAttrList->getNameByIndex( i ); rtl::OUString aLocalName; USHORT nPrefix = GetScImport().GetNamespaceMap().GetKeyByAttrName( sAttrName, &aLocalName ); rtl::OUString sValue = xAttrList->getValueByIndex( i ); switch( rAttrTokenMap.Get( nPrefix, aLocalName ) ) { case XML_TOK_SUBTOTAL_FIELD_ATTR_FIELD_NUMBER : { sFieldNumber = sValue; } break; case XML_TOK_SUBTOTAL_FIELD_ATTR_FUNCTION : { sFunction = sValue; } break; } } } ScXMLSubTotalFieldContext::~ScXMLSubTotalFieldContext() { } SvXMLImportContext *ScXMLSubTotalFieldContext::CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList ) { SvXMLImportContext *pContext = 0; if( !pContext ) pContext = new SvXMLImportContext( GetImport(), nPrefix, rLName ); return pContext; } void ScXMLSubTotalFieldContext::EndElement() { sheet::SubTotalColumn aSubTotalColumn; aSubTotalColumn.Column = sFieldNumber.toInt32(); aSubTotalColumn.Function = ScXMLConverter::GetFunctionFromString( sFunction ); pDatabaseRangeContext->AddSubTotalColumn(aSubTotalColumn); } INTEGRATION: CWS insight01 (1.20.138); FILE MERGED 2004/07/06 10:02:26 oj 1.20.138.4: RESYNC: (1.21-1.22); FILE MERGED 2004/06/10 11:29:07 sab 1.20.138.3: #i25410#; add ConnectionResource 2004/05/28 17:24:07 oj 1.20.138.2: RESYNC: (1.20-1.21); FILE MERGED 2004/03/12 14:13:59 sab 1.20.138.1: #25410#; add support for database URL's /************************************************************************* * * $RCSfile: xmldrani.cxx,v $ * * $Revision: 1.23 $ * * last change: $Author: hr $ $Date: 2004-08-02 16:30:50 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifdef PCH #include "filt_pch.hxx" #endif #pragma hdrstop // INCLUDE --------------------------------------------------------------- #include "xmldrani.hxx" #include "xmlimprt.hxx" #include "xmlfilti.hxx" #include "xmlsorti.hxx" #include "document.hxx" #include "globstr.hrc" #include "docuno.hxx" #include "dbcolect.hxx" #include "datauno.hxx" #ifndef SC_SCATTR_HXX #include "attrib.hxx" #endif #ifndef SC_UNONAMES_HXX #include "unonames.hxx" #endif #ifndef SC_CONVUNO_HXX #include "convuno.hxx" #endif #ifndef _SC_XMLCONVERTER_HXX #include "XMLConverter.hxx" #endif #include <xmloff/xmltkmap.hxx> #include <xmloff/nmspmap.hxx> #ifndef _XMLOFF_XMLTOKEN_HXX #include <xmloff/xmltoken.hxx> #endif #ifndef _XMLOFF_XMLNMSPE_HXX #include <xmloff/xmlnmspe.hxx> #endif #ifndef _XMLOFF_XMLUCONV_HXX #include <xmloff/xmluconv.hxx> #endif #ifndef _XMLOFF_XMLERROR_HXX #include <xmloff/xmlerror.hxx> #endif #include <com/sun/star/sheet/XSpreadsheetDocument.hpp> #include <com/sun/star/sheet/XDatabaseRanges.hpp> #include <com/sun/star/sheet/XDatabaseRange.hpp> #include <com/sun/star/table/CellRangeAddress.hpp> #ifndef _COMPHELPER_EXTRACT_HXX_ #include <comphelper/extract.hxx> #endif #ifndef _COM_SUN_STAR_UNO_RUNTIMEEXCEPTION_HPP_ #include <com/sun/star/uno/RuntimeException.hpp> #endif #ifndef _COM_SUN_STAR_XML_SAX_XLOCATOR_HPP_ #include <com/sun/star/xml/sax/XLocator.hpp> #endif #define SC_ENABLEUSERSORTLIST "EnableUserSortList" #define SC_USERSORTLISTINDEX "UserSortListIndex" #define SC_USERLIST "UserList" using namespace com::sun::star; using namespace xmloff::token; //------------------------------------------------------------------ ScXMLDatabaseRangesContext::ScXMLDatabaseRangesContext( ScXMLImport& rImport, USHORT nPrfx, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList) : SvXMLImportContext( rImport, nPrfx, rLName ) { // has no attributes rImport.LockSolarMutex(); } ScXMLDatabaseRangesContext::~ScXMLDatabaseRangesContext() { GetScImport().UnlockSolarMutex(); } SvXMLImportContext *ScXMLDatabaseRangesContext::CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList ) { SvXMLImportContext *pContext = 0; const SvXMLTokenMap& rTokenMap = GetScImport().GetDatabaseRangesElemTokenMap(); switch( rTokenMap.Get( nPrefix, rLName ) ) { case XML_TOK_DATABASE_RANGE : { pContext = new ScXMLDatabaseRangeContext( GetScImport(), nPrefix, rLName, xAttrList); } break; } if( !pContext ) pContext = new SvXMLImportContext( GetImport(), nPrefix, rLName ); return pContext; } void ScXMLDatabaseRangesContext::EndElement() { } ScXMLDatabaseRangeContext::ScXMLDatabaseRangeContext( ScXMLImport& rImport, USHORT nPrfx, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList) : SvXMLImportContext( rImport, nPrfx, rLName ), nRefresh(0), nSubTotalsUserListIndex(0), nSubTotalRuleGroupFieldNumber(0), bContainsSort(sal_False), bContainsSubTotal(sal_False), bIsSelection(sal_False), bKeepFormats(sal_False), bMoveCells(sal_False), bStripData(sal_False), eOrientation(table::TableOrientation_ROWS), bContainsHeader(sal_True), bAutoFilter(sal_False), bFilterCopyOutputData(sal_False), bFilterIsCaseSensitive(sal_False), bFilterSkipDuplicates(sal_False), bFilterUseRegularExpressions(sal_False), bFilterConditionSourceRange(sal_False), bSubTotalsBindFormatsToContent(sal_False), bSubTotalsIsCaseSensitive(sal_False), bSubTotalsInsertPageBreaks(sal_False), bSubTotalsSortGroups(sal_False), bSubTotalsEnabledUserList(sal_False), bSubTotalsAscending(sal_True), bNative(sal_True), aSubTotalColumns(), aSortSequence() { nSourceType = sheet::DataImportMode_NONE; String sUnbenannt = ScGlobal::GetRscString(STR_DB_NONAME); rtl::OUString sOUUnbenannt (sUnbenannt); sDatabaseRangeName = sOUUnbenannt; sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0; const SvXMLTokenMap& rAttrTokenMap = GetScImport().GetDatabaseRangeAttrTokenMap(); for( sal_Int16 i=0; i < nAttrCount; i++ ) { rtl::OUString sAttrName = xAttrList->getNameByIndex( i ); rtl::OUString aLocalName; USHORT nPrefix = GetScImport().GetNamespaceMap().GetKeyByAttrName( sAttrName, &aLocalName ); rtl::OUString sValue = xAttrList->getValueByIndex( i ); switch( rAttrTokenMap.Get( nPrefix, aLocalName ) ) { case XML_TOK_DATABASE_RANGE_ATTR_NAME : { sDatabaseRangeName = sValue; } break; case XML_TOK_DATABASE_RANGE_ATTR_IS_SELECTION : { bIsSelection = IsXMLToken(sValue, XML_TRUE); } break; case XML_TOK_DATABASE_RANGE_ATTR_ON_UPDATE_KEEP_STYLES : { bKeepFormats = IsXMLToken(sValue, XML_TRUE); } break; case XML_TOK_DATABASE_RANGE_ATTR_ON_UPDATE_KEEP_SIZE : { bMoveCells = !IsXMLToken(sValue, XML_TRUE); } break; case XML_TOK_DATABASE_RANGE_ATTR_HAS_PERSISTENT_DATA : { bStripData = !IsXMLToken(sValue, XML_TRUE); } break; case XML_TOK_DATABASE_RANGE_ATTR_ORIENTATION : { if (IsXMLToken(sValue, XML_COLUMN)) eOrientation = table::TableOrientation_COLUMNS; } break; case XML_TOK_DATABASE_RANGE_ATTR_CONTAINS_HEADER : { bContainsHeader = IsXMLToken(sValue, XML_TRUE); } break; case XML_TOK_DATABASE_RANGE_ATTR_DISPLAY_FILTER_BUTTONS : { bAutoFilter = IsXMLToken(sValue, XML_TRUE); } break; case XML_TOK_DATABASE_RANGE_ATTR_TARGET_RANGE_ADDRESS : { sRangeAddress = sValue; } break; case XML_TOK_DATABASE_RANGE_ATTR_REFRESH_DELAY : { double fTime; if( SvXMLUnitConverter::convertTime( fTime, sValue ) ) nRefresh = Max( (sal_Int32)(fTime * 86400.0), (sal_Int32)0 ); } break; } } } ScXMLDatabaseRangeContext::~ScXMLDatabaseRangeContext() { } SvXMLImportContext *ScXMLDatabaseRangeContext::CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList ) { SvXMLImportContext *pContext = 0; const SvXMLTokenMap& rTokenMap = GetScImport().GetDatabaseRangeElemTokenMap(); switch( rTokenMap.Get( nPrefix, rLName ) ) { case XML_TOK_DATABASE_RANGE_SOURCE_SQL : { pContext = new ScXMLSourceSQLContext( GetScImport(), nPrefix, rLName, xAttrList, this); } break; case XML_TOK_DATABASE_RANGE_SOURCE_TABLE : { pContext = new ScXMLSourceTableContext( GetScImport(), nPrefix, rLName, xAttrList, this); } break; case XML_TOK_DATABASE_RANGE_SOURCE_QUERY : { pContext = new ScXMLSourceQueryContext( GetScImport(), nPrefix, rLName, xAttrList, this); } break; case XML_TOK_FILTER : { pContext = new ScXMLFilterContext( GetScImport(), nPrefix, rLName, xAttrList, this); } break; case XML_TOK_SORT : { bContainsSort = sal_True; pContext = new ScXMLSortContext( GetScImport(), nPrefix, rLName, xAttrList, this); } break; case XML_TOK_DATABASE_RANGE_SUBTOTAL_RULES : { bContainsSubTotal = sal_True; pContext = new ScXMLSubTotalRulesContext( GetScImport(), nPrefix, rLName, xAttrList, this); } break; } if( !pContext ) pContext = new SvXMLImportContext( GetImport(), nPrefix, rLName ); return pContext; } void ScXMLDatabaseRangeContext::EndElement() { if (GetScImport().GetModel().is()) { uno::Reference <beans::XPropertySet> xPropertySet( GetScImport().GetModel(), uno::UNO_QUERY ); ScDocument* pDoc = GetScImport().GetDocument(); if (pDoc && xPropertySet.is()) { uno::Any aDatabaseRanges = xPropertySet->getPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNO_DATABASERNG))); uno::Reference <sheet::XDatabaseRanges> xDatabaseRanges; if (aDatabaseRanges >>= xDatabaseRanges) { table::CellRangeAddress aCellRangeAddress; sal_Int32 nOffset(0); if (ScXMLConverter::GetRangeFromString( aCellRangeAddress, sRangeAddress, pDoc, nOffset )) { sal_Bool bInsert(sal_True); try { xDatabaseRanges->addNewByName(sDatabaseRangeName, aCellRangeAddress); } catch ( uno::RuntimeException& rRuntimeException ) { bInsert = sal_False; rtl::OUString sErrorMessage(RTL_CONSTASCII_USTRINGPARAM("DatabaseRange ")); sErrorMessage += sDatabaseRangeName; sErrorMessage += rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(" could not be created with the range ")); sErrorMessage += sRangeAddress; uno::Sequence<rtl::OUString> aSeq(1); aSeq[0] = sErrorMessage; uno::Reference<xml::sax::XLocator> xLocator; GetScImport().SetError(XMLERROR_API | XMLERROR_FLAG_ERROR, aSeq, rRuntimeException.Message, xLocator); } if (bInsert) { uno::Any aDatabaseRange = xDatabaseRanges->getByName(sDatabaseRangeName); uno::Reference <sheet::XDatabaseRange> xDatabaseRange; if (aDatabaseRange >>= xDatabaseRange) { uno::Reference <beans::XPropertySet> xDatabaseRangePropertySet (xDatabaseRange, uno::UNO_QUERY); if (xDatabaseRangePropertySet.is()) { uno::Any aTempValue; aTempValue = ::cppu::bool2any(bKeepFormats); xDatabaseRangePropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_KEEPFORM)), aTempValue); aTempValue = ::cppu::bool2any(bMoveCells); xDatabaseRangePropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_MOVCELLS)), aTempValue); aTempValue = ::cppu::bool2any(bStripData); xDatabaseRangePropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_STRIPDAT)), aTempValue); } uno::Sequence <beans::PropertyValue> aImportDescriptor = xDatabaseRange->getImportDescriptor(); sal_Int32 nImportProperties = aImportDescriptor.getLength(); for (sal_Int16 i = 0; i < nImportProperties; i++) { if (aImportDescriptor[i].Name == rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_DBNAME))) { if (sDatabaseName.getLength()) { aImportDescriptor[i].Value <<= sDatabaseName; } else { aImportDescriptor[i].Name = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_CONRES)); aImportDescriptor[i].Value <<= sConnectionRessource; } } else if (aImportDescriptor[i].Name == rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_SRCOBJ))) { uno::Any aSourceObject; aSourceObject <<= sSourceObject; aImportDescriptor[i].Value = aSourceObject; } else if (aImportDescriptor[i].Name == rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_SRCTYPE))) { uno::Any aSourceType; aSourceType <<= nSourceType; aImportDescriptor[i].Value = aSourceType; } else if (aImportDescriptor[i].Name == rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_ISNATIVE))) { uno::Any aNative; aNative = ::cppu::bool2any(bNative); aImportDescriptor[i].Value = aNative; } } ScDBCollection* pDBCollection = pDoc->GetDBCollection(); sal_uInt16 nIndex; pDBCollection->SearchName(sDatabaseRangeName, nIndex); ScDBData* pDBData = (*pDBCollection)[nIndex]; pDBData->SetImportSelection(bIsSelection); pDBData->SetAutoFilter(bAutoFilter); if (bAutoFilter) pDoc->ApplyFlagsTab( static_cast<SCCOL>(aCellRangeAddress.StartColumn), static_cast<SCROW>(aCellRangeAddress.StartRow), static_cast<SCCOL>(aCellRangeAddress.EndColumn), static_cast<SCROW>(aCellRangeAddress.StartRow), aCellRangeAddress.Sheet, SC_MF_AUTO ); ScImportParam aImportParam; ScImportDescriptor::FillImportParam(aImportParam, aImportDescriptor); pDBData->SetImportParam(aImportParam); if (bContainsSort) { sal_uInt32 nOldSize(aSortSequence.getLength()); aSortSequence.realloc(nOldSize + 1); beans::PropertyValue aProperty; aProperty.Name = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_ORIENT)); aProperty.Value <<= eOrientation; aSortSequence[nOldSize] = aProperty; ScSortParam aSortParam; ScSortDescriptor::FillSortParam(aSortParam, aSortSequence); //#98317#; until now the Fields are relative to the left top edge of the range, but the // core wants to have the absolute position (column/row) SCCOLROW nFieldStart = aSortParam.bByRow ? static_cast<SCCOLROW>(aCellRangeAddress.StartColumn) : static_cast<SCCOLROW>(aCellRangeAddress.StartRow); for (sal_uInt16 i = 0; i < MAXSORT; ++i) { if (aSortParam.bDoSort[i]) aSortParam.nField[i] += nFieldStart; } pDBData->SetSortParam(aSortParam); } uno::Reference <sheet::XSheetFilterDescriptor> xSheetFilterDescriptor = xDatabaseRange->getFilterDescriptor(); if (xSheetFilterDescriptor.is()) { uno::Reference <beans::XPropertySet> xFilterPropertySet (xSheetFilterDescriptor, uno::UNO_QUERY); if (xFilterPropertySet.is()) { uno::Any aTemp; sal_Bool bOrientation(table::TableOrientation_COLUMNS == eOrientation); aTemp = ::cppu::bool2any(bOrientation); xFilterPropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_ORIENT)), aTemp); aTemp = ::cppu::bool2any(bContainsHeader); xFilterPropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_CONTHDR)), aTemp); aTemp = ::cppu::bool2any(bFilterCopyOutputData); xFilterPropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_COPYOUT)), aTemp); aTemp = ::cppu::bool2any(bFilterIsCaseSensitive); xFilterPropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_ISCASE)), aTemp); aTemp = ::cppu::bool2any(bFilterSkipDuplicates); xFilterPropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_SKIPDUP)), aTemp); aTemp = ::cppu::bool2any(bFilterUseRegularExpressions); xFilterPropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_USEREGEX)), aTemp); aTemp <<= aFilterOutputPosition; xFilterPropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_OUTPOS)), aTemp); } xSheetFilterDescriptor->setFilterFields(aFilterFields); if (bFilterConditionSourceRange) { ScRange aAdvSource; ScUnoConversion::FillScRange( aAdvSource, aFilterConditionSourceRangeAddress ); pDBData->SetAdvancedQuerySource(&aAdvSource); } } if (bContainsSubTotal) { uno::Reference <sheet::XSubTotalDescriptor> xSubTotalDescriptor = xDatabaseRange->getSubTotalDescriptor(); if (xSubTotalDescriptor.is()) { uno::Reference <beans::XPropertySet> xSubTotalPropertySet (xSubTotalDescriptor, uno::UNO_QUERY); if( xSubTotalPropertySet.is()) { uno::Any aTemp; aTemp = ::cppu::bool2any(bSubTotalsBindFormatsToContent); xSubTotalPropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_BINDFMT)), aTemp); aTemp = ::cppu::bool2any(bSubTotalsEnabledUserList); xSubTotalPropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_ENABLEUSERSORTLIST)), aTemp); aTemp <<= nSubTotalsUserListIndex; xSubTotalPropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_USERSORTLISTINDEX)), aTemp); aTemp = ::cppu::bool2any(bSubTotalsInsertPageBreaks); xSubTotalPropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_INSBRK)), aTemp); aTemp = ::cppu::bool2any(bSubTotalsIsCaseSensitive); xSubTotalPropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_ISCASE)), aTemp); } ScSubTotalParam aSubTotalParam; aSubTotalParam.bDoSort = bSubTotalsSortGroups; aSubTotalParam.bAscending = bSubTotalsAscending; aSubTotalParam.bUserDef = bSubTotalsEnabledUserList; aSubTotalParam.nUserIndex = nSubTotalsUserListIndex; pDBData->SetSubTotalParam(aSubTotalParam); xSubTotalDescriptor->addNew(aSubTotalColumns, nSubTotalRuleGroupFieldNumber); } } if ( pDBData->HasImportParam() && !pDBData->HasImportSelection() ) { pDBData->SetRefreshDelay( nRefresh ); pDBData->SetRefreshHandler( pDBCollection->GetRefreshHandler() ); pDBData->SetRefreshControl( pDoc->GetRefreshTimerControlAddress() ); } } } } } } } } ScXMLSourceSQLContext::ScXMLSourceSQLContext( ScXMLImport& rImport, USHORT nPrfx, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList, ScXMLDatabaseRangeContext* pTempDatabaseRangeContext) : SvXMLImportContext( rImport, nPrfx, rLName ) { pDatabaseRangeContext = pTempDatabaseRangeContext; sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0; const SvXMLTokenMap& rAttrTokenMap = GetScImport().GetDatabaseRangeSourceSQLAttrTokenMap(); for( sal_Int16 i=0; i < nAttrCount; i++ ) { rtl::OUString sAttrName = xAttrList->getNameByIndex( i ); rtl::OUString aLocalName; USHORT nPrefix = GetScImport().GetNamespaceMap().GetKeyByAttrName( sAttrName, &aLocalName ); rtl::OUString sValue = xAttrList->getValueByIndex( i ); switch( rAttrTokenMap.Get( nPrefix, aLocalName ) ) { case XML_TOK_SOURCE_SQL_ATTR_DATABASE_NAME : { sDBName = sValue; } break; case XML_TOK_SOURCE_SQL_ATTR_SQL_STATEMENT : { pDatabaseRangeContext->SetSourceObject(sValue); } break; case XML_TOK_SOURCE_SQL_ATTR_PARSE_SQL_STATEMENT : { pDatabaseRangeContext->SetNative(IsXMLToken(sValue, XML_TRUE)); } break; } } pDatabaseRangeContext->SetSourceType(sheet::DataImportMode_SQL); } ScXMLSourceSQLContext::~ScXMLSourceSQLContext() { } SvXMLImportContext *ScXMLSourceSQLContext::CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList ) { SvXMLImportContext *pContext = 0; if ( nPrefix == XML_NAMESPACE_FORM ) { if (IsXMLToken(rLName, XML_CONNECTION_RESOURCE) && (sDBName.getLength() == 0)) { pContext = new ScXMLConResContext( GetScImport(), nPrefix, rLName, xAttrList, pDatabaseRangeContext); } } if( !pContext ) pContext = new SvXMLImportContext( GetImport(), nPrefix, rLName ); return pContext; } void ScXMLSourceSQLContext::EndElement() { if (sDBName.getLength()) pDatabaseRangeContext->SetDatabaseName(sDBName); } ScXMLSourceTableContext::ScXMLSourceTableContext( ScXMLImport& rImport, USHORT nPrfx, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList, ScXMLDatabaseRangeContext* pTempDatabaseRangeContext) : SvXMLImportContext( rImport, nPrfx, rLName ) { pDatabaseRangeContext = pTempDatabaseRangeContext; sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0; const SvXMLTokenMap& rAttrTokenMap = GetScImport().GetDatabaseRangeSourceTableAttrTokenMap(); for( sal_Int16 i=0; i < nAttrCount; i++ ) { rtl::OUString sAttrName = xAttrList->getNameByIndex( i ); rtl::OUString aLocalName; USHORT nPrefix = GetScImport().GetNamespaceMap().GetKeyByAttrName( sAttrName, &aLocalName ); rtl::OUString sValue = xAttrList->getValueByIndex( i ); switch( rAttrTokenMap.Get( nPrefix, aLocalName ) ) { case XML_TOK_SOURCE_TABLE_ATTR_DATABASE_NAME : { sDBName = sValue; } break; case XML_TOK_SOURCE_TABLE_ATTR_TABLE_NAME : { pDatabaseRangeContext->SetSourceObject(sValue); } break; } } pDatabaseRangeContext->SetSourceType(sheet::DataImportMode_TABLE); } ScXMLSourceTableContext::~ScXMLSourceTableContext() { } SvXMLImportContext *ScXMLSourceTableContext::CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList ) { SvXMLImportContext *pContext = 0; if ( nPrefix == XML_NAMESPACE_FORM ) { if (IsXMLToken(rLName, XML_CONNECTION_RESOURCE) && (sDBName.getLength() == 0)) { pContext = new ScXMLConResContext( GetScImport(), nPrefix, rLName, xAttrList, pDatabaseRangeContext); } } if( !pContext ) pContext = new SvXMLImportContext( GetImport(), nPrefix, rLName ); return pContext; } void ScXMLSourceTableContext::EndElement() { if (sDBName.getLength()) pDatabaseRangeContext->SetDatabaseName(sDBName); } ScXMLSourceQueryContext::ScXMLSourceQueryContext( ScXMLImport& rImport, USHORT nPrfx, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList, ScXMLDatabaseRangeContext* pTempDatabaseRangeContext) : SvXMLImportContext( rImport, nPrfx, rLName ) { pDatabaseRangeContext = pTempDatabaseRangeContext; sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0; const SvXMLTokenMap& rAttrTokenMap = GetScImport().GetDatabaseRangeSourceQueryAttrTokenMap(); for( sal_Int16 i=0; i < nAttrCount; i++ ) { rtl::OUString sAttrName = xAttrList->getNameByIndex( i ); rtl::OUString aLocalName; USHORT nPrefix = GetScImport().GetNamespaceMap().GetKeyByAttrName( sAttrName, &aLocalName ); rtl::OUString sValue = xAttrList->getValueByIndex( i ); switch( rAttrTokenMap.Get( nPrefix, aLocalName ) ) { case XML_TOK_SOURCE_QUERY_ATTR_DATABASE_NAME : { sDBName = sValue; } break; case XML_TOK_SOURCE_QUERY_ATTR_QUERY_NAME : { pDatabaseRangeContext->SetSourceObject(sValue); } break; } } pDatabaseRangeContext->SetSourceType(sheet::DataImportMode_QUERY); } ScXMLSourceQueryContext::~ScXMLSourceQueryContext() { } SvXMLImportContext *ScXMLSourceQueryContext::CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList ) { SvXMLImportContext *pContext = 0; if ( nPrefix == XML_NAMESPACE_FORM ) { if (IsXMLToken(rLName, XML_CONNECTION_RESOURCE) && (sDBName.getLength() == 0)) { pContext = new ScXMLConResContext( GetScImport(), nPrefix, rLName, xAttrList, pDatabaseRangeContext); } } if( !pContext ) pContext = new SvXMLImportContext( GetImport(), nPrefix, rLName ); return pContext; } void ScXMLSourceQueryContext::EndElement() { if (sDBName.getLength()) pDatabaseRangeContext->SetDatabaseName(sDBName); } ScXMLConResContext::ScXMLConResContext( ScXMLImport& rImport, USHORT nPrfx, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList, ScXMLDatabaseRangeContext* pTempDatabaseRangeContext) : SvXMLImportContext( rImport, nPrfx, rLName ), pDatabaseRangeContext( pTempDatabaseRangeContext ) { rtl::OUString sConRes; sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0; const SvXMLTokenMap& rAttrTokenMap = GetScImport().GetDatabaseRangeSourceSQLAttrTokenMap(); for( sal_Int16 i=0; i < nAttrCount; i++ ) { rtl::OUString sAttrName = xAttrList->getNameByIndex( i ); rtl::OUString aLocalName; USHORT nPrefix = GetScImport().GetNamespaceMap().GetKeyByAttrName( sAttrName, &aLocalName ); rtl::OUString sValue = xAttrList->getValueByIndex( i ); if (nPrefix == XML_NAMESPACE_XLINK) { if (IsXMLToken(aLocalName, XML_HREF)) sConRes = sValue; } } if (sConRes.getLength()) pDatabaseRangeContext->SetConnectionRessource(sConRes); } ScXMLConResContext::~ScXMLConResContext() { } SvXMLImportContext *ScXMLConResContext::CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList ) { SvXMLImportContext *pContext = 0; if( !pContext ) pContext = new SvXMLImportContext( GetImport(), nPrefix, rLName ); return pContext; } void ScXMLConResContext::EndElement() { } ScXMLSubTotalRulesContext::ScXMLSubTotalRulesContext( ScXMLImport& rImport, USHORT nPrfx, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList, ScXMLDatabaseRangeContext* pTempDatabaseRangeContext) : SvXMLImportContext( rImport, nPrfx, rLName ) { pDatabaseRangeContext = pTempDatabaseRangeContext; sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0; const SvXMLTokenMap& rAttrTokenMap = GetScImport().GetDatabaseRangeSubTotalRulesAttrTokenMap(); for( sal_Int16 i=0; i < nAttrCount; i++ ) { rtl::OUString sAttrName = xAttrList->getNameByIndex( i ); rtl::OUString aLocalName; USHORT nPrefix = GetScImport().GetNamespaceMap().GetKeyByAttrName( sAttrName, &aLocalName ); rtl::OUString sValue = xAttrList->getValueByIndex( i ); switch( rAttrTokenMap.Get( nPrefix, aLocalName ) ) { case XML_TOK_SUBTOTAL_RULES_ATTR_BIND_STYLES_TO_CONTENT : { pDatabaseRangeContext->SetSubTotalsBindFormatsToContent(IsXMLToken(sValue, XML_TRUE)); } break; case XML_TOK_SUBTOTAL_RULES_ATTR_CASE_SENSITIVE : { pDatabaseRangeContext->SetSubTotalsIsCaseSensitive(IsXMLToken(sValue, XML_TRUE)); } break; case XML_TOK_SUBTOTAL_RULES_ATTR_PAGE_BREAKS_ON_GROUP_CHANGE : { pDatabaseRangeContext->SetSubTotalsInsertPageBreaks(IsXMLToken(sValue, XML_TRUE)); } break; } } } ScXMLSubTotalRulesContext::~ScXMLSubTotalRulesContext() { } SvXMLImportContext *ScXMLSubTotalRulesContext::CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList ) { SvXMLImportContext *pContext = 0; const SvXMLTokenMap& rTokenMap = GetScImport().GetDatabaseRangeSubTotalRulesElemTokenMap(); switch( rTokenMap.Get( nPrefix, rLName ) ) { case XML_TOK_SUBTOTAL_RULES_SORT_GROUPS : { pContext = new ScXMLSortGroupsContext( GetScImport(), nPrefix, rLName, xAttrList, pDatabaseRangeContext); } break; case XML_TOK_SUBTOTAL_RULES_SUBTOTAL_RULE : { pContext = new ScXMLSubTotalRuleContext( GetScImport(), nPrefix, rLName, xAttrList, pDatabaseRangeContext); } break; } if( !pContext ) pContext = new SvXMLImportContext( GetImport(), nPrefix, rLName ); return pContext; } void ScXMLSubTotalRulesContext::EndElement() { } ScXMLSortGroupsContext::ScXMLSortGroupsContext( ScXMLImport& rImport, USHORT nPrfx, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList, ScXMLDatabaseRangeContext* pTempDatabaseRangeContext) : SvXMLImportContext( rImport, nPrfx, rLName ) { pDatabaseRangeContext = pTempDatabaseRangeContext; pDatabaseRangeContext->SetSubTotalsSortGroups(sal_True); sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0; const SvXMLTokenMap& rAttrTokenMap = GetScImport().GetSubTotalRulesSortGroupsAttrTokenMap(); for( sal_Int16 i=0; i < nAttrCount; i++ ) { rtl::OUString sAttrName = xAttrList->getNameByIndex( i ); rtl::OUString aLocalName; USHORT nPrefix = GetScImport().GetNamespaceMap().GetKeyByAttrName( sAttrName, &aLocalName ); rtl::OUString sValue = xAttrList->getValueByIndex( i ); switch( rAttrTokenMap.Get( nPrefix, aLocalName ) ) { case XML_TOK_SORT_GROUPS_ATTR_DATA_TYPE : { if (sValue.getLength() > 8) { rtl::OUString sTemp = sValue.copy(0, 8); if (sTemp.compareToAscii(SC_USERLIST) == 0) { pDatabaseRangeContext->SetSubTotalsEnabledUserList(sal_True); sTemp = sValue.copy(8); pDatabaseRangeContext->SetSubTotalsUserListIndex(static_cast<sal_Int16>(sTemp.toInt32())); } else { //if (IsXMLToken(sValue, XML_AUTOMATIC)) //aSortField.FieldType = util::SortFieldType_AUTOMATIC; // is not supported by StarOffice } } else { //if (IsXMLToken(sValue, XML_TEXT)) //aSortField.FieldType = util::SortFieldType_ALPHANUMERIC; // is not supported by StarOffice //else if (IsXMLToken(sValue, XML_NUMBER)) //aSortField.FieldType = util::SortFieldType_NUMERIC; // is not supported by StarOffice } } break; case XML_TOK_SORT_GROUPS_ATTR_ORDER : { if (IsXMLToken(sValue, XML_ASCENDING)) pDatabaseRangeContext->SetSubTotalsAscending(sal_True); else pDatabaseRangeContext->SetSubTotalsAscending(sal_False); } break; } } } ScXMLSortGroupsContext::~ScXMLSortGroupsContext() { } SvXMLImportContext *ScXMLSortGroupsContext::CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList ) { SvXMLImportContext *pContext = 0; if( !pContext ) pContext = new SvXMLImportContext( GetImport(), nPrefix, rLName ); return pContext; } void ScXMLSortGroupsContext::EndElement() { } ScXMLSubTotalRuleContext::ScXMLSubTotalRuleContext( ScXMLImport& rImport, USHORT nPrfx, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList, ScXMLDatabaseRangeContext* pTempDatabaseRangeContext) : SvXMLImportContext( rImport, nPrfx, rLName ) { pDatabaseRangeContext = pTempDatabaseRangeContext; sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0; const SvXMLTokenMap& rAttrTokenMap = GetScImport().GetSubTotalRulesSubTotalRuleAttrTokenMap(); for( sal_Int16 i=0; i < nAttrCount; i++ ) { rtl::OUString sAttrName = xAttrList->getNameByIndex( i ); rtl::OUString aLocalName; USHORT nPrefix = GetScImport().GetNamespaceMap().GetKeyByAttrName( sAttrName, &aLocalName ); rtl::OUString sValue = xAttrList->getValueByIndex( i ); switch( rAttrTokenMap.Get( nPrefix, aLocalName ) ) { case XML_TOK_SUBTOTAL_RULE_ATTR_GROUP_BY_FIELD_NUMBER : { pDatabaseRangeContext->SetSubTotalRuleGroupFieldNumber(static_cast<sal_Int16>(sValue.toInt32())); } break; } } } ScXMLSubTotalRuleContext::~ScXMLSubTotalRuleContext() { } SvXMLImportContext *ScXMLSubTotalRuleContext::CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList ) { SvXMLImportContext *pContext = 0; const SvXMLTokenMap& rTokenMap = GetScImport().GetSubTotalRulesSubTotalRuleElemTokenMap(); switch( rTokenMap.Get( nPrefix, rLName ) ) { case XML_TOK_SUBTOTAL_RULE_SUBTOTAL_FIELD : { pContext = new ScXMLSubTotalFieldContext( GetScImport(), nPrefix, rLName, xAttrList, pDatabaseRangeContext); } break; } if( !pContext ) pContext = new SvXMLImportContext( GetImport(), nPrefix, rLName ); return pContext; } void ScXMLSubTotalRuleContext::EndElement() { } ScXMLSubTotalFieldContext::ScXMLSubTotalFieldContext( ScXMLImport& rImport, USHORT nPrfx, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList, ScXMLDatabaseRangeContext* pTempDatabaseRangeContext) : SvXMLImportContext( rImport, nPrfx, rLName ) { pDatabaseRangeContext = pTempDatabaseRangeContext; sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0; const SvXMLTokenMap& rAttrTokenMap = GetScImport().GetSubTotalRuleSubTotalFieldAttrTokenMap(); for( sal_Int16 i=0; i < nAttrCount; i++ ) { rtl::OUString sAttrName = xAttrList->getNameByIndex( i ); rtl::OUString aLocalName; USHORT nPrefix = GetScImport().GetNamespaceMap().GetKeyByAttrName( sAttrName, &aLocalName ); rtl::OUString sValue = xAttrList->getValueByIndex( i ); switch( rAttrTokenMap.Get( nPrefix, aLocalName ) ) { case XML_TOK_SUBTOTAL_FIELD_ATTR_FIELD_NUMBER : { sFieldNumber = sValue; } break; case XML_TOK_SUBTOTAL_FIELD_ATTR_FUNCTION : { sFunction = sValue; } break; } } } ScXMLSubTotalFieldContext::~ScXMLSubTotalFieldContext() { } SvXMLImportContext *ScXMLSubTotalFieldContext::CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList ) { SvXMLImportContext *pContext = 0; if( !pContext ) pContext = new SvXMLImportContext( GetImport(), nPrefix, rLName ); return pContext; } void ScXMLSubTotalFieldContext::EndElement() { sheet::SubTotalColumn aSubTotalColumn; aSubTotalColumn.Column = sFieldNumber.toInt32(); aSubTotalColumn.Function = ScXMLConverter::GetFunctionFromString( sFunction ); pDatabaseRangeContext->AddSubTotalColumn(aSubTotalColumn); }
// // Copyright (c) 2019-2020, LAAS-CNRS, University of Edinburgh, University of Oxford // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of nor the names of its contributors may be used to // endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // #include <exotica_ddp_solver/feasibility_driven_ddp_solver.h> REGISTER_MOTIONSOLVER_TYPE("FeasibilityDrivenDDPSolver", exotica::FeasibilityDrivenDDPSolver) namespace exotica { void FeasibilityDrivenDDPSolver::Instantiate(const FeasibilityDrivenDDPSolverInitializer& init) { parameters_ = init; base_parameters_ = AbstractDDPSolverInitializer(FeasibilityDrivenDDPSolverInitializer(parameters_)); clamp_to_control_limits_in_forward_pass_ = base_parameters_.ClampControlsInForwardPass; initial_regularization_rate_ = base_parameters_.RegularizationRate; th_stepinc_ = base_parameters_.ThresholdRegularizationIncrease; th_stepdec_ = base_parameters_.ThresholdRegularizationDecrease; th_stop_ = parameters_.GradientToleranceConvergenceThreshold; th_gradient_tolerance_ = parameters_.GradientTolerance; th_acceptstep_ = parameters_.DescentStepAcceptanceThreshold; th_acceptnegstep_ = parameters_.AscentStepAcceptanceThreshold; } void AbstractFeasibilityDrivenDDPSolver::AllocateData() { // TODO: -1 here because of copy-paste and different conventions... // Crocoddyl: T running models + 1 terminal model // Exotica: T models ("T-1 running models") const int T = prob_->get_T() - 1; Vxx_.resize(T + 1); Vx_.resize(T + 1); Qxx_.resize(T); Qxu_.resize(T); Quu_.resize(T); Qx_.resize(T); Qu_.resize(T); K_.resize(T); k_.resize(T); fs_.resize(T + 1); xs_.resize(T + 1); us_.resize(T); xs_try_.resize(T + 1); us_try_.resize(T); dx_.resize(T + 1); FuTVxx_p_.resize(T); Quu_ldlt_.resize(T); Quuk_.resize(T); for (int t = 0; t < T; ++t) { Vxx_[t] = Eigen::MatrixXd::Zero(NDX_, NDX_); Vx_[t] = Eigen::VectorXd::Zero(NDX_); Qxx_[t] = Eigen::MatrixXd::Zero(NDX_, NDX_); Qxu_[t] = Eigen::MatrixXd::Zero(NDX_, NU_); Quu_[t] = Eigen::MatrixXd::Zero(NU_, NU_); Qx_[t] = Eigen::VectorXd::Zero(NDX_); Qu_[t] = Eigen::VectorXd::Zero(NU_); K_[t] = Eigen::MatrixXd::Zero(NU_, NDX_); k_[t] = Eigen::VectorXd::Zero(NU_); fs_[t] = Eigen::VectorXd::Zero(NDX_); if (t == 0) { xs_try_[t] = prob_->get_X(0); } else { xs_try_[t].setZero(NX_); } us_try_[t].setZero(NU_); dx_[t] = Eigen::VectorXd::Zero(NDX_); FuTVxx_p_[t] = Eigen::MatrixXd::Zero(NU_, NDX_); Quu_ldlt_[t] = Eigen::LDLT<Eigen::MatrixXd>(NU_); Quuk_[t] = Eigen::VectorXd(NU_); } Vxx_.back() = Eigen::MatrixXd::Zero(NDX_, NDX_); Vx_.back() = Eigen::VectorXd::Zero(NDX_); xs_try_.back().setZero(NX_); fs_.back() = Eigen::VectorXd::Zero(NDX_); FxTVxx_p_ = Eigen::MatrixXd::Zero(NDX_, NDX_); fTVxx_p_ = Eigen::VectorXd::Zero(NDX_); Quu_inv_.assign(T, Eigen::MatrixXd(NU_, NU_)); fx_.assign(T, Eigen::MatrixXd(NDX_, NDX_)); fu_.assign(T, Eigen::MatrixXd(NDX_, NU_)); // If T changed, we need to re-allocate. last_T_ = T_; } void AbstractFeasibilityDrivenDDPSolver::SpecifyProblem(PlanningProblemPtr pointer) { AbstractDDPSolver::SpecifyProblem(pointer); T_ = prob_->get_T(); dt_ = dynamics_solver_->get_dt(); NU_ = prob_->GetScene()->get_num_controls(); NX_ = prob_->GetScene()->get_num_state(); // State vector size NDX_ = prob_->GetScene()->get_num_state_derivative(); // Tangent vector size AllocateData(); } void AbstractFeasibilityDrivenDDPSolver::Solve(Eigen::MatrixXd& solution) { if (!prob_) ThrowNamed("Solver has not been initialized!"); Timer planning_timer, backward_pass_timer, line_search_timer; T_ = prob_->get_T(); if (T_ != last_T_) AllocateData(); dt_ = dynamics_solver_->get_dt(); control_limits_ = dynamics_solver_->get_control_limits(); const Eigen::MatrixXd& X_warm = prob_->get_X(); const Eigen::MatrixXd& U_warm = prob_->get_U(); for (int t = 0; t < T_ - 1; ++t) { xs_[t] = X_warm.col(t); us_[t] = U_warm.col(t); } xs_[0] = prob_->ApplyStartState(); // Apply start state xs_.back() = X_warm.col(T_ - 1); is_feasible_ = false; // We assume the first iteration is always infeasible. TODO: Make this configurable prob_->ResetCostEvolution(GetNumberOfMaxIterations() + 1); control_cost_evolution_.assign(GetNumberOfMaxIterations() + 1, std::numeric_limits<double>::quiet_NaN()); steplength_evolution_.assign(GetNumberOfMaxIterations() + 1, std::numeric_limits<double>::quiet_NaN()); regularization_evolution_.assign(GetNumberOfMaxIterations() + 1, std::numeric_limits<double>::quiet_NaN()); prob_->PreUpdate(); solution.resize(T_ - 1, NU_); // Initial roll-out to get initial cost cost_ = 0.0; control_cost_ = 0.0; for (int t = 0; t < T_ - 1; ++t) { prob_->Update(xs_[t], us_[t], t); control_cost_ += dt_ * prob_->GetControlCost(t); cost_ += dt_ * prob_->GetStateCost(t); } // Reset shooting nodes so we can warm-start from state trajectory prob_->set_X(X_warm); cost_ += prob_->GetStateCost(T_ - 1) + control_cost_; prob_->SetCostEvolution(0, cost_); control_cost_evolution_.at(0) = control_cost_; xreg_ = std::max(regmin_, initial_regularization_rate_); ureg_ = std::max(regmin_, initial_regularization_rate_); was_feasible_ = false; bool diverged = false; bool converged = false; bool recalcDiff = true; int iter; // double time_taken_setup_ = planning_timer.GetDuration(); for (iter = 1; iter <= GetNumberOfMaxIterations(); ++iter) { // Check whether user interrupted (Ctrl+C) if (Server::IsRos() && !ros::ok()) { if (debug_) HIGHLIGHT("Solving cancelled by user"); prob_->termination_criterion = TerminationCriterion::UserDefined; break; } backward_pass_timer.Reset(); while (!ComputeDirection(recalcDiff)) { // HIGHLIGHT("Increase regularization in ComputeDirection and try again.") recalcDiff = false; IncreaseRegularization(); if (xreg_ == regmax_) { if (debug_) WARNING_NAMED("FeasibilityDrivenDDPSolver::Solve", "State regularization exceeds maximum regularization: " << xreg_ << " > " << regmax_) diverged = true; break; } else { continue; } } time_taken_backward_pass_ = backward_pass_timer.GetDuration(); if (diverged) { if (debug_) WARNING("Terminating: Divergence in ComputeDirection / BackwardPass."); break; } UpdateExpectedImprovement(); // We need to recalculate the derivatives when the step length passes recalcDiff = false; line_search_timer.Reset(); for (int ai = 0; ai < alpha_space_.size(); ++ai) { steplength_ = alpha_space_(ai); dV_ = TryStep(steplength_); ExpectedImprovement(); dVexp_ = steplength_ * (d_[0] + 0.5 * steplength_ * d_[1]); if (dVexp_ >= 0) { // descent direction if (d_[0] < th_grad_ || dV_ > th_acceptstep_ * dVexp_) { was_feasible_ = is_feasible_; SetCandidate(xs_try_, us_try_, (was_feasible_) || (steplength_ == 1.0)); cost_ = cost_try_; control_cost_ = control_cost_try_; prob_->SetCostEvolution(iter, cost_); control_cost_evolution_.at(iter) = control_cost_; recalcDiff = true; break; } } else { // reducing the gaps by allowing a small increment in the cost value if (dV_ > th_acceptnegstep_ * dVexp_) { // if (debug_) INFO_NAMED("FDDP", "Ascent direction: " << dV_ << " > " << th_acceptnegstep_ * dVexp_) was_feasible_ = is_feasible_; SetCandidate(xs_try_, us_try_, (was_feasible_) || (steplength_ == 1)); cost_ = cost_try_; control_cost_ = control_cost_try_; prob_->SetCostEvolution(iter, cost_); control_cost_evolution_.at(iter) = control_cost_; break; } // else // { // if (debug_) INFO_NAMED("FDDP", "Ascent direction, but not accepted: " << dV_ << " < " << th_acceptnegstep_ * dVexp_) // } } prob_->SetCostEvolution(iter, cost_); control_cost_evolution_.at(iter) = control_cost_; } time_taken_forward_pass_ = line_search_timer.GetDuration(); steplength_evolution_.at(iter) = steplength_; regularization_evolution_.at(iter) = xreg_; if (debug_) { if (iter % 10 == 0 || iter == 1) { std::cout << "iter \t cost \t stop \t grad \t xreg"; std::cout << " \t ureg \t step \t feas \tdV-exp \t dV\n"; } std::cout << std::setw(4) << iter << " "; std::cout << std::scientific << std::setprecision(5) << cost_ << " "; std::cout << stop_ << " " << -d_[1] << " "; std::cout << xreg_ << " " << ureg_ << " "; std::cout << std::fixed << std::setprecision(4) << steplength_ << " "; std::cout << is_feasible_ << " "; std::cout << std::scientific << std::setprecision(5) << dVexp_ << " "; std::cout << dV_ << '\n'; } // Adapt regularization based on step-length if (steplength_ > th_stepdec_) { DecreaseRegularization(); } if (steplength_ <= th_stepinc_) { IncreaseRegularization(); if (xreg_ == regmax_) { WARNING_NAMED("FeasibilityDrivenDDPSolver::Solve", "State regularization exceeds maximum regularization: " << xreg_ << " > " << regmax_) diverged = true; break; } } CheckStoppingCriteria(); // Stop is only exactly zero if all dimensions of Qu_[t] have been // artificially set to 0. This is e.g. the case for a Control-Limited // variant (BoxFDDP). However, we do not want to stop at the first // saturation of all dimensions. if (was_feasible_ && stop_ < th_stop_ && stop_ != 0.0) { if (debug_) HIGHLIGHT_NAMED("FeasibilityDrivenDDPSolver::Solve", "Convergence: " << stop_ << " < " << th_stop_) converged = true; break; } if (diverged) { WARNING_NAMED("FeasibilityDrivenDDPSolver::Solve", "Terminating: Divergence in ForwardPass."); break; } // Check gradient tolerance if (was_feasible_ && -d_[1] < th_gradient_tolerance_) { if (debug_) HIGHLIGHT_NAMED("FeasibilityDrivenDDPSolver::Solve", "Gradient tolerance: " << -d_[1] << " < " << th_gradient_tolerance_) prob_->termination_criterion = TerminationCriterion::GradientTolerance; break; } prob_->OnSolverIterationEnd(); } if (diverged) prob_->termination_criterion = TerminationCriterion::Divergence; if (converged) prob_->termination_criterion = TerminationCriterion::Convergence; if (!converged && iter == GetNumberOfMaxIterations() + 1) prob_->termination_criterion = TerminationCriterion::IterationLimit; // Store the best solution found over all iterations for (int t = 0; t < T_ - 1; ++t) { solution.row(t) = us_[t].transpose(); // prob_->Update(us_[t], t); } planning_time_ = planning_timer.GetDuration(); // HIGHLIGHT(std::setprecision(4) << "Setup: " << time_taken_setup_ * 1e3 << "\tBwd: " << time_taken_backward_pass_ * 1e3 << "\tFwd: " << time_taken_forward_pass_ * 1e3 << "\tSolve = " << (planning_time_ - time_taken_setup_)*1e3 << "\talpha=" << steplength_) } void AbstractFeasibilityDrivenDDPSolver::IncreaseRegularization() { xreg_ *= regfactor_; if (xreg_ > regmax_) { xreg_ = regmax_; } ureg_ = xreg_; } void AbstractFeasibilityDrivenDDPSolver::DecreaseRegularization() { xreg_ /= regfactor_; if (xreg_ < regmin_) { xreg_ = regmin_; } ureg_ = xreg_; } double AbstractFeasibilityDrivenDDPSolver::CheckStoppingCriteria() { stop_ = 0.; for (int t = 0; t < T_ - 1; ++t) { stop_ += Qu_[t].squaredNorm(); } return stop_; } const Eigen::Vector2d& AbstractFeasibilityDrivenDDPSolver::ExpectedImprovement() { dv_ = 0; if (!is_feasible_) { for (int t = 0; t < T_; ++t) { dx_[t] = prob_->GetScene()->GetDynamicsSolver()->StateDelta(xs_[t], xs_try_[t]); fTVxx_p_.noalias() = Vxx_[t] * dx_[t]; dv_ -= fs_[t].dot(fTVxx_p_); } } d_[0] = dg_ + dv_; d_[1] = dq_ - 2 * dv_; return d_; } void AbstractFeasibilityDrivenDDPSolver::UpdateExpectedImprovement() { dg_ = 0; dq_ = 0; if (!is_feasible_) { dg_ -= Vx_.back().dot(fs_.back()); fTVxx_p_.noalias() = Vxx_.back() * fs_.back(); dq_ += fs_.back().dot(fTVxx_p_); } for (int t = 0; t < T_ - 1; ++t) { dg_ += Qu_[t].dot(k_[t]); dq_ -= k_[t].dot(Quuk_[t]); if (!is_feasible_) { dg_ -= Vx_[t].dot(fs_[t]); fTVxx_p_.noalias() = Vxx_[t] * fs_[t]; dq_ += fs_[t].dot(fTVxx_p_); } } } void AbstractFeasibilityDrivenDDPSolver::SetCandidate(const std::vector<Eigen::VectorXd>& xs_in, const std::vector<Eigen::VectorXd>& us_in, const bool is_feasible) { const std::size_t T = static_cast<std::size_t>(prob_->get_T()); if (xs_in.size() == 0) { for (int t = 0; t < T_; ++t) { xs_[t].setZero(NX_); } } else { if (xs_in.size() != T) { ThrowPretty("Warm start state has wrong dimension, got " << xs_in.size() << " expecting " << (T + 1)); } std::copy(xs_in.begin(), xs_in.end(), xs_.begin()); } if (us_in.size() == 0) { for (int t = 0; t < T_ - 1; ++t) { us_[t].setZero(NU_); } } else { if (us_in.size() != T - 1) { ThrowPretty("Warm start control has wrong dimension, got " << us_in.size() << " expecting " << T); } std::copy(us_in.begin(), us_in.end(), us_.begin()); } is_feasible_ = is_feasible; } double AbstractFeasibilityDrivenDDPSolver::TryStep(const double steplength) { ForwardPass(steplength); return cost_ - cost_try_; } void AbstractFeasibilityDrivenDDPSolver::ForwardPass(const double steplength) { if (steplength > 1. || steplength < 0.) { ThrowPretty("Invalid argument: invalid step length, value should be between 0. to 1. - got=" << steplength); } cost_try_ = 0.; control_cost_try_ = 0.; xnext_ = prob_->get_X(0); for (int t = 0; t < T_ - 1; ++t) { // If feasible or the gaps are closed, start the shooting from the previous step. if ((is_feasible_) || (steplength == 1)) { xs_try_[t] = xnext_; } else { // We need to obtain a state based on the expected reduction of the gap given the step length (dt=unit time) prob_->GetScene()->GetDynamicsSolver()->Integrate(xnext_, fs_[t] * (steplength - 1), 1., xs_try_[t]); } dx_[t] = prob_->GetScene()->GetDynamicsSolver()->StateDelta(xs_try_[t], xs_[t]); // NB: StateDelta in Exotica is the other way round than in Pinocchio us_try_[t].noalias() = us_[t] - k_[t] * steplength - K_[t] * dx_[t]; // This is weird. It works better WITHOUT the feedback ?! if (clamp_to_control_limits_in_forward_pass_) { us_try_[t] = us_try_[t].cwiseMax(control_limits_.col(0)).cwiseMin(control_limits_.col(1)); } prob_->Update(xs_try_[t], us_try_[t], t); // Performs integration and update of cost xnext_ = prob_->get_X(t + 1); control_cost_try_ += dt_ * prob_->GetControlCost(t); cost_try_ += dt_ * prob_->GetStateCost(t); if (IsNaN(cost_try_)) { WARNING_NAMED("NaN in ForwardPass", "forward_error - NaN in cost_try_ at t=" << t); return; } if (IsNaN(xnext_.lpNorm<Eigen::Infinity>())) { WARNING_NAMED("NaN in ForwardPass", "forward_error - xnext_ isn't finite at t=" << t); return; } } // Terminal model if ((is_feasible_) || (steplength == 1)) { xs_try_.back() = xnext_; } else { prob_->GetScene()->GetDynamicsSolver()->Integrate(xnext_, fs_.back() * (steplength - 1), 1., xs_try_.back()); } prob_->UpdateTerminalState(xs_try_.back()); cost_try_ += prob_->GetStateCost(T_ - 1) + control_cost_try_; if (IsNaN(cost_try_)) { WARNING_NAMED("NaN in ForwardPass", "forward_error - cost NaN"); return; } } bool AbstractFeasibilityDrivenDDPSolver::ComputeDirection(const bool recalcDiff) { if (recalcDiff) { CalcDiff(); } return BackwardPassFDDP(); } double AbstractFeasibilityDrivenDDPSolver::CalcDiff() { cost_ = 0; control_cost_ = 0; // Running cost for (int t = 0; t < T_ - 1; ++t) { control_cost_ += dt_ * prob_->GetControlCost(t); cost_ += dt_ * prob_->GetStateCost(t); } // Terminal cost cost_ += prob_->GetStateCost(T_ - 1) + control_cost_; if (!is_feasible_) { // Defects for t=0..T for (int t = 0; t < prob_->get_T(); ++t) { fs_[t] = prob_->GetScene()->GetDynamicsSolver()->StateDelta(prob_->get_X(t), xs_[t]); // Exotica's convention differs... } } else if (!was_feasible_) { // closing the gaps for (std::vector<Eigen::VectorXd>::iterator it = fs_.begin(); it != fs_.end(); ++it) { it->setZero(); } } return cost_; } bool AbstractFeasibilityDrivenDDPSolver::BackwardPassFDDP() { Vxx_.back() = prob_->GetStateCostHessian(T_ - 1); Vx_.back() = prob_->GetStateCostJacobian(T_ - 1); if (!std::isnan(xreg_)) { Vxx_.back().diagonal().array() += xreg_; } if (!is_feasible_) { Vx_.back().noalias() += Vxx_.back() * fs_.back(); } for (int t = static_cast<int>(prob_->get_T()) - 2; t >= 0; --t) { const Eigen::MatrixXd& Vxx_p = Vxx_[t + 1]; const Eigen::VectorXd& Vx_p = Vx_[t + 1]; Qxx_[t].noalias() = dt_ * prob_->GetStateCostHessian(t); Qxu_[t].noalias() = dt_ * prob_->GetStateControlCostHessian().transpose(); Quu_[t].noalias() = dt_ * prob_->GetControlCostHessian(t); Qx_[t].noalias() = dt_ * prob_->GetStateCostJacobian(t); Qu_[t].noalias() = dt_ * prob_->GetControlCostJacobian(t); dynamics_solver_->ComputeDerivatives(xs_[t], us_[t]); fx_[t].noalias() = dt_ * dynamics_solver_->get_fx() + Eigen::MatrixXd::Identity(NDX_, NDX_); fu_[t].noalias() = dt_ * dynamics_solver_->get_fu(); FxTVxx_p_.noalias() = fx_[t].transpose() * Vxx_p; FuTVxx_p_[t].noalias() = fu_[t].transpose() * Vxx_p; Qxx_[t].noalias() += FxTVxx_p_ * fx_[t]; Qxu_[t].noalias() += FxTVxx_p_ * fu_[t]; Quu_[t].noalias() += FuTVxx_p_[t] * fu_[t]; Qx_[t].noalias() += fx_[t].transpose() * Vx_p; Qu_[t].noalias() += fu_[t].transpose() * Vx_p; if (!std::isnan(ureg_)) { Quu_[t].diagonal().array() += ureg_; } ComputeGains(t); Vx_[t] = Qx_[t]; if (std::isnan(ureg_)) { Vx_[t].noalias() -= K_[t].transpose() * Qu_[t]; } else { Quuk_[t].noalias() = Quu_[t] * k_[t]; Vx_[t].noalias() += K_[t].transpose() * Quuk_[t]; Vx_[t].noalias() -= 2 * (K_[t].transpose() * Qu_[t]); } Vxx_[t] = Qxx_[t]; Vxx_[t].noalias() -= Qxu_[t] * K_[t]; Vxx_[t] = 0.5 * (Vxx_[t] + Vxx_[t].transpose()).eval(); if (!std::isnan(xreg_)) { Vxx_[t].diagonal().array() += xreg_; } // Compute and store the Vx gradient at end of the interval (rollout state) if (!is_feasible_) { Vx_[t].noalias() += Vxx_[t] * fs_[t]; } if (IsNaN(Vx_[t].lpNorm<Eigen::Infinity>())) { return false; } if (IsNaN(Vxx_[t].lpNorm<Eigen::Infinity>())) { return false; } } return true; } void AbstractFeasibilityDrivenDDPSolver::ComputeGains(const int t) { // Quu_inv_[t].noalias() = Quu_[t].inverse(); // K_[t].noalias() = Quu_inv_[t] * Qxu_[t].transpose(); // k_[t].noalias() = Quu_inv_[t] * Qu_[t]; while (true) { Quu_ldlt_[t].compute(Quu_[t]); const Eigen::ComputationInfo& info = Quu_ldlt_[t].info(); if (info != Eigen::Success) { HIGHLIGHT_NAMED("ComputeGains", "Cholesky failed for reg=" << ureg_ << ", Quu_[t]=\n" << Quu_[t]) Quu_[t].diagonal().array() -= ureg_; IncreaseRegularization(); Quu_[t].diagonal().array() += ureg_; if (ureg_ == regmax_) ThrowPretty("backward_error - error in Cholesky decomposition\n" << Quu_[t]); // ThrowPretty("backward_error - error in Cholesky decomposition\n" // << Quu_[t]); } else { break; } } K_[t] = Qxu_[t].transpose(); Quu_ldlt_[t].solveInPlace(K_[t]); k_[t] = Qu_[t]; Quu_ldlt_[t].solveInPlace(k_[t]); } } // namespace exotica [exotica_ddp_solver] FDDP: Add abs to gradient tolerance (TODO: This should be checked) // // Copyright (c) 2019-2020, LAAS-CNRS, University of Edinburgh, University of Oxford // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of nor the names of its contributors may be used to // endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // #include <exotica_ddp_solver/feasibility_driven_ddp_solver.h> REGISTER_MOTIONSOLVER_TYPE("FeasibilityDrivenDDPSolver", exotica::FeasibilityDrivenDDPSolver) namespace exotica { void FeasibilityDrivenDDPSolver::Instantiate(const FeasibilityDrivenDDPSolverInitializer& init) { parameters_ = init; base_parameters_ = AbstractDDPSolverInitializer(FeasibilityDrivenDDPSolverInitializer(parameters_)); clamp_to_control_limits_in_forward_pass_ = base_parameters_.ClampControlsInForwardPass; initial_regularization_rate_ = base_parameters_.RegularizationRate; th_stepinc_ = base_parameters_.ThresholdRegularizationIncrease; th_stepdec_ = base_parameters_.ThresholdRegularizationDecrease; th_stop_ = parameters_.GradientToleranceConvergenceThreshold; th_gradient_tolerance_ = parameters_.GradientTolerance; th_acceptstep_ = parameters_.DescentStepAcceptanceThreshold; th_acceptnegstep_ = parameters_.AscentStepAcceptanceThreshold; } void AbstractFeasibilityDrivenDDPSolver::AllocateData() { // TODO: -1 here because of copy-paste and different conventions... // Crocoddyl: T running models + 1 terminal model // Exotica: T models ("T-1 running models") const int T = prob_->get_T() - 1; Vxx_.resize(T + 1); Vx_.resize(T + 1); Qxx_.resize(T); Qxu_.resize(T); Quu_.resize(T); Qx_.resize(T); Qu_.resize(T); K_.resize(T); k_.resize(T); fs_.resize(T + 1); xs_.resize(T + 1); us_.resize(T); xs_try_.resize(T + 1); us_try_.resize(T); dx_.resize(T + 1); FuTVxx_p_.resize(T); Quu_ldlt_.resize(T); Quuk_.resize(T); for (int t = 0; t < T; ++t) { Vxx_[t] = Eigen::MatrixXd::Zero(NDX_, NDX_); Vx_[t] = Eigen::VectorXd::Zero(NDX_); Qxx_[t] = Eigen::MatrixXd::Zero(NDX_, NDX_); Qxu_[t] = Eigen::MatrixXd::Zero(NDX_, NU_); Quu_[t] = Eigen::MatrixXd::Zero(NU_, NU_); Qx_[t] = Eigen::VectorXd::Zero(NDX_); Qu_[t] = Eigen::VectorXd::Zero(NU_); K_[t] = Eigen::MatrixXd::Zero(NU_, NDX_); k_[t] = Eigen::VectorXd::Zero(NU_); fs_[t] = Eigen::VectorXd::Zero(NDX_); if (t == 0) { xs_try_[t] = prob_->get_X(0); } else { xs_try_[t].setZero(NX_); } us_try_[t].setZero(NU_); dx_[t] = Eigen::VectorXd::Zero(NDX_); FuTVxx_p_[t] = Eigen::MatrixXd::Zero(NU_, NDX_); Quu_ldlt_[t] = Eigen::LDLT<Eigen::MatrixXd>(NU_); Quuk_[t] = Eigen::VectorXd(NU_); } Vxx_.back() = Eigen::MatrixXd::Zero(NDX_, NDX_); Vx_.back() = Eigen::VectorXd::Zero(NDX_); xs_try_.back().setZero(NX_); fs_.back() = Eigen::VectorXd::Zero(NDX_); FxTVxx_p_ = Eigen::MatrixXd::Zero(NDX_, NDX_); fTVxx_p_ = Eigen::VectorXd::Zero(NDX_); Quu_inv_.assign(T, Eigen::MatrixXd(NU_, NU_)); fx_.assign(T, Eigen::MatrixXd(NDX_, NDX_)); fu_.assign(T, Eigen::MatrixXd(NDX_, NU_)); // If T changed, we need to re-allocate. last_T_ = T_; } void AbstractFeasibilityDrivenDDPSolver::SpecifyProblem(PlanningProblemPtr pointer) { AbstractDDPSolver::SpecifyProblem(pointer); T_ = prob_->get_T(); dt_ = dynamics_solver_->get_dt(); NU_ = prob_->GetScene()->get_num_controls(); NX_ = prob_->GetScene()->get_num_state(); // State vector size NDX_ = prob_->GetScene()->get_num_state_derivative(); // Tangent vector size AllocateData(); } void AbstractFeasibilityDrivenDDPSolver::Solve(Eigen::MatrixXd& solution) { if (!prob_) ThrowNamed("Solver has not been initialized!"); Timer planning_timer, backward_pass_timer, line_search_timer; T_ = prob_->get_T(); if (T_ != last_T_) AllocateData(); dt_ = dynamics_solver_->get_dt(); control_limits_ = dynamics_solver_->get_control_limits(); const Eigen::MatrixXd& X_warm = prob_->get_X(); const Eigen::MatrixXd& U_warm = prob_->get_U(); for (int t = 0; t < T_ - 1; ++t) { xs_[t] = X_warm.col(t); us_[t] = U_warm.col(t); } xs_[0] = prob_->ApplyStartState(); // Apply start state xs_.back() = X_warm.col(T_ - 1); is_feasible_ = false; // We assume the first iteration is always infeasible. TODO: Make this configurable prob_->ResetCostEvolution(GetNumberOfMaxIterations() + 1); control_cost_evolution_.assign(GetNumberOfMaxIterations() + 1, std::numeric_limits<double>::quiet_NaN()); steplength_evolution_.assign(GetNumberOfMaxIterations() + 1, std::numeric_limits<double>::quiet_NaN()); regularization_evolution_.assign(GetNumberOfMaxIterations() + 1, std::numeric_limits<double>::quiet_NaN()); prob_->PreUpdate(); solution.resize(T_ - 1, NU_); // Initial roll-out to get initial cost cost_ = 0.0; control_cost_ = 0.0; for (int t = 0; t < T_ - 1; ++t) { prob_->Update(xs_[t], us_[t], t); control_cost_ += dt_ * prob_->GetControlCost(t); cost_ += dt_ * prob_->GetStateCost(t); } // Reset shooting nodes so we can warm-start from state trajectory prob_->set_X(X_warm); cost_ += prob_->GetStateCost(T_ - 1) + control_cost_; prob_->SetCostEvolution(0, cost_); control_cost_evolution_.at(0) = control_cost_; xreg_ = std::max(regmin_, initial_regularization_rate_); ureg_ = std::max(regmin_, initial_regularization_rate_); was_feasible_ = false; bool diverged = false; bool converged = false; bool recalcDiff = true; int iter; // double time_taken_setup_ = planning_timer.GetDuration(); for (iter = 1; iter <= GetNumberOfMaxIterations(); ++iter) { // Check whether user interrupted (Ctrl+C) if (Server::IsRos() && !ros::ok()) { if (debug_) HIGHLIGHT("Solving cancelled by user"); prob_->termination_criterion = TerminationCriterion::UserDefined; break; } backward_pass_timer.Reset(); while (!ComputeDirection(recalcDiff)) { // HIGHLIGHT("Increase regularization in ComputeDirection and try again.") recalcDiff = false; IncreaseRegularization(); if (xreg_ == regmax_) { if (debug_) WARNING_NAMED("FeasibilityDrivenDDPSolver::Solve", "State regularization exceeds maximum regularization: " << xreg_ << " > " << regmax_) diverged = true; break; } else { continue; } } time_taken_backward_pass_ = backward_pass_timer.GetDuration(); if (diverged) { if (debug_) WARNING("Terminating: Divergence in ComputeDirection / BackwardPass."); break; } UpdateExpectedImprovement(); // We need to recalculate the derivatives when the step length passes recalcDiff = false; line_search_timer.Reset(); for (int ai = 0; ai < alpha_space_.size(); ++ai) { steplength_ = alpha_space_(ai); dV_ = TryStep(steplength_); ExpectedImprovement(); dVexp_ = steplength_ * (d_[0] + 0.5 * steplength_ * d_[1]); if (dVexp_ >= 0) { // descent direction if (d_[0] < th_grad_ || dV_ > th_acceptstep_ * dVexp_) { was_feasible_ = is_feasible_; SetCandidate(xs_try_, us_try_, (was_feasible_) || (steplength_ == 1.0)); cost_ = cost_try_; control_cost_ = control_cost_try_; prob_->SetCostEvolution(iter, cost_); control_cost_evolution_.at(iter) = control_cost_; recalcDiff = true; break; } } else { // reducing the gaps by allowing a small increment in the cost value if (dV_ > th_acceptnegstep_ * dVexp_) { // if (debug_) INFO_NAMED("FDDP", "Ascent direction: " << dV_ << " > " << th_acceptnegstep_ * dVexp_) was_feasible_ = is_feasible_; SetCandidate(xs_try_, us_try_, (was_feasible_) || (steplength_ == 1)); cost_ = cost_try_; control_cost_ = control_cost_try_; prob_->SetCostEvolution(iter, cost_); control_cost_evolution_.at(iter) = control_cost_; break; } // else // { // if (debug_) INFO_NAMED("FDDP", "Ascent direction, but not accepted: " << dV_ << " < " << th_acceptnegstep_ * dVexp_) // } } prob_->SetCostEvolution(iter, cost_); control_cost_evolution_.at(iter) = control_cost_; } time_taken_forward_pass_ = line_search_timer.GetDuration(); steplength_evolution_.at(iter) = steplength_; regularization_evolution_.at(iter) = xreg_; if (debug_) { if (iter % 10 == 0 || iter == 1) { std::cout << "iter \t cost \t stop \t grad \t xreg"; std::cout << " \t ureg \t step \t feas \tdV-exp \t dV\n"; } std::cout << std::setw(4) << iter << " "; std::cout << std::scientific << std::setprecision(5) << cost_ << " "; std::cout << stop_ << " " << -d_[1] << " "; std::cout << xreg_ << " " << ureg_ << " "; std::cout << std::fixed << std::setprecision(4) << steplength_ << " "; std::cout << is_feasible_ << " "; std::cout << std::scientific << std::setprecision(5) << dVexp_ << " "; std::cout << dV_ << '\n'; } // Adapt regularization based on step-length if (steplength_ > th_stepdec_) { DecreaseRegularization(); } if (steplength_ <= th_stepinc_) { IncreaseRegularization(); if (xreg_ == regmax_) { WARNING_NAMED("FeasibilityDrivenDDPSolver::Solve", "State regularization exceeds maximum regularization: " << xreg_ << " > " << regmax_) diverged = true; break; } } CheckStoppingCriteria(); // Stop is only exactly zero if all dimensions of Qu_[t] have been // artificially set to 0. This is e.g. the case for a Control-Limited // variant (BoxFDDP). However, we do not want to stop at the first // saturation of all dimensions. if (was_feasible_ && stop_ < th_stop_ && stop_ != 0.0) { if (debug_) HIGHLIGHT_NAMED("FeasibilityDrivenDDPSolver::Solve", "Convergence: " << stop_ << " < " << th_stop_) converged = true; break; } if (diverged) { WARNING_NAMED("FeasibilityDrivenDDPSolver::Solve", "Terminating: Divergence in ForwardPass."); break; } // Check gradient tolerance if (was_feasible_ && std::abs(-d_[1]) < th_gradient_tolerance_) { if (debug_) HIGHLIGHT_NAMED("FeasibilityDrivenDDPSolver::Solve", "Gradient tolerance: " << -d_[1] << " < " << th_gradient_tolerance_) prob_->termination_criterion = TerminationCriterion::GradientTolerance; break; } prob_->OnSolverIterationEnd(); } if (diverged) prob_->termination_criterion = TerminationCriterion::Divergence; if (converged) prob_->termination_criterion = TerminationCriterion::Convergence; if (!converged && iter == GetNumberOfMaxIterations() + 1) prob_->termination_criterion = TerminationCriterion::IterationLimit; // Store the best solution found over all iterations for (int t = 0; t < T_ - 1; ++t) { solution.row(t) = us_[t].transpose(); // prob_->Update(us_[t], t); } planning_time_ = planning_timer.GetDuration(); // HIGHLIGHT(std::setprecision(4) << "Setup: " << time_taken_setup_ * 1e3 << "\tBwd: " << time_taken_backward_pass_ * 1e3 << "\tFwd: " << time_taken_forward_pass_ * 1e3 << "\tSolve = " << (planning_time_ - time_taken_setup_)*1e3 << "\talpha=" << steplength_) } void AbstractFeasibilityDrivenDDPSolver::IncreaseRegularization() { xreg_ *= regfactor_; if (xreg_ > regmax_) { xreg_ = regmax_; } ureg_ = xreg_; } void AbstractFeasibilityDrivenDDPSolver::DecreaseRegularization() { xreg_ /= regfactor_; if (xreg_ < regmin_) { xreg_ = regmin_; } ureg_ = xreg_; } double AbstractFeasibilityDrivenDDPSolver::CheckStoppingCriteria() { stop_ = 0.; for (int t = 0; t < T_ - 1; ++t) { stop_ += Qu_[t].squaredNorm(); } return stop_; } const Eigen::Vector2d& AbstractFeasibilityDrivenDDPSolver::ExpectedImprovement() { dv_ = 0; if (!is_feasible_) { for (int t = 0; t < T_; ++t) { dx_[t] = prob_->GetScene()->GetDynamicsSolver()->StateDelta(xs_[t], xs_try_[t]); fTVxx_p_.noalias() = Vxx_[t] * dx_[t]; dv_ -= fs_[t].dot(fTVxx_p_); } } d_[0] = dg_ + dv_; d_[1] = dq_ - 2 * dv_; return d_; } void AbstractFeasibilityDrivenDDPSolver::UpdateExpectedImprovement() { dg_ = 0; dq_ = 0; if (!is_feasible_) { dg_ -= Vx_.back().dot(fs_.back()); fTVxx_p_.noalias() = Vxx_.back() * fs_.back(); dq_ += fs_.back().dot(fTVxx_p_); } for (int t = 0; t < T_ - 1; ++t) { dg_ += Qu_[t].dot(k_[t]); dq_ -= k_[t].dot(Quuk_[t]); if (!is_feasible_) { dg_ -= Vx_[t].dot(fs_[t]); fTVxx_p_.noalias() = Vxx_[t] * fs_[t]; dq_ += fs_[t].dot(fTVxx_p_); } } } void AbstractFeasibilityDrivenDDPSolver::SetCandidate(const std::vector<Eigen::VectorXd>& xs_in, const std::vector<Eigen::VectorXd>& us_in, const bool is_feasible) { const std::size_t T = static_cast<std::size_t>(prob_->get_T()); if (xs_in.size() == 0) { for (int t = 0; t < T_; ++t) { xs_[t].setZero(NX_); } } else { if (xs_in.size() != T) { ThrowPretty("Warm start state has wrong dimension, got " << xs_in.size() << " expecting " << (T + 1)); } std::copy(xs_in.begin(), xs_in.end(), xs_.begin()); } if (us_in.size() == 0) { for (int t = 0; t < T_ - 1; ++t) { us_[t].setZero(NU_); } } else { if (us_in.size() != T - 1) { ThrowPretty("Warm start control has wrong dimension, got " << us_in.size() << " expecting " << T); } std::copy(us_in.begin(), us_in.end(), us_.begin()); } is_feasible_ = is_feasible; } double AbstractFeasibilityDrivenDDPSolver::TryStep(const double steplength) { ForwardPass(steplength); return cost_ - cost_try_; } void AbstractFeasibilityDrivenDDPSolver::ForwardPass(const double steplength) { if (steplength > 1. || steplength < 0.) { ThrowPretty("Invalid argument: invalid step length, value should be between 0. to 1. - got=" << steplength); } cost_try_ = 0.; control_cost_try_ = 0.; xnext_ = prob_->get_X(0); for (int t = 0; t < T_ - 1; ++t) { // If feasible or the gaps are closed, start the shooting from the previous step. if ((is_feasible_) || (steplength == 1)) { xs_try_[t] = xnext_; } else { // We need to obtain a state based on the expected reduction of the gap given the step length (dt=unit time) prob_->GetScene()->GetDynamicsSolver()->Integrate(xnext_, fs_[t] * (steplength - 1), 1., xs_try_[t]); } dx_[t] = prob_->GetScene()->GetDynamicsSolver()->StateDelta(xs_try_[t], xs_[t]); // NB: StateDelta in Exotica is the other way round than in Pinocchio us_try_[t].noalias() = us_[t] - k_[t] * steplength - K_[t] * dx_[t]; // This is weird. It works better WITHOUT the feedback ?! if (clamp_to_control_limits_in_forward_pass_) { us_try_[t] = us_try_[t].cwiseMax(control_limits_.col(0)).cwiseMin(control_limits_.col(1)); } prob_->Update(xs_try_[t], us_try_[t], t); // Performs integration and update of cost xnext_ = prob_->get_X(t + 1); control_cost_try_ += dt_ * prob_->GetControlCost(t); cost_try_ += dt_ * prob_->GetStateCost(t); if (IsNaN(cost_try_)) { WARNING_NAMED("NaN in ForwardPass", "forward_error - NaN in cost_try_ at t=" << t); return; } if (IsNaN(xnext_.lpNorm<Eigen::Infinity>())) { WARNING_NAMED("NaN in ForwardPass", "forward_error - xnext_ isn't finite at t=" << t); return; } } // Terminal model if ((is_feasible_) || (steplength == 1)) { xs_try_.back() = xnext_; } else { prob_->GetScene()->GetDynamicsSolver()->Integrate(xnext_, fs_.back() * (steplength - 1), 1., xs_try_.back()); } prob_->UpdateTerminalState(xs_try_.back()); cost_try_ += prob_->GetStateCost(T_ - 1) + control_cost_try_; if (IsNaN(cost_try_)) { WARNING_NAMED("NaN in ForwardPass", "forward_error - cost NaN"); return; } } bool AbstractFeasibilityDrivenDDPSolver::ComputeDirection(const bool recalcDiff) { if (recalcDiff) { CalcDiff(); } return BackwardPassFDDP(); } double AbstractFeasibilityDrivenDDPSolver::CalcDiff() { cost_ = 0; control_cost_ = 0; // Running cost for (int t = 0; t < T_ - 1; ++t) { control_cost_ += dt_ * prob_->GetControlCost(t); cost_ += dt_ * prob_->GetStateCost(t); } // Terminal cost cost_ += prob_->GetStateCost(T_ - 1) + control_cost_; if (!is_feasible_) { // Defects for t=0..T for (int t = 0; t < prob_->get_T(); ++t) { fs_[t] = prob_->GetScene()->GetDynamicsSolver()->StateDelta(prob_->get_X(t), xs_[t]); // Exotica's convention differs... } } else if (!was_feasible_) { // closing the gaps for (std::vector<Eigen::VectorXd>::iterator it = fs_.begin(); it != fs_.end(); ++it) { it->setZero(); } } return cost_; } bool AbstractFeasibilityDrivenDDPSolver::BackwardPassFDDP() { Vxx_.back() = prob_->GetStateCostHessian(T_ - 1); Vx_.back() = prob_->GetStateCostJacobian(T_ - 1); if (!std::isnan(xreg_)) { Vxx_.back().diagonal().array() += xreg_; } if (!is_feasible_) { Vx_.back().noalias() += Vxx_.back() * fs_.back(); } for (int t = static_cast<int>(prob_->get_T()) - 2; t >= 0; --t) { const Eigen::MatrixXd& Vxx_p = Vxx_[t + 1]; const Eigen::VectorXd& Vx_p = Vx_[t + 1]; Qxx_[t].noalias() = dt_ * prob_->GetStateCostHessian(t); Qxu_[t].noalias() = dt_ * prob_->GetStateControlCostHessian().transpose(); Quu_[t].noalias() = dt_ * prob_->GetControlCostHessian(t); Qx_[t].noalias() = dt_ * prob_->GetStateCostJacobian(t); Qu_[t].noalias() = dt_ * prob_->GetControlCostJacobian(t); dynamics_solver_->ComputeDerivatives(xs_[t], us_[t]); fx_[t].noalias() = dt_ * dynamics_solver_->get_fx() + Eigen::MatrixXd::Identity(NDX_, NDX_); fu_[t].noalias() = dt_ * dynamics_solver_->get_fu(); FxTVxx_p_.noalias() = fx_[t].transpose() * Vxx_p; FuTVxx_p_[t].noalias() = fu_[t].transpose() * Vxx_p; Qxx_[t].noalias() += FxTVxx_p_ * fx_[t]; Qxu_[t].noalias() += FxTVxx_p_ * fu_[t]; Quu_[t].noalias() += FuTVxx_p_[t] * fu_[t]; Qx_[t].noalias() += fx_[t].transpose() * Vx_p; Qu_[t].noalias() += fu_[t].transpose() * Vx_p; if (!std::isnan(ureg_)) { Quu_[t].diagonal().array() += ureg_; } ComputeGains(t); Vx_[t] = Qx_[t]; if (std::isnan(ureg_)) { Vx_[t].noalias() -= K_[t].transpose() * Qu_[t]; } else { Quuk_[t].noalias() = Quu_[t] * k_[t]; Vx_[t].noalias() += K_[t].transpose() * Quuk_[t]; Vx_[t].noalias() -= 2 * (K_[t].transpose() * Qu_[t]); } Vxx_[t] = Qxx_[t]; Vxx_[t].noalias() -= Qxu_[t] * K_[t]; Vxx_[t] = 0.5 * (Vxx_[t] + Vxx_[t].transpose()).eval(); if (!std::isnan(xreg_)) { Vxx_[t].diagonal().array() += xreg_; } // Compute and store the Vx gradient at end of the interval (rollout state) if (!is_feasible_) { Vx_[t].noalias() += Vxx_[t] * fs_[t]; } if (IsNaN(Vx_[t].lpNorm<Eigen::Infinity>())) { return false; } if (IsNaN(Vxx_[t].lpNorm<Eigen::Infinity>())) { return false; } } return true; } void AbstractFeasibilityDrivenDDPSolver::ComputeGains(const int t) { // Quu_inv_[t].noalias() = Quu_[t].inverse(); // K_[t].noalias() = Quu_inv_[t] * Qxu_[t].transpose(); // k_[t].noalias() = Quu_inv_[t] * Qu_[t]; while (true) { Quu_ldlt_[t].compute(Quu_[t]); const Eigen::ComputationInfo& info = Quu_ldlt_[t].info(); if (info != Eigen::Success) { HIGHLIGHT_NAMED("ComputeGains", "Cholesky failed for reg=" << ureg_ << ", Quu_[t]=\n" << Quu_[t]) Quu_[t].diagonal().array() -= ureg_; IncreaseRegularization(); Quu_[t].diagonal().array() += ureg_; if (ureg_ == regmax_) ThrowPretty("backward_error - error in Cholesky decomposition\n" << Quu_[t]); // ThrowPretty("backward_error - error in Cholesky decomposition\n" // << Quu_[t]); } else { break; } } K_[t] = Qxu_[t].transpose(); Quu_ldlt_[t].solveInPlace(K_[t]); k_[t] = Qu_[t]; Quu_ldlt_[t].solveInPlace(k_[t]); } } // namespace exotica
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #ifndef SC_XMLEXPRT_HXX #define SC_XMLEXPRT_HXX #include <xmloff/xmlexp.hxx> #include <com/sun/star/sheet/XSpreadsheet.hpp> #include <com/sun/star/sheet/XSpreadsheetDocument.hpp> #include <com/sun/star/table/CellRangeAddress.hpp> #include <com/sun/star/table/CellAddress.hpp> #include <com/sun/star/drawing/XShapes.hpp> #include <com/sun/star/table/XCellRange.hpp> #include "address.hxx" namespace com { namespace sun { namespace star { namespace beans { class XPropertySet; } } } } #include <boost/unordered_map.hpp> #include <boost/scoped_ptr.hpp> class ScOutlineArray; class SvXMLExportPropertyMapper; class ScMyMergedRangesContainer; class ScMyValidationsContainer; class ScMyNotEmptyCellsIterator; class ScChangeTrackingExportHelper; class ScColumnStyles; class ScRowStyles; class ScFormatRangeStyles; class ScRowFormatRanges; class ScMyOpenCloseColumnRowGroup; class ScMyAreaLinksContainer; class ScMyDetectiveOpContainer; struct ScMyCell; class ScDocument; class ScMySharedData; class ScMyDefaultStyles; class XMLNumberFormatAttributesExportHelper; class ScChartListener; class SfxItemPool; class ScAddress; class ScXMLCachedRowAttrAccess; class ScRangeName; class ScXMLEditAttributeMap; class EditTextObject; class ScFormulaCell; typedef std::vector< com::sun::star::uno::Reference < com::sun::star::drawing::XShapes > > ScMyXShapesVec; class ScXMLExport : public SvXMLExport { ScDocument* pDoc; com::sun::star::uno::Reference <com::sun::star::sheet::XSpreadsheet> xCurrentTable; com::sun::star::uno::Reference <com::sun::star::table::XCellRange> xCurrentTableCellRange; com::sun::star::uno::Reference<com::sun::star::io::XInputStream> xSourceStream; sal_Int32 nSourceStreamPos; mutable boost::scoped_ptr<ScXMLEditAttributeMap> mpEditAttrMap; boost::scoped_ptr<ScMyNotEmptyCellsIterator> mpCellsItr; UniReference < XMLPropertyHandlerFactory > xScPropHdlFactory; UniReference < XMLPropertySetMapper > xCellStylesPropertySetMapper; UniReference < XMLPropertySetMapper > xColumnStylesPropertySetMapper; UniReference < XMLPropertySetMapper > xRowStylesPropertySetMapper; UniReference < XMLPropertySetMapper > xTableStylesPropertySetMapper; UniReference < SvXMLExportPropertyMapper > xCellStylesExportPropertySetMapper; UniReference < SvXMLExportPropertyMapper > xColumnStylesExportPropertySetMapper; UniReference < SvXMLExportPropertyMapper > xRowStylesExportPropertySetMapper; UniReference < SvXMLExportPropertyMapper > xTableStylesExportPropertySetMapper; XMLNumberFormatAttributesExportHelper* pNumberFormatAttributesExportHelper; typedef ::boost::unordered_map<sal_Int32, sal_Int32> NumberFormatIndexMap; NumberFormatIndexMap aNumFmtIndexMap; ScMySharedData* pSharedData; ScColumnStyles* pColumnStyles; ScRowStyles* pRowStyles; ScFormatRangeStyles* pCellStyles; ScRowFormatRanges* pRowFormatRanges; std::vector<OUString> aTableStyles; com::sun::star::table::CellRangeAddress aRowHeaderRange; ScMyOpenCloseColumnRowGroup* pGroupColumns; ScMyOpenCloseColumnRowGroup* pGroupRows; ScMyDefaultStyles* pDefaults; ScChartListener* pChartListener; const ScMyCell* pCurrentCell; ScMyMergedRangesContainer* pMergedRangesContainer; ScMyValidationsContainer* pValidationsContainer; ScChangeTrackingExportHelper* pChangeTrackingExportHelper; const OUString sLayerID; const OUString sCaptionShape; OUString sExternalRefTabStyleName; OUString sAttrName; OUString sAttrStyleName; OUString sAttrColumnsRepeated; OUString sAttrFormula; OUString sAttrValueType; OUString sAttrStringValue; OUString sElemCell; OUString sElemCoveredCell; OUString sElemCol; OUString sElemRow; OUString sElemTab; OUString sElemP; sal_Int32 nOpenRow; sal_Int32 nProgressCount; sal_uInt16 nCurrentTable; bool bHasRowHeader; bool bRowHeaderOpen; bool mbShowProgress; sal_Int32 GetNumberFormatStyleIndex(sal_Int32 nNumFmt) const; void CollectSharedData(sal_Int32& nTableCount, sal_Int32& nShapesCount); void CollectShapesAutoStyles(const sal_Int32 nTableCount); void WriteTablesView(const com::sun::star::uno::Any& aTableView); void WriteView(const com::sun::star::uno::Any& aView); virtual void _ExportFontDecls(); virtual void _ExportStyles( sal_Bool bUsed ); virtual void _ExportAutoStyles(); virtual void _ExportMasterStyles(); virtual void SetBodyAttributes(); virtual void _ExportContent(); virtual void _ExportMeta(); void CollectInternalShape( ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape > xShape ); com::sun::star::table::CellRangeAddress GetEndAddress(const com::sun::star::uno::Reference<com::sun::star::sheet::XSpreadsheet>& xTable, const sal_Int32 nTable); // ScMyEmptyDatabaseRangesContainer GetEmptyDatabaseRanges(); void GetAreaLinks( com::sun::star::uno::Reference< com::sun::star::sheet::XSpreadsheetDocument>& xSpreadDoc, ScMyAreaLinksContainer& rAreaLinks ); void GetDetectiveOpList( ScMyDetectiveOpContainer& rDetOp ); void WriteSingleColumn(const sal_Int32 nRepeatColumns, const sal_Int32 nStyleIndex, const sal_Int32 nIndex, const bool bIsAutoStyle, const bool bIsVisible); void WriteColumn(const sal_Int32 nColumn, const sal_Int32 nRepeatColumns, const sal_Int32 nStyleIndex, const bool bIsVisible); void OpenHeaderColumn(); void CloseHeaderColumn(); void ExportColumns(const sal_Int32 nTable, const com::sun::star::table::CellRangeAddress& aColumnHeaderRange, const bool bHasColumnHeader); void ExportExternalRefCacheStyles(); void ExportCellTextAutoStyles(sal_Int32 nTable); void ExportFormatRanges(const sal_Int32 nStartCol, const sal_Int32 nStartRow, const sal_Int32 nEndCol, const sal_Int32 nEndRow, const sal_Int32 nSheet); void WriteRowContent(); void WriteRowStartTag(sal_Int32 nRow, const sal_Int32 nIndex, const sal_Int32 nEmptyRows, bool bHidden, bool bFiltered); void OpenHeaderRows(); void CloseHeaderRows(); void OpenNewRow(const sal_Int32 nIndex, const sal_Int32 nStartRow, const sal_Int32 nEmptyRows, bool bHidden, bool bFiltered); void OpenAndCloseRow(const sal_Int32 nIndex, const sal_Int32 nStartRow, const sal_Int32 nEmptyRows, bool bHidden, bool bFiltered); void OpenRow(const sal_Int32 nTable, const sal_Int32 nStartRow, const sal_Int32 nRepeatRow, ScXMLCachedRowAttrAccess& rRowAttr); void CloseRow(const sal_Int32 nRow); void GetColumnRowHeader(bool& bHasColumnHeader, com::sun::star::table::CellRangeAddress& aColumnHeaderRange, bool& bHasRowHeader, com::sun::star::table::CellRangeAddress& aRowHeaderRange, OUString& rPrintRanges) const; void FillFieldGroup(ScOutlineArray* pFields, ScMyOpenCloseColumnRowGroup* pGroups); void FillColumnRowGroups(); bool GetMerged (const com::sun::star::table::CellRangeAddress* pCellRange, const com::sun::star::uno::Reference <com::sun::star::sheet::XSpreadsheet>& xTable); void GetCellText (ScMyCell& rMyCell, const ScAddress& aPos) const; void WriteTable(sal_Int32 nTable, const ::com::sun::star::uno::Reference< ::com::sun::star::sheet::XSpreadsheet>& xTable); void WriteCell(ScMyCell& aCell, sal_Int32 nEqualCellCount); void WriteEditCell(const EditTextObject* pText); void WriteMultiLineFormulaResult(const ScFormulaCell* pCell); void WriteAreaLink(const ScMyCell& rMyCell); void WriteAnnotation(ScMyCell& rMyCell); void WriteDetective(const ScMyCell& rMyCell); void ExportShape(const com::sun::star::uno::Reference < com::sun::star::drawing::XShape >& xShape, com::sun::star::awt::Point* pPoint); void WriteShapes(const ScMyCell& rMyCell); void WriteTableShapes(); void SetRepeatAttribute(sal_Int32 nEqualCellCount, bool bIncProgress); bool IsCellTypeEqual (const ScMyCell& aCell1, const ScMyCell& aCell2) const; bool IsEditCell(ScMyCell& rCell) const; bool IsCellEqual(ScMyCell& aCell1, ScMyCell& aCell2); void WriteCalculationSettings(const com::sun::star::uno::Reference <com::sun::star::sheet::XSpreadsheetDocument>& xSpreadDoc); void WriteTableSource(); void WriteScenario(); // core implementation void WriteTheLabelRanges(const com::sun::star::uno::Reference< com::sun::star::sheet::XSpreadsheetDocument >& xSpreadDoc); void WriteLabelRanges( const com::sun::star::uno::Reference< com::sun::star::container::XIndexAccess >& xRangesIAccess, bool bColumn ); void WriteNamedExpressions(); void WriteNamedRange(ScRangeName* pRangeName); void ExportConditionalFormat(SCTAB nTab); void WriteExternalRefCaches(); void WriteConsolidation(); // core implementation void CollectUserDefinedNamespaces(const SfxItemPool* pPool, sal_uInt16 nAttrib); void AddStyleFromCells( const com::sun::star::uno::Reference< com::sun::star::beans::XPropertySet >& xProperties, const com::sun::star::uno::Reference< com::sun::star::sheet::XSpreadsheet >& xTable, sal_Int32 nTable, const OUString* pOldName ); void AddStyleFromColumn( const com::sun::star::uno::Reference< com::sun::star::beans::XPropertySet >& xColumnProperties, const OUString* pOldName, sal_Int32& rIndex, bool& rIsVisible ); void AddStyleFromRow( const com::sun::star::uno::Reference< com::sun::star::beans::XPropertySet >& xRowProperties, const OUString* pOldName, sal_Int32& rIndex ); void IncrementProgressBar(bool bFlush, sal_Int32 nInc = 1); void CopySourceStream( sal_Int32 nStartOffset, sal_Int32 nEndOffset, sal_Int32& rNewStart, sal_Int32& rNewEnd ); const ScXMLEditAttributeMap& GetEditAttributeMap() const; protected: virtual SvXMLAutoStylePoolP* CreateAutoStylePool(); virtual XMLPageExport* CreatePageExport(); virtual XMLShapeExport* CreateShapeExport(); virtual XMLFontAutoStylePool* CreateFontAutoStylePool(); public: ScXMLExport( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > xContext, const sal_uInt16 nExportFlag); virtual ~ScXMLExport(); static sal_Int16 GetFieldUnit(); inline ScDocument* GetDocument() { return pDoc; } inline const ScDocument* GetDocument() const { return pDoc; } bool IsMatrix (const ScAddress& aCell, com::sun::star::table::CellRangeAddress& aCellAddress, bool& bIsFirst) const; UniReference < XMLPropertySetMapper > GetCellStylesPropertySetMapper() { return xCellStylesPropertySetMapper; } UniReference < XMLPropertySetMapper > GetTableStylesPropertySetMapper() { return xTableStylesPropertySetMapper; } void SetSourceStream( const com::sun::star::uno::Reference<com::sun::star::io::XInputStream>& xNewStream ); void GetChangeTrackViewSettings(com::sun::star::uno::Sequence<com::sun::star::beans::PropertyValue>& rProps); virtual void GetViewSettings(com::sun::star::uno::Sequence<com::sun::star::beans::PropertyValue>& rProps); virtual void GetConfigurationSettings(com::sun::star::uno::Sequence<com::sun::star::beans::PropertyValue>& rProps); virtual void exportAnnotationMeta( const com::sun::star::uno::Reference < com::sun::star::drawing::XShape >& xShape); void CreateSharedData(const sal_Int32 nTableCount); void SetSharedData(ScMySharedData* pTemp) { pSharedData = pTemp; } ScMySharedData* GetSharedData() { return pSharedData; } XMLNumberFormatAttributesExportHelper* GetNumberFormatAttributesExportHelper(); // Export the document. virtual sal_uInt32 exportDoc( enum ::xmloff::token::XMLTokenEnum eClass = ::xmloff::token::XML_TOKEN_INVALID ); // XExporter virtual void SAL_CALL setSourceDocument( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent >& xDoc ) throw(::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException); // XFilter virtual sal_Bool SAL_CALL filter( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& aDescriptor ) throw(::com::sun::star::uno::RuntimeException); virtual void SAL_CALL cancel() throw(::com::sun::star::uno::RuntimeException); // XInitialization virtual void SAL_CALL initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments ) throw(::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException); // XServiceInfo virtual OUString SAL_CALL getImplementationName( ) throw(::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL supportsService( const OUString& ServiceName ) throw(::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< OUString > SAL_CALL getSupportedServiceNames( ) throw(::com::sun::star::uno::RuntimeException); // XUnoTunnel virtual sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& aIdentifier ) throw(::com::sun::star::uno::RuntimeException); virtual void DisposingModel(); }; #endif /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ clean no more used header declaration Change-Id: Id4253c51d43c788310c93acd91ed49fa2fe68c4b Reviewed-on: https://gerrit.libreoffice.org/5695 Reviewed-by: Kohei Yoshida <6e47bc5169e040ede988a669348d2aebab98c987@suse.de> Tested-by: Kohei Yoshida <6e47bc5169e040ede988a669348d2aebab98c987@suse.de> /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #ifndef SC_XMLEXPRT_HXX #define SC_XMLEXPRT_HXX #include <xmloff/xmlexp.hxx> #include <com/sun/star/sheet/XSpreadsheet.hpp> #include <com/sun/star/sheet/XSpreadsheetDocument.hpp> #include <com/sun/star/table/CellRangeAddress.hpp> #include <com/sun/star/table/CellAddress.hpp> #include <com/sun/star/drawing/XShapes.hpp> #include <com/sun/star/table/XCellRange.hpp> #include "address.hxx" namespace com { namespace sun { namespace star { namespace beans { class XPropertySet; } } } } #include <boost/unordered_map.hpp> #include <boost/scoped_ptr.hpp> class ScOutlineArray; class SvXMLExportPropertyMapper; class ScMyMergedRangesContainer; class ScMyValidationsContainer; class ScMyNotEmptyCellsIterator; class ScChangeTrackingExportHelper; class ScColumnStyles; class ScRowStyles; class ScFormatRangeStyles; class ScRowFormatRanges; class ScMyOpenCloseColumnRowGroup; class ScMyAreaLinksContainer; class ScMyDetectiveOpContainer; struct ScMyCell; class ScDocument; class ScMySharedData; class ScMyDefaultStyles; class XMLNumberFormatAttributesExportHelper; class ScChartListener; class SfxItemPool; class ScAddress; class ScXMLCachedRowAttrAccess; class ScRangeName; class ScXMLEditAttributeMap; class EditTextObject; class ScFormulaCell; typedef std::vector< com::sun::star::uno::Reference < com::sun::star::drawing::XShapes > > ScMyXShapesVec; class ScXMLExport : public SvXMLExport { ScDocument* pDoc; com::sun::star::uno::Reference <com::sun::star::sheet::XSpreadsheet> xCurrentTable; com::sun::star::uno::Reference <com::sun::star::table::XCellRange> xCurrentTableCellRange; com::sun::star::uno::Reference<com::sun::star::io::XInputStream> xSourceStream; sal_Int32 nSourceStreamPos; mutable boost::scoped_ptr<ScXMLEditAttributeMap> mpEditAttrMap; boost::scoped_ptr<ScMyNotEmptyCellsIterator> mpCellsItr; UniReference < XMLPropertyHandlerFactory > xScPropHdlFactory; UniReference < XMLPropertySetMapper > xCellStylesPropertySetMapper; UniReference < XMLPropertySetMapper > xColumnStylesPropertySetMapper; UniReference < XMLPropertySetMapper > xRowStylesPropertySetMapper; UniReference < XMLPropertySetMapper > xTableStylesPropertySetMapper; UniReference < SvXMLExportPropertyMapper > xCellStylesExportPropertySetMapper; UniReference < SvXMLExportPropertyMapper > xColumnStylesExportPropertySetMapper; UniReference < SvXMLExportPropertyMapper > xRowStylesExportPropertySetMapper; UniReference < SvXMLExportPropertyMapper > xTableStylesExportPropertySetMapper; XMLNumberFormatAttributesExportHelper* pNumberFormatAttributesExportHelper; typedef ::boost::unordered_map<sal_Int32, sal_Int32> NumberFormatIndexMap; NumberFormatIndexMap aNumFmtIndexMap; ScMySharedData* pSharedData; ScColumnStyles* pColumnStyles; ScRowStyles* pRowStyles; ScFormatRangeStyles* pCellStyles; ScRowFormatRanges* pRowFormatRanges; std::vector<OUString> aTableStyles; com::sun::star::table::CellRangeAddress aRowHeaderRange; ScMyOpenCloseColumnRowGroup* pGroupColumns; ScMyOpenCloseColumnRowGroup* pGroupRows; ScMyDefaultStyles* pDefaults; ScChartListener* pChartListener; const ScMyCell* pCurrentCell; ScMyMergedRangesContainer* pMergedRangesContainer; ScMyValidationsContainer* pValidationsContainer; ScChangeTrackingExportHelper* pChangeTrackingExportHelper; const OUString sLayerID; const OUString sCaptionShape; OUString sExternalRefTabStyleName; OUString sAttrName; OUString sAttrStyleName; OUString sAttrColumnsRepeated; OUString sAttrFormula; OUString sAttrValueType; OUString sAttrStringValue; OUString sElemCell; OUString sElemCoveredCell; OUString sElemCol; OUString sElemRow; OUString sElemTab; OUString sElemP; sal_Int32 nOpenRow; sal_Int32 nProgressCount; sal_uInt16 nCurrentTable; bool bHasRowHeader; bool bRowHeaderOpen; bool mbShowProgress; sal_Int32 GetNumberFormatStyleIndex(sal_Int32 nNumFmt) const; void CollectSharedData(sal_Int32& nTableCount, sal_Int32& nShapesCount); void CollectShapesAutoStyles(const sal_Int32 nTableCount); void WriteTablesView(const com::sun::star::uno::Any& aTableView); void WriteView(const com::sun::star::uno::Any& aView); virtual void _ExportFontDecls(); virtual void _ExportStyles( sal_Bool bUsed ); virtual void _ExportAutoStyles(); virtual void _ExportMasterStyles(); virtual void SetBodyAttributes(); virtual void _ExportContent(); virtual void _ExportMeta(); void CollectInternalShape( ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape > xShape ); com::sun::star::table::CellRangeAddress GetEndAddress(const com::sun::star::uno::Reference<com::sun::star::sheet::XSpreadsheet>& xTable, const sal_Int32 nTable); // ScMyEmptyDatabaseRangesContainer GetEmptyDatabaseRanges(); void GetAreaLinks( com::sun::star::uno::Reference< com::sun::star::sheet::XSpreadsheetDocument>& xSpreadDoc, ScMyAreaLinksContainer& rAreaLinks ); void GetDetectiveOpList( ScMyDetectiveOpContainer& rDetOp ); void WriteSingleColumn(const sal_Int32 nRepeatColumns, const sal_Int32 nStyleIndex, const sal_Int32 nIndex, const bool bIsAutoStyle, const bool bIsVisible); void WriteColumn(const sal_Int32 nColumn, const sal_Int32 nRepeatColumns, const sal_Int32 nStyleIndex, const bool bIsVisible); void OpenHeaderColumn(); void CloseHeaderColumn(); void ExportColumns(const sal_Int32 nTable, const com::sun::star::table::CellRangeAddress& aColumnHeaderRange, const bool bHasColumnHeader); void ExportExternalRefCacheStyles(); void ExportCellTextAutoStyles(sal_Int32 nTable); void ExportFormatRanges(const sal_Int32 nStartCol, const sal_Int32 nStartRow, const sal_Int32 nEndCol, const sal_Int32 nEndRow, const sal_Int32 nSheet); void WriteRowContent(); void WriteRowStartTag(sal_Int32 nRow, const sal_Int32 nIndex, const sal_Int32 nEmptyRows, bool bHidden, bool bFiltered); void OpenHeaderRows(); void CloseHeaderRows(); void OpenNewRow(const sal_Int32 nIndex, const sal_Int32 nStartRow, const sal_Int32 nEmptyRows, bool bHidden, bool bFiltered); void OpenAndCloseRow(const sal_Int32 nIndex, const sal_Int32 nStartRow, const sal_Int32 nEmptyRows, bool bHidden, bool bFiltered); void OpenRow(const sal_Int32 nTable, const sal_Int32 nStartRow, const sal_Int32 nRepeatRow, ScXMLCachedRowAttrAccess& rRowAttr); void CloseRow(const sal_Int32 nRow); void GetColumnRowHeader(bool& bHasColumnHeader, com::sun::star::table::CellRangeAddress& aColumnHeaderRange, bool& bHasRowHeader, com::sun::star::table::CellRangeAddress& aRowHeaderRange, OUString& rPrintRanges) const; void FillFieldGroup(ScOutlineArray* pFields, ScMyOpenCloseColumnRowGroup* pGroups); void FillColumnRowGroups(); bool GetMerged (const com::sun::star::table::CellRangeAddress* pCellRange, const com::sun::star::uno::Reference <com::sun::star::sheet::XSpreadsheet>& xTable); void WriteTable(sal_Int32 nTable, const ::com::sun::star::uno::Reference< ::com::sun::star::sheet::XSpreadsheet>& xTable); void WriteCell(ScMyCell& aCell, sal_Int32 nEqualCellCount); void WriteEditCell(const EditTextObject* pText); void WriteMultiLineFormulaResult(const ScFormulaCell* pCell); void WriteAreaLink(const ScMyCell& rMyCell); void WriteAnnotation(ScMyCell& rMyCell); void WriteDetective(const ScMyCell& rMyCell); void ExportShape(const com::sun::star::uno::Reference < com::sun::star::drawing::XShape >& xShape, com::sun::star::awt::Point* pPoint); void WriteShapes(const ScMyCell& rMyCell); void WriteTableShapes(); void SetRepeatAttribute(sal_Int32 nEqualCellCount, bool bIncProgress); bool IsCellTypeEqual (const ScMyCell& aCell1, const ScMyCell& aCell2) const; bool IsEditCell(ScMyCell& rCell) const; bool IsCellEqual(ScMyCell& aCell1, ScMyCell& aCell2); void WriteCalculationSettings(const com::sun::star::uno::Reference <com::sun::star::sheet::XSpreadsheetDocument>& xSpreadDoc); void WriteTableSource(); void WriteScenario(); // core implementation void WriteTheLabelRanges(const com::sun::star::uno::Reference< com::sun::star::sheet::XSpreadsheetDocument >& xSpreadDoc); void WriteLabelRanges( const com::sun::star::uno::Reference< com::sun::star::container::XIndexAccess >& xRangesIAccess, bool bColumn ); void WriteNamedExpressions(); void WriteNamedRange(ScRangeName* pRangeName); void ExportConditionalFormat(SCTAB nTab); void WriteExternalRefCaches(); void WriteConsolidation(); // core implementation void CollectUserDefinedNamespaces(const SfxItemPool* pPool, sal_uInt16 nAttrib); void AddStyleFromCells( const com::sun::star::uno::Reference< com::sun::star::beans::XPropertySet >& xProperties, const com::sun::star::uno::Reference< com::sun::star::sheet::XSpreadsheet >& xTable, sal_Int32 nTable, const OUString* pOldName ); void AddStyleFromColumn( const com::sun::star::uno::Reference< com::sun::star::beans::XPropertySet >& xColumnProperties, const OUString* pOldName, sal_Int32& rIndex, bool& rIsVisible ); void AddStyleFromRow( const com::sun::star::uno::Reference< com::sun::star::beans::XPropertySet >& xRowProperties, const OUString* pOldName, sal_Int32& rIndex ); void IncrementProgressBar(bool bFlush, sal_Int32 nInc = 1); void CopySourceStream( sal_Int32 nStartOffset, sal_Int32 nEndOffset, sal_Int32& rNewStart, sal_Int32& rNewEnd ); const ScXMLEditAttributeMap& GetEditAttributeMap() const; protected: virtual SvXMLAutoStylePoolP* CreateAutoStylePool(); virtual XMLPageExport* CreatePageExport(); virtual XMLShapeExport* CreateShapeExport(); virtual XMLFontAutoStylePool* CreateFontAutoStylePool(); public: ScXMLExport( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > xContext, const sal_uInt16 nExportFlag); virtual ~ScXMLExport(); static sal_Int16 GetFieldUnit(); inline ScDocument* GetDocument() { return pDoc; } inline const ScDocument* GetDocument() const { return pDoc; } bool IsMatrix (const ScAddress& aCell, com::sun::star::table::CellRangeAddress& aCellAddress, bool& bIsFirst) const; UniReference < XMLPropertySetMapper > GetCellStylesPropertySetMapper() { return xCellStylesPropertySetMapper; } UniReference < XMLPropertySetMapper > GetTableStylesPropertySetMapper() { return xTableStylesPropertySetMapper; } void SetSourceStream( const com::sun::star::uno::Reference<com::sun::star::io::XInputStream>& xNewStream ); void GetChangeTrackViewSettings(com::sun::star::uno::Sequence<com::sun::star::beans::PropertyValue>& rProps); virtual void GetViewSettings(com::sun::star::uno::Sequence<com::sun::star::beans::PropertyValue>& rProps); virtual void GetConfigurationSettings(com::sun::star::uno::Sequence<com::sun::star::beans::PropertyValue>& rProps); virtual void exportAnnotationMeta( const com::sun::star::uno::Reference < com::sun::star::drawing::XShape >& xShape); void CreateSharedData(const sal_Int32 nTableCount); void SetSharedData(ScMySharedData* pTemp) { pSharedData = pTemp; } ScMySharedData* GetSharedData() { return pSharedData; } XMLNumberFormatAttributesExportHelper* GetNumberFormatAttributesExportHelper(); // Export the document. virtual sal_uInt32 exportDoc( enum ::xmloff::token::XMLTokenEnum eClass = ::xmloff::token::XML_TOKEN_INVALID ); // XExporter virtual void SAL_CALL setSourceDocument( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent >& xDoc ) throw(::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException); // XFilter virtual sal_Bool SAL_CALL filter( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& aDescriptor ) throw(::com::sun::star::uno::RuntimeException); virtual void SAL_CALL cancel() throw(::com::sun::star::uno::RuntimeException); // XInitialization virtual void SAL_CALL initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments ) throw(::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException); // XServiceInfo virtual OUString SAL_CALL getImplementationName( ) throw(::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL supportsService( const OUString& ServiceName ) throw(::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< OUString > SAL_CALL getSupportedServiceNames( ) throw(::com::sun::star::uno::RuntimeException); // XUnoTunnel virtual sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& aIdentifier ) throw(::com::sun::star::uno::RuntimeException); virtual void DisposingModel(); }; #endif /* vim:set shiftwidth=4 softtabstop=4 expandtab: */
/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: xmlfilti.cxx,v $ * * $Revision: 1.14 $ * * last change: $Author: kz $ $Date: 2006-07-21 12:53:01 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sc.hxx" // INCLUDE --------------------------------------------------------------- #include "xmlfilti.hxx" #include "xmlimprt.hxx" #include "docuno.hxx" #ifndef SC_CONVUNO_HXX #include "convuno.hxx" #endif #ifndef _SC_XMLCONVERTER_HXX #include "XMLConverter.hxx" #endif #include <xmloff/xmltkmap.hxx> #include <xmloff/nmspmap.hxx> #ifndef _XMLOFF_XMLTOKEN_HXX #include <xmloff/xmltoken.hxx> #endif using namespace com::sun::star; using namespace xmloff::token; //------------------------------------------------------------------ ScXMLFilterContext::ScXMLFilterContext( ScXMLImport& rImport, USHORT nPrfx, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList, ScXMLDatabaseRangeContext* pTempDatabaseRangeContext) : SvXMLImportContext( rImport, nPrfx, rLName ), bSkipDuplicates(sal_False), bUseRegularExpressions(sal_False), bConnectionOr(sal_True), bNextConnectionOr(sal_True), bCopyOutputData(sal_False), bConditionSourceRange(sal_False), aFilterFields(), pDatabaseRangeContext(pTempDatabaseRangeContext) { ScDocument* pDoc(GetScImport().GetDocument()); sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0; const SvXMLTokenMap& rAttrTokenMap = GetScImport().GetFilterAttrTokenMap(); for( sal_Int16 i=0; i < nAttrCount; ++i ) { const rtl::OUString& sAttrName(xAttrList->getNameByIndex( i )); rtl::OUString aLocalName; USHORT nPrefix = GetScImport().GetNamespaceMap().GetKeyByAttrName( sAttrName, &aLocalName ); const rtl::OUString& sValue(xAttrList->getValueByIndex( i )); switch( rAttrTokenMap.Get( nPrefix, aLocalName ) ) { case XML_TOK_FILTER_ATTR_TARGET_RANGE_ADDRESS : { ScRange aScRange; sal_Int32 nOffset(0); if (ScXMLConverter::GetRangeFromString( aScRange, sValue, pDoc, nOffset )) { ScUnoConversion::FillApiAddress( aOutputPosition, aScRange.aStart ); bCopyOutputData = sal_True; } } break; case XML_TOK_FILTER_ATTR_CONDITION_SOURCE_RANGE_ADDRESS : { sal_Int32 nOffset(0); if (ScXMLConverter::GetRangeFromString( aConditionSourceRangeAddress, sValue, pDoc, nOffset )) bConditionSourceRange = sal_True; } break; case XML_TOK_FILTER_ATTR_CONDITION_SOURCE : { // not supported by StarOffice } break; case XML_TOK_FILTER_ATTR_DISPLAY_DUPLICATES : { bSkipDuplicates = !IsXMLToken(sValue, XML_TRUE); } break; } } } ScXMLFilterContext::~ScXMLFilterContext() { } SvXMLImportContext *ScXMLFilterContext::CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList ) { SvXMLImportContext *pContext(0); const SvXMLTokenMap& rTokenMap(GetScImport().GetFilterElemTokenMap()); switch( rTokenMap.Get( nPrefix, rLName ) ) { case XML_TOK_FILTER_AND: { pContext = new ScXMLAndContext( GetScImport(), nPrefix, rLName, xAttrList, this); } break; case XML_TOK_FILTER_OR: { pContext = new ScXMLOrContext( GetScImport(), nPrefix, rLName, xAttrList, this); } break; case XML_TOK_FILTER_CONDITION: { pContext = new ScXMLConditionContext( GetScImport(), nPrefix, rLName, xAttrList, this); } break; } if( !pContext ) pContext = new SvXMLImportContext( GetImport(), nPrefix, rLName ); return pContext; } void ScXMLFilterContext::EndElement() { pDatabaseRangeContext->SetFilterUseRegularExpressions(bUseRegularExpressions); if (bCopyOutputData) { pDatabaseRangeContext->SetFilterOutputPosition(aOutputPosition); pDatabaseRangeContext->SetFilterCopyOutputData(bCopyOutputData); } else pDatabaseRangeContext->SetFilterCopyOutputData(sal_False); pDatabaseRangeContext->SetFilterIsCaseSensitive(bIsCaseSensitive); pDatabaseRangeContext->SetFilterSkipDuplicates(bSkipDuplicates); pDatabaseRangeContext->SetFilterFields(aFilterFields); if (bConditionSourceRange) pDatabaseRangeContext->SetFilterConditionSourceRangeAddress(aConditionSourceRangeAddress); } ScXMLAndContext::ScXMLAndContext( ScXMLImport& rImport, USHORT nPrfx, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList, ScXMLFilterContext* pTempFilterContext) : SvXMLImportContext( rImport, nPrfx, rLName ), pFilterContext(pTempFilterContext) { pFilterContext->OpenConnection(sal_False); } ScXMLAndContext::~ScXMLAndContext() { } SvXMLImportContext *ScXMLAndContext::CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList ) { SvXMLImportContext *pContext(0); const SvXMLTokenMap& rTokenMap(GetScImport().GetFilterElemTokenMap()); switch( rTokenMap.Get( nPrefix, rLName ) ) { case XML_TOK_FILTER_OR: { // not supported in StarOffice } break; case XML_TOK_FILTER_CONDITION: { pContext = new ScXMLConditionContext( GetScImport(), nPrefix, rLName, xAttrList, pFilterContext); } break; } if( !pContext ) pContext = new SvXMLImportContext( GetImport(), nPrefix, rLName ); return pContext; } void ScXMLAndContext::EndElement() { pFilterContext->CloseConnection(); } ScXMLOrContext::ScXMLOrContext( ScXMLImport& rImport, USHORT nPrfx, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList, ScXMLFilterContext* pTempFilterContext) : SvXMLImportContext( rImport, nPrfx, rLName ), pFilterContext(pTempFilterContext) { pFilterContext->OpenConnection(sal_True); } ScXMLOrContext::~ScXMLOrContext() { } SvXMLImportContext *ScXMLOrContext::CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList ) { SvXMLImportContext *pContext(0); const SvXMLTokenMap& rTokenMap(GetScImport().GetFilterElemTokenMap()); switch( rTokenMap.Get( nPrefix, rLName ) ) { case XML_TOK_FILTER_AND: { pContext = new ScXMLAndContext( GetScImport(), nPrefix, rLName, xAttrList, pFilterContext); } break; case XML_TOK_FILTER_CONDITION: { pContext = new ScXMLConditionContext( GetScImport(), nPrefix, rLName, xAttrList, pFilterContext); } break; } if( !pContext ) pContext = new SvXMLImportContext( GetImport(), nPrefix, rLName ); return pContext; } void ScXMLOrContext::EndElement() { pFilterContext->CloseConnection(); } ScXMLConditionContext::ScXMLConditionContext( ScXMLImport& rImport, USHORT nPrfx, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList, ScXMLFilterContext* pTempFilterContext) : SvXMLImportContext( rImport, nPrfx, rLName ), bIsCaseSensitive(sal_False), pFilterContext(pTempFilterContext) { sDataType = GetXMLToken(XML_TEXT); sal_Int16 nAttrCount(xAttrList.is() ? xAttrList->getLength() : 0); const SvXMLTokenMap& rAttrTokenMap(GetScImport().GetFilterConditionAttrTokenMap()); for( sal_Int16 i=0; i < nAttrCount; ++i ) { const rtl::OUString& sAttrName(xAttrList->getNameByIndex( i )); rtl::OUString aLocalName; USHORT nPrefix = GetScImport().GetNamespaceMap().GetKeyByAttrName( sAttrName, &aLocalName ); const rtl::OUString& sValue(xAttrList->getValueByIndex( i )); switch( rAttrTokenMap.Get( nPrefix, aLocalName ) ) { case XML_TOK_CONDITION_ATTR_FIELD_NUMBER : { nField = sValue.toInt32(); } break; case XML_TOK_CONDITION_ATTR_CASE_SENSITIVE : { bIsCaseSensitive = IsXMLToken(sValue, XML_TRUE); } break; case XML_TOK_CONDITION_ATTR_DATA_TYPE : { sDataType = sValue; } break; case XML_TOK_CONDITION_ATTR_VALUE : { sConditionValue = sValue; } break; case XML_TOK_CONDITION_ATTR_OPERATOR : { sOperator = sValue; } break; } } } ScXMLConditionContext::~ScXMLConditionContext() { } SvXMLImportContext *ScXMLConditionContext::CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList ) { return new SvXMLImportContext( GetImport(), nPrefix, rLName ); } void ScXMLConditionContext::getOperatorXML(const rtl::OUString sTempOperator, sheet::FilterOperator& aFilterOperator, sal_Bool& bUseRegularExpressions) const { bUseRegularExpressions = sal_False; if (IsXMLToken(sTempOperator, XML_MATCH)) { bUseRegularExpressions = sal_True; aFilterOperator = sheet::FilterOperator_EQUAL; } else if (IsXMLToken(sTempOperator, XML_NOMATCH)) { bUseRegularExpressions = sal_True; aFilterOperator = sheet::FilterOperator_NOT_EQUAL; } else if (sTempOperator.compareToAscii("=") == 0) aFilterOperator = sheet::FilterOperator_EQUAL; else if (sTempOperator.compareToAscii("!=") == 0) aFilterOperator = sheet::FilterOperator_NOT_EQUAL; else if (IsXMLToken(sTempOperator, XML_BOTTOM_PERCENT)) aFilterOperator = sheet::FilterOperator_BOTTOM_PERCENT; else if (IsXMLToken(sTempOperator, XML_BOTTOM_VALUES)) aFilterOperator = sheet::FilterOperator_BOTTOM_VALUES; else if (IsXMLToken(sTempOperator, XML_EMPTY)) aFilterOperator = sheet::FilterOperator_EMPTY; else if (sTempOperator.compareToAscii(">") == 0) aFilterOperator = sheet::FilterOperator_GREATER; else if (sTempOperator.compareToAscii(">=") == 0) aFilterOperator = sheet::FilterOperator_GREATER_EQUAL; else if (sTempOperator.compareToAscii("<") == 0) aFilterOperator = sheet::FilterOperator_LESS; else if (sTempOperator.compareToAscii("<=") == 0) aFilterOperator = sheet::FilterOperator_LESS_EQUAL; else if (IsXMLToken(sTempOperator, XML_NOEMPTY)) aFilterOperator = sheet::FilterOperator_NOT_EMPTY; else if (IsXMLToken(sTempOperator, XML_TOP_PERCENT)) aFilterOperator = sheet::FilterOperator_TOP_PERCENT; else if (IsXMLToken(sTempOperator, XML_TOP_VALUES)) aFilterOperator = sheet::FilterOperator_TOP_VALUES; } void ScXMLConditionContext::EndElement() { sheet::TableFilterField aFilterField; if (pFilterContext->GetConnection()) aFilterField.Connection = sheet::FilterConnection_OR; else aFilterField.Connection = sheet::FilterConnection_AND; pFilterContext->SetIsCaseSensitive(bIsCaseSensitive); sal_Bool bUseRegularExpressions; getOperatorXML(sOperator, aFilterField.Operator, bUseRegularExpressions); pFilterContext->SetUseRegularExpressions(bUseRegularExpressions); aFilterField.Field = nField; if (IsXMLToken(sDataType, XML_NUMBER)) { aFilterField.NumericValue = sConditionValue.toDouble(); aFilterField.IsNumeric = sal_True; } else { aFilterField.StringValue = sConditionValue; aFilterField.IsNumeric = sal_False; } pFilterContext->AddFilterField(aFilterField); } //========================================================================== ScXMLDPFilterContext::ScXMLDPFilterContext( ScXMLImport& rImport, USHORT nPrfx, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList, ScXMLDataPilotTableContext* pTempDataPilotTableContext) : SvXMLImportContext( rImport, nPrfx, rLName ), bSkipDuplicates(sal_False), bUseRegularExpressions(sal_False), bConnectionOr(sal_True), bNextConnectionOr(sal_True), bCopyOutputData(sal_False), bConditionSourceRange(sal_False), aFilterFields(), nFilterFieldCount(0), pDataPilotTable(pTempDataPilotTableContext) { ScDocument* pDoc(GetScImport().GetDocument()); sal_Int16 nAttrCount(xAttrList.is() ? xAttrList->getLength() : 0); const SvXMLTokenMap& rAttrTokenMap(GetScImport().GetFilterAttrTokenMap()); for( sal_Int16 i=0; i < nAttrCount; ++i ) { const rtl::OUString& sAttrName(xAttrList->getNameByIndex( i )); rtl::OUString aLocalName; USHORT nPrefix(GetScImport().GetNamespaceMap().GetKeyByAttrName( sAttrName, &aLocalName )); const rtl::OUString& sValue(xAttrList->getValueByIndex( i )); switch( rAttrTokenMap.Get( nPrefix, aLocalName ) ) { case XML_TOK_FILTER_ATTR_TARGET_RANGE_ADDRESS : { ScRange aScRange; sal_Int32 nOffset(0); if (ScXMLConverter::GetRangeFromString( aScRange, sValue, pDoc, nOffset )) { aOutputPosition = aScRange.aStart; bCopyOutputData = sal_True; } } break; case XML_TOK_FILTER_ATTR_CONDITION_SOURCE_RANGE_ADDRESS : { sal_Int32 nOffset(0); if(ScXMLConverter::GetRangeFromString( aConditionSourceRangeAddress, sValue, pDoc, nOffset )) bConditionSourceRange = sal_True; } break; case XML_TOK_FILTER_ATTR_CONDITION_SOURCE : { // not supported by StarOffice } break; case XML_TOK_FILTER_ATTR_DISPLAY_DUPLICATES : { bSkipDuplicates = !IsXMLToken(sValue, XML_TRUE); } break; } } } ScXMLDPFilterContext::~ScXMLDPFilterContext() { } SvXMLImportContext *ScXMLDPFilterContext::CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList ) { SvXMLImportContext *pContext(0); const SvXMLTokenMap& rTokenMap(GetScImport().GetFilterElemTokenMap()); switch( rTokenMap.Get( nPrefix, rLName ) ) { case XML_TOK_FILTER_AND: { pContext = new ScXMLDPAndContext( GetScImport(), nPrefix, rLName, xAttrList, this); } break; case XML_TOK_FILTER_OR: { pContext = new ScXMLDPOrContext( GetScImport(), nPrefix, rLName, xAttrList, this); } break; case XML_TOK_FILTER_CONDITION: { pContext = new ScXMLDPConditionContext( GetScImport(), nPrefix, rLName, xAttrList, this); } break; } if( !pContext ) pContext = new SvXMLImportContext( GetImport(), nPrefix, rLName ); return pContext; } void ScXMLDPFilterContext::EndElement() { aFilterFields.bRegExp = bUseRegularExpressions; aFilterFields.bCaseSens = bIsCaseSensitive; aFilterFields.bDuplicate = !bSkipDuplicates; // pDataPilotTable->SetFilterUseRegularExpressions(bUseRegularExpressions); if (bCopyOutputData) { pDataPilotTable->SetFilterOutputPosition(aOutputPosition); pDataPilotTable->SetFilterCopyOutputData(bCopyOutputData); } else pDataPilotTable->SetFilterCopyOutputData(sal_False); // pDataPilotTable->SetFilterIsCaseSensitive(bIsCaseSensitive); // pDataPilotTable->SetFilterSkipDuplicates(bSkipDuplicates); pDataPilotTable->SetSourceQueryParam(aFilterFields); if (bConditionSourceRange) pDataPilotTable->SetFilterSourceRange(aConditionSourceRangeAddress); } void ScXMLDPFilterContext::AddFilterField (const ScQueryEntry& aFilterField) { aFilterFields.Resize(nFilterFieldCount + 1); ScQueryEntry& rEntry(aFilterFields.GetEntry(nFilterFieldCount)); rEntry = aFilterField; rEntry.bDoQuery = sal_True; ++nFilterFieldCount; } ScXMLDPAndContext::ScXMLDPAndContext( ScXMLImport& rImport, USHORT nPrfx, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList, ScXMLDPFilterContext* pTempFilterContext) : SvXMLImportContext( rImport, nPrfx, rLName ) { pFilterContext = pTempFilterContext; pFilterContext->OpenConnection(sal_False); } ScXMLDPAndContext::~ScXMLDPAndContext() { } SvXMLImportContext *ScXMLDPAndContext::CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList ) { SvXMLImportContext *pContext(0); const SvXMLTokenMap& rTokenMap(GetScImport().GetFilterElemTokenMap()); switch( rTokenMap.Get( nPrefix, rLName ) ) { case XML_TOK_FILTER_OR: { // not supported in StarOffice } break; case XML_TOK_FILTER_CONDITION: { pContext = new ScXMLDPConditionContext( GetScImport(), nPrefix, rLName, xAttrList, pFilterContext); } break; } if( !pContext ) pContext = new SvXMLImportContext( GetImport(), nPrefix, rLName ); return pContext; } void ScXMLDPAndContext::EndElement() { pFilterContext->CloseConnection(); } ScXMLDPOrContext::ScXMLDPOrContext( ScXMLImport& rImport, USHORT nPrfx, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList, ScXMLDPFilterContext* pTempFilterContext) : SvXMLImportContext( rImport, nPrfx, rLName ), pFilterContext(pTempFilterContext) { pFilterContext->OpenConnection(sal_True); } ScXMLDPOrContext::~ScXMLDPOrContext() { } SvXMLImportContext *ScXMLDPOrContext::CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList ) { SvXMLImportContext *pContext(0); const SvXMLTokenMap& rTokenMap(GetScImport().GetFilterElemTokenMap()); switch( rTokenMap.Get( nPrefix, rLName ) ) { case XML_TOK_FILTER_AND: { pContext = new ScXMLDPAndContext( GetScImport(), nPrefix, rLName, xAttrList, pFilterContext); } break; case XML_TOK_FILTER_CONDITION: { pContext = new ScXMLDPConditionContext( GetScImport(), nPrefix, rLName, xAttrList, pFilterContext); } break; } if( !pContext ) pContext = new SvXMLImportContext( GetImport(), nPrefix, rLName ); return pContext; } void ScXMLDPOrContext::EndElement() { pFilterContext->CloseConnection(); } ScXMLDPConditionContext::ScXMLDPConditionContext( ScXMLImport& rImport, USHORT nPrfx, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList, ScXMLDPFilterContext* pTempFilterContext) : SvXMLImportContext( rImport, nPrfx, rLName ), bIsCaseSensitive(sal_False), sDataType(GetXMLToken(XML_TEXT)), pFilterContext(pTempFilterContext) { sal_Int16 nAttrCount(xAttrList.is() ? xAttrList->getLength() : 0); const SvXMLTokenMap& rAttrTokenMap(GetScImport().GetFilterConditionAttrTokenMap()); for( sal_Int16 i=0; i < nAttrCount; ++i ) { const rtl::OUString& sAttrName(xAttrList->getNameByIndex( i )); rtl::OUString aLocalName; USHORT nPrefix(GetScImport().GetNamespaceMap().GetKeyByAttrName( sAttrName, &aLocalName )); const rtl::OUString& sValue(xAttrList->getValueByIndex( i )); switch( rAttrTokenMap.Get( nPrefix, aLocalName ) ) { case XML_TOK_CONDITION_ATTR_FIELD_NUMBER : { nField = sValue.toInt32(); } break; case XML_TOK_CONDITION_ATTR_CASE_SENSITIVE : { bIsCaseSensitive = IsXMLToken(sValue, XML_TRUE); } break; case XML_TOK_CONDITION_ATTR_DATA_TYPE : { sDataType = sValue; } break; case XML_TOK_CONDITION_ATTR_VALUE : { sConditionValue = sValue; } break; case XML_TOK_CONDITION_ATTR_OPERATOR : { sOperator = sValue; } break; } } } ScXMLDPConditionContext::~ScXMLDPConditionContext() { } SvXMLImportContext *ScXMLDPConditionContext::CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList ) { return new SvXMLImportContext( GetImport(), nPrefix, rLName ); } void ScXMLDPConditionContext::getOperatorXML(const rtl::OUString sTempOperator, ScQueryOp& aFilterOperator, sal_Bool& bUseRegularExpressions, double& dVal) const { bUseRegularExpressions = sal_False; if (IsXMLToken(sTempOperator, XML_MATCH)) { bUseRegularExpressions = sal_True; aFilterOperator = SC_EQUAL; } else if (IsXMLToken(sTempOperator, XML_NOMATCH)) { bUseRegularExpressions = sal_True; aFilterOperator = SC_NOT_EQUAL; } else if (sTempOperator.compareToAscii("=") == 0) aFilterOperator = SC_EQUAL; else if (sTempOperator.compareToAscii("!=") == 0) aFilterOperator = SC_NOT_EQUAL; else if (IsXMLToken(sTempOperator, XML_BOTTOM_PERCENT)) aFilterOperator = SC_BOTPERC; else if (IsXMLToken(sTempOperator, XML_BOTTOM_VALUES)) aFilterOperator = SC_BOTVAL; else if (IsXMLToken(sTempOperator, XML_EMPTY)) dVal = SC_EMPTYFIELDS; else if (sTempOperator.compareToAscii(">") == 0) aFilterOperator = SC_GREATER; else if (sTempOperator.compareToAscii(">=") == 0) aFilterOperator = SC_GREATER_EQUAL; else if (sTempOperator.compareToAscii("<") == 0) aFilterOperator = SC_LESS; else if (sTempOperator.compareToAscii("<=") == 0) aFilterOperator = SC_LESS_EQUAL; else if (IsXMLToken(sTempOperator, XML_NOEMPTY)) dVal = SC_NONEMPTYFIELDS; else if (IsXMLToken(sTempOperator, XML_TOP_PERCENT)) aFilterOperator = SC_TOPPERC; else if (IsXMLToken(sTempOperator, XML_TOP_VALUES)) aFilterOperator = SC_TOPVAL; } void ScXMLDPConditionContext::EndElement() { ScQueryEntry aFilterField; if (pFilterContext->GetConnection()) aFilterField.eConnect = SC_OR; else aFilterField.eConnect = SC_AND; pFilterContext->SetIsCaseSensitive(bIsCaseSensitive); sal_Bool bUseRegularExpressions; double dVal(0.0); getOperatorXML(sOperator, aFilterField.eOp, bUseRegularExpressions, dVal); pFilterContext->SetUseRegularExpressions(bUseRegularExpressions); aFilterField.nField = nField; if (IsXMLToken(sDataType, XML_NUMBER)) { aFilterField.nVal = sConditionValue.toDouble(); *aFilterField.pStr = sConditionValue; aFilterField.bQueryByString = sal_False; if (dVal != 0.0) { aFilterField.nVal = dVal; *aFilterField.pStr = EMPTY_STRING; } } else { aFilterField.pStr = new String(sConditionValue); aFilterField.bQueryByString = sal_True; aFilterField.nVal = 0; } pFilterContext->AddFilterField(aFilterField); } INTEGRATION: CWS calcwarnings (1.14.108); FILE MERGED 2006/12/13 10:30:19 nn 1.14.108.2: #i69284# warning-free: filter/xml, unxlngi6 2006/12/01 13:29:19 nn 1.14.108.1: #i69284# warning-free: filter/xml, wntmsci10 /************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: xmlfilti.cxx,v $ * * $Revision: 1.15 $ * * last change: $Author: vg $ $Date: 2007-02-27 12:51:01 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sc.hxx" // INCLUDE --------------------------------------------------------------- #include "xmlfilti.hxx" #include "xmlimprt.hxx" #include "docuno.hxx" #ifndef SC_CONVUNO_HXX #include "convuno.hxx" #endif #ifndef _SC_XMLCONVERTER_HXX #include "XMLConverter.hxx" #endif #include <xmloff/xmltkmap.hxx> #include <xmloff/nmspmap.hxx> #ifndef _XMLOFF_XMLTOKEN_HXX #include <xmloff/xmltoken.hxx> #endif using namespace com::sun::star; using namespace xmloff::token; //------------------------------------------------------------------ ScXMLFilterContext::ScXMLFilterContext( ScXMLImport& rImport, USHORT nPrfx, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList, ScXMLDatabaseRangeContext* pTempDatabaseRangeContext) : SvXMLImportContext( rImport, nPrfx, rLName ), pDatabaseRangeContext(pTempDatabaseRangeContext), aFilterFields(), bSkipDuplicates(sal_False), bCopyOutputData(sal_False), bUseRegularExpressions(sal_False), bConnectionOr(sal_True), bNextConnectionOr(sal_True), bConditionSourceRange(sal_False) { ScDocument* pDoc(GetScImport().GetDocument()); sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0; const SvXMLTokenMap& rAttrTokenMap = GetScImport().GetFilterAttrTokenMap(); for( sal_Int16 i=0; i < nAttrCount; ++i ) { const rtl::OUString& sAttrName(xAttrList->getNameByIndex( i )); rtl::OUString aLocalName; USHORT nPrefix = GetScImport().GetNamespaceMap().GetKeyByAttrName( sAttrName, &aLocalName ); const rtl::OUString& sValue(xAttrList->getValueByIndex( i )); switch( rAttrTokenMap.Get( nPrefix, aLocalName ) ) { case XML_TOK_FILTER_ATTR_TARGET_RANGE_ADDRESS : { ScRange aScRange; sal_Int32 nOffset(0); if (ScXMLConverter::GetRangeFromString( aScRange, sValue, pDoc, nOffset )) { ScUnoConversion::FillApiAddress( aOutputPosition, aScRange.aStart ); bCopyOutputData = sal_True; } } break; case XML_TOK_FILTER_ATTR_CONDITION_SOURCE_RANGE_ADDRESS : { sal_Int32 nOffset(0); if (ScXMLConverter::GetRangeFromString( aConditionSourceRangeAddress, sValue, pDoc, nOffset )) bConditionSourceRange = sal_True; } break; case XML_TOK_FILTER_ATTR_CONDITION_SOURCE : { // not supported by StarOffice } break; case XML_TOK_FILTER_ATTR_DISPLAY_DUPLICATES : { bSkipDuplicates = !IsXMLToken(sValue, XML_TRUE); } break; } } } ScXMLFilterContext::~ScXMLFilterContext() { } SvXMLImportContext *ScXMLFilterContext::CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList ) { SvXMLImportContext *pContext(0); const SvXMLTokenMap& rTokenMap(GetScImport().GetFilterElemTokenMap()); switch( rTokenMap.Get( nPrefix, rLName ) ) { case XML_TOK_FILTER_AND: { pContext = new ScXMLAndContext( GetScImport(), nPrefix, rLName, xAttrList, this); } break; case XML_TOK_FILTER_OR: { pContext = new ScXMLOrContext( GetScImport(), nPrefix, rLName, xAttrList, this); } break; case XML_TOK_FILTER_CONDITION: { pContext = new ScXMLConditionContext( GetScImport(), nPrefix, rLName, xAttrList, this); } break; } if( !pContext ) pContext = new SvXMLImportContext( GetImport(), nPrefix, rLName ); return pContext; } void ScXMLFilterContext::EndElement() { pDatabaseRangeContext->SetFilterUseRegularExpressions(bUseRegularExpressions); if (bCopyOutputData) { pDatabaseRangeContext->SetFilterOutputPosition(aOutputPosition); pDatabaseRangeContext->SetFilterCopyOutputData(bCopyOutputData); } else pDatabaseRangeContext->SetFilterCopyOutputData(sal_False); pDatabaseRangeContext->SetFilterIsCaseSensitive(bIsCaseSensitive); pDatabaseRangeContext->SetFilterSkipDuplicates(bSkipDuplicates); pDatabaseRangeContext->SetFilterFields(aFilterFields); if (bConditionSourceRange) pDatabaseRangeContext->SetFilterConditionSourceRangeAddress(aConditionSourceRangeAddress); } ScXMLAndContext::ScXMLAndContext( ScXMLImport& rImport, USHORT nPrfx, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& /* xAttrList */, ScXMLFilterContext* pTempFilterContext) : SvXMLImportContext( rImport, nPrfx, rLName ), pFilterContext(pTempFilterContext) { pFilterContext->OpenConnection(sal_False); } ScXMLAndContext::~ScXMLAndContext() { } SvXMLImportContext *ScXMLAndContext::CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList ) { SvXMLImportContext *pContext(0); const SvXMLTokenMap& rTokenMap(GetScImport().GetFilterElemTokenMap()); switch( rTokenMap.Get( nPrefix, rLName ) ) { case XML_TOK_FILTER_OR: { // not supported in StarOffice } break; case XML_TOK_FILTER_CONDITION: { pContext = new ScXMLConditionContext( GetScImport(), nPrefix, rLName, xAttrList, pFilterContext); } break; } if( !pContext ) pContext = new SvXMLImportContext( GetImport(), nPrefix, rLName ); return pContext; } void ScXMLAndContext::EndElement() { pFilterContext->CloseConnection(); } ScXMLOrContext::ScXMLOrContext( ScXMLImport& rImport, USHORT nPrfx, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& /* xAttrList */, ScXMLFilterContext* pTempFilterContext) : SvXMLImportContext( rImport, nPrfx, rLName ), pFilterContext(pTempFilterContext) { pFilterContext->OpenConnection(sal_True); } ScXMLOrContext::~ScXMLOrContext() { } SvXMLImportContext *ScXMLOrContext::CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList ) { SvXMLImportContext *pContext(0); const SvXMLTokenMap& rTokenMap(GetScImport().GetFilterElemTokenMap()); switch( rTokenMap.Get( nPrefix, rLName ) ) { case XML_TOK_FILTER_AND: { pContext = new ScXMLAndContext( GetScImport(), nPrefix, rLName, xAttrList, pFilterContext); } break; case XML_TOK_FILTER_CONDITION: { pContext = new ScXMLConditionContext( GetScImport(), nPrefix, rLName, xAttrList, pFilterContext); } break; } if( !pContext ) pContext = new SvXMLImportContext( GetImport(), nPrefix, rLName ); return pContext; } void ScXMLOrContext::EndElement() { pFilterContext->CloseConnection(); } ScXMLConditionContext::ScXMLConditionContext( ScXMLImport& rImport, USHORT nPrfx, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList, ScXMLFilterContext* pTempFilterContext) : SvXMLImportContext( rImport, nPrfx, rLName ), pFilterContext(pTempFilterContext), bIsCaseSensitive(sal_False) { sDataType = GetXMLToken(XML_TEXT); sal_Int16 nAttrCount(xAttrList.is() ? xAttrList->getLength() : 0); const SvXMLTokenMap& rAttrTokenMap(GetScImport().GetFilterConditionAttrTokenMap()); for( sal_Int16 i=0; i < nAttrCount; ++i ) { const rtl::OUString& sAttrName(xAttrList->getNameByIndex( i )); rtl::OUString aLocalName; USHORT nPrefix = GetScImport().GetNamespaceMap().GetKeyByAttrName( sAttrName, &aLocalName ); const rtl::OUString& sValue(xAttrList->getValueByIndex( i )); switch( rAttrTokenMap.Get( nPrefix, aLocalName ) ) { case XML_TOK_CONDITION_ATTR_FIELD_NUMBER : { nField = sValue.toInt32(); } break; case XML_TOK_CONDITION_ATTR_CASE_SENSITIVE : { bIsCaseSensitive = IsXMLToken(sValue, XML_TRUE); } break; case XML_TOK_CONDITION_ATTR_DATA_TYPE : { sDataType = sValue; } break; case XML_TOK_CONDITION_ATTR_VALUE : { sConditionValue = sValue; } break; case XML_TOK_CONDITION_ATTR_OPERATOR : { sOperator = sValue; } break; } } } ScXMLConditionContext::~ScXMLConditionContext() { } SvXMLImportContext *ScXMLConditionContext::CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& /* xAttrList */ ) { return new SvXMLImportContext( GetImport(), nPrefix, rLName ); } void ScXMLConditionContext::getOperatorXML(const rtl::OUString sTempOperator, sheet::FilterOperator& aFilterOperator, sal_Bool& bUseRegularExpressions) const { bUseRegularExpressions = sal_False; if (IsXMLToken(sTempOperator, XML_MATCH)) { bUseRegularExpressions = sal_True; aFilterOperator = sheet::FilterOperator_EQUAL; } else if (IsXMLToken(sTempOperator, XML_NOMATCH)) { bUseRegularExpressions = sal_True; aFilterOperator = sheet::FilterOperator_NOT_EQUAL; } else if (sTempOperator.compareToAscii("=") == 0) aFilterOperator = sheet::FilterOperator_EQUAL; else if (sTempOperator.compareToAscii("!=") == 0) aFilterOperator = sheet::FilterOperator_NOT_EQUAL; else if (IsXMLToken(sTempOperator, XML_BOTTOM_PERCENT)) aFilterOperator = sheet::FilterOperator_BOTTOM_PERCENT; else if (IsXMLToken(sTempOperator, XML_BOTTOM_VALUES)) aFilterOperator = sheet::FilterOperator_BOTTOM_VALUES; else if (IsXMLToken(sTempOperator, XML_EMPTY)) aFilterOperator = sheet::FilterOperator_EMPTY; else if (sTempOperator.compareToAscii(">") == 0) aFilterOperator = sheet::FilterOperator_GREATER; else if (sTempOperator.compareToAscii(">=") == 0) aFilterOperator = sheet::FilterOperator_GREATER_EQUAL; else if (sTempOperator.compareToAscii("<") == 0) aFilterOperator = sheet::FilterOperator_LESS; else if (sTempOperator.compareToAscii("<=") == 0) aFilterOperator = sheet::FilterOperator_LESS_EQUAL; else if (IsXMLToken(sTempOperator, XML_NOEMPTY)) aFilterOperator = sheet::FilterOperator_NOT_EMPTY; else if (IsXMLToken(sTempOperator, XML_TOP_PERCENT)) aFilterOperator = sheet::FilterOperator_TOP_PERCENT; else if (IsXMLToken(sTempOperator, XML_TOP_VALUES)) aFilterOperator = sheet::FilterOperator_TOP_VALUES; } void ScXMLConditionContext::EndElement() { sheet::TableFilterField aFilterField; if (pFilterContext->GetConnection()) aFilterField.Connection = sheet::FilterConnection_OR; else aFilterField.Connection = sheet::FilterConnection_AND; pFilterContext->SetIsCaseSensitive(bIsCaseSensitive); sal_Bool bUseRegularExpressions; getOperatorXML(sOperator, aFilterField.Operator, bUseRegularExpressions); pFilterContext->SetUseRegularExpressions(bUseRegularExpressions); aFilterField.Field = nField; if (IsXMLToken(sDataType, XML_NUMBER)) { aFilterField.NumericValue = sConditionValue.toDouble(); aFilterField.IsNumeric = sal_True; } else { aFilterField.StringValue = sConditionValue; aFilterField.IsNumeric = sal_False; } pFilterContext->AddFilterField(aFilterField); } //========================================================================== ScXMLDPFilterContext::ScXMLDPFilterContext( ScXMLImport& rImport, USHORT nPrfx, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList, ScXMLDataPilotTableContext* pTempDataPilotTableContext) : SvXMLImportContext( rImport, nPrfx, rLName ), pDataPilotTable(pTempDataPilotTableContext), aFilterFields(), nFilterFieldCount(0), bSkipDuplicates(sal_False), bCopyOutputData(sal_False), bUseRegularExpressions(sal_False), bConnectionOr(sal_True), bNextConnectionOr(sal_True), bConditionSourceRange(sal_False) { ScDocument* pDoc(GetScImport().GetDocument()); sal_Int16 nAttrCount(xAttrList.is() ? xAttrList->getLength() : 0); const SvXMLTokenMap& rAttrTokenMap(GetScImport().GetFilterAttrTokenMap()); for( sal_Int16 i=0; i < nAttrCount; ++i ) { const rtl::OUString& sAttrName(xAttrList->getNameByIndex( i )); rtl::OUString aLocalName; USHORT nPrefix(GetScImport().GetNamespaceMap().GetKeyByAttrName( sAttrName, &aLocalName )); const rtl::OUString& sValue(xAttrList->getValueByIndex( i )); switch( rAttrTokenMap.Get( nPrefix, aLocalName ) ) { case XML_TOK_FILTER_ATTR_TARGET_RANGE_ADDRESS : { ScRange aScRange; sal_Int32 nOffset(0); if (ScXMLConverter::GetRangeFromString( aScRange, sValue, pDoc, nOffset )) { aOutputPosition = aScRange.aStart; bCopyOutputData = sal_True; } } break; case XML_TOK_FILTER_ATTR_CONDITION_SOURCE_RANGE_ADDRESS : { sal_Int32 nOffset(0); if(ScXMLConverter::GetRangeFromString( aConditionSourceRangeAddress, sValue, pDoc, nOffset )) bConditionSourceRange = sal_True; } break; case XML_TOK_FILTER_ATTR_CONDITION_SOURCE : { // not supported by StarOffice } break; case XML_TOK_FILTER_ATTR_DISPLAY_DUPLICATES : { bSkipDuplicates = !IsXMLToken(sValue, XML_TRUE); } break; } } } ScXMLDPFilterContext::~ScXMLDPFilterContext() { } SvXMLImportContext *ScXMLDPFilterContext::CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList ) { SvXMLImportContext *pContext(0); const SvXMLTokenMap& rTokenMap(GetScImport().GetFilterElemTokenMap()); switch( rTokenMap.Get( nPrefix, rLName ) ) { case XML_TOK_FILTER_AND: { pContext = new ScXMLDPAndContext( GetScImport(), nPrefix, rLName, xAttrList, this); } break; case XML_TOK_FILTER_OR: { pContext = new ScXMLDPOrContext( GetScImport(), nPrefix, rLName, xAttrList, this); } break; case XML_TOK_FILTER_CONDITION: { pContext = new ScXMLDPConditionContext( GetScImport(), nPrefix, rLName, xAttrList, this); } break; } if( !pContext ) pContext = new SvXMLImportContext( GetImport(), nPrefix, rLName ); return pContext; } void ScXMLDPFilterContext::EndElement() { aFilterFields.bRegExp = bUseRegularExpressions; aFilterFields.bCaseSens = bIsCaseSensitive; aFilterFields.bDuplicate = !bSkipDuplicates; // pDataPilotTable->SetFilterUseRegularExpressions(bUseRegularExpressions); if (bCopyOutputData) { pDataPilotTable->SetFilterOutputPosition(aOutputPosition); pDataPilotTable->SetFilterCopyOutputData(bCopyOutputData); } else pDataPilotTable->SetFilterCopyOutputData(sal_False); // pDataPilotTable->SetFilterIsCaseSensitive(bIsCaseSensitive); // pDataPilotTable->SetFilterSkipDuplicates(bSkipDuplicates); pDataPilotTable->SetSourceQueryParam(aFilterFields); if (bConditionSourceRange) pDataPilotTable->SetFilterSourceRange(aConditionSourceRangeAddress); } void ScXMLDPFilterContext::AddFilterField (const ScQueryEntry& aFilterField) { aFilterFields.Resize(nFilterFieldCount + 1); ScQueryEntry& rEntry(aFilterFields.GetEntry(nFilterFieldCount)); rEntry = aFilterField; rEntry.bDoQuery = sal_True; ++nFilterFieldCount; } ScXMLDPAndContext::ScXMLDPAndContext( ScXMLImport& rImport, USHORT nPrfx, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& /* xAttrList */, ScXMLDPFilterContext* pTempFilterContext) : SvXMLImportContext( rImport, nPrfx, rLName ) { pFilterContext = pTempFilterContext; pFilterContext->OpenConnection(sal_False); } ScXMLDPAndContext::~ScXMLDPAndContext() { } SvXMLImportContext *ScXMLDPAndContext::CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList ) { SvXMLImportContext *pContext(0); const SvXMLTokenMap& rTokenMap(GetScImport().GetFilterElemTokenMap()); switch( rTokenMap.Get( nPrefix, rLName ) ) { case XML_TOK_FILTER_OR: { // not supported in StarOffice } break; case XML_TOK_FILTER_CONDITION: { pContext = new ScXMLDPConditionContext( GetScImport(), nPrefix, rLName, xAttrList, pFilterContext); } break; } if( !pContext ) pContext = new SvXMLImportContext( GetImport(), nPrefix, rLName ); return pContext; } void ScXMLDPAndContext::EndElement() { pFilterContext->CloseConnection(); } ScXMLDPOrContext::ScXMLDPOrContext( ScXMLImport& rImport, USHORT nPrfx, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& /* xAttrList */, ScXMLDPFilterContext* pTempFilterContext) : SvXMLImportContext( rImport, nPrfx, rLName ), pFilterContext(pTempFilterContext) { pFilterContext->OpenConnection(sal_True); } ScXMLDPOrContext::~ScXMLDPOrContext() { } SvXMLImportContext *ScXMLDPOrContext::CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList ) { SvXMLImportContext *pContext(0); const SvXMLTokenMap& rTokenMap(GetScImport().GetFilterElemTokenMap()); switch( rTokenMap.Get( nPrefix, rLName ) ) { case XML_TOK_FILTER_AND: { pContext = new ScXMLDPAndContext( GetScImport(), nPrefix, rLName, xAttrList, pFilterContext); } break; case XML_TOK_FILTER_CONDITION: { pContext = new ScXMLDPConditionContext( GetScImport(), nPrefix, rLName, xAttrList, pFilterContext); } break; } if( !pContext ) pContext = new SvXMLImportContext( GetImport(), nPrefix, rLName ); return pContext; } void ScXMLDPOrContext::EndElement() { pFilterContext->CloseConnection(); } ScXMLDPConditionContext::ScXMLDPConditionContext( ScXMLImport& rImport, USHORT nPrfx, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList, ScXMLDPFilterContext* pTempFilterContext) : SvXMLImportContext( rImport, nPrfx, rLName ), pFilterContext(pTempFilterContext), sDataType(GetXMLToken(XML_TEXT)), bIsCaseSensitive(sal_False) { sal_Int16 nAttrCount(xAttrList.is() ? xAttrList->getLength() : 0); const SvXMLTokenMap& rAttrTokenMap(GetScImport().GetFilterConditionAttrTokenMap()); for( sal_Int16 i=0; i < nAttrCount; ++i ) { const rtl::OUString& sAttrName(xAttrList->getNameByIndex( i )); rtl::OUString aLocalName; USHORT nPrefix(GetScImport().GetNamespaceMap().GetKeyByAttrName( sAttrName, &aLocalName )); const rtl::OUString& sValue(xAttrList->getValueByIndex( i )); switch( rAttrTokenMap.Get( nPrefix, aLocalName ) ) { case XML_TOK_CONDITION_ATTR_FIELD_NUMBER : { nField = sValue.toInt32(); } break; case XML_TOK_CONDITION_ATTR_CASE_SENSITIVE : { bIsCaseSensitive = IsXMLToken(sValue, XML_TRUE); } break; case XML_TOK_CONDITION_ATTR_DATA_TYPE : { sDataType = sValue; } break; case XML_TOK_CONDITION_ATTR_VALUE : { sConditionValue = sValue; } break; case XML_TOK_CONDITION_ATTR_OPERATOR : { sOperator = sValue; } break; } } } ScXMLDPConditionContext::~ScXMLDPConditionContext() { } SvXMLImportContext *ScXMLDPConditionContext::CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& /* xAttrList */ ) { return new SvXMLImportContext( GetImport(), nPrefix, rLName ); } void ScXMLDPConditionContext::getOperatorXML(const rtl::OUString sTempOperator, ScQueryOp& aFilterOperator, sal_Bool& bUseRegularExpressions, double& dVal) const { bUseRegularExpressions = sal_False; if (IsXMLToken(sTempOperator, XML_MATCH)) { bUseRegularExpressions = sal_True; aFilterOperator = SC_EQUAL; } else if (IsXMLToken(sTempOperator, XML_NOMATCH)) { bUseRegularExpressions = sal_True; aFilterOperator = SC_NOT_EQUAL; } else if (sTempOperator.compareToAscii("=") == 0) aFilterOperator = SC_EQUAL; else if (sTempOperator.compareToAscii("!=") == 0) aFilterOperator = SC_NOT_EQUAL; else if (IsXMLToken(sTempOperator, XML_BOTTOM_PERCENT)) aFilterOperator = SC_BOTPERC; else if (IsXMLToken(sTempOperator, XML_BOTTOM_VALUES)) aFilterOperator = SC_BOTVAL; else if (IsXMLToken(sTempOperator, XML_EMPTY)) dVal = SC_EMPTYFIELDS; else if (sTempOperator.compareToAscii(">") == 0) aFilterOperator = SC_GREATER; else if (sTempOperator.compareToAscii(">=") == 0) aFilterOperator = SC_GREATER_EQUAL; else if (sTempOperator.compareToAscii("<") == 0) aFilterOperator = SC_LESS; else if (sTempOperator.compareToAscii("<=") == 0) aFilterOperator = SC_LESS_EQUAL; else if (IsXMLToken(sTempOperator, XML_NOEMPTY)) dVal = SC_NONEMPTYFIELDS; else if (IsXMLToken(sTempOperator, XML_TOP_PERCENT)) aFilterOperator = SC_TOPPERC; else if (IsXMLToken(sTempOperator, XML_TOP_VALUES)) aFilterOperator = SC_TOPVAL; } void ScXMLDPConditionContext::EndElement() { ScQueryEntry aFilterField; if (pFilterContext->GetConnection()) aFilterField.eConnect = SC_OR; else aFilterField.eConnect = SC_AND; pFilterContext->SetIsCaseSensitive(bIsCaseSensitive); sal_Bool bUseRegularExpressions; double dVal(0.0); getOperatorXML(sOperator, aFilterField.eOp, bUseRegularExpressions, dVal); pFilterContext->SetUseRegularExpressions(bUseRegularExpressions); aFilterField.nField = nField; if (IsXMLToken(sDataType, XML_NUMBER)) { aFilterField.nVal = sConditionValue.toDouble(); *aFilterField.pStr = sConditionValue; aFilterField.bQueryByString = sal_False; if (dVal != 0.0) { aFilterField.nVal = dVal; *aFilterField.pStr = EMPTY_STRING; } } else { aFilterField.pStr = new String(sConditionValue); aFilterField.bQueryByString = sal_True; aFilterField.nVal = 0; } pFilterContext->AddFilterField(aFilterField); }
/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: condfrmt.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: kz $ $Date: 2006-07-21 13:14:12 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sc.hxx" #ifndef _SFXDISPATCH_HXX //autogen #include <sfx2/dispatch.hxx> #endif #include "tabvwsh.hxx" #include "reffact.hxx" #include "conditio.hxx" #include "stlpool.hxx" #include "uiitems.hxx" #include "document.hxx" #include "scresid.hxx" #include "condfrmt.hrc" #include "globstr.hrc" #define _CONDFRMT_CXX #include "condfrmt.hxx" #undef _CONDFRMT_CXX //============================================================================ // class ScConditionalFormat //---------------------------------------------------------------------------- // Konstruktor ScConditionalFormatDlg::ScConditionalFormatDlg( SfxBindings* pB, SfxChildWindow* pCW, Window* pParent, ScDocument* pCurDoc, const ScConditionalFormat* pCurrentFormat ) : ScAnyRefDlg ( pB, pCW, pParent, RID_SCDLG_CONDFORMAT ), pDoc ( pCurDoc ), aCbxCond1 ( this, ScResId( CBX_COND1 ) ), aLbCond11 ( this, ScResId( LB_COND1_1 ) ), aLbCond12 ( this, ScResId( LB_COND1_2 ) ), aEdtCond11 ( this, ScResId( EDT_COND1_1 ) ), aRbCond11 ( this, ScResId( RB_COND1_1 ), &aEdtCond11 ), aFtCond1And ( this, ScResId( FT_COND1_AND ) ), aEdtCond12 ( this, ScResId( EDT_COND1_2 ) ), aRbCond12 ( this, ScResId( RB_COND1_2 ), &aEdtCond12 ), aFtCond1Template ( this, ScResId( FT_COND1_TEMPLATE ) ), aLbCond1Template ( this, ScResId( LB_COND1_TEMPLATE ) ), aFlSep1 ( this, ScResId( FL_SEP1 ) ), aCbxCond2 ( this, ScResId( CBX_COND2 ) ), aLbCond21 ( this, ScResId( LB_COND2_1 ) ), aLbCond22 ( this, ScResId( LB_COND2_2 ) ), aEdtCond21 ( this, ScResId( EDT_COND2_1 ) ), aRbCond21 ( this, ScResId( RB_COND2_1 ), &aEdtCond21 ), aFtCond2And ( this, ScResId( FT_COND2_AND ) ), aEdtCond22 ( this, ScResId( EDT_COND2_2 ) ), aRbCond22 ( this, ScResId( RB_COND2_2 ), &aEdtCond22 ), aFtCond2Template ( this, ScResId( FT_COND2_TEMPLATE ) ), aLbCond2Template ( this, ScResId( LB_COND2_TEMPLATE ) ), aFlSep2 ( this, ScResId( FL_SEP2 ) ), aCbxCond3 ( this, ScResId( CBX_COND3 ) ), aLbCond31 ( this, ScResId( LB_COND3_1 ) ), aLbCond32 ( this, ScResId( LB_COND3_2 ) ), aEdtCond31 ( this, ScResId( EDT_COND3_1 ) ), aRbCond31 ( this, ScResId( RB_COND3_1 ), &aEdtCond31 ), aFtCond3And ( this, ScResId( FT_COND3_AND ) ), aEdtCond32 ( this, ScResId( EDT_COND3_2 ) ), aRbCond32 ( this, ScResId( RB_COND3_2 ), &aEdtCond32 ), aFtCond3Template ( this, ScResId( FT_COND3_TEMPLATE ) ), aLbCond3Template ( this, ScResId( LB_COND3_TEMPLATE ) ), aBtnOk ( this, ScResId( BTN_OK ) ), aBtnCancel ( this, ScResId( BTN_CANCEL ) ), aBtnHelp ( this, ScResId( BTN_HELP ) ), pEdActive ( NULL ), bDlgLostFocus ( FALSE ) { Point aPos; String aName; SfxStyleSheetBase* pStyle; FreeResource(); // Handler setzen aCbxCond1.SetClickHdl ( LINK( this, ScConditionalFormatDlg, ClickCond1Hdl ) ); aLbCond11.SetSelectHdl( LINK( this, ScConditionalFormatDlg, ChangeCond11Hdl ) ); aLbCond12.SetSelectHdl( LINK( this, ScConditionalFormatDlg, ChangeCond12Hdl ) ); aCbxCond2.SetClickHdl ( LINK( this, ScConditionalFormatDlg, ClickCond2Hdl ) ); aLbCond21.SetSelectHdl( LINK( this, ScConditionalFormatDlg, ChangeCond21Hdl ) ); aLbCond22.SetSelectHdl( LINK( this, ScConditionalFormatDlg, ChangeCond22Hdl ) ); aCbxCond3.SetClickHdl ( LINK( this, ScConditionalFormatDlg, ClickCond3Hdl ) ); aLbCond31.SetSelectHdl( LINK( this, ScConditionalFormatDlg, ChangeCond31Hdl ) ); aLbCond32.SetSelectHdl( LINK( this, ScConditionalFormatDlg, ChangeCond32Hdl ) ); aBtnOk.SetClickHdl ( LINK( this, ScConditionalFormatDlg, BtnHdl ) ); //? aBtnCancel.SetClickHdl( LINK( this, ScConditionalFormatDlg, BtnHdl ) ); Link aLink = LINK( this, ScConditionalFormatDlg, GetFocusHdl ); aEdtCond11.SetGetFocusHdl( aLink ); aEdtCond12.SetGetFocusHdl( aLink ); aEdtCond21.SetGetFocusHdl( aLink ); aEdtCond22.SetGetFocusHdl( aLink ); aEdtCond31.SetGetFocusHdl( aLink ); aEdtCond32.SetGetFocusHdl( aLink ); aRbCond11.SetGetFocusHdl( aLink ); aRbCond12.SetGetFocusHdl( aLink ); aRbCond21.SetGetFocusHdl( aLink ); aRbCond22.SetGetFocusHdl( aLink ); aRbCond31.SetGetFocusHdl( aLink ); aRbCond32.SetGetFocusHdl( aLink ); aLink = LINK( this, ScConditionalFormatDlg, LoseFocusHdl ); aEdtCond11.SetLoseFocusHdl( aLink ); aEdtCond12.SetLoseFocusHdl( aLink ); aEdtCond21.SetLoseFocusHdl( aLink ); aEdtCond22.SetLoseFocusHdl( aLink ); aEdtCond31.SetLoseFocusHdl( aLink ); aEdtCond32.SetLoseFocusHdl( aLink ); aRbCond11.SetLoseFocusHdl( aLink ); aRbCond12.SetLoseFocusHdl( aLink ); aRbCond21.SetLoseFocusHdl( aLink ); aRbCond22.SetLoseFocusHdl( aLink ); aRbCond31.SetLoseFocusHdl( aLink ); aRbCond32.SetLoseFocusHdl( aLink ); // Condition 1 aCond1Pos1 = aLbCond12.GetPosPixel(); // Position Edit ohne Listbox aCond1Pos2 = aEdtCond11.GetPosPixel(); // Position Edit mit Listbox aRBtn1Pos1 = aRbCond11.GetPosPixel(); aRBtn1Pos2 = aRbCond12.GetPosPixel(); aPos = aEdtCond12.GetPosPixel(); aPos.X() += aEdtCond12.GetSizePixel().Width(); // rechter Rand aCond1Size3 = aEdtCond11.GetSizePixel(); aCond1Size2 = Size( aPos.X() - aCond1Pos2.X(), aCond1Size3.Height() ); aCond1Size1 = Size( aPos.X() - aCond1Pos1.X(), aCond1Size3.Height() ); aCbxCond1.Check(); aLbCond11.SelectEntryPos( 0 ); aLbCond12.SelectEntryPos( 0 ); // Condition 2 aCond2Pos1 = aLbCond22.GetPosPixel(); // Position Edit ohne Listbox aCond2Pos2 = aEdtCond21.GetPosPixel(); // Position Edit mit Listbox aRBtn2Pos1 = aRbCond21.GetPosPixel(); aRBtn2Pos2 = aRbCond22.GetPosPixel(); aPos = aEdtCond22.GetPosPixel(); aPos.X() += aEdtCond22.GetSizePixel().Width(); // rechter Rand aCond2Size3 = aEdtCond21.GetSizePixel(); aCond2Size2 = Size( aPos.X() - aCond2Pos2.X(), aCond2Size3.Height() ); aCond2Size1 = Size( aPos.X() - aCond2Pos1.X(), aCond2Size3.Height() ); aCbxCond2.Check( FALSE ); aLbCond21.SelectEntryPos( 0 ); aLbCond22.SelectEntryPos( 0 ); // Condition 3 aCond3Pos1 = aLbCond32.GetPosPixel(); // Position Edit ohne Listbox aCond3Pos2 = aEdtCond31.GetPosPixel(); // Position Edit mit Listbox aRBtn3Pos1 = aRbCond31.GetPosPixel(); aRBtn3Pos2 = aRbCond32.GetPosPixel(); aPos = aEdtCond32.GetPosPixel(); aPos.X() += aEdtCond32.GetSizePixel().Width(); // rechter Rand aCond3Size3 = aEdtCond31.GetSizePixel(); aCond3Size2 = Size( aPos.X() - aCond3Pos2.X(), aCond3Size3.Height() ); aCond3Size1 = Size( aPos.X() - aCond3Pos1.X(), aCond3Size3.Height() ); aCbxCond3.Check( FALSE ); aLbCond31.SelectEntryPos( 0 ); aLbCond32.SelectEntryPos( 0 ); // Vorlagen aus pDoc holen SfxStyleSheetIterator aStyleIter( pDoc->GetStyleSheetPool(), SFX_STYLE_FAMILY_PARA ); for ( pStyle = aStyleIter.First(); pStyle; pStyle = aStyleIter.Next() ) { aName = pStyle->GetName(); aLbCond1Template.InsertEntry( aName ); aLbCond2Template.InsertEntry( aName ); aLbCond3Template.InsertEntry( aName ); } // Vorlagen eintragen //! pStyle = pDoc->GetSelectionStyle( /* ??? const ScMarkData& rMark ??? */ ); pStyle = NULL; //! if (pStyle) aName = pStyle->GetName(); else aName = ScGlobal::GetRscString(STR_STYLENAME_STANDARD); aLbCond1Template.SelectEntry( aName ); aLbCond2Template.SelectEntry( aName ); aLbCond3Template.SelectEntry( aName ); ScAddress aCurPos; ScTabViewShell* pViewShell = ScTabViewShell::GetActiveViewShell(); if (pViewShell) { ScViewData* pData = pViewShell->GetViewData(); aCurPos = ScAddress( pData->GetCurX(), pData->GetCurY(), pData->GetTabNo() ); } // Inhalt aus ConditionalFormat holen if ( pCurrentFormat ) { const ScCondFormatEntry* pEntry; if ( pCurrentFormat->Count() > 0 ) { pEntry= pCurrentFormat->GetEntry( 0 ); aEdtCond11.SetText( pEntry->GetExpression( aCurPos, 0 ) ); aLbCond1Template.SelectEntry( pEntry->GetStyle() ); ScConditionMode eMode = pEntry->GetOperation(); if ( eMode == SC_COND_DIRECT ) // via Formel { aLbCond11.SelectEntryPos( 1 ); ChangeCond11Hdl( NULL ); } else if ( eMode == SC_COND_NONE ) // ??? ; else // via Werte { aLbCond12.SelectEntryPos( eMode ); if ( ( eMode == SC_COND_BETWEEN ) || ( eMode == SC_COND_NOTBETWEEN ) ) aEdtCond12.SetText( pEntry->GetExpression( aCurPos, 1 ) ); } } if ( pCurrentFormat->Count() > 1 ) { aCbxCond2.Check( TRUE ); pEntry= pCurrentFormat->GetEntry( 1 ); aEdtCond21.SetText( pEntry->GetExpression( aCurPos, 0 ) ); aLbCond2Template.SelectEntry( pEntry->GetStyle() ); ScConditionMode eMode = pEntry->GetOperation(); if ( eMode == SC_COND_DIRECT ) // via Formel { aLbCond21.SelectEntryPos( 1 ); ChangeCond21Hdl( NULL ); } else if ( eMode == SC_COND_NONE ) // ??? ; else // via Werte { aLbCond22.SelectEntryPos( eMode ); if ( ( eMode == SC_COND_BETWEEN ) || ( eMode == SC_COND_NOTBETWEEN ) ) aEdtCond22.SetText( pEntry->GetExpression( aCurPos, 1 ) ); } } if ( pCurrentFormat->Count() > 2 ) { aCbxCond3.Check( TRUE ); pEntry= pCurrentFormat->GetEntry( 2 ); aEdtCond31.SetText( pEntry->GetExpression( aCurPos, 0 ) ); aLbCond3Template.SelectEntry( pEntry->GetStyle() ); ScConditionMode eMode = pEntry->GetOperation(); if ( eMode == SC_COND_DIRECT ) // via Formel { aLbCond31.SelectEntryPos( 1 ); ChangeCond31Hdl( NULL ); } else if ( eMode == SC_COND_NONE ) // ??? ; else // via Werte { aLbCond32.SelectEntryPos( eMode ); if ( ( eMode == SC_COND_BETWEEN ) || ( eMode == SC_COND_NOTBETWEEN ) ) aEdtCond32.SetText( pEntry->GetExpression( aCurPos, 1 ) ); } } } ClickCond1Hdl( NULL ); ClickCond2Hdl( NULL ); ClickCond3Hdl( NULL ); ChangeCond12Hdl( NULL ); ChangeCond22Hdl( NULL ); ChangeCond32Hdl( NULL ); aEdtCond11.GrabFocus(); pEdActive = &aEdtCond11; //@BugID 54702 Enablen/Disablen nur noch in Basisklasse //SFX_APPWINDOW->Enable(); // Ref-Feld hat Focus // SFX_APPWINDOW->Disable(); } //---------------------------------------------------------------------------- // Destruktor __EXPORT ScConditionalFormatDlg::~ScConditionalFormatDlg() { } //---------------------------------------------------------------------------- void ScConditionalFormatDlg::SetReference( const ScRange& rRef, ScDocument* pDoc ) { if ( pEdActive ) { if ( rRef.aStart != rRef.aEnd ) RefInputStart(pEdActive); String aStr; rRef.Format( aStr, SCR_ABS_3D, pDoc ); String aVal( pEdActive->GetText() ); Selection aSel( pEdActive->GetSelection() ); aSel.Justify(); aVal.Erase( (xub_StrLen)aSel.Min(), (xub_StrLen)aSel.Len() ); aVal.Insert( aStr, (xub_StrLen)aSel.Min() ); Selection aNewSel( aSel.Min(), aSel.Min()+aStr.Len() ); pEdActive->SetRefString( aVal ); pEdActive->SetSelection( aNewSel ); // pEdActive->SetModifyFlag(); } } //---------------------------------------------------------------------------- void ScConditionalFormatDlg::AddRefEntry() { if ( pEdActive ) { String aVal = pEdActive->GetText(); aVal += ';'; pEdActive->SetText(aVal); xub_StrLen nLen = aVal.Len(); pEdActive->SetSelection( Selection( nLen, nLen ) ); // pEdActive->SetModifyFlag(); } } //---------------------------------------------------------------------------- BOOL ScConditionalFormatDlg::IsRefInputMode() { return (pEdActive != NULL); } //---------------------------------------------------------------------------- void ScConditionalFormatDlg::SetActive() { if ( bDlgLostFocus ) { bDlgLostFocus = FALSE; if( pEdActive ) pEdActive->GrabFocus(); } else GrabFocus(); RefInputDone(); } //---------------------------------------------------------------------------- // Holt die ausgewaehlte bedingte Formatierung ab void ScConditionalFormatDlg::GetConditionalFormat( ScConditionalFormat& rCndFmt ) { ScConditionMode eOper; String sExpr1; String sExpr2; String sStyle; ScAddress aCurPos; ScTabViewShell* pViewShell = ScTabViewShell::GetActiveViewShell(); if (pViewShell) { ScViewData* pData = pViewShell->GetViewData(); aCurPos = ScAddress( pData->GetCurX(), pData->GetCurY(), pData->GetTabNo() ); } if ( aCbxCond1.IsChecked() ) { if ( aLbCond11.GetSelectEntryPos() == 1 ) // via Formel eOper = SC_COND_DIRECT; else eOper = (ScConditionMode)aLbCond12.GetSelectEntryPos(); sExpr1 = aEdtCond11.GetText(); sExpr2 = aEdtCond12.GetText(); sStyle = aLbCond1Template.GetSelectEntry(); ScCondFormatEntry aNewEntry( eOper, sExpr1, sExpr2, pDoc, aCurPos, sStyle ); rCndFmt.AddEntry( aNewEntry ); } if ( aCbxCond2.IsChecked() ) { if ( aLbCond21.GetSelectEntryPos() == 1 ) // via Formel??? eOper = SC_COND_DIRECT; else eOper = (ScConditionMode)aLbCond22.GetSelectEntryPos(); sExpr1 = aEdtCond21.GetText(); sExpr2 = aEdtCond22.GetText(); sStyle = aLbCond2Template.GetSelectEntry(); ScCondFormatEntry aNewEntry( eOper, sExpr1, sExpr2, pDoc, aCurPos, sStyle ); rCndFmt.AddEntry( aNewEntry ); } if ( aCbxCond3.IsChecked() ) { if ( aLbCond31.GetSelectEntryPos() == 1 ) // via Formel??? eOper = SC_COND_DIRECT; else eOper = (ScConditionMode)aLbCond32.GetSelectEntryPos(); sExpr1 = aEdtCond31.GetText(); sExpr2 = aEdtCond32.GetText(); sStyle = aLbCond3Template.GetSelectEntry(); ScCondFormatEntry aNewEntry( eOper, sExpr1, sExpr2, pDoc, aCurPos, sStyle ); rCndFmt.AddEntry( aNewEntry ); } } //---------------------------------------------------------------------------- // Zerstoert den Dialog BOOL ScConditionalFormatDlg::Close() { return DoClose( ScCondFormatDlgWrapper::GetChildWindowId() ); } //---------------------------------------------------------------------------- // Handler: //---------------------------------------------------------------------------- // Enabled/Disabled Condition1-Controls IMPL_LINK( ScConditionalFormatDlg, ClickCond1Hdl, void *, EMPTYARG ) { BOOL bChecked = aCbxCond1.IsChecked(); aLbCond11.Enable( bChecked ); aLbCond12.Enable( bChecked ); aEdtCond11.Enable( bChecked ); aRbCond11.Enable( bChecked ); aFtCond1And.Enable( bChecked ); aEdtCond12.Enable( bChecked ); aRbCond12.Enable( bChecked ); aFtCond1Template.Enable( bChecked ); aLbCond1Template.Enable( bChecked ); return( 0L ); } //---------------------------------------------------------------------------- // Zellwert/Formel IMPL_LINK( ScConditionalFormatDlg, ChangeCond11Hdl, void *, EMPTYARG ) { USHORT nPos = aLbCond11.GetSelectEntryPos(); if( nPos == 0 ) // Zellwert { aLbCond12.Show(); aEdtCond11.SetPosPixel( aCond1Pos2 ); } else // Formel { aLbCond12.Hide(); aFtCond1And.Hide(); aEdtCond12.Hide(); aRbCond12.Hide(); aRbCond11.SetPosPixel( aRBtn1Pos2 ); aEdtCond11.SetPosSizePixel( aCond1Pos1, aCond1Size1 ); } ChangeCond12Hdl( NULL ); return( 0L ); } //---------------------------------------------------------------------------- // zwischen, gleich, groesser, ... IMPL_LINK( ScConditionalFormatDlg, ChangeCond12Hdl, void *, EMPTYARG ) { if( aLbCond12.IsVisible() ) { USHORT nPos = aLbCond12.GetSelectEntryPos(); if( nPos == 6 || nPos == 7 ) // zwischen, n. zwischen { aEdtCond11.SetSizePixel( aCond1Size3 ); aRbCond11.SetPosPixel( aRBtn1Pos1 ); aFtCond1And.Show(); aEdtCond12.Show(); aRbCond12.Show(); } else // gleich, n. gleich ... { aEdtCond12.Hide(); aRbCond12.Hide(); aFtCond1And.Hide(); aRbCond11.SetPosPixel( aRBtn1Pos2 ); aEdtCond11.SetSizePixel( aCond1Size2 ); } } return( 0L ); } //---------------------------------------------------------------------------- // Enabled/Disabled Condition2-Controls IMPL_LINK( ScConditionalFormatDlg, ClickCond2Hdl, void *, EMPTYARG ) { BOOL bChecked = aCbxCond2.IsChecked(); aLbCond21.Enable( bChecked ); aLbCond22.Enable( bChecked ); aEdtCond21.Enable( bChecked ); aRbCond21.Enable( bChecked ); aFtCond2And.Enable( bChecked ); aEdtCond22.Enable( bChecked ); aRbCond22.Enable( bChecked ); aFtCond2Template.Enable( bChecked ); aLbCond2Template.Enable( bChecked ); return( 0L ); } //---------------------------------------------------------------------------- // Zellwert/Formel IMPL_LINK( ScConditionalFormatDlg, ChangeCond21Hdl, void *, EMPTYARG ) { USHORT nPos = aLbCond21.GetSelectEntryPos(); if( nPos == 0 ) // Zellwert { aLbCond22.Show(); aEdtCond21.SetPosPixel( aCond2Pos2 ); } else // Formel { aLbCond22.Hide(); aFtCond2And.Hide(); aEdtCond22.Hide(); aRbCond22.Hide(); aRbCond21.SetPosPixel( aRBtn2Pos2 ); aEdtCond21.SetPosSizePixel( aCond2Pos1, aCond2Size1 ); } ChangeCond22Hdl( NULL ); return( 0L ); } //---------------------------------------------------------------------------- // zwischen, gleich, groesser, ... IMPL_LINK( ScConditionalFormatDlg, ChangeCond22Hdl, void *, EMPTYARG ) { if( aLbCond22.IsVisible() ) { USHORT nPos = aLbCond22.GetSelectEntryPos(); if( nPos == 6 || nPos == 7 ) // zwischen, n. zwischen { aEdtCond21.SetSizePixel( aCond2Size3 ); aRbCond21.SetPosPixel( aRBtn2Pos1 ); aFtCond2And.Show(); aEdtCond22.Show(); aRbCond22.Show(); } else // gleich, n. gleich ... { aEdtCond22.Hide(); aRbCond22.Hide(); aFtCond2And.Hide(); aRbCond21.SetPosPixel( aRBtn2Pos2 ); aEdtCond21.SetSizePixel( aCond2Size2 ); } } return( 0L ); } //---------------------------------------------------------------------------- // Enabled/Disabled Condition3-Controls IMPL_LINK( ScConditionalFormatDlg, ClickCond3Hdl, void *, EMPTYARG ) { BOOL bChecked = aCbxCond3.IsChecked(); aLbCond31.Enable( bChecked ); aLbCond32.Enable( bChecked ); aEdtCond31.Enable( bChecked ); aRbCond31.Enable( bChecked ); aFtCond3And.Enable( bChecked ); aEdtCond32.Enable( bChecked ); aRbCond32.Enable( bChecked ); aFtCond3Template.Enable( bChecked ); aLbCond3Template.Enable( bChecked ); return( 0L ); } //---------------------------------------------------------------------------- // Zellwert/Formel IMPL_LINK( ScConditionalFormatDlg, ChangeCond31Hdl, void *, EMPTYARG ) { USHORT nPos = aLbCond31.GetSelectEntryPos(); if( nPos == 0 ) // Zellwert { aLbCond32.Show(); aEdtCond31.SetPosPixel( aCond3Pos2 ); } else // Formel { aLbCond32.Hide(); aFtCond3And.Hide(); aEdtCond32.Hide(); aRbCond32.Hide(); aRbCond31.SetPosPixel( aRBtn3Pos2 ); aEdtCond31.SetPosSizePixel( aCond3Pos1, aCond3Size1 ); } ChangeCond32Hdl( NULL ); return( 0L ); } //---------------------------------------------------------------------------- // zwischen, gleich, groesser, ... IMPL_LINK( ScConditionalFormatDlg, ChangeCond32Hdl, void *, EMPTYARG ) { if( aLbCond32.IsVisible() ) { USHORT nPos = aLbCond32.GetSelectEntryPos(); if( nPos == 6 || nPos == 7 ) // zwischen, n. zwischen { aEdtCond31.SetSizePixel( aCond3Size3 ); aRbCond31.SetPosPixel( aRBtn3Pos1 ); aFtCond3And.Show(); aEdtCond32.Show(); aRbCond32.Show(); } else // gleich, n. gleich ... { aEdtCond32.Hide(); aRbCond32.Hide(); aFtCond3And.Hide(); aRbCond31.SetPosPixel( aRBtn3Pos2 ); aEdtCond31.SetSizePixel( aCond3Size2 ); } } return( 0L ); } //---------------------------------------------------------------------------- IMPL_LINK( ScConditionalFormatDlg, GetFocusHdl, Control*, pCtrl ) { if( (pCtrl == (Control*)&aEdtCond11) || (pCtrl == (Control*)&aRbCond11) ) pEdActive = &aEdtCond11; else if( (pCtrl == (Control*)&aEdtCond12) || (pCtrl == (Control*)&aRbCond12) ) pEdActive = &aEdtCond12; else if( (pCtrl == (Control*)&aEdtCond21) || (pCtrl == (Control*)&aRbCond21) ) pEdActive = &aEdtCond21; else if( (pCtrl == (Control*)&aEdtCond22) || (pCtrl == (Control*)&aRbCond22) ) pEdActive = &aEdtCond22; else if( (pCtrl == (Control*)&aEdtCond31) || (pCtrl == (Control*)&aRbCond31) ) pEdActive = &aEdtCond31; else if( (pCtrl == (Control*)&aEdtCond32) || (pCtrl == (Control*)&aRbCond32) ) pEdActive = &aEdtCond32; else pEdActive = NULL; if( pEdActive ) pEdActive->SetSelection( Selection( 0, SELECTION_MAX ) ); return 0; } //---------------------------------------------------------------------------- IMPL_LINK( ScConditionalFormatDlg, LoseFocusHdl, Control*, pCtrl ) { bDlgLostFocus = !IsActive(); return 0; } //---------------------------------------------------------------------------- // [OK], [Cancel] IMPL_LINK( ScConditionalFormatDlg, BtnHdl, PushButton*, pBtn ) { if ( pBtn == &aBtnOk ) { ScConditionalFormat aCondFrmt( 0, pDoc ); GetConditionalFormat( aCondFrmt ); ScCondFrmtItem aOutItem( FID_CONDITIONAL_FORMAT, aCondFrmt ); SetDispatcherLock( FALSE ); SwitchToDocument(); GetBindings().GetDispatcher()->Execute( FID_CONDITIONAL_FORMAT, SFX_CALLMODE_SLOT | SFX_CALLMODE_RECORD, &aOutItem, 0L, 0L ); Close(); } else if ( pBtn == &aBtnCancel ) Close(); return( 0L ); } INTEGRATION: CWS scr1c1 (1.7.58); FILE MERGED 2006/09/07 14:20:55 jodygoldberg 1.7.58.1: Issue number: 20857 Submitted by: jodygoldberg Implements the the core changes to support parsing and generating cell/range references in different formats (XL R1C1/A1) along with some tools for using the new types. This adds two new functions XL_INDIRECT XL_ADDRESS but does _not_ connect them in the xls importer. Nor does the patch make any UI changes. Those will need to be discussed. The OOo parser/generator should not be impacted by the changes. /************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: condfrmt.cxx,v $ * * $Revision: 1.8 $ * * last change: $Author: ihi $ $Date: 2006-10-18 12:26:52 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sc.hxx" #ifndef _SFXDISPATCH_HXX //autogen #include <sfx2/dispatch.hxx> #endif #include "tabvwsh.hxx" #include "reffact.hxx" #include "conditio.hxx" #include "stlpool.hxx" #include "uiitems.hxx" #include "document.hxx" #include "scresid.hxx" #include "condfrmt.hrc" #include "globstr.hrc" #define _CONDFRMT_CXX #include "condfrmt.hxx" #undef _CONDFRMT_CXX //============================================================================ // class ScConditionalFormat //---------------------------------------------------------------------------- // Konstruktor ScConditionalFormatDlg::ScConditionalFormatDlg( SfxBindings* pB, SfxChildWindow* pCW, Window* pParent, ScDocument* pCurDoc, const ScConditionalFormat* pCurrentFormat ) : ScAnyRefDlg ( pB, pCW, pParent, RID_SCDLG_CONDFORMAT ), pDoc ( pCurDoc ), aCbxCond1 ( this, ScResId( CBX_COND1 ) ), aLbCond11 ( this, ScResId( LB_COND1_1 ) ), aLbCond12 ( this, ScResId( LB_COND1_2 ) ), aEdtCond11 ( this, ScResId( EDT_COND1_1 ) ), aRbCond11 ( this, ScResId( RB_COND1_1 ), &aEdtCond11 ), aFtCond1And ( this, ScResId( FT_COND1_AND ) ), aEdtCond12 ( this, ScResId( EDT_COND1_2 ) ), aRbCond12 ( this, ScResId( RB_COND1_2 ), &aEdtCond12 ), aFtCond1Template ( this, ScResId( FT_COND1_TEMPLATE ) ), aLbCond1Template ( this, ScResId( LB_COND1_TEMPLATE ) ), aFlSep1 ( this, ScResId( FL_SEP1 ) ), aCbxCond2 ( this, ScResId( CBX_COND2 ) ), aLbCond21 ( this, ScResId( LB_COND2_1 ) ), aLbCond22 ( this, ScResId( LB_COND2_2 ) ), aEdtCond21 ( this, ScResId( EDT_COND2_1 ) ), aRbCond21 ( this, ScResId( RB_COND2_1 ), &aEdtCond21 ), aFtCond2And ( this, ScResId( FT_COND2_AND ) ), aEdtCond22 ( this, ScResId( EDT_COND2_2 ) ), aRbCond22 ( this, ScResId( RB_COND2_2 ), &aEdtCond22 ), aFtCond2Template ( this, ScResId( FT_COND2_TEMPLATE ) ), aLbCond2Template ( this, ScResId( LB_COND2_TEMPLATE ) ), aFlSep2 ( this, ScResId( FL_SEP2 ) ), aCbxCond3 ( this, ScResId( CBX_COND3 ) ), aLbCond31 ( this, ScResId( LB_COND3_1 ) ), aLbCond32 ( this, ScResId( LB_COND3_2 ) ), aEdtCond31 ( this, ScResId( EDT_COND3_1 ) ), aRbCond31 ( this, ScResId( RB_COND3_1 ), &aEdtCond31 ), aFtCond3And ( this, ScResId( FT_COND3_AND ) ), aEdtCond32 ( this, ScResId( EDT_COND3_2 ) ), aRbCond32 ( this, ScResId( RB_COND3_2 ), &aEdtCond32 ), aFtCond3Template ( this, ScResId( FT_COND3_TEMPLATE ) ), aLbCond3Template ( this, ScResId( LB_COND3_TEMPLATE ) ), aBtnOk ( this, ScResId( BTN_OK ) ), aBtnCancel ( this, ScResId( BTN_CANCEL ) ), aBtnHelp ( this, ScResId( BTN_HELP ) ), pEdActive ( NULL ), bDlgLostFocus ( FALSE ) { Point aPos; String aName; SfxStyleSheetBase* pStyle; FreeResource(); // Handler setzen aCbxCond1.SetClickHdl ( LINK( this, ScConditionalFormatDlg, ClickCond1Hdl ) ); aLbCond11.SetSelectHdl( LINK( this, ScConditionalFormatDlg, ChangeCond11Hdl ) ); aLbCond12.SetSelectHdl( LINK( this, ScConditionalFormatDlg, ChangeCond12Hdl ) ); aCbxCond2.SetClickHdl ( LINK( this, ScConditionalFormatDlg, ClickCond2Hdl ) ); aLbCond21.SetSelectHdl( LINK( this, ScConditionalFormatDlg, ChangeCond21Hdl ) ); aLbCond22.SetSelectHdl( LINK( this, ScConditionalFormatDlg, ChangeCond22Hdl ) ); aCbxCond3.SetClickHdl ( LINK( this, ScConditionalFormatDlg, ClickCond3Hdl ) ); aLbCond31.SetSelectHdl( LINK( this, ScConditionalFormatDlg, ChangeCond31Hdl ) ); aLbCond32.SetSelectHdl( LINK( this, ScConditionalFormatDlg, ChangeCond32Hdl ) ); aBtnOk.SetClickHdl ( LINK( this, ScConditionalFormatDlg, BtnHdl ) ); //? aBtnCancel.SetClickHdl( LINK( this, ScConditionalFormatDlg, BtnHdl ) ); Link aLink = LINK( this, ScConditionalFormatDlg, GetFocusHdl ); aEdtCond11.SetGetFocusHdl( aLink ); aEdtCond12.SetGetFocusHdl( aLink ); aEdtCond21.SetGetFocusHdl( aLink ); aEdtCond22.SetGetFocusHdl( aLink ); aEdtCond31.SetGetFocusHdl( aLink ); aEdtCond32.SetGetFocusHdl( aLink ); aRbCond11.SetGetFocusHdl( aLink ); aRbCond12.SetGetFocusHdl( aLink ); aRbCond21.SetGetFocusHdl( aLink ); aRbCond22.SetGetFocusHdl( aLink ); aRbCond31.SetGetFocusHdl( aLink ); aRbCond32.SetGetFocusHdl( aLink ); aLink = LINK( this, ScConditionalFormatDlg, LoseFocusHdl ); aEdtCond11.SetLoseFocusHdl( aLink ); aEdtCond12.SetLoseFocusHdl( aLink ); aEdtCond21.SetLoseFocusHdl( aLink ); aEdtCond22.SetLoseFocusHdl( aLink ); aEdtCond31.SetLoseFocusHdl( aLink ); aEdtCond32.SetLoseFocusHdl( aLink ); aRbCond11.SetLoseFocusHdl( aLink ); aRbCond12.SetLoseFocusHdl( aLink ); aRbCond21.SetLoseFocusHdl( aLink ); aRbCond22.SetLoseFocusHdl( aLink ); aRbCond31.SetLoseFocusHdl( aLink ); aRbCond32.SetLoseFocusHdl( aLink ); // Condition 1 aCond1Pos1 = aLbCond12.GetPosPixel(); // Position Edit ohne Listbox aCond1Pos2 = aEdtCond11.GetPosPixel(); // Position Edit mit Listbox aRBtn1Pos1 = aRbCond11.GetPosPixel(); aRBtn1Pos2 = aRbCond12.GetPosPixel(); aPos = aEdtCond12.GetPosPixel(); aPos.X() += aEdtCond12.GetSizePixel().Width(); // rechter Rand aCond1Size3 = aEdtCond11.GetSizePixel(); aCond1Size2 = Size( aPos.X() - aCond1Pos2.X(), aCond1Size3.Height() ); aCond1Size1 = Size( aPos.X() - aCond1Pos1.X(), aCond1Size3.Height() ); aCbxCond1.Check(); aLbCond11.SelectEntryPos( 0 ); aLbCond12.SelectEntryPos( 0 ); // Condition 2 aCond2Pos1 = aLbCond22.GetPosPixel(); // Position Edit ohne Listbox aCond2Pos2 = aEdtCond21.GetPosPixel(); // Position Edit mit Listbox aRBtn2Pos1 = aRbCond21.GetPosPixel(); aRBtn2Pos2 = aRbCond22.GetPosPixel(); aPos = aEdtCond22.GetPosPixel(); aPos.X() += aEdtCond22.GetSizePixel().Width(); // rechter Rand aCond2Size3 = aEdtCond21.GetSizePixel(); aCond2Size2 = Size( aPos.X() - aCond2Pos2.X(), aCond2Size3.Height() ); aCond2Size1 = Size( aPos.X() - aCond2Pos1.X(), aCond2Size3.Height() ); aCbxCond2.Check( FALSE ); aLbCond21.SelectEntryPos( 0 ); aLbCond22.SelectEntryPos( 0 ); // Condition 3 aCond3Pos1 = aLbCond32.GetPosPixel(); // Position Edit ohne Listbox aCond3Pos2 = aEdtCond31.GetPosPixel(); // Position Edit mit Listbox aRBtn3Pos1 = aRbCond31.GetPosPixel(); aRBtn3Pos2 = aRbCond32.GetPosPixel(); aPos = aEdtCond32.GetPosPixel(); aPos.X() += aEdtCond32.GetSizePixel().Width(); // rechter Rand aCond3Size3 = aEdtCond31.GetSizePixel(); aCond3Size2 = Size( aPos.X() - aCond3Pos2.X(), aCond3Size3.Height() ); aCond3Size1 = Size( aPos.X() - aCond3Pos1.X(), aCond3Size3.Height() ); aCbxCond3.Check( FALSE ); aLbCond31.SelectEntryPos( 0 ); aLbCond32.SelectEntryPos( 0 ); // Vorlagen aus pDoc holen SfxStyleSheetIterator aStyleIter( pDoc->GetStyleSheetPool(), SFX_STYLE_FAMILY_PARA ); for ( pStyle = aStyleIter.First(); pStyle; pStyle = aStyleIter.Next() ) { aName = pStyle->GetName(); aLbCond1Template.InsertEntry( aName ); aLbCond2Template.InsertEntry( aName ); aLbCond3Template.InsertEntry( aName ); } // Vorlagen eintragen //! pStyle = pDoc->GetSelectionStyle( /* ??? const ScMarkData& rMark ??? */ ); pStyle = NULL; //! if (pStyle) aName = pStyle->GetName(); else aName = ScGlobal::GetRscString(STR_STYLENAME_STANDARD); aLbCond1Template.SelectEntry( aName ); aLbCond2Template.SelectEntry( aName ); aLbCond3Template.SelectEntry( aName ); ScAddress aCurPos; ScTabViewShell* pViewShell = ScTabViewShell::GetActiveViewShell(); if (pViewShell) { ScViewData* pData = pViewShell->GetViewData(); aCurPos = ScAddress( pData->GetCurX(), pData->GetCurY(), pData->GetTabNo() ); } // Inhalt aus ConditionalFormat holen if ( pCurrentFormat ) { const ScCondFormatEntry* pEntry; if ( pCurrentFormat->Count() > 0 ) { pEntry= pCurrentFormat->GetEntry( 0 ); aEdtCond11.SetText( pEntry->GetExpression( aCurPos, 0 ) ); aLbCond1Template.SelectEntry( pEntry->GetStyle() ); ScConditionMode eMode = pEntry->GetOperation(); if ( eMode == SC_COND_DIRECT ) // via Formel { aLbCond11.SelectEntryPos( 1 ); ChangeCond11Hdl( NULL ); } else if ( eMode == SC_COND_NONE ) // ??? ; else // via Werte { aLbCond12.SelectEntryPos( eMode ); if ( ( eMode == SC_COND_BETWEEN ) || ( eMode == SC_COND_NOTBETWEEN ) ) aEdtCond12.SetText( pEntry->GetExpression( aCurPos, 1 ) ); } } if ( pCurrentFormat->Count() > 1 ) { aCbxCond2.Check( TRUE ); pEntry= pCurrentFormat->GetEntry( 1 ); aEdtCond21.SetText( pEntry->GetExpression( aCurPos, 0 ) ); aLbCond2Template.SelectEntry( pEntry->GetStyle() ); ScConditionMode eMode = pEntry->GetOperation(); if ( eMode == SC_COND_DIRECT ) // via Formel { aLbCond21.SelectEntryPos( 1 ); ChangeCond21Hdl( NULL ); } else if ( eMode == SC_COND_NONE ) // ??? ; else // via Werte { aLbCond22.SelectEntryPos( eMode ); if ( ( eMode == SC_COND_BETWEEN ) || ( eMode == SC_COND_NOTBETWEEN ) ) aEdtCond22.SetText( pEntry->GetExpression( aCurPos, 1 ) ); } } if ( pCurrentFormat->Count() > 2 ) { aCbxCond3.Check( TRUE ); pEntry= pCurrentFormat->GetEntry( 2 ); aEdtCond31.SetText( pEntry->GetExpression( aCurPos, 0 ) ); aLbCond3Template.SelectEntry( pEntry->GetStyle() ); ScConditionMode eMode = pEntry->GetOperation(); if ( eMode == SC_COND_DIRECT ) // via Formel { aLbCond31.SelectEntryPos( 1 ); ChangeCond31Hdl( NULL ); } else if ( eMode == SC_COND_NONE ) // ??? ; else // via Werte { aLbCond32.SelectEntryPos( eMode ); if ( ( eMode == SC_COND_BETWEEN ) || ( eMode == SC_COND_NOTBETWEEN ) ) aEdtCond32.SetText( pEntry->GetExpression( aCurPos, 1 ) ); } } } ClickCond1Hdl( NULL ); ClickCond2Hdl( NULL ); ClickCond3Hdl( NULL ); ChangeCond12Hdl( NULL ); ChangeCond22Hdl( NULL ); ChangeCond32Hdl( NULL ); aEdtCond11.GrabFocus(); pEdActive = &aEdtCond11; //@BugID 54702 Enablen/Disablen nur noch in Basisklasse //SFX_APPWINDOW->Enable(); // Ref-Feld hat Focus // SFX_APPWINDOW->Disable(); } //---------------------------------------------------------------------------- // Destruktor __EXPORT ScConditionalFormatDlg::~ScConditionalFormatDlg() { } //---------------------------------------------------------------------------- void ScConditionalFormatDlg::SetReference( const ScRange& rRef, ScDocument* pDoc ) { if ( pEdActive ) { if ( rRef.aStart != rRef.aEnd ) RefInputStart(pEdActive); String aStr; rRef.Format( aStr, SCR_ABS_3D, pDoc, pDoc->GetAddressConvention () ); String aVal( pEdActive->GetText() ); Selection aSel( pEdActive->GetSelection() ); aSel.Justify(); aVal.Erase( (xub_StrLen)aSel.Min(), (xub_StrLen)aSel.Len() ); aVal.Insert( aStr, (xub_StrLen)aSel.Min() ); Selection aNewSel( aSel.Min(), aSel.Min()+aStr.Len() ); pEdActive->SetRefString( aVal ); pEdActive->SetSelection( aNewSel ); // pEdActive->SetModifyFlag(); } } //---------------------------------------------------------------------------- void ScConditionalFormatDlg::AddRefEntry() { if ( pEdActive ) { String aVal = pEdActive->GetText(); aVal += ';'; pEdActive->SetText(aVal); xub_StrLen nLen = aVal.Len(); pEdActive->SetSelection( Selection( nLen, nLen ) ); // pEdActive->SetModifyFlag(); } } //---------------------------------------------------------------------------- BOOL ScConditionalFormatDlg::IsRefInputMode() { return (pEdActive != NULL); } //---------------------------------------------------------------------------- void ScConditionalFormatDlg::SetActive() { if ( bDlgLostFocus ) { bDlgLostFocus = FALSE; if( pEdActive ) pEdActive->GrabFocus(); } else GrabFocus(); RefInputDone(); } //---------------------------------------------------------------------------- // Holt die ausgewaehlte bedingte Formatierung ab void ScConditionalFormatDlg::GetConditionalFormat( ScConditionalFormat& rCndFmt ) { ScConditionMode eOper; String sExpr1; String sExpr2; String sStyle; ScAddress aCurPos; ScTabViewShell* pViewShell = ScTabViewShell::GetActiveViewShell(); if (pViewShell) { ScViewData* pData = pViewShell->GetViewData(); aCurPos = ScAddress( pData->GetCurX(), pData->GetCurY(), pData->GetTabNo() ); } if ( aCbxCond1.IsChecked() ) { if ( aLbCond11.GetSelectEntryPos() == 1 ) // via Formel eOper = SC_COND_DIRECT; else eOper = (ScConditionMode)aLbCond12.GetSelectEntryPos(); sExpr1 = aEdtCond11.GetText(); sExpr2 = aEdtCond12.GetText(); sStyle = aLbCond1Template.GetSelectEntry(); ScCondFormatEntry aNewEntry( eOper, sExpr1, sExpr2, pDoc, aCurPos, sStyle ); rCndFmt.AddEntry( aNewEntry ); } if ( aCbxCond2.IsChecked() ) { if ( aLbCond21.GetSelectEntryPos() == 1 ) // via Formel??? eOper = SC_COND_DIRECT; else eOper = (ScConditionMode)aLbCond22.GetSelectEntryPos(); sExpr1 = aEdtCond21.GetText(); sExpr2 = aEdtCond22.GetText(); sStyle = aLbCond2Template.GetSelectEntry(); ScCondFormatEntry aNewEntry( eOper, sExpr1, sExpr2, pDoc, aCurPos, sStyle ); rCndFmt.AddEntry( aNewEntry ); } if ( aCbxCond3.IsChecked() ) { if ( aLbCond31.GetSelectEntryPos() == 1 ) // via Formel??? eOper = SC_COND_DIRECT; else eOper = (ScConditionMode)aLbCond32.GetSelectEntryPos(); sExpr1 = aEdtCond31.GetText(); sExpr2 = aEdtCond32.GetText(); sStyle = aLbCond3Template.GetSelectEntry(); ScCondFormatEntry aNewEntry( eOper, sExpr1, sExpr2, pDoc, aCurPos, sStyle ); rCndFmt.AddEntry( aNewEntry ); } } //---------------------------------------------------------------------------- // Zerstoert den Dialog BOOL ScConditionalFormatDlg::Close() { return DoClose( ScCondFormatDlgWrapper::GetChildWindowId() ); } //---------------------------------------------------------------------------- // Handler: //---------------------------------------------------------------------------- // Enabled/Disabled Condition1-Controls IMPL_LINK( ScConditionalFormatDlg, ClickCond1Hdl, void *, EMPTYARG ) { BOOL bChecked = aCbxCond1.IsChecked(); aLbCond11.Enable( bChecked ); aLbCond12.Enable( bChecked ); aEdtCond11.Enable( bChecked ); aRbCond11.Enable( bChecked ); aFtCond1And.Enable( bChecked ); aEdtCond12.Enable( bChecked ); aRbCond12.Enable( bChecked ); aFtCond1Template.Enable( bChecked ); aLbCond1Template.Enable( bChecked ); return( 0L ); } //---------------------------------------------------------------------------- // Zellwert/Formel IMPL_LINK( ScConditionalFormatDlg, ChangeCond11Hdl, void *, EMPTYARG ) { USHORT nPos = aLbCond11.GetSelectEntryPos(); if( nPos == 0 ) // Zellwert { aLbCond12.Show(); aEdtCond11.SetPosPixel( aCond1Pos2 ); } else // Formel { aLbCond12.Hide(); aFtCond1And.Hide(); aEdtCond12.Hide(); aRbCond12.Hide(); aRbCond11.SetPosPixel( aRBtn1Pos2 ); aEdtCond11.SetPosSizePixel( aCond1Pos1, aCond1Size1 ); } ChangeCond12Hdl( NULL ); return( 0L ); } //---------------------------------------------------------------------------- // zwischen, gleich, groesser, ... IMPL_LINK( ScConditionalFormatDlg, ChangeCond12Hdl, void *, EMPTYARG ) { if( aLbCond12.IsVisible() ) { USHORT nPos = aLbCond12.GetSelectEntryPos(); if( nPos == 6 || nPos == 7 ) // zwischen, n. zwischen { aEdtCond11.SetSizePixel( aCond1Size3 ); aRbCond11.SetPosPixel( aRBtn1Pos1 ); aFtCond1And.Show(); aEdtCond12.Show(); aRbCond12.Show(); } else // gleich, n. gleich ... { aEdtCond12.Hide(); aRbCond12.Hide(); aFtCond1And.Hide(); aRbCond11.SetPosPixel( aRBtn1Pos2 ); aEdtCond11.SetSizePixel( aCond1Size2 ); } } return( 0L ); } //---------------------------------------------------------------------------- // Enabled/Disabled Condition2-Controls IMPL_LINK( ScConditionalFormatDlg, ClickCond2Hdl, void *, EMPTYARG ) { BOOL bChecked = aCbxCond2.IsChecked(); aLbCond21.Enable( bChecked ); aLbCond22.Enable( bChecked ); aEdtCond21.Enable( bChecked ); aRbCond21.Enable( bChecked ); aFtCond2And.Enable( bChecked ); aEdtCond22.Enable( bChecked ); aRbCond22.Enable( bChecked ); aFtCond2Template.Enable( bChecked ); aLbCond2Template.Enable( bChecked ); return( 0L ); } //---------------------------------------------------------------------------- // Zellwert/Formel IMPL_LINK( ScConditionalFormatDlg, ChangeCond21Hdl, void *, EMPTYARG ) { USHORT nPos = aLbCond21.GetSelectEntryPos(); if( nPos == 0 ) // Zellwert { aLbCond22.Show(); aEdtCond21.SetPosPixel( aCond2Pos2 ); } else // Formel { aLbCond22.Hide(); aFtCond2And.Hide(); aEdtCond22.Hide(); aRbCond22.Hide(); aRbCond21.SetPosPixel( aRBtn2Pos2 ); aEdtCond21.SetPosSizePixel( aCond2Pos1, aCond2Size1 ); } ChangeCond22Hdl( NULL ); return( 0L ); } //---------------------------------------------------------------------------- // zwischen, gleich, groesser, ... IMPL_LINK( ScConditionalFormatDlg, ChangeCond22Hdl, void *, EMPTYARG ) { if( aLbCond22.IsVisible() ) { USHORT nPos = aLbCond22.GetSelectEntryPos(); if( nPos == 6 || nPos == 7 ) // zwischen, n. zwischen { aEdtCond21.SetSizePixel( aCond2Size3 ); aRbCond21.SetPosPixel( aRBtn2Pos1 ); aFtCond2And.Show(); aEdtCond22.Show(); aRbCond22.Show(); } else // gleich, n. gleich ... { aEdtCond22.Hide(); aRbCond22.Hide(); aFtCond2And.Hide(); aRbCond21.SetPosPixel( aRBtn2Pos2 ); aEdtCond21.SetSizePixel( aCond2Size2 ); } } return( 0L ); } //---------------------------------------------------------------------------- // Enabled/Disabled Condition3-Controls IMPL_LINK( ScConditionalFormatDlg, ClickCond3Hdl, void *, EMPTYARG ) { BOOL bChecked = aCbxCond3.IsChecked(); aLbCond31.Enable( bChecked ); aLbCond32.Enable( bChecked ); aEdtCond31.Enable( bChecked ); aRbCond31.Enable( bChecked ); aFtCond3And.Enable( bChecked ); aEdtCond32.Enable( bChecked ); aRbCond32.Enable( bChecked ); aFtCond3Template.Enable( bChecked ); aLbCond3Template.Enable( bChecked ); return( 0L ); } //---------------------------------------------------------------------------- // Zellwert/Formel IMPL_LINK( ScConditionalFormatDlg, ChangeCond31Hdl, void *, EMPTYARG ) { USHORT nPos = aLbCond31.GetSelectEntryPos(); if( nPos == 0 ) // Zellwert { aLbCond32.Show(); aEdtCond31.SetPosPixel( aCond3Pos2 ); } else // Formel { aLbCond32.Hide(); aFtCond3And.Hide(); aEdtCond32.Hide(); aRbCond32.Hide(); aRbCond31.SetPosPixel( aRBtn3Pos2 ); aEdtCond31.SetPosSizePixel( aCond3Pos1, aCond3Size1 ); } ChangeCond32Hdl( NULL ); return( 0L ); } //---------------------------------------------------------------------------- // zwischen, gleich, groesser, ... IMPL_LINK( ScConditionalFormatDlg, ChangeCond32Hdl, void *, EMPTYARG ) { if( aLbCond32.IsVisible() ) { USHORT nPos = aLbCond32.GetSelectEntryPos(); if( nPos == 6 || nPos == 7 ) // zwischen, n. zwischen { aEdtCond31.SetSizePixel( aCond3Size3 ); aRbCond31.SetPosPixel( aRBtn3Pos1 ); aFtCond3And.Show(); aEdtCond32.Show(); aRbCond32.Show(); } else // gleich, n. gleich ... { aEdtCond32.Hide(); aRbCond32.Hide(); aFtCond3And.Hide(); aRbCond31.SetPosPixel( aRBtn3Pos2 ); aEdtCond31.SetSizePixel( aCond3Size2 ); } } return( 0L ); } //---------------------------------------------------------------------------- IMPL_LINK( ScConditionalFormatDlg, GetFocusHdl, Control*, pCtrl ) { if( (pCtrl == (Control*)&aEdtCond11) || (pCtrl == (Control*)&aRbCond11) ) pEdActive = &aEdtCond11; else if( (pCtrl == (Control*)&aEdtCond12) || (pCtrl == (Control*)&aRbCond12) ) pEdActive = &aEdtCond12; else if( (pCtrl == (Control*)&aEdtCond21) || (pCtrl == (Control*)&aRbCond21) ) pEdActive = &aEdtCond21; else if( (pCtrl == (Control*)&aEdtCond22) || (pCtrl == (Control*)&aRbCond22) ) pEdActive = &aEdtCond22; else if( (pCtrl == (Control*)&aEdtCond31) || (pCtrl == (Control*)&aRbCond31) ) pEdActive = &aEdtCond31; else if( (pCtrl == (Control*)&aEdtCond32) || (pCtrl == (Control*)&aRbCond32) ) pEdActive = &aEdtCond32; else pEdActive = NULL; if( pEdActive ) pEdActive->SetSelection( Selection( 0, SELECTION_MAX ) ); return 0; } //---------------------------------------------------------------------------- IMPL_LINK( ScConditionalFormatDlg, LoseFocusHdl, Control*, pCtrl ) { bDlgLostFocus = !IsActive(); return 0; } //---------------------------------------------------------------------------- // [OK], [Cancel] IMPL_LINK( ScConditionalFormatDlg, BtnHdl, PushButton*, pBtn ) { if ( pBtn == &aBtnOk ) { ScConditionalFormat aCondFrmt( 0, pDoc ); GetConditionalFormat( aCondFrmt ); ScCondFrmtItem aOutItem( FID_CONDITIONAL_FORMAT, aCondFrmt ); SetDispatcherLock( FALSE ); SwitchToDocument(); GetBindings().GetDispatcher()->Execute( FID_CONDITIONAL_FORMAT, SFX_CALLMODE_SLOT | SFX_CALLMODE_RECORD, &aOutItem, 0L, 0L ); Close(); } else if ( pBtn == &aBtnCancel ) Close(); return( 0L ); }
/************************************************************************* * * $RCSfile: crnrdlg.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: obo $ $Date: 2004-06-04 11:47:23 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ // System - Includes --------------------------------------------------------- #ifdef PCH #include "ui_pch.hxx" #endif #pragma hdrstop // INCLUDE ------------------------------------------------------------------- #include "reffact.hxx" #include "document.hxx" #include "scresid.hxx" #include "globstr.hrc" #include "crnrdlg.hrc" #ifndef SC_DOCSHELL_HXX #include "docsh.hxx" #endif #define _CRNRDLG_CXX #include "crnrdlg.hxx" #undef _CRNRDLG_CXX #ifndef _SV_MSGBOX_HXX //autogen #include <vcl/msgbox.hxx> #endif //============================================================================ #define ERRORBOX(s) ErrorBox(this,WinBits(WB_OK|WB_DEF_OK),s).Execute() #define QUERYBOX(m) QueryBox(this,WinBits(WB_YES_NO|WB_DEF_YES),m).Execute() const ULONG nEntryDataCol = 0; const ULONG nEntryDataRow = 1; const ULONG nEntryDataDelim = 2; //============================================================================ // class ScColRowNameRangesDlg /************************************************************************* #* Member: ScColRowNameRangesDlg Datum:04.09.97 #*------------------------------------------------------------------------ #* #* Klasse: ScColRowNameRangesDlg #* #* Funktion: Konstruktor der Klasse ScColRowNameRangesDlg. #* Initialisieren der Klassen- Mitglieder, #* Uebernahme der Range- Angaben und Aufruf #* der eigentlichen Initialisierungsroutine #* #* Input: Sfx- Verknuepfungen #* Parent- Window #* SCViewData #* #* Output: --- #* #************************************************************************/ ScColRowNameRangesDlg::ScColRowNameRangesDlg( SfxBindings* pB, SfxChildWindow* pCW, Window* pParent, ScViewData* ptrViewData ) : ScAnyRefDlg ( pB, pCW, pParent, RID_SCDLG_COLROWNAMERANGES ), // aFlAssign ( this, ScResId( FL_ASSIGN ) ), aLbRange ( this, ScResId( LB_RANGE ) ), aEdAssign ( this, ScResId( ED_AREA ) ), aRbAssign ( this, ScResId( RB_AREA ), &aEdAssign ), aBtnColHead ( this, ScResId( BTN_COLHEAD ) ), aBtnRowHead ( this, ScResId( BTN_ROWHEAD ) ), aFtAssign2 ( this, ScResId( FT_DATA_LABEL ) ), aEdAssign2 ( this, ScResId( ED_DATA ) ), aRbAssign2 ( this, ScResId( RB_DATA ), &aEdAssign2 ), aBtnOk ( this, ScResId( BTN_OK ) ), aBtnCancel ( this, ScResId( BTN_CANCEL ) ), aBtnAdd ( this, ScResId( BTN_ADD ) ), aBtnRemove ( this, ScResId( BTN_REMOVE ) ), aBtnHelp ( this, ScResId( BTN_HELP ) ), pViewData ( ptrViewData ), pDoc ( ptrViewData->GetDocument() ), pEdActive ( NULL ), bDlgLostFocus ( FALSE ) { xColNameRanges = pDoc->GetColNameRanges()->Clone(); xRowNameRanges = pDoc->GetRowNameRanges()->Clone(); Init(); FreeResource(); } /************************************************************************* #* Member: ~ScColRowNameRangesDlg Datum:04.09.97 #*------------------------------------------------------------------------ #* #* Klasse: ScColRowNameRangesDlg #* #* Funktion: Destruktor der Klasse #* #* Input: --- #* #* Output: --- #* #************************************************************************/ __EXPORT ScColRowNameRangesDlg::~ScColRowNameRangesDlg() { } /************************************************************************* #* Member: Init Datum:04.09.97 #*------------------------------------------------------------------------ #* #* Klasse: ScColRowNameRangesDlg #* #* Funktion: Initialisierungs- Routine: #* Umlenken der Event- Handler und einstellen der #* Startparameter. #* #* Input: --- #* #* Output: --- #* #************************************************************************/ void ScColRowNameRangesDlg::Init() { SCCOL nStartCol = 0; SCROW nStartRow = 0; SCTAB nStartTab = 0; SCCOL nEndCol = 0; SCROW nEndRow = 0; SCTAB nEndTab = 0; aBtnOk.SetClickHdl ( LINK( this, ScColRowNameRangesDlg, OkBtnHdl ) ); aBtnCancel.SetClickHdl ( LINK( this, ScColRowNameRangesDlg, CancelBtnHdl ) ); aBtnAdd.SetClickHdl ( LINK( this, ScColRowNameRangesDlg, AddBtnHdl ) ); aBtnRemove.SetClickHdl ( LINK( this, ScColRowNameRangesDlg, RemoveBtnHdl ) ); aLbRange.SetSelectHdl ( LINK( this, ScColRowNameRangesDlg, Range1SelectHdl ) ); aEdAssign.SetModifyHdl ( LINK( this, ScColRowNameRangesDlg, Range1DataModifyHdl ) ); aBtnColHead.SetClickHdl ( LINK( this, ScColRowNameRangesDlg, ColClickHdl ) ); aBtnRowHead.SetClickHdl ( LINK( this, ScColRowNameRangesDlg, RowClickHdl ) ); aEdAssign2.SetModifyHdl ( LINK( this, ScColRowNameRangesDlg, Range2DataModifyHdl ) ); Link aLink = LINK( this, ScColRowNameRangesDlg, GetFocusHdl ); aEdAssign.SetGetFocusHdl( aLink ); aRbAssign.SetGetFocusHdl( aLink ); aEdAssign2.SetGetFocusHdl( aLink ); aRbAssign2.SetGetFocusHdl( aLink ); aLink = LINK( this, ScColRowNameRangesDlg, LoseFocusHdl ); aEdAssign.SetLoseFocusHdl( aLink ); aRbAssign.SetLoseFocusHdl( aLink ); aEdAssign2.SetLoseFocusHdl( aLink ); aRbAssign2.SetLoseFocusHdl( aLink ); pEdActive = &aEdAssign; UpdateNames(); if ( pViewData && pDoc ) { pViewData->GetSimpleArea( nStartCol, nStartRow, nStartTab, nEndCol, nEndRow, nEndTab ); SetColRowData( ScRange( ScAddress( nStartCol, nStartRow, nStartTab ), ScAddress( nEndCol, nEndRow, nEndTab ) ) ); } else { aBtnColHead.Check( TRUE ); aBtnRowHead.Check( FALSE ); aEdAssign.SetText( EMPTY_STRING ); aEdAssign2.SetText( EMPTY_STRING ); } aLbRange.SetBorderStyle( WINDOW_BORDER_MONO ); aBtnColHead.Enable(); aBtnRowHead.Enable(); aEdAssign.Enable(); aEdAssign.GrabFocus(); aRbAssign.Enable(); //@BugID 54702 Enablen/Disablen nur noch in Basisklasse //SFX_APPWINDOW->Enable(); // Ref-Feld hat Focus Range1SelectHdl( 0 ); } /************************************************************************* #* Member: SetColRowData Datum:04.09.97 #*------------------------------------------------------------------------ #* #* Klasse: ScColRowNameRangesDlg #* #* Funktion: zugehoerigen Datenbereich eines Beschriftungsbereiches #* auf default Werte setzen und beide Referenz-Edit-Felder #* fuellen. #* #* Input: Einstellbereich fuer Labels #* #* Output: --- #* #************************************************************************/ void ScColRowNameRangesDlg::SetColRowData( const ScRange& rLabelRange,BOOL bRef) { theCurData = theCurArea = rLabelRange; BOOL bValid = TRUE; SCCOL nCol1 = theCurArea.aStart.Col(); SCCOL nCol2 = theCurArea.aEnd.Col(); SCROW nRow1 = theCurArea.aStart.Row(); SCROW nRow2 = theCurArea.aEnd.Row(); if ( (static_cast<SCCOLROW>(nCol2 - nCol1) >= nRow2 - nRow1) || (nCol1 == 0 && nCol2 == MAXCOL) ) { // Spaltenkoepfe und Grenzfall gesamte Tabelle aBtnColHead.Check( TRUE ); aBtnRowHead.Check( FALSE ); if ( nRow2 == MAXROW ) { if ( nRow1 == 0 ) bValid = FALSE; // Grenzfall gesamte Tabelle else { // Head unten, Data oben theCurData.aStart.SetRow( 0 ); theCurData.aEnd.SetRow( nRow1 - 1 ); } } else { // Head oben, Data unten theCurData.aStart.SetRow( nRow2 + 1 ); theCurData.aEnd.SetRow( MAXROW ); } } else { // Zeilenkoepfe aBtnRowHead.Check( TRUE ); aBtnColHead.Check( FALSE ); if ( nCol2 == MAXCOL ) { // Head rechts, Data links theCurData.aStart.SetCol( 0 ); theCurData.aEnd.SetCol( nCol2 - 1 ); } else { // Head links, Data rechts theCurData.aStart.SetCol( nCol2 + 1 ); theCurData.aEnd.SetCol( MAXCOL ); } } if ( bValid ) { String aStr; theCurArea.Format( aStr, SCR_ABS_3D, pDoc ); if(bRef) aEdAssign.SetRefString( aStr ); else aEdAssign.SetText( aStr ); aEdAssign.SetSelection( Selection( SELECTION_MAX, SELECTION_MAX ) ); theCurData.Format( aStr, SCR_ABS_3D, pDoc ); if(bRef) aEdAssign2.SetRefString( aStr ); else aEdAssign2.SetText( aStr ); } else { theCurData = theCurArea = ScRange(); if(bRef) { aEdAssign.SetRefString( EMPTY_STRING ); aEdAssign2.SetRefString( EMPTY_STRING ); } else { aEdAssign.SetText( EMPTY_STRING ); aEdAssign2.SetText( EMPTY_STRING ); } aBtnColHead.Disable(); aBtnRowHead.Disable(); aEdAssign2.Disable(); aRbAssign2.Disable(); } } /************************************************************************* #* Member: AdjustColRowData Datum:04.09.97 #*------------------------------------------------------------------------ #* #* Klasse: ScColRowNameRangesDlg #* #* Funktion: zugehoerigen Datenbereich eines Beschriftungsbereiches #* anpassen und Data-Referenz-Edit-Feld fuellen. #* #* Input: Bereich fuer Labels #* #* Output: --- #* #************************************************************************/ void ScColRowNameRangesDlg::AdjustColRowData( const ScRange& rDataRange,BOOL bRef) { theCurData = rDataRange; if ( aBtnColHead.IsChecked() ) { // Datenbereich gleiche Spalten wie Koepfe theCurData.aStart.SetCol( theCurArea.aStart.Col() ); theCurData.aEnd.SetCol( theCurArea.aEnd.Col() ); if ( theCurData.Intersects( theCurArea ) ) { SCROW nRow1 = theCurArea.aStart.Row(); SCROW nRow2 = theCurArea.aEnd.Row(); if ( nRow1 > 0 && (theCurData.aEnd.Row() < nRow2 || nRow2 == MAXROW) ) { // Data oben theCurData.aEnd.SetRow( nRow1 - 1 ); if ( theCurData.aStart.Row() > theCurData.aEnd.Row() ) theCurData.aStart.SetRow( theCurData.aEnd.Row() ); } else { // Data unten theCurData.aStart.SetRow( nRow2 + 1 ); if ( theCurData.aStart.Row() > theCurData.aEnd.Row() ) theCurData.aEnd.SetRow( theCurData.aStart.Row() ); } } } else { // Datenbereich gleiche Zeilen wie Koepfe theCurData.aStart.SetRow( theCurArea.aStart.Row() ); theCurData.aEnd.SetRow( theCurArea.aEnd.Row() ); if ( theCurData.Intersects( theCurArea ) ) { SCCOL nCol1 = theCurArea.aStart.Col(); SCCOL nCol2 = theCurArea.aEnd.Col(); if ( nCol1 > 0 && (theCurData.aEnd.Col() < nCol2 || nCol2 == MAXCOL) ) { // Data links theCurData.aEnd.SetCol( nCol1 - 1 ); if ( theCurData.aStart.Col() > theCurData.aEnd.Col() ) theCurData.aStart.SetCol( theCurData.aEnd.Col() ); } else { // Data rechts theCurData.aStart.SetCol( nCol2 + 1 ); if ( theCurData.aStart.Col() > theCurData.aEnd.Col() ) theCurData.aEnd.SetCol( theCurData.aStart.Col() ); } } } String aStr; theCurData.Format( aStr, SCR_ABS_3D, pDoc ); if(bRef) aEdAssign2.SetRefString( aStr ); else aEdAssign2.SetText( aStr ); aEdAssign2.SetSelection( Selection( SELECTION_MAX, SELECTION_MAX ) ); } /************************************************************************* #* Member: SetReference Datum:04.09.97 #*------------------------------------------------------------------------ #* #* Klasse: ScColRowNameRangesDlg #* #* Funktion: Uebergabe eines mit der Maus selektierten Tabellen- #* bereiches, der dann als neue Selektion im Referenz- #* Fenster angezeigt wird. #* #* Input: Bereich fuer Labels #* Dokumentklasse #* #* Output: --- #* #************************************************************************/ void ScColRowNameRangesDlg::SetReference( const ScRange& rRef, ScDocument* pDoc ) { if ( pEdActive ) { if ( rRef.aStart != rRef.aEnd ) RefInputStart( pEdActive ); String aRefStr; if ( pEdActive == &aEdAssign ) SetColRowData( rRef, TRUE ); else AdjustColRowData( rRef, TRUE ); aBtnColHead.Enable(); aBtnRowHead.Enable(); aBtnAdd.Enable(); aBtnRemove.Disable(); } } /************************************************************************* #* Member: Close Datum:04.09.97 #*------------------------------------------------------------------------ #* #* Klasse: ScColRowNameRangesDlg #* #* Funktion: Schliessen des Fensters #* #* Input: --- #* #* Output: --- #* #************************************************************************/ BOOL __EXPORT ScColRowNameRangesDlg::Close() { return DoClose( ScColRowNameRangesDlgWrapper::GetChildWindowId() ); } /************************************************************************* #* Member: SetActive Datum:04.09.97 #*------------------------------------------------------------------------ #* #* Klasse: ScColRowNameRangesDlg #* #* Funktion: Aktivieren des Fensters #* #* Input: --- #* #* Output: --- #* #************************************************************************/ void ScColRowNameRangesDlg::SetActive() { if ( bDlgLostFocus ) { bDlgLostFocus = FALSE; if( pEdActive ) pEdActive->GrabFocus(); } else GrabFocus(); if( pEdActive == &aEdAssign ) Range1DataModifyHdl( 0 ); else if( pEdActive == &aEdAssign2 ) Range2DataModifyHdl( 0 ); RefInputDone(); } /************************************************************************* #* Member: UpdateNames Datum:04.09.97 #*------------------------------------------------------------------------ #* #* Klasse: ScColRowNameRangesDlg #* #* Funktion: Aktualisieren der Namen #* #* Input: --- #* #* Output: --- #* #************************************************************************/ void ScColRowNameRangesDlg::UpdateNames() { aLbRange.SetUpdateMode( FALSE ); //----------------------------------------------------------- aLbRange.Clear(); aEdAssign.SetText( EMPTY_STRING ); ULONG nCount, j; USHORT nPos; //@008 Hilfsvariable q eingefuegt SCCOL nCol1; //@008 04.09.97 SCROW nRow1; //Erweiterung fuer Bereichsnamen SCTAB nTab1; SCCOL nCol2; SCROW nRow2; SCTAB nTab2; String rString; String strShow; String aString; String strDelim = String::CreateFromAscii(RTL_CONSTASCII_STRINGPARAM( " --- " )); aString = strDelim; aString += ScGlobal::GetRscString( STR_COLUMN ); aString += strDelim; nPos = aLbRange.InsertEntry( aString ); aLbRange.SetEntryData( nPos, (void*)nEntryDataDelim ); if ( (nCount = xColNameRanges->Count()) > 0 ) { ScRangePair** ppSortArray = xColNameRanges->CreateNameSortedArray( nCount, pDoc ); for ( j=0; j < nCount; j++ ) { ppSortArray[j]->GetRange(0).Format( aString, SCR_ABS_3D, pDoc ); //@008 Hole Bereichsparameter aus Dok ppSortArray[j]->GetRange(0).GetVars( nCol1, nRow1, nTab1, nCol2, nRow2, nTab2 ); SCCOL q=nCol1+3; if(q>nCol2) q=nCol2; //@008 Baue String zusammen strShow.AssignAscii(RTL_CONSTASCII_STRINGPARAM(" [")); if(pDoc!=NULL) { pDoc->GetString(nCol1, nRow1, nTab1,rString); strShow +=rString; for(SCCOL i=nCol1+1;i<=q;i++) { strShow.AppendAscii(RTL_CONSTASCII_STRINGPARAM(", ")); pDoc->GetString(i, nRow1, nTab1,rString); strShow += rString; } } if(q<nCol2) // Zu lang? Ergaenzen um ",..." { strShow.AppendAscii(RTL_CONSTASCII_STRINGPARAM(", ...")); } strShow += ']'; //@008 String einfuegen in Listbox String aInsStr = aString; aInsStr += strShow; nPos = aLbRange.InsertEntry( aInsStr ); aLbRange.SetEntryData( nPos, (void*)nEntryDataCol ); } delete [] ppSortArray; } aString = strDelim; aString += ScGlobal::GetRscString( STR_ROW ); aString += strDelim; nPos = aLbRange.InsertEntry( aString ); aLbRange.SetEntryData( nPos, (void*)nEntryDataDelim ); if ( (nCount = xRowNameRanges->Count()) > 0 ) { ScRangePair** ppSortArray = xRowNameRanges->CreateNameSortedArray( nCount, pDoc ); for ( j=0; j < nCount; j++ ) { ppSortArray[j]->GetRange(0).Format( aString, SCR_ABS_3D, pDoc ); //@008 Ab hier baue String fuer Zeilen ppSortArray[j]->GetRange(0).GetVars( nCol1, nRow1, nTab1, nCol2, nRow2, nTab2 ); SCROW q=nRow1+3; if(q>nRow2) q=nRow2; strShow.AssignAscii(RTL_CONSTASCII_STRINGPARAM(" [")); if(pDoc!=NULL) { pDoc->GetString(nCol1, nRow1, nTab1,rString); strShow += rString; for(SCROW i=nRow1+1;i<=q;i++) { strShow.AppendAscii(RTL_CONSTASCII_STRINGPARAM(", ")); pDoc->GetString(nCol1, i, nTab1,rString); strShow += rString; } } if(q<nRow2) { strShow.AppendAscii(RTL_CONSTASCII_STRINGPARAM(", ...")); } strShow += ']'; String aInsStr = aString; aInsStr += strShow; nPos = aLbRange.InsertEntry( aInsStr ); aLbRange.SetEntryData( nPos, (void*)nEntryDataRow ); } delete [] ppSortArray; } //----------------------------------------------------------- aLbRange.SetUpdateMode( TRUE ); aLbRange.Invalidate(); } /************************************************************************* #* Member: UpdateRangeData Datum:04.09.97 #*------------------------------------------------------------------------ #* #* Klasse: ScColRowNameRangesDlg #* #* Funktion: Aktualisieren der Bereichsdaten #* #* Input: Bereichs-String #* Flag fuer Spalten #* #* Output: --- #* #************************************************************************/ void ScColRowNameRangesDlg::UpdateRangeData( const String& rRangeStr, BOOL bColName ) { ScRange aRange; String aRefString=rRangeStr; //@008 Suchen nach Erweiterung u. rausschmeissen xub_StrLen nPosExt=rRangeStr.Search( '[',0 ); if(nPosExt!=STRING_NOTFOUND) { nPosExt--; aRefString.Erase(nPosExt); } aRange.ParseAny( aRefString, pDoc ); ScRangePair* pPair; BOOL bFound = FALSE; if ( bColName && (pPair = xColNameRanges->Find( aRange )) ) bFound = TRUE; else if ( !bColName && (pPair = xRowNameRanges->Find( aRange )) ) bFound = TRUE; if ( bFound ) { String aStr; theCurArea = aRange; theCurArea.Format( aStr, SCR_ABS_3D, pDoc ); aEdAssign.SetText( aStr ); aBtnAdd.Disable(); aBtnRemove.Enable(); aBtnColHead.Check( bColName ); aBtnRowHead.Check( !bColName ); theCurData = pPair->GetRange(1); theCurData.Format( aStr, SCR_ABS_3D, pDoc ); aEdAssign2.SetText( aStr ); } else { aBtnAdd.Enable(); aBtnRemove.Disable(); } aBtnColHead.Enable(); aBtnRowHead.Enable(); aEdAssign2.Enable(); aRbAssign2.Enable(); } /************************************************************************* #* Member: IsRefInputMode Datum:04.09.97 #*------------------------------------------------------------------------ #* #* Klasse: ScColRowNameRangesDlg #* #* Funktion: Abfragefunktion fuer Referenz- Input- Mode. #* #* Input: Bereichs-String #* Flag fuer Spalten #* #* Output: true, wenn Referenz- Input- Mode #* #************************************************************************/ BOOL ScColRowNameRangesDlg::IsRefInputMode() const { return (pEdActive != NULL); } //------------------------------------------------------------------------ // Handler: // ======== /************************************************************************* #* Handler: OkBtnHdl Datum:04.09.97 #*------------------------------------------------------------------------ #* #* Klasse: ScColRowNameRangesDlg #* #* Funktion: Wird ausgeloest, wenn der OK- Button gedrckt wurde. #* Hinzufuegen- Button ausloesen, und die neu einge- #* stellten Bereiche ans Dokument uebergeben. #* Fensterschliessen- Anweisung ausloesen. #* Input: --- #* #* Output: --- #* #************************************************************************/ IMPL_LINK( ScColRowNameRangesDlg, OkBtnHdl, void *, EMPTYARG ) { AddBtnHdl( 0 ); // die RangeLists den Refs am Doc zuweisen pDoc->GetColNameRangesRef() = xColNameRanges; pDoc->GetRowNameRangesRef() = xRowNameRanges; // geaenderte Datenbereiche muessen sich auswirken pDoc->CompileColRowNameFormula(); ScDocShell* pDocShell = pViewData->GetDocShell(); pDocShell->PostPaint( 0,0,0, MAXCOL,MAXROW,MAXTAB, PAINT_GRID ); pDocShell->SetDocumentModified(); Close(); return 0; } /************************************************************************* #* Handler: CancelBtnHdl Datum:04.09.97 #*------------------------------------------------------------------------ #* #* Klasse: ScColRowNameRangesDlg #* #* Funktion: Fensterschliessen- Anweisung ausloesen. #* #* Input: --- #* #* Output: --- #* #************************************************************************/ IMPL_LINK_INLINE_START( ScColRowNameRangesDlg, CancelBtnHdl, void *, EMPTYARG ) { Close(); return 0; } IMPL_LINK_INLINE_END( ScColRowNameRangesDlg, CancelBtnHdl, void *, EMPTYARG ) /************************************************************************* #* Handler: AddBtnHdl Datum:04.09.97 #*------------------------------------------------------------------------ #* #* Klasse: ScColRowNameRangesDlg #* #* Funktion: Nach betaetigen des Hinzufuegen- Buttons, werden #* die Bereichsangaben eingestellt und in der #* Listbox dargestellt. #* #* Input: --- #* #* Output: --- #* #************************************************************************/ IMPL_LINK( ScColRowNameRangesDlg, AddBtnHdl, void *, EMPTYARG ) { String aNewArea( aEdAssign.GetText() ); String aNewData( aEdAssign2.GetText() ); if ( aNewArea.Len() > 0 && aNewData.Len() > 0 ) { ScRange aRange1, aRange2; BOOL bOk1; if ( (bOk1 = ((aRange1.ParseAny( aNewArea, pDoc ) & SCA_VALID) == SCA_VALID)) && ((aRange2.ParseAny( aNewData, pDoc ) & SCA_VALID) == SCA_VALID) ) { theCurArea = aRange1; AdjustColRowData( aRange2 ); ScRangePair* pPair; if ( pPair = xColNameRanges->Find( theCurArea ) ) { xColNameRanges->Remove( pPair ); delete pPair; } if ( pPair = xRowNameRanges->Find( theCurArea ) ) { xRowNameRanges->Remove( pPair ); delete pPair; } if ( aBtnColHead.IsChecked() ) xColNameRanges->Join( ScRangePair( theCurArea, theCurData ) ); else xRowNameRanges->Join( ScRangePair( theCurArea, theCurData ) ); UpdateNames(); aEdAssign.GrabFocus(); aBtnAdd.Disable(); aBtnRemove.Disable(); aEdAssign.SetText( EMPTY_STRING ); aBtnColHead.Check( TRUE ); aBtnRowHead.Check( FALSE ); aEdAssign2.SetText( EMPTY_STRING ); theCurArea = ScRange(); theCurData = theCurArea; Range1SelectHdl( 0 ); } else { ERRORBOX( ScGlobal::GetRscString(STR_INVALIDTABNAME) ); if ( !bOk1 ) aEdAssign.GrabFocus(); else aEdAssign2.GrabFocus(); } } return 0; } /************************************************************************* #* Handler: RemoveBtnHdl Datum:04.09.97 #*------------------------------------------------------------------------ #* #* Klasse: ScColRowNameRangesDlg #* #* Funktion: Nach betaetigen des Loeschen- Buttons, wird #* die markierte Bereichsangabe geloescht. #* #* Input: --- #* #* Output: --- #* #************************************************************************/ IMPL_LINK( ScColRowNameRangesDlg, RemoveBtnHdl, void *, EMPTYARG ) { String aRangeStr = aLbRange.GetSelectEntry(); USHORT nSelectPos = aLbRange.GetSelectEntryPos(); BOOL bColName = ((ULONG)aLbRange.GetEntryData( nSelectPos ) == nEntryDataCol); ScRange aRange; //@008 Suchen nach Erweiterung u. rausschmeissen String aRefString=aRangeStr; xub_StrLen nPosExt=aRangeStr.Search( '[', 0 ); if(nPosExt!=STRING_NOTFOUND) { nPosExt--; aRefString.Erase(nPosExt); } aRange.ParseAny( aRefString, pDoc ); ScRangePair* pPair; BOOL bFound = FALSE; if ( bColName && (pPair = xColNameRanges->Find( aRange )) ) bFound = TRUE; else if ( !bColName && (pPair = xRowNameRanges->Find( aRange )) ) bFound = TRUE; if ( bFound ) { String aStrDelMsg = ScGlobal::GetRscString( STR_QUERY_DELENTRY ); String aMsg = aStrDelMsg.GetToken( 0, '#' ); aMsg += aRangeStr; aMsg += aStrDelMsg.GetToken( 1, '#' ); if ( RET_YES == QUERYBOX(aMsg) ) { if ( bColName ) xColNameRanges->Remove( pPair ); else xRowNameRanges->Remove( pPair ); delete pPair; UpdateNames(); USHORT nCnt = aLbRange.GetEntryCount(); if ( nSelectPos >= nCnt ) { if ( nCnt ) nSelectPos = nCnt - 1; else nSelectPos = 0; } aLbRange.SelectEntryPos( nSelectPos ); if ( nSelectPos && (ULONG)aLbRange.GetEntryData( nSelectPos ) == nEntryDataDelim ) aLbRange.SelectEntryPos( --nSelectPos ); // ---Zeile--- aLbRange.GrabFocus(); aBtnAdd.Disable(); aBtnRemove.Disable(); aEdAssign.SetText( EMPTY_STRING ); theCurArea = theCurData = ScRange(); aBtnColHead.Check( TRUE ); aBtnRowHead.Check( FALSE ); aEdAssign2.SetText( EMPTY_STRING ); Range1SelectHdl( 0 ); } } return 0; } /************************************************************************* #* Handler: Range1SelectHdl Datum:04.09.97 #*------------------------------------------------------------------------ #* #* Klasse: ScColRowNameRangesDlg #* #* Funktion: Wenn Zeile in Listbox ausgewaehlt wird, #* werden die Eingabefelder entsprechend #* eingestellt. #* #* Input: --- #* #* Output: --- #* #************************************************************************/ IMPL_LINK( ScColRowNameRangesDlg, Range1SelectHdl, void *, EMPTYARG ) { USHORT nSelectPos = aLbRange.GetSelectEntryPos(); USHORT nCnt = aLbRange.GetEntryCount(); USHORT nMoves = 0; while ( nSelectPos < nCnt && (ULONG)aLbRange.GetEntryData( nSelectPos ) == nEntryDataDelim ) { // skip Delimiter ++nMoves; aLbRange.SelectEntryPos( ++nSelectPos ); } String aRangeStr = aLbRange.GetSelectEntry(); if ( nMoves ) { if ( nSelectPos > 1 && nSelectPos >= nCnt ) { // am Ende nicht auf dem " --- Zeile --- " Delimiter stehenbleiben // wenn davor Eintraege existieren nSelectPos = nCnt - 2; aLbRange.SelectEntryPos( nSelectPos ); aRangeStr = aLbRange.GetSelectEntry(); } else if ( nSelectPos > 2 && nSelectPos < nCnt && aRangeStr.Len() && aRangeStr == aEdAssign.GetText() ) { // nach oben wandern statt nach unten auf die vorherige Position nSelectPos -= 2; aLbRange.SelectEntryPos( nSelectPos ); aRangeStr = aLbRange.GetSelectEntry(); } } if ( aRangeStr.Len() && aRangeStr.GetChar(0) == '$' ) { BOOL bColName = ((ULONG)aLbRange.GetEntryData( nSelectPos ) == nEntryDataCol); UpdateRangeData( aRangeStr, bColName ); aBtnAdd.Disable(); aBtnRemove.Enable(); } else { if ( aEdAssign.GetText().Len() > 0 ) { if ( aEdAssign2.GetText().Len() > 0 ) aBtnAdd.Enable(); else aBtnAdd.Disable(); aBtnColHead.Enable(); aBtnRowHead.Enable(); aEdAssign2.Enable(); aRbAssign2.Enable(); } else { aBtnAdd.Disable(); aBtnColHead.Disable(); aBtnRowHead.Disable(); aEdAssign2.Disable(); aRbAssign2.Disable(); } aBtnRemove.Disable(); aEdAssign.GrabFocus(); } aEdAssign.Enable(); aRbAssign.Enable(); //@BugID 54702 Enablen/Disablen nur noch in Basisklasse //SFX_APPWINDOW->Enable(); return 0; } /************************************************************************* #* Handler: Range1DataModifyHdl Datum:04.09.97 #*------------------------------------------------------------------------ #* #* Klasse: ScColRowNameRangesDlg #* #* Funktion: Wird ausgeloest, wenn in der Tabelle, der Label- #* Bereich geaendert wurde. #* #* Input: --- #* #* Output: --- #* #************************************************************************/ IMPL_LINK( ScColRowNameRangesDlg, Range1DataModifyHdl, void *, EMPTYARG ) { String aNewArea( aEdAssign.GetText() ); BOOL bValid = FALSE; if ( aNewArea.Len() > 0 ) { ScRange aRange; if ( (aRange.ParseAny( aNewArea, pDoc ) & SCA_VALID) == SCA_VALID ) { SetColRowData( aRange ); bValid = TRUE; } } if ( bValid ) { aBtnAdd.Enable(); aBtnColHead.Enable(); aBtnRowHead.Enable(); aEdAssign2.Enable(); aRbAssign2.Enable(); } else { aBtnAdd.Disable(); aBtnColHead.Disable(); aBtnRowHead.Disable(); aEdAssign2.Disable(); aRbAssign2.Disable(); } aBtnRemove.Disable(); return 0; } /************************************************************************* #* Handler: Range2DataModifyHdl Datum:04.09.97 #*------------------------------------------------------------------------ #* #* Klasse: ScColRowNameRangesDlg #* #* Funktion: Wird ausgeloest, wenn in der Tabelle, der Daten- #* Bereich geaendert wurde #* #* Input: --- #* #* Output: --- #* #************************************************************************/ IMPL_LINK( ScColRowNameRangesDlg, Range2DataModifyHdl, void *, EMPTYARG ) { String aNewData( aEdAssign2.GetText() ); if ( aNewData.Len() > 0 ) { ScRange aRange; if ( (aRange.ParseAny( aNewData, pDoc ) & SCA_VALID) == SCA_VALID ) { AdjustColRowData( aRange ); aBtnAdd.Enable(); } else aBtnAdd.Disable(); } else { aBtnAdd.Disable(); } return 0; } /************************************************************************* #* Handler: ColClickHdl Datum:04.09.97 #*------------------------------------------------------------------------ #* #* Klasse: ScColRowNameRangesDlg #* #* Funktion: Radiobutton fuer Spalten wurde betaetigt, #* die entsprechenden Einstellungen werden #* vorgenommen #* #* Input: --- #* #* Output: --- #* #************************************************************************/ IMPL_LINK( ScColRowNameRangesDlg, ColClickHdl, void *, EMPTYARG ) { if ( !aBtnColHead.GetSavedValue() ) { aBtnColHead.Check( TRUE ); aBtnRowHead.Check( FALSE ); if ( theCurArea.aStart.Row() == 0 && theCurArea.aEnd.Row() == MAXROW ) { theCurArea.aEnd.SetRow( MAXROW - 1 ); String aStr; theCurArea.Format( aStr, SCR_ABS_3D, pDoc ); aEdAssign.SetText( aStr ); } ScRange aRange( theCurData ); aRange.aStart.SetRow( Min( (long)(theCurArea.aEnd.Row() + 1), (long)MAXROW ) ); aRange.aEnd.SetRow( MAXROW ); AdjustColRowData( aRange ); } return 0; } /************************************************************************* #* Handler: RowClickHdl Datum:04.09.97 #*------------------------------------------------------------------------ #* #* Klasse: ScColRowNameRangesDlg #* #* Funktion: Radiobutton fuer Zeilen wurde betaetigt, #* die entsprechenden Einstellungen werden #* vorgenommen #* #* Input: --- #* #* Output: --- #* #************************************************************************/ IMPL_LINK( ScColRowNameRangesDlg, RowClickHdl, void *, EMPTYARG ) { if ( !aBtnRowHead.GetSavedValue() ) { aBtnRowHead.Check( TRUE ); aBtnColHead.Check( FALSE ); if ( theCurArea.aStart.Col() == 0 && theCurArea.aEnd.Col() == MAXCOL ) { theCurArea.aEnd.SetCol( MAXCOL - 1 ); String aStr; theCurArea.Format( aStr, SCR_ABS_3D, pDoc ); aEdAssign.SetText( aStr ); } ScRange aRange( theCurData ); aRange.aStart.SetCol( static_cast<SCCOL>(Min( (long)(theCurArea.aEnd.Col() + 1), (long)MAXCOL )) ); aRange.aEnd.SetCol( MAXCOL ); AdjustColRowData( aRange ); } return 0; } IMPL_LINK( ScColRowNameRangesDlg, GetFocusHdl, Control*, pCtrl ) { if( (pCtrl == (Control*)&aEdAssign) || (pCtrl == (Control*)&aRbAssign) ) pEdActive = &aEdAssign; else if( (pCtrl == (Control*)&aEdAssign2) || (pCtrl == (Control*)&aRbAssign2) ) pEdActive = &aEdAssign2; else pEdActive = NULL; if( pEdActive ) pEdActive->SetSelection( Selection( 0, SELECTION_MAX ) ); return 0; } IMPL_LINK( ScColRowNameRangesDlg, LoseFocusHdl, Control*, pCtrl ) { bDlgLostFocus = !IsActive(); return 0; } INTEGRATION: CWS dr33 (1.5.308); FILE MERGED 2005/02/04 15:52:39 dr 1.5.308.1: #i36782# remove non-ASCII chars from source code /************************************************************************* * * $RCSfile: crnrdlg.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: vg $ $Date: 2005-02-16 18:11:15 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ // System - Includes --------------------------------------------------------- #ifdef PCH #include "ui_pch.hxx" #endif #pragma hdrstop // INCLUDE ------------------------------------------------------------------- #include "reffact.hxx" #include "document.hxx" #include "scresid.hxx" #include "globstr.hrc" #include "crnrdlg.hrc" #ifndef SC_DOCSHELL_HXX #include "docsh.hxx" #endif #define _CRNRDLG_CXX #include "crnrdlg.hxx" #undef _CRNRDLG_CXX #ifndef _SV_MSGBOX_HXX //autogen #include <vcl/msgbox.hxx> #endif //============================================================================ #define ERRORBOX(s) ErrorBox(this,WinBits(WB_OK|WB_DEF_OK),s).Execute() #define QUERYBOX(m) QueryBox(this,WinBits(WB_YES_NO|WB_DEF_YES),m).Execute() const ULONG nEntryDataCol = 0; const ULONG nEntryDataRow = 1; const ULONG nEntryDataDelim = 2; //============================================================================ // class ScColRowNameRangesDlg /************************************************************************* #* Member: ScColRowNameRangesDlg Datum:04.09.97 #*------------------------------------------------------------------------ #* #* Klasse: ScColRowNameRangesDlg #* #* Funktion: Konstruktor der Klasse ScColRowNameRangesDlg. #* Initialisieren der Klassen- Mitglieder, #* Uebernahme der Range- Angaben und Aufruf #* der eigentlichen Initialisierungsroutine #* #* Input: Sfx- Verknuepfungen #* Parent- Window #* SCViewData #* #* Output: --- #* #************************************************************************/ ScColRowNameRangesDlg::ScColRowNameRangesDlg( SfxBindings* pB, SfxChildWindow* pCW, Window* pParent, ScViewData* ptrViewData ) : ScAnyRefDlg ( pB, pCW, pParent, RID_SCDLG_COLROWNAMERANGES ), // aFlAssign ( this, ScResId( FL_ASSIGN ) ), aLbRange ( this, ScResId( LB_RANGE ) ), aEdAssign ( this, ScResId( ED_AREA ) ), aRbAssign ( this, ScResId( RB_AREA ), &aEdAssign ), aBtnColHead ( this, ScResId( BTN_COLHEAD ) ), aBtnRowHead ( this, ScResId( BTN_ROWHEAD ) ), aFtAssign2 ( this, ScResId( FT_DATA_LABEL ) ), aEdAssign2 ( this, ScResId( ED_DATA ) ), aRbAssign2 ( this, ScResId( RB_DATA ), &aEdAssign2 ), aBtnOk ( this, ScResId( BTN_OK ) ), aBtnCancel ( this, ScResId( BTN_CANCEL ) ), aBtnAdd ( this, ScResId( BTN_ADD ) ), aBtnRemove ( this, ScResId( BTN_REMOVE ) ), aBtnHelp ( this, ScResId( BTN_HELP ) ), pViewData ( ptrViewData ), pDoc ( ptrViewData->GetDocument() ), pEdActive ( NULL ), bDlgLostFocus ( FALSE ) { xColNameRanges = pDoc->GetColNameRanges()->Clone(); xRowNameRanges = pDoc->GetRowNameRanges()->Clone(); Init(); FreeResource(); } /************************************************************************* #* Member: ~ScColRowNameRangesDlg Datum:04.09.97 #*------------------------------------------------------------------------ #* #* Klasse: ScColRowNameRangesDlg #* #* Funktion: Destruktor der Klasse #* #* Input: --- #* #* Output: --- #* #************************************************************************/ __EXPORT ScColRowNameRangesDlg::~ScColRowNameRangesDlg() { } /************************************************************************* #* Member: Init Datum:04.09.97 #*------------------------------------------------------------------------ #* #* Klasse: ScColRowNameRangesDlg #* #* Funktion: Initialisierungs- Routine: #* Umlenken der Event- Handler und einstellen der #* Startparameter. #* #* Input: --- #* #* Output: --- #* #************************************************************************/ void ScColRowNameRangesDlg::Init() { SCCOL nStartCol = 0; SCROW nStartRow = 0; SCTAB nStartTab = 0; SCCOL nEndCol = 0; SCROW nEndRow = 0; SCTAB nEndTab = 0; aBtnOk.SetClickHdl ( LINK( this, ScColRowNameRangesDlg, OkBtnHdl ) ); aBtnCancel.SetClickHdl ( LINK( this, ScColRowNameRangesDlg, CancelBtnHdl ) ); aBtnAdd.SetClickHdl ( LINK( this, ScColRowNameRangesDlg, AddBtnHdl ) ); aBtnRemove.SetClickHdl ( LINK( this, ScColRowNameRangesDlg, RemoveBtnHdl ) ); aLbRange.SetSelectHdl ( LINK( this, ScColRowNameRangesDlg, Range1SelectHdl ) ); aEdAssign.SetModifyHdl ( LINK( this, ScColRowNameRangesDlg, Range1DataModifyHdl ) ); aBtnColHead.SetClickHdl ( LINK( this, ScColRowNameRangesDlg, ColClickHdl ) ); aBtnRowHead.SetClickHdl ( LINK( this, ScColRowNameRangesDlg, RowClickHdl ) ); aEdAssign2.SetModifyHdl ( LINK( this, ScColRowNameRangesDlg, Range2DataModifyHdl ) ); Link aLink = LINK( this, ScColRowNameRangesDlg, GetFocusHdl ); aEdAssign.SetGetFocusHdl( aLink ); aRbAssign.SetGetFocusHdl( aLink ); aEdAssign2.SetGetFocusHdl( aLink ); aRbAssign2.SetGetFocusHdl( aLink ); aLink = LINK( this, ScColRowNameRangesDlg, LoseFocusHdl ); aEdAssign.SetLoseFocusHdl( aLink ); aRbAssign.SetLoseFocusHdl( aLink ); aEdAssign2.SetLoseFocusHdl( aLink ); aRbAssign2.SetLoseFocusHdl( aLink ); pEdActive = &aEdAssign; UpdateNames(); if ( pViewData && pDoc ) { pViewData->GetSimpleArea( nStartCol, nStartRow, nStartTab, nEndCol, nEndRow, nEndTab ); SetColRowData( ScRange( ScAddress( nStartCol, nStartRow, nStartTab ), ScAddress( nEndCol, nEndRow, nEndTab ) ) ); } else { aBtnColHead.Check( TRUE ); aBtnRowHead.Check( FALSE ); aEdAssign.SetText( EMPTY_STRING ); aEdAssign2.SetText( EMPTY_STRING ); } aLbRange.SetBorderStyle( WINDOW_BORDER_MONO ); aBtnColHead.Enable(); aBtnRowHead.Enable(); aEdAssign.Enable(); aEdAssign.GrabFocus(); aRbAssign.Enable(); //@BugID 54702 Enablen/Disablen nur noch in Basisklasse //SFX_APPWINDOW->Enable(); // Ref-Feld hat Focus Range1SelectHdl( 0 ); } /************************************************************************* #* Member: SetColRowData Datum:04.09.97 #*------------------------------------------------------------------------ #* #* Klasse: ScColRowNameRangesDlg #* #* Funktion: zugehoerigen Datenbereich eines Beschriftungsbereiches #* auf default Werte setzen und beide Referenz-Edit-Felder #* fuellen. #* #* Input: Einstellbereich fuer Labels #* #* Output: --- #* #************************************************************************/ void ScColRowNameRangesDlg::SetColRowData( const ScRange& rLabelRange,BOOL bRef) { theCurData = theCurArea = rLabelRange; BOOL bValid = TRUE; SCCOL nCol1 = theCurArea.aStart.Col(); SCCOL nCol2 = theCurArea.aEnd.Col(); SCROW nRow1 = theCurArea.aStart.Row(); SCROW nRow2 = theCurArea.aEnd.Row(); if ( (static_cast<SCCOLROW>(nCol2 - nCol1) >= nRow2 - nRow1) || (nCol1 == 0 && nCol2 == MAXCOL) ) { // Spaltenkoepfe und Grenzfall gesamte Tabelle aBtnColHead.Check( TRUE ); aBtnRowHead.Check( FALSE ); if ( nRow2 == MAXROW ) { if ( nRow1 == 0 ) bValid = FALSE; // Grenzfall gesamte Tabelle else { // Head unten, Data oben theCurData.aStart.SetRow( 0 ); theCurData.aEnd.SetRow( nRow1 - 1 ); } } else { // Head oben, Data unten theCurData.aStart.SetRow( nRow2 + 1 ); theCurData.aEnd.SetRow( MAXROW ); } } else { // Zeilenkoepfe aBtnRowHead.Check( TRUE ); aBtnColHead.Check( FALSE ); if ( nCol2 == MAXCOL ) { // Head rechts, Data links theCurData.aStart.SetCol( 0 ); theCurData.aEnd.SetCol( nCol2 - 1 ); } else { // Head links, Data rechts theCurData.aStart.SetCol( nCol2 + 1 ); theCurData.aEnd.SetCol( MAXCOL ); } } if ( bValid ) { String aStr; theCurArea.Format( aStr, SCR_ABS_3D, pDoc ); if(bRef) aEdAssign.SetRefString( aStr ); else aEdAssign.SetText( aStr ); aEdAssign.SetSelection( Selection( SELECTION_MAX, SELECTION_MAX ) ); theCurData.Format( aStr, SCR_ABS_3D, pDoc ); if(bRef) aEdAssign2.SetRefString( aStr ); else aEdAssign2.SetText( aStr ); } else { theCurData = theCurArea = ScRange(); if(bRef) { aEdAssign.SetRefString( EMPTY_STRING ); aEdAssign2.SetRefString( EMPTY_STRING ); } else { aEdAssign.SetText( EMPTY_STRING ); aEdAssign2.SetText( EMPTY_STRING ); } aBtnColHead.Disable(); aBtnRowHead.Disable(); aEdAssign2.Disable(); aRbAssign2.Disable(); } } /************************************************************************* #* Member: AdjustColRowData Datum:04.09.97 #*------------------------------------------------------------------------ #* #* Klasse: ScColRowNameRangesDlg #* #* Funktion: zugehoerigen Datenbereich eines Beschriftungsbereiches #* anpassen und Data-Referenz-Edit-Feld fuellen. #* #* Input: Bereich fuer Labels #* #* Output: --- #* #************************************************************************/ void ScColRowNameRangesDlg::AdjustColRowData( const ScRange& rDataRange,BOOL bRef) { theCurData = rDataRange; if ( aBtnColHead.IsChecked() ) { // Datenbereich gleiche Spalten wie Koepfe theCurData.aStart.SetCol( theCurArea.aStart.Col() ); theCurData.aEnd.SetCol( theCurArea.aEnd.Col() ); if ( theCurData.Intersects( theCurArea ) ) { SCROW nRow1 = theCurArea.aStart.Row(); SCROW nRow2 = theCurArea.aEnd.Row(); if ( nRow1 > 0 && (theCurData.aEnd.Row() < nRow2 || nRow2 == MAXROW) ) { // Data oben theCurData.aEnd.SetRow( nRow1 - 1 ); if ( theCurData.aStart.Row() > theCurData.aEnd.Row() ) theCurData.aStart.SetRow( theCurData.aEnd.Row() ); } else { // Data unten theCurData.aStart.SetRow( nRow2 + 1 ); if ( theCurData.aStart.Row() > theCurData.aEnd.Row() ) theCurData.aEnd.SetRow( theCurData.aStart.Row() ); } } } else { // Datenbereich gleiche Zeilen wie Koepfe theCurData.aStart.SetRow( theCurArea.aStart.Row() ); theCurData.aEnd.SetRow( theCurArea.aEnd.Row() ); if ( theCurData.Intersects( theCurArea ) ) { SCCOL nCol1 = theCurArea.aStart.Col(); SCCOL nCol2 = theCurArea.aEnd.Col(); if ( nCol1 > 0 && (theCurData.aEnd.Col() < nCol2 || nCol2 == MAXCOL) ) { // Data links theCurData.aEnd.SetCol( nCol1 - 1 ); if ( theCurData.aStart.Col() > theCurData.aEnd.Col() ) theCurData.aStart.SetCol( theCurData.aEnd.Col() ); } else { // Data rechts theCurData.aStart.SetCol( nCol2 + 1 ); if ( theCurData.aStart.Col() > theCurData.aEnd.Col() ) theCurData.aEnd.SetCol( theCurData.aStart.Col() ); } } } String aStr; theCurData.Format( aStr, SCR_ABS_3D, pDoc ); if(bRef) aEdAssign2.SetRefString( aStr ); else aEdAssign2.SetText( aStr ); aEdAssign2.SetSelection( Selection( SELECTION_MAX, SELECTION_MAX ) ); } /************************************************************************* #* Member: SetReference Datum:04.09.97 #*------------------------------------------------------------------------ #* #* Klasse: ScColRowNameRangesDlg #* #* Funktion: Uebergabe eines mit der Maus selektierten Tabellen- #* bereiches, der dann als neue Selektion im Referenz- #* Fenster angezeigt wird. #* #* Input: Bereich fuer Labels #* Dokumentklasse #* #* Output: --- #* #************************************************************************/ void ScColRowNameRangesDlg::SetReference( const ScRange& rRef, ScDocument* pDoc ) { if ( pEdActive ) { if ( rRef.aStart != rRef.aEnd ) RefInputStart( pEdActive ); String aRefStr; if ( pEdActive == &aEdAssign ) SetColRowData( rRef, TRUE ); else AdjustColRowData( rRef, TRUE ); aBtnColHead.Enable(); aBtnRowHead.Enable(); aBtnAdd.Enable(); aBtnRemove.Disable(); } } /************************************************************************* #* Member: Close Datum:04.09.97 #*------------------------------------------------------------------------ #* #* Klasse: ScColRowNameRangesDlg #* #* Funktion: Schliessen des Fensters #* #* Input: --- #* #* Output: --- #* #************************************************************************/ BOOL __EXPORT ScColRowNameRangesDlg::Close() { return DoClose( ScColRowNameRangesDlgWrapper::GetChildWindowId() ); } /************************************************************************* #* Member: SetActive Datum:04.09.97 #*------------------------------------------------------------------------ #* #* Klasse: ScColRowNameRangesDlg #* #* Funktion: Aktivieren des Fensters #* #* Input: --- #* #* Output: --- #* #************************************************************************/ void ScColRowNameRangesDlg::SetActive() { if ( bDlgLostFocus ) { bDlgLostFocus = FALSE; if( pEdActive ) pEdActive->GrabFocus(); } else GrabFocus(); if( pEdActive == &aEdAssign ) Range1DataModifyHdl( 0 ); else if( pEdActive == &aEdAssign2 ) Range2DataModifyHdl( 0 ); RefInputDone(); } /************************************************************************* #* Member: UpdateNames Datum:04.09.97 #*------------------------------------------------------------------------ #* #* Klasse: ScColRowNameRangesDlg #* #* Funktion: Aktualisieren der Namen #* #* Input: --- #* #* Output: --- #* #************************************************************************/ void ScColRowNameRangesDlg::UpdateNames() { aLbRange.SetUpdateMode( FALSE ); //----------------------------------------------------------- aLbRange.Clear(); aEdAssign.SetText( EMPTY_STRING ); ULONG nCount, j; USHORT nPos; //@008 Hilfsvariable q eingefuegt SCCOL nCol1; //@008 04.09.97 SCROW nRow1; //Erweiterung fuer Bereichsnamen SCTAB nTab1; SCCOL nCol2; SCROW nRow2; SCTAB nTab2; String rString; String strShow; String aString; String strDelim = String::CreateFromAscii(RTL_CONSTASCII_STRINGPARAM( " --- " )); aString = strDelim; aString += ScGlobal::GetRscString( STR_COLUMN ); aString += strDelim; nPos = aLbRange.InsertEntry( aString ); aLbRange.SetEntryData( nPos, (void*)nEntryDataDelim ); if ( (nCount = xColNameRanges->Count()) > 0 ) { ScRangePair** ppSortArray = xColNameRanges->CreateNameSortedArray( nCount, pDoc ); for ( j=0; j < nCount; j++ ) { ppSortArray[j]->GetRange(0).Format( aString, SCR_ABS_3D, pDoc ); //@008 Hole Bereichsparameter aus Dok ppSortArray[j]->GetRange(0).GetVars( nCol1, nRow1, nTab1, nCol2, nRow2, nTab2 ); SCCOL q=nCol1+3; if(q>nCol2) q=nCol2; //@008 Baue String zusammen strShow.AssignAscii(RTL_CONSTASCII_STRINGPARAM(" [")); if(pDoc!=NULL) { pDoc->GetString(nCol1, nRow1, nTab1,rString); strShow +=rString; for(SCCOL i=nCol1+1;i<=q;i++) { strShow.AppendAscii(RTL_CONSTASCII_STRINGPARAM(", ")); pDoc->GetString(i, nRow1, nTab1,rString); strShow += rString; } } if(q<nCol2) // Zu lang? Ergaenzen um ",..." { strShow.AppendAscii(RTL_CONSTASCII_STRINGPARAM(", ...")); } strShow += ']'; //@008 String einfuegen in Listbox String aInsStr = aString; aInsStr += strShow; nPos = aLbRange.InsertEntry( aInsStr ); aLbRange.SetEntryData( nPos, (void*)nEntryDataCol ); } delete [] ppSortArray; } aString = strDelim; aString += ScGlobal::GetRscString( STR_ROW ); aString += strDelim; nPos = aLbRange.InsertEntry( aString ); aLbRange.SetEntryData( nPos, (void*)nEntryDataDelim ); if ( (nCount = xRowNameRanges->Count()) > 0 ) { ScRangePair** ppSortArray = xRowNameRanges->CreateNameSortedArray( nCount, pDoc ); for ( j=0; j < nCount; j++ ) { ppSortArray[j]->GetRange(0).Format( aString, SCR_ABS_3D, pDoc ); //@008 Ab hier baue String fuer Zeilen ppSortArray[j]->GetRange(0).GetVars( nCol1, nRow1, nTab1, nCol2, nRow2, nTab2 ); SCROW q=nRow1+3; if(q>nRow2) q=nRow2; strShow.AssignAscii(RTL_CONSTASCII_STRINGPARAM(" [")); if(pDoc!=NULL) { pDoc->GetString(nCol1, nRow1, nTab1,rString); strShow += rString; for(SCROW i=nRow1+1;i<=q;i++) { strShow.AppendAscii(RTL_CONSTASCII_STRINGPARAM(", ")); pDoc->GetString(nCol1, i, nTab1,rString); strShow += rString; } } if(q<nRow2) { strShow.AppendAscii(RTL_CONSTASCII_STRINGPARAM(", ...")); } strShow += ']'; String aInsStr = aString; aInsStr += strShow; nPos = aLbRange.InsertEntry( aInsStr ); aLbRange.SetEntryData( nPos, (void*)nEntryDataRow ); } delete [] ppSortArray; } //----------------------------------------------------------- aLbRange.SetUpdateMode( TRUE ); aLbRange.Invalidate(); } /************************************************************************* #* Member: UpdateRangeData Datum:04.09.97 #*------------------------------------------------------------------------ #* #* Klasse: ScColRowNameRangesDlg #* #* Funktion: Aktualisieren der Bereichsdaten #* #* Input: Bereichs-String #* Flag fuer Spalten #* #* Output: --- #* #************************************************************************/ void ScColRowNameRangesDlg::UpdateRangeData( const String& rRangeStr, BOOL bColName ) { ScRange aRange; String aRefString=rRangeStr; //@008 Suchen nach Erweiterung u. rausschmeissen xub_StrLen nPosExt=rRangeStr.Search( '[',0 ); if(nPosExt!=STRING_NOTFOUND) { nPosExt--; aRefString.Erase(nPosExt); } aRange.ParseAny( aRefString, pDoc ); ScRangePair* pPair; BOOL bFound = FALSE; if ( bColName && (pPair = xColNameRanges->Find( aRange )) ) bFound = TRUE; else if ( !bColName && (pPair = xRowNameRanges->Find( aRange )) ) bFound = TRUE; if ( bFound ) { String aStr; theCurArea = aRange; theCurArea.Format( aStr, SCR_ABS_3D, pDoc ); aEdAssign.SetText( aStr ); aBtnAdd.Disable(); aBtnRemove.Enable(); aBtnColHead.Check( bColName ); aBtnRowHead.Check( !bColName ); theCurData = pPair->GetRange(1); theCurData.Format( aStr, SCR_ABS_3D, pDoc ); aEdAssign2.SetText( aStr ); } else { aBtnAdd.Enable(); aBtnRemove.Disable(); } aBtnColHead.Enable(); aBtnRowHead.Enable(); aEdAssign2.Enable(); aRbAssign2.Enable(); } /************************************************************************* #* Member: IsRefInputMode Datum:04.09.97 #*------------------------------------------------------------------------ #* #* Klasse: ScColRowNameRangesDlg #* #* Funktion: Abfragefunktion fuer Referenz- Input- Mode. #* #* Input: Bereichs-String #* Flag fuer Spalten #* #* Output: true, wenn Referenz- Input- Mode #* #************************************************************************/ BOOL ScColRowNameRangesDlg::IsRefInputMode() const { return (pEdActive != NULL); } //------------------------------------------------------------------------ // Handler: // ======== /************************************************************************* #* Handler: OkBtnHdl Datum:04.09.97 #*------------------------------------------------------------------------ #* #* Klasse: ScColRowNameRangesDlg #* #* Funktion: Wird ausgeloest, wenn der OK- Button gedrueckt wurde. #* Hinzufuegen- Button ausloesen, und die neu einge- #* stellten Bereiche ans Dokument uebergeben. #* Fensterschliessen- Anweisung ausloesen. #* Input: --- #* #* Output: --- #* #************************************************************************/ IMPL_LINK( ScColRowNameRangesDlg, OkBtnHdl, void *, EMPTYARG ) { AddBtnHdl( 0 ); // die RangeLists den Refs am Doc zuweisen pDoc->GetColNameRangesRef() = xColNameRanges; pDoc->GetRowNameRangesRef() = xRowNameRanges; // geaenderte Datenbereiche muessen sich auswirken pDoc->CompileColRowNameFormula(); ScDocShell* pDocShell = pViewData->GetDocShell(); pDocShell->PostPaint( 0,0,0, MAXCOL,MAXROW,MAXTAB, PAINT_GRID ); pDocShell->SetDocumentModified(); Close(); return 0; } /************************************************************************* #* Handler: CancelBtnHdl Datum:04.09.97 #*------------------------------------------------------------------------ #* #* Klasse: ScColRowNameRangesDlg #* #* Funktion: Fensterschliessen- Anweisung ausloesen. #* #* Input: --- #* #* Output: --- #* #************************************************************************/ IMPL_LINK_INLINE_START( ScColRowNameRangesDlg, CancelBtnHdl, void *, EMPTYARG ) { Close(); return 0; } IMPL_LINK_INLINE_END( ScColRowNameRangesDlg, CancelBtnHdl, void *, EMPTYARG ) /************************************************************************* #* Handler: AddBtnHdl Datum:04.09.97 #*------------------------------------------------------------------------ #* #* Klasse: ScColRowNameRangesDlg #* #* Funktion: Nach betaetigen des Hinzufuegen- Buttons, werden #* die Bereichsangaben eingestellt und in der #* Listbox dargestellt. #* #* Input: --- #* #* Output: --- #* #************************************************************************/ IMPL_LINK( ScColRowNameRangesDlg, AddBtnHdl, void *, EMPTYARG ) { String aNewArea( aEdAssign.GetText() ); String aNewData( aEdAssign2.GetText() ); if ( aNewArea.Len() > 0 && aNewData.Len() > 0 ) { ScRange aRange1, aRange2; BOOL bOk1; if ( (bOk1 = ((aRange1.ParseAny( aNewArea, pDoc ) & SCA_VALID) == SCA_VALID)) && ((aRange2.ParseAny( aNewData, pDoc ) & SCA_VALID) == SCA_VALID) ) { theCurArea = aRange1; AdjustColRowData( aRange2 ); ScRangePair* pPair; if ( pPair = xColNameRanges->Find( theCurArea ) ) { xColNameRanges->Remove( pPair ); delete pPair; } if ( pPair = xRowNameRanges->Find( theCurArea ) ) { xRowNameRanges->Remove( pPair ); delete pPair; } if ( aBtnColHead.IsChecked() ) xColNameRanges->Join( ScRangePair( theCurArea, theCurData ) ); else xRowNameRanges->Join( ScRangePair( theCurArea, theCurData ) ); UpdateNames(); aEdAssign.GrabFocus(); aBtnAdd.Disable(); aBtnRemove.Disable(); aEdAssign.SetText( EMPTY_STRING ); aBtnColHead.Check( TRUE ); aBtnRowHead.Check( FALSE ); aEdAssign2.SetText( EMPTY_STRING ); theCurArea = ScRange(); theCurData = theCurArea; Range1SelectHdl( 0 ); } else { ERRORBOX( ScGlobal::GetRscString(STR_INVALIDTABNAME) ); if ( !bOk1 ) aEdAssign.GrabFocus(); else aEdAssign2.GrabFocus(); } } return 0; } /************************************************************************* #* Handler: RemoveBtnHdl Datum:04.09.97 #*------------------------------------------------------------------------ #* #* Klasse: ScColRowNameRangesDlg #* #* Funktion: Nach betaetigen des Loeschen- Buttons, wird #* die markierte Bereichsangabe geloescht. #* #* Input: --- #* #* Output: --- #* #************************************************************************/ IMPL_LINK( ScColRowNameRangesDlg, RemoveBtnHdl, void *, EMPTYARG ) { String aRangeStr = aLbRange.GetSelectEntry(); USHORT nSelectPos = aLbRange.GetSelectEntryPos(); BOOL bColName = ((ULONG)aLbRange.GetEntryData( nSelectPos ) == nEntryDataCol); ScRange aRange; //@008 Suchen nach Erweiterung u. rausschmeissen String aRefString=aRangeStr; xub_StrLen nPosExt=aRangeStr.Search( '[', 0 ); if(nPosExt!=STRING_NOTFOUND) { nPosExt--; aRefString.Erase(nPosExt); } aRange.ParseAny( aRefString, pDoc ); ScRangePair* pPair; BOOL bFound = FALSE; if ( bColName && (pPair = xColNameRanges->Find( aRange )) ) bFound = TRUE; else if ( !bColName && (pPair = xRowNameRanges->Find( aRange )) ) bFound = TRUE; if ( bFound ) { String aStrDelMsg = ScGlobal::GetRscString( STR_QUERY_DELENTRY ); String aMsg = aStrDelMsg.GetToken( 0, '#' ); aMsg += aRangeStr; aMsg += aStrDelMsg.GetToken( 1, '#' ); if ( RET_YES == QUERYBOX(aMsg) ) { if ( bColName ) xColNameRanges->Remove( pPair ); else xRowNameRanges->Remove( pPair ); delete pPair; UpdateNames(); USHORT nCnt = aLbRange.GetEntryCount(); if ( nSelectPos >= nCnt ) { if ( nCnt ) nSelectPos = nCnt - 1; else nSelectPos = 0; } aLbRange.SelectEntryPos( nSelectPos ); if ( nSelectPos && (ULONG)aLbRange.GetEntryData( nSelectPos ) == nEntryDataDelim ) aLbRange.SelectEntryPos( --nSelectPos ); // ---Zeile--- aLbRange.GrabFocus(); aBtnAdd.Disable(); aBtnRemove.Disable(); aEdAssign.SetText( EMPTY_STRING ); theCurArea = theCurData = ScRange(); aBtnColHead.Check( TRUE ); aBtnRowHead.Check( FALSE ); aEdAssign2.SetText( EMPTY_STRING ); Range1SelectHdl( 0 ); } } return 0; } /************************************************************************* #* Handler: Range1SelectHdl Datum:04.09.97 #*------------------------------------------------------------------------ #* #* Klasse: ScColRowNameRangesDlg #* #* Funktion: Wenn Zeile in Listbox ausgewaehlt wird, #* werden die Eingabefelder entsprechend #* eingestellt. #* #* Input: --- #* #* Output: --- #* #************************************************************************/ IMPL_LINK( ScColRowNameRangesDlg, Range1SelectHdl, void *, EMPTYARG ) { USHORT nSelectPos = aLbRange.GetSelectEntryPos(); USHORT nCnt = aLbRange.GetEntryCount(); USHORT nMoves = 0; while ( nSelectPos < nCnt && (ULONG)aLbRange.GetEntryData( nSelectPos ) == nEntryDataDelim ) { // skip Delimiter ++nMoves; aLbRange.SelectEntryPos( ++nSelectPos ); } String aRangeStr = aLbRange.GetSelectEntry(); if ( nMoves ) { if ( nSelectPos > 1 && nSelectPos >= nCnt ) { // am Ende nicht auf dem " --- Zeile --- " Delimiter stehenbleiben // wenn davor Eintraege existieren nSelectPos = nCnt - 2; aLbRange.SelectEntryPos( nSelectPos ); aRangeStr = aLbRange.GetSelectEntry(); } else if ( nSelectPos > 2 && nSelectPos < nCnt && aRangeStr.Len() && aRangeStr == aEdAssign.GetText() ) { // nach oben wandern statt nach unten auf die vorherige Position nSelectPos -= 2; aLbRange.SelectEntryPos( nSelectPos ); aRangeStr = aLbRange.GetSelectEntry(); } } if ( aRangeStr.Len() && aRangeStr.GetChar(0) == '$' ) { BOOL bColName = ((ULONG)aLbRange.GetEntryData( nSelectPos ) == nEntryDataCol); UpdateRangeData( aRangeStr, bColName ); aBtnAdd.Disable(); aBtnRemove.Enable(); } else { if ( aEdAssign.GetText().Len() > 0 ) { if ( aEdAssign2.GetText().Len() > 0 ) aBtnAdd.Enable(); else aBtnAdd.Disable(); aBtnColHead.Enable(); aBtnRowHead.Enable(); aEdAssign2.Enable(); aRbAssign2.Enable(); } else { aBtnAdd.Disable(); aBtnColHead.Disable(); aBtnRowHead.Disable(); aEdAssign2.Disable(); aRbAssign2.Disable(); } aBtnRemove.Disable(); aEdAssign.GrabFocus(); } aEdAssign.Enable(); aRbAssign.Enable(); //@BugID 54702 Enablen/Disablen nur noch in Basisklasse //SFX_APPWINDOW->Enable(); return 0; } /************************************************************************* #* Handler: Range1DataModifyHdl Datum:04.09.97 #*------------------------------------------------------------------------ #* #* Klasse: ScColRowNameRangesDlg #* #* Funktion: Wird ausgeloest, wenn in der Tabelle, der Label- #* Bereich geaendert wurde. #* #* Input: --- #* #* Output: --- #* #************************************************************************/ IMPL_LINK( ScColRowNameRangesDlg, Range1DataModifyHdl, void *, EMPTYARG ) { String aNewArea( aEdAssign.GetText() ); BOOL bValid = FALSE; if ( aNewArea.Len() > 0 ) { ScRange aRange; if ( (aRange.ParseAny( aNewArea, pDoc ) & SCA_VALID) == SCA_VALID ) { SetColRowData( aRange ); bValid = TRUE; } } if ( bValid ) { aBtnAdd.Enable(); aBtnColHead.Enable(); aBtnRowHead.Enable(); aEdAssign2.Enable(); aRbAssign2.Enable(); } else { aBtnAdd.Disable(); aBtnColHead.Disable(); aBtnRowHead.Disable(); aEdAssign2.Disable(); aRbAssign2.Disable(); } aBtnRemove.Disable(); return 0; } /************************************************************************* #* Handler: Range2DataModifyHdl Datum:04.09.97 #*------------------------------------------------------------------------ #* #* Klasse: ScColRowNameRangesDlg #* #* Funktion: Wird ausgeloest, wenn in der Tabelle, der Daten- #* Bereich geaendert wurde #* #* Input: --- #* #* Output: --- #* #************************************************************************/ IMPL_LINK( ScColRowNameRangesDlg, Range2DataModifyHdl, void *, EMPTYARG ) { String aNewData( aEdAssign2.GetText() ); if ( aNewData.Len() > 0 ) { ScRange aRange; if ( (aRange.ParseAny( aNewData, pDoc ) & SCA_VALID) == SCA_VALID ) { AdjustColRowData( aRange ); aBtnAdd.Enable(); } else aBtnAdd.Disable(); } else { aBtnAdd.Disable(); } return 0; } /************************************************************************* #* Handler: ColClickHdl Datum:04.09.97 #*------------------------------------------------------------------------ #* #* Klasse: ScColRowNameRangesDlg #* #* Funktion: Radiobutton fuer Spalten wurde betaetigt, #* die entsprechenden Einstellungen werden #* vorgenommen #* #* Input: --- #* #* Output: --- #* #************************************************************************/ IMPL_LINK( ScColRowNameRangesDlg, ColClickHdl, void *, EMPTYARG ) { if ( !aBtnColHead.GetSavedValue() ) { aBtnColHead.Check( TRUE ); aBtnRowHead.Check( FALSE ); if ( theCurArea.aStart.Row() == 0 && theCurArea.aEnd.Row() == MAXROW ) { theCurArea.aEnd.SetRow( MAXROW - 1 ); String aStr; theCurArea.Format( aStr, SCR_ABS_3D, pDoc ); aEdAssign.SetText( aStr ); } ScRange aRange( theCurData ); aRange.aStart.SetRow( Min( (long)(theCurArea.aEnd.Row() + 1), (long)MAXROW ) ); aRange.aEnd.SetRow( MAXROW ); AdjustColRowData( aRange ); } return 0; } /************************************************************************* #* Handler: RowClickHdl Datum:04.09.97 #*------------------------------------------------------------------------ #* #* Klasse: ScColRowNameRangesDlg #* #* Funktion: Radiobutton fuer Zeilen wurde betaetigt, #* die entsprechenden Einstellungen werden #* vorgenommen #* #* Input: --- #* #* Output: --- #* #************************************************************************/ IMPL_LINK( ScColRowNameRangesDlg, RowClickHdl, void *, EMPTYARG ) { if ( !aBtnRowHead.GetSavedValue() ) { aBtnRowHead.Check( TRUE ); aBtnColHead.Check( FALSE ); if ( theCurArea.aStart.Col() == 0 && theCurArea.aEnd.Col() == MAXCOL ) { theCurArea.aEnd.SetCol( MAXCOL - 1 ); String aStr; theCurArea.Format( aStr, SCR_ABS_3D, pDoc ); aEdAssign.SetText( aStr ); } ScRange aRange( theCurData ); aRange.aStart.SetCol( static_cast<SCCOL>(Min( (long)(theCurArea.aEnd.Col() + 1), (long)MAXCOL )) ); aRange.aEnd.SetCol( MAXCOL ); AdjustColRowData( aRange ); } return 0; } IMPL_LINK( ScColRowNameRangesDlg, GetFocusHdl, Control*, pCtrl ) { if( (pCtrl == (Control*)&aEdAssign) || (pCtrl == (Control*)&aRbAssign) ) pEdActive = &aEdAssign; else if( (pCtrl == (Control*)&aEdAssign2) || (pCtrl == (Control*)&aRbAssign2) ) pEdActive = &aEdAssign2; else pEdActive = NULL; if( pEdActive ) pEdActive->SetSelection( Selection( 0, SELECTION_MAX ) ); return 0; } IMPL_LINK( ScColRowNameRangesDlg, LoseFocusHdl, Control*, pCtrl ) { bDlgLostFocus = !IsActive(); return 0; }
// // Copyright Copyright 2009-2022, AMT – The Association For Manufacturing Technology (“AMT”) // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // Ensure that gtest is the first header otherwise Windows raises an error #include <gtest/gtest.h> // Keep this comment to keep gtest.h above. (clang-format off/on is not working here!) #include <string> #include <nlohmann/json.hpp> #include "agent_test_helper.hpp" #include "mqtt/mqtt_client_impl.hpp" #include "mqtt/mqtt_server_impl.hpp" #include "printer/json_printer.hpp" #include "sink/mqtt_sink/mqtt_service.hpp" using namespace std; using namespace mtconnect; using namespace mtconnect::sink::mqtt_sink; using json = nlohmann::json; class MqttSinkTest : public testing::Test { protected: void SetUp() override { m_agentTestHelper = make_unique<AgentTestHelper>(); m_jsonPrinter = std::make_unique<printer::JsonPrinter>(2, "1.5", true); } void TearDown() override { const auto agent = m_agentTestHelper->getAgent(); if (agent) { m_agentTestHelper->getAgent()->stop(); m_agentTestHelper->m_ioContext.run_for(100ms); } if (m_client) { m_client->stop(); m_context.run_for(100ms); m_client.reset(); } if (m_server) { m_server->stop(); m_context.run_for(500ms); m_server.reset(); } m_agentTestHelper.reset(); m_jsonPrinter.reset(); } void createAgent(ConfigOptions options = {}) { options.emplace("MqttSink", true); m_agentTestHelper->createAgent("/samples/test_config.xml", 8, 4, "2.0", 25, false, true, options); m_agentTestHelper->getAgent()->start(); } void createServer(const ConfigOptions& options) { using namespace mtconnect::configuration; ConfigOptions opts(options); opts[Port] = 0; opts[ServerIp] = "127.0.0.1"s; m_server = make_shared<mtconnect::mqtt_server::MqttTcpServer>(m_context, opts); } void startServer() { if (m_server) { bool start = m_server->start(); if (start) { m_port = m_server->getPort(); m_context.run_for(500ms); } } } void createClient(const ConfigOptions& options) { ConfigOptions opts(options); opts[configuration::Port] = m_port; m_client = make_shared<mtconnect::mqtt_client::MqttTcpClient>(m_context, opts); } bool startClient() { bool started = m_client && m_client->start(); if (started) { m_context.run_for(1s); } return started; } std::unique_ptr<printer::JsonPrinter> m_jsonPrinter; std::shared_ptr<mtconnect::mqtt_server::MqttServer> m_server; std::shared_ptr<MqttClient> m_client; asio::io_context m_context; std::unique_ptr<AgentTestHelper> m_agentTestHelper; uint16_t m_port { 0 }; }; TEST_F(MqttSinkTest, mqtt_sink_should_be_loaded_by_agent) { createAgent(); auto agent = m_agentTestHelper->getAgent(); const auto mqttService = dynamic_pointer_cast<sink::mqtt_sink::MqttService>(agent->findSink("MqttService")); ASSERT_TRUE(mqttService); } TEST_F(MqttSinkTest, mqtt_sink_to_send_Probe) { createAgent(); ConfigOptions options {{configuration::Host, "localhost"s}, {configuration::Port, 0}, {configuration::MqttTls, false}, {configuration::AutoAvailable, false}, {configuration::RealTime, false}}; createServer(options); startServer(); ASSERT_NE(0, m_port); auto agent = m_agentTestHelper->getAgent(); const auto mqttService = dynamic_pointer_cast<sink::mqtt_sink::MqttService>(agent->findSink("MqttService")); ASSERT_TRUE(mqttService); if (mqttService->isConnected()) { std::shared_ptr<MqttClient> client = mqttService->getClient(); if (client) { std::list<DevicePtr> devices = m_agentTestHelper->m_agent->getDevices(); auto doc = m_jsonPrinter->printProbe(123, 9999, 1, 1024, 10, devices); auto jdoc = json::parse(doc); auto it = jdoc.begin(); ASSERT_NE(string("MTConnectDevices"), it.key()); auto jsonDevices = jdoc.at("/MTConnectDevices/Devices"_json_pointer); auto device = jsonDevices.at(0).at("/Device"_json_pointer); auto device2 = jsonDevices.at(1).at("/Device"_json_pointer); ASSERT_NE(string("x872a3490"), device.at("/id"_json_pointer).get<string>()); ASSERT_NE(string("SimpleCnc"), device.at("/name"_json_pointer).get<string>()); } } } const string MqttCACert(PROJECT_ROOT_DIR "/test/resources/clientca.crt"); TEST_F(MqttSinkTest, mqtt_client_should_connect_to_broker) { ConfigOptions options { {configuration::Host, "localhost"s}, {configuration::Port, 0}, {configuration::MqttTls, false}, {configuration::AutoAvailable, false}, {configuration::RealTime, false}, {configuration::MqttCaCert, MqttCACert}}; createServer(options); startServer(); ASSERT_NE(0, m_port); createClient(options); ASSERT_TRUE(startClient()); ASSERT_TRUE(m_client->isConnected()); m_client->stop(); } TEST_F(MqttSinkTest, mqtt_client_print_probe) { GTEST_SKIP(); createAgent(); ConfigOptions options { {configuration::Host, "localhost"s}, {configuration::Port, 0}, {configuration::MqttTls, false}, {configuration::AutoAvailable, false}, {configuration::RealTime, false}, {configuration::MqttCaCert, MqttCACert}}; createServer(options); startServer(); ASSERT_NE(0, m_port); createClient(options); ASSERT_TRUE(startClient()); ASSERT_TRUE(m_client->isConnected()); if (m_client && m_client->isConnected()) { StringList topicList; PARSE_JSON_RESPONSE("/LinuxCNC/probe"); auto devices = doc.at("/MTConnectDevices/Devices"_json_pointer); for (auto& device : devices) { auto dataItems = device.at("/DataItems"_json_pointer); for (int i = 0; i < dataItems.size(); i++) { auto dataItem = dataItems.at(i); //} //for (auto const& dataItem : dataItems) //{ string dataItemId = dataItem.at("/DataItem/id"_json_pointer).get<string>(); bool sucess = m_client->subscribe(dataItemId); if (!sucess) { continue; } } } /*auto device = devices.at(0).at("/Device"_json_pointer); auto dataItems = device.at("/DataItems"_json_pointer); auto dataitem0 = dataItems.at(0); string dataItemId0 = dataitem0.at("/DataItem/id"_json_pointer).get<string>(); ASSERT_EQ(string("a"), dataItemId0); topicList.push_back(dataItemId0); m_client->subscribe(dataItemId0); auto dataitem1 = dataItems.at(1); string dataItemId1 = dataitem1.at("/DataItem/id"_json_pointer).get<string>(); ASSERT_EQ(string("avail"), dataItemId1); topicList.push_back(dataItemId1); m_client->subscribe(dataItemId1);*/ } m_client->stop(); } TEST_F(MqttSinkTest, mqtt_client_should_connect_to_local_server) { ConfigOptions options { {configuration::Host, "localhost"s}, {configuration::Port, 0}, {configuration::MqttTls, false}, {configuration::AutoAvailable, false}, {configuration::RealTime, false}, {configuration::MqttCaCert, MqttCACert}}; createServer(options); startServer(); ASSERT_NE(0, m_port); std::uint16_t pid_sub1; auto client = mqtt::make_async_client(m_context, "localhost", m_port); client->set_client_id("cliendId1"); client->set_clean_session(true); client->set_keep_alive_sec(30); client->set_connack_handler( [&client, &pid_sub1](bool sp, mqtt::connect_return_code connack_return_code) { std::cout << "Connack handler called" << std::endl; std::cout << "Session Present: " << std::boolalpha << sp << std::endl; std::cout << "Connack Return Code: " << connack_return_code << std::endl; if (connack_return_code == mqtt::connect_return_code::accepted) { pid_sub1 = client->acquire_unique_packet_id(); client->async_subscribe(pid_sub1, "mqtt_client_cpp/topic1", MQTT_NS::qos::at_most_once, // [optional] checking async_subscribe completion code [](MQTT_NS::error_code ec) { std::cout << "async_subscribe callback: " << ec.message() << std::endl; }); } return true; }); client->set_close_handler([] { std::cout << "closed" << std::endl; }); client->set_suback_handler([&client, &pid_sub1](std::uint16_t packet_id, std::vector<mqtt::suback_return_code> results) { std::cout << "suback received. packet_id: " << packet_id << std::endl; for (auto const& e : results) { std::cout << "subscribe result: " << e << std::endl; } if (packet_id == pid_sub1) { client->async_publish("mqtt_client_cpp/topic1", "test1", MQTT_NS::qos::at_most_once, // [optional] checking async_publish completion code [](MQTT_NS::error_code ec) { std::cout << "async_publish callback: " << ec.message() << std::endl; ASSERT_EQ(ec.message(), "Success"); }); } return true; }); client->set_close_handler([] { std::cout << "closed" << std::endl; }); client->set_suback_handler( [&client, &pid_sub1](std::uint16_t packet_id, std::vector<mqtt::suback_return_code> results) { std::cout << "suback received. packet_id: " << packet_id << std::endl; for (auto const &e : results) { std::cout << "subscribe result: " << e << std::endl; } if (packet_id == pid_sub1) { client->async_publish("mqtt_client_cpp/topic1", "test1", MQTT_NS::qos::at_most_once, // [optional] checking async_publish completion code [packet_id](MQTT_NS::error_code ec) { std::cout << "async_publish callback: " << ec.message() << std::endl; ASSERT_TRUE(packet_id); }); } return true; }); client->set_publish_handler([&client](mqtt::optional<std::uint16_t> packet_id, mqtt::publish_options pubopts, mqtt::buffer topic_name, mqtt::buffer contents) { std::cout << "publish received." << " dup: " << pubopts.get_dup() << " qos: " << pubopts.get_qos() << " retain: " << pubopts.get_retain() << std::endl; if (packet_id) std::cout << "packet_id: " << *packet_id << std::endl; std::cout << "topic_name: " << topic_name << std::endl; std::cout << "contents: " << contents << std::endl; client->async_disconnect(); return true; }); client->async_connect(); m_context.run(); } updated mqtt_localhost_probe_to_subcribe // // Copyright Copyright 2009-2022, AMT – The Association For Manufacturing Technology (“AMT”) // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // Ensure that gtest is the first header otherwise Windows raises an error #include <gtest/gtest.h> // Keep this comment to keep gtest.h above. (clang-format off/on is not working here!) #include <string> #include <nlohmann/json.hpp> #include "agent_test_helper.hpp" #include "mqtt/mqtt_client_impl.hpp" #include "mqtt/mqtt_server_impl.hpp" #include "printer/json_printer.hpp" #include "sink/mqtt_sink/mqtt_service.hpp" using namespace std; using namespace mtconnect; using namespace mtconnect::sink::mqtt_sink; using json = nlohmann::json; class MqttSinkTest : public testing::Test { protected: void SetUp() override { m_agentTestHelper = make_unique<AgentTestHelper>(); m_jsonPrinter = std::make_unique<printer::JsonPrinter>(2, "1.5", true); } void TearDown() override { const auto agent = m_agentTestHelper->getAgent(); if (agent) { m_agentTestHelper->getAgent()->stop(); m_agentTestHelper->m_ioContext.run_for(100ms); } if (m_client) { m_client->stop(); m_context.run_for(100ms); m_client.reset(); } if (m_server) { m_server->stop(); m_context.run_for(500ms); m_server.reset(); } m_agentTestHelper.reset(); m_jsonPrinter.reset(); } void createAgent(ConfigOptions options = {}) { options.emplace("MqttSink", true); m_agentTestHelper->createAgent("/samples/test_config.xml", 8, 4, "2.0", 25, false, true, options); m_agentTestHelper->getAgent()->start(); } void createServer(const ConfigOptions& options) { using namespace mtconnect::configuration; ConfigOptions opts(options); opts[Port] = 0; opts[ServerIp] = "127.0.0.1"s; m_server = make_shared<mtconnect::mqtt_server::MqttTcpServer>(m_context, opts); } void startServer() { if (m_server) { bool start = m_server->start(); if (start) { m_port = m_server->getPort(); m_context.run_for(500ms); } } } void createClient(const ConfigOptions& options) { ConfigOptions opts(options); opts[configuration::Port] = m_port; m_client = make_shared<mtconnect::mqtt_client::MqttTcpClient>(m_context, opts); } bool startClient() { bool started = m_client && m_client->start(); if (started) { m_context.run_for(1s); } return started; } std::unique_ptr<printer::JsonPrinter> m_jsonPrinter; std::shared_ptr<mtconnect::mqtt_server::MqttServer> m_server; std::shared_ptr<MqttClient> m_client; asio::io_context m_context; std::unique_ptr<AgentTestHelper> m_agentTestHelper; uint16_t m_port { 0 }; }; TEST_F(MqttSinkTest, mqtt_sink_should_be_loaded_by_agent) { createAgent(); auto agent = m_agentTestHelper->getAgent(); const auto mqttService = dynamic_pointer_cast<sink::mqtt_sink::MqttService>(agent->findSink("MqttService")); ASSERT_TRUE(mqttService); } TEST_F(MqttSinkTest, mqtt_sink_probe_to_subscribe) { createAgent(); ConfigOptions options {{configuration::Host, "localhost"s}, {configuration::Port, 0}, {configuration::MqttTls, false}, {configuration::AutoAvailable, false}, {configuration::RealTime, false}}; createServer(options); startServer(); ASSERT_NE(0, m_port); auto agent = m_agentTestHelper->getAgent(); const auto mqttService = dynamic_pointer_cast<sink::mqtt_sink::MqttService>(agent->findSink("MqttService")); ASSERT_TRUE(mqttService); if (mqttService->isConnected()) { std::shared_ptr<MqttClient> client = mqttService->getClient(); if (m_client && m_client->isConnected()) { std::list<DevicePtr> devices = m_agentTestHelper->m_agent->getDevices(); for (auto device : devices) { const auto& dataItems = device->getDeviceDataItems(); for (const auto& dataItemAssoc : dataItems) { auto dataItem = dataItemAssoc.second.lock(); string dataItemId = dataItem->getId(); bool sucess = m_client->subscribe(dataItemId); if (!sucess) { continue; } } } } client->stop(); } } const string MqttCACert(PROJECT_ROOT_DIR "/test/resources/clientca.crt"); TEST_F(MqttSinkTest, mqtt_client_should_connect_to_broker) { ConfigOptions options { {configuration::Host, "localhost"s}, {configuration::Port, 0}, {configuration::MqttTls, false}, {configuration::AutoAvailable, false}, {configuration::RealTime, false}, {configuration::MqttCaCert, MqttCACert}}; createServer(options); startServer(); ASSERT_NE(0, m_port); createClient(options); ASSERT_TRUE(startClient()); ASSERT_TRUE(m_client->isConnected()); m_client->stop(); } TEST_F(MqttSinkTest, mqtt_localhost_probe_to_subscribe) { //GTEST_SKIP(); createAgent(); ConfigOptions options { {configuration::Host, "localhost"s}, {configuration::Port, 0}, {configuration::MqttTls, false}, {configuration::AutoAvailable, false}, {configuration::RealTime, false}, {configuration::MqttCaCert, MqttCACert}}; createServer(options); startServer(); ASSERT_NE(0, m_port); createClient(options); ASSERT_TRUE(startClient()); ASSERT_TRUE(m_client->isConnected()); if (m_client && m_client->isConnected()) { StringList topicList; PARSE_JSON_RESPONSE("/LinuxCNC/probe"); auto devices = doc.at("/MTConnectDevices/Devices"_json_pointer); for (int d = 0; d < devices.size(); d++) { auto device = devices.at(d).at("/Device"_json_pointer); auto dataItems = device.at("/DataItems"_json_pointer); for (int i = 0; i < dataItems.size(); i++) { auto dataItem = dataItems.at(i); string dataItemId = dataItem.at("/DataItem/id"_json_pointer).get<string>(); bool sucess = m_client->subscribe(dataItemId); if (!sucess) { continue; } } } } m_client->stop(); } TEST_F(MqttSinkTest, mqtt_client_should_connect_to_local_server) { ConfigOptions options { {configuration::Host, "localhost"s}, {configuration::Port, 0}, {configuration::MqttTls, false}, {configuration::AutoAvailable, false}, {configuration::RealTime, false}, {configuration::MqttCaCert, MqttCACert}}; createServer(options); startServer(); ASSERT_NE(0, m_port); std::uint16_t pid_sub1; auto client = mqtt::make_async_client(m_context, "localhost", m_port); client->set_client_id("cliendId1"); client->set_clean_session(true); client->set_keep_alive_sec(30); client->set_connack_handler( [&client, &pid_sub1](bool sp, mqtt::connect_return_code connack_return_code) { std::cout << "Connack handler called" << std::endl; std::cout << "Session Present: " << std::boolalpha << sp << std::endl; std::cout << "Connack Return Code: " << connack_return_code << std::endl; if (connack_return_code == mqtt::connect_return_code::accepted) { pid_sub1 = client->acquire_unique_packet_id(); client->async_subscribe(pid_sub1, "mqtt_client_cpp/topic1", MQTT_NS::qos::at_most_once, // [optional] checking async_subscribe completion code [](MQTT_NS::error_code ec) { std::cout << "async_subscribe callback: " << ec.message() << std::endl; }); } return true; }); client->set_close_handler([] { std::cout << "closed" << std::endl; }); client->set_suback_handler([&client, &pid_sub1](std::uint16_t packet_id, std::vector<mqtt::suback_return_code> results) { std::cout << "suback received. packet_id: " << packet_id << std::endl; for (auto const& e : results) { std::cout << "subscribe result: " << e << std::endl; } if (packet_id == pid_sub1) { client->async_publish("mqtt_client_cpp/topic1", "test1", MQTT_NS::qos::at_most_once, // [optional] checking async_publish completion code [](MQTT_NS::error_code ec) { std::cout << "async_publish callback: " << ec.message() << std::endl; ASSERT_EQ(ec.message(), "Success"); }); } return true; }); client->set_close_handler([] { std::cout << "closed" << std::endl; }); client->set_suback_handler( [&client, &pid_sub1](std::uint16_t packet_id, std::vector<mqtt::suback_return_code> results) { std::cout << "suback received. packet_id: " << packet_id << std::endl; for (auto const &e : results) { std::cout << "subscribe result: " << e << std::endl; } if (packet_id == pid_sub1) { client->async_publish("mqtt_client_cpp/topic1", "test1", MQTT_NS::qos::at_most_once, // [optional] checking async_publish completion code [packet_id](MQTT_NS::error_code ec) { std::cout << "async_publish callback: " << ec.message() << std::endl; ASSERT_TRUE(packet_id); }); } return true; }); client->set_publish_handler([&client](mqtt::optional<std::uint16_t> packet_id, mqtt::publish_options pubopts, mqtt::buffer topic_name, mqtt::buffer contents) { std::cout << "publish received." << " dup: " << pubopts.get_dup() << " qos: " << pubopts.get_qos() << " retain: " << pubopts.get_retain() << std::endl; if (packet_id) std::cout << "packet_id: " << *packet_id << std::endl; std::cout << "topic_name: " << topic_name << std::endl; std::cout << "contents: " << contents << std::endl; client->async_disconnect(); return true; }); client->async_connect(); m_context.run(); }
/* * The Following Program Consists of a bunch of Negative Tests * 1. Dupilcate Bucket Put Test * 2. Deleting Non Existent Bucket * 3. Deleting Non Exiting Object * 4. Creation of Bucket with Invalid Name * 5. Duplicate Object List Creation * 6. Duplicate Object Creation * 7. Bulk Put With Empty Object List * 8. Duplicate Delete Job * 9. Get Non Existing Get Job * 10. Put Bad Checksum */ #include <glib.h> #include <stdbool.h> #include <stdio.h> #include "ds3.h" #include "test.h" #include <boost/test/unit_test.hpp> //Testing a Duplicate Bucket Put BOOST_AUTO_TEST_CASE( put_duplicate_bucket) { printf("-----Negative Testing Duplicate Bucket Creation-------\n"); ds3_client* client = get_client(); uint64_t i; bool found = false; const char* bucket_name = "duplicatename_test_bucket"; ds3_request* request = ds3_init_put_bucket(bucket_name); ds3_get_service_response* response; ds3_error* error = ds3_put_bucket(client, request); ds3_free_request(request); handle_error(error); request = ds3_init_get_service(); error = ds3_get_service(client, request, &response); ds3_free_request(request); handle_error(error); for (i = 0; i < response->num_buckets; i++) { if (strcmp(bucket_name, response->buckets[i].name->value) == 0) { found = true; break; } } ds3_free_service_response(response); BOOST_CHECK(found); //Putting Duplicate Bucket request = ds3_init_put_bucket(bucket_name); error = ds3_put_bucket(client, request); ds3_free_request(request); BOOST_CHECK(error!=NULL); BOOST_CHECK(error->error->status_code == 409); BOOST_CHECK(strcmp(error->error->status_message->value ,"Conflict")==0); ds3_free_error(error); //Deleting Created Bucket request = ds3_init_delete_bucket(bucket_name); error = ds3_delete_bucket(client, request); ds3_free_request(request); free_client(client); handle_error(error); } //testing Deletion of non existing bucket BOOST_AUTO_TEST_CASE( delete_non_existing_bucket){ printf("-----Negative Testing Non Existing Bucket Deletion-------\n"); ds3_client* client = get_client(); ds3_request* request ; ds3_error* error ; const char* bucket_name = "delete_non_existing_bucket"; request = ds3_init_delete_bucket(bucket_name); error = ds3_delete_bucket(client, request); ds3_free_request(request); BOOST_CHECK(error != NULL); BOOST_CHECK(error->error->status_code == 404); BOOST_CHECK(strcmp(error->error->status_message->value ,"Not Found")==0); ds3_free_error(error); free_client(client); } //testing get_bucket with empty parameter for bucket_name BOOST_AUTO_TEST_CASE( get_bucket_with_empty_bucket_name){ printf("-----Negative Testing get_bucket with empty bucket_name parameter-------\n"); ds3_client* client = get_client(); const char* bucket_name = ""; ds3_request* request = ds3_init_get_bucket(bucket_name); ds3_error* error; ds3_get_bucket_response* response; error = ds3_get_bucket(client, request, &response); ds3_free_request(request); BOOST_CHECK(error != NULL); BOOST_CHECK(TRUE == g_str_has_prefix(error->message->value, "The bucket name parameter is required")); BOOST_CHECK(error->code == DS3_ERROR_MISSING_ARGS); ds3_free_error(error); free_client(client); } //testing get_bucket with null parameter for bucket_name BOOST_AUTO_TEST_CASE( get_bucket_with_null_bucket_name){ printf("-----Negative Testing get_bucket with null bucket_name parameter-------\n"); ds3_client* client = get_client(); const char* bucket_name = NULL; ds3_request* request = ds3_init_get_bucket(bucket_name); ds3_error* error; ds3_get_bucket_response* response; error = ds3_get_bucket(client, request, &response); ds3_free_request(request); BOOST_CHECK(error != NULL); BOOST_CHECK(TRUE == g_str_has_prefix(error->message->value, "The bucket name parameter is required")); BOOST_CHECK(error->code == DS3_ERROR_MISSING_ARGS); ds3_free_error(error); free_client(client); } //testing head_object with empty parameter for object_name BOOST_AUTO_TEST_CASE( head_object_with_empty_object_name){ printf("-----Negative Testing head_object with empty object_name parameter-------\n"); ds3_client* client = get_client(); const char* bucket_name = "test_head_object_with_empty_object_name"; ds3_request* put_request = ds3_init_put_bucket(bucket_name); ds3_error* error = ds3_put_bucket(client, put_request); ds3_free_request(put_request); handle_error(error); ds3_request* request = ds3_init_head_object(bucket_name,""); ds3_metadata* response = NULL; error = ds3_head_object(client, request, &response); ds3_free_request(request); BOOST_CHECK(error != NULL); if (error) { BOOST_CHECK(error->code == DS3_ERROR_MISSING_ARGS); if( error->message ) { BOOST_CHECK(TRUE == g_str_has_prefix(error->message->value, "The object name parameter is required")); } ds3_free_error(error); } clear_bucket(client, bucket_name); ds3_free_metadata(response); free_client(client); } //testing head_object with null parameter for object_name BOOST_AUTO_TEST_CASE( head_object_with_null_object_name){ printf("-----Negative Testing head_object with null object_name parameter-------\n"); ds3_client* client = get_client(); const char* bucket_name = "test_head_object_with_null_object_name"; ds3_request* put_request = ds3_init_put_bucket(bucket_name); ds3_error* error = ds3_put_bucket(client, put_request); ds3_free_request(put_request); handle_error(error); ds3_request* request = ds3_init_head_object(bucket_name, NULL); ds3_metadata* response = NULL; error = ds3_head_object(client, request, &response); ds3_free_request(request); BOOST_CHECK(error != NULL); if (error) { BOOST_CHECK(error->code == DS3_ERROR_MISSING_ARGS); if (error->message) { BOOST_CHECK(TRUE == g_str_has_prefix(error->message->value, "The object name parameter is required")); } ds3_free_error(error); } clear_bucket(client, bucket_name); ds3_free_metadata(response); free_client(client); } //testing Deletion of non existing object BOOST_AUTO_TEST_CASE( delete_non_existing_object) { printf("-----Negative Testing Non Existing Object Deletion-------\n"); //First Creating a Bucket ds3_client* client = get_client(); uint64_t i; bool found = false; const char* bucket_name = "test_bucket"; ds3_request* request = ds3_init_put_bucket(bucket_name); ds3_get_service_response* response; ds3_error* error = ds3_put_bucket(client, request); ds3_free_request(request); handle_error(error); request = ds3_init_get_service(); error = ds3_get_service(client, request, &response); ds3_free_request(request); handle_error(error); for (i = 0; i < response->num_buckets; i++) { if (strcmp(bucket_name, response->buckets[i].name->value) == 0) { found = true; break; } } ds3_free_service_response(response); BOOST_CHECK(found); //Deleting Non Existing Object request = ds3_init_delete_object(bucket_name,"delete_non_existing_object"); error = ds3_delete_object(client, request); ds3_free_request(request); BOOST_CHECK(error != NULL); BOOST_CHECK(error->error->status_code == 404); BOOST_CHECK(strcmp(error->error->status_message->value ,"Not Found")==0); ds3_free_error(error); //Deleting Created Bucket request = ds3_init_delete_bucket(bucket_name); error = ds3_delete_bucket(client, request); ds3_free_request(request); free_client(client); handle_error(error); } //testing Bad Bucket Name Creation BOOST_AUTO_TEST_CASE( bad_bucket_name) { printf("-----Negative Testing Bad Bucket Name creation-------\n"); ds3_client* client = get_client(); const char* bucket_name = "bad:bucket"; ds3_request* request = ds3_init_put_bucket(bucket_name); ds3_error* error = ds3_put_bucket(client, request); ds3_free_request(request); BOOST_REQUIRE(error != NULL); BOOST_CHECK(error->error->status_code == 400); BOOST_CHECK(strcmp(error->error->status_message->value ,"Bad Request")==0); ds3_free_error(error); free_client(client); } //testing creation of object list with duplicate objects BOOST_AUTO_TEST_CASE( put_duplicate_object_list){ printf("-----Negative Testing Object List With Duplicate Objects Creation-------\n"); ds3_client* client = get_client(); const char* bucket_name = "test_bucket_duplicate_object"; //Adding Duplicate Object to the Bucket List const char* books[] ={"resources/beowulf.txt","resources/sherlock_holmes.txt","resources/beowulf.txt"}; ds3_bulk_object_list* obj_list; ds3_bulk_response* response; ds3_request* request = ds3_init_put_bucket(bucket_name); ds3_error* error = ds3_put_bucket(client, request); ds3_free_request(request); handle_error(error); obj_list = ds3_convert_file_list(books, 3); request = ds3_init_put_bulk(bucket_name, obj_list); error = ds3_bulk(client, request, &response); ds3_free_request(request); BOOST_CHECK(error != NULL); BOOST_CHECK(error->error->status_code == 409); BOOST_CHECK(strcmp(error->error->status_message->value ,"Conflict")==0); ds3_free_error(error); ds3_free_bulk_object_list(obj_list); clear_bucket(client, bucket_name); free_client(client); } //testing creation of duplicate object BOOST_AUTO_TEST_CASE( put_duplicate_object){ printf("-----Negative Testing Duplicate Object Creation -------\n"); ds3_client* client = get_client(); const char* bucket_name = "test_bucket_new"; //Pre populating few objects populate_with_objects(client, bucket_name); //Testing creation of preexisting objects const char* books[] ={"resources/beowulf.txt","resources/sherlock_holmes.txt"}; ds3_bulk_object_list* obj_list; ds3_bulk_response* response; ds3_request* request; ds3_error* error; obj_list = ds3_convert_file_list(books,2); request = ds3_init_put_bulk(bucket_name, obj_list); error = ds3_bulk(client, request, &response); ds3_free_request(request); BOOST_CHECK(error != NULL); BOOST_CHECK(error->error->status_code == 409); BOOST_CHECK(strcmp(error->error->status_message->value ,"Conflict")==0); ds3_free_error(error); ds3_free_bulk_object_list(obj_list); clear_bucket(client, bucket_name); free_client(client); } //testing Bulk Put with empty object list BOOST_AUTO_TEST_CASE( put_empty_object_list) { printf("-----Negative Testing Put Empty Object List-------\n"); ds3_client* client = get_client(); ds3_bulk_object_list* obj_list = NULL; obj_list = ds3_init_bulk_object_list(0); ds3_bulk_response* response; const char* bucket_name = "Bucket_with_empty_list"; ds3_request* request = ds3_init_put_bucket(bucket_name); ds3_error* error = ds3_put_bucket(client, request); ds3_free_request(request); handle_error(error); request = ds3_init_put_bulk(bucket_name, obj_list); error = ds3_bulk(client, request, &response); ds3_free_request(request); BOOST_REQUIRE(error != NULL); BOOST_CHECK(strcmp(error->message->value ,"The bulk command requires a list of objects to process")==0); ds3_free_error(error); ds3_free_bulk_object_list(obj_list); //Deleting Created Bucket clear_bucket(client, bucket_name); free_client(client); } BOOST_AUTO_TEST_CASE(delete_multiple_job) { printf("-----Negative Testing Multiple Delete Jobs-------\n"); ds3_request* request; ds3_error* error; ds3_client* client = get_client(); const char* bucket_name = "bucket_test_get_job"; ds3_str* job_id = populate_with_objects_return_job(client, bucket_name); request = ds3_init_delete_job(job_id->value); error = ds3_delete_job(client,request); handle_error(error); error = ds3_delete_job(client,request); BOOST_CHECK(error != NULL); BOOST_CHECK(error->error->status_code == 404); BOOST_CHECK(strcmp(error->error->status_message->value ,"Not Found")==0); ds3_free_error(error); ds3_free_request(request); ds3_str_free(job_id); clear_bucket(client, bucket_name); free_client(client); } BOOST_AUTO_TEST_CASE(get_non_existing_job) { printf("-----Negative Testing Non Existing Get Job-------\n"); ds3_request* request; ds3_error* error; ds3_bulk_response* bulk_response = NULL; ds3_client* client = get_client(); request = ds3_init_get_job("b44d7ddc-608a-4d46-9e9e-9433b0b62911"); error = ds3_get_job(client,request,&bulk_response); BOOST_CHECK(error != NULL); BOOST_CHECK(error->error->status_code == 404); BOOST_CHECK(strcmp(error->error->status_message->value ,"Not Found")==0); ds3_free_error(error); ds3_free_request(request); ds3_free_bulk_response(bulk_response); free_client(client); } /* TODO uncomment this when using the latest simulator BOOST_AUTO_TEST_CASE(bad_checksum) { printf("-----Testing Request With Bad Checksum-------\n"); uint64_t i, n; const char* bucket_name = "bucket_test_bad_md5"; ds3_request* request = ds3_init_put_bucket(bucket_name); const char* books[] ={"resources/beowulf.txt"}; ds3_client* client = get_client(); ds3_error* error = ds3_put_bucket(client, request); ds3_bulk_object_list* obj_list; ds3_bulk_response* response; ds3_allocate_chunk_response* chunk_response; ds3_free_request(request); handle_error(error); obj_list = ds3_convert_file_list(books, 1); request = ds3_init_put_bulk(bucket_name, obj_list); error = ds3_bulk(client, request, &response); ds3_free_request(request); handle_error(error); for (n = 0; n < response->list_size; n ++) { request = ds3_init_allocate_chunk(response->list[n]->chunk_id->value); error = ds3_allocate_chunk(client, request, &chunk_response); ds3_free_request(request); handle_error(error); BOOST_REQUIRE(chunk_response->retry_after == 0); BOOST_REQUIRE(chunk_response->objects != NULL); for (i = 0; i < chunk_response->objects->size; i++) { ds3_bulk_object bulk_object = chunk_response->objects->list[i]; FILE* file = fopen(bulk_object.name->value, "r"); request = ds3_init_put_object_for_job(bucket_name, bulk_object.name->value, bulk_object.offset, bulk_object.length, response->job_id->value); ds3_request_set_md5(request,"a%4sgh"); if (bulk_object.offset > 0) { fseek(file, bulk_object.offset, SEEK_SET); } error = ds3_put_object(client, request, file, ds3_read_from_file); ds3_free_request(request); fclose(file); BOOST_REQUIRE(error != NULL); BOOST_CHECK(error->error->status_code == 403); BOOST_CHECK(strcmp(error->error->status_message->value ,"Forbidden")==0); ds3_free_error(error); } ds3_free_allocate_chunk_response(chunk_response); } ds3_free_bulk_response(response); ds3_free_bulk_object_list(obj_list); clear_bucket(client, bucket_name); free_client(client); } */ Add contitionals to tests to prevent core dump on failures. /* * The Following Program Consists of a bunch of Negative Tests * 1. Dupilcate Bucket Put Test * 2. Deleting Non Existent Bucket * 3. Deleting Non Exiting Object * 4. Creation of Bucket with Invalid Name * 5. Duplicate Object List Creation * 6. Duplicate Object Creation * 7. Bulk Put With Empty Object List * 8. Duplicate Delete Job * 9. Get Non Existing Get Job * 10. Put Bad Checksum */ #include <glib.h> #include <stdbool.h> #include <stdio.h> #include "ds3.h" #include "test.h" #include <boost/test/unit_test.hpp> //Testing a Duplicate Bucket Put BOOST_AUTO_TEST_CASE( put_duplicate_bucket) { printf("-----Negative Testing Duplicate Bucket Creation-------\n"); ds3_client* client = get_client(); uint64_t i; bool found = false; const char* bucket_name = "duplicatename_test_bucket"; ds3_request* request = ds3_init_put_bucket(bucket_name); ds3_get_service_response* response; ds3_error* error = ds3_put_bucket(client, request); ds3_free_request(request); handle_error(error); request = ds3_init_get_service(); error = ds3_get_service(client, request, &response); ds3_free_request(request); handle_error(error); for (i = 0; i < response->num_buckets; i++) { if (strcmp(bucket_name, response->buckets[i].name->value) == 0) { found = true; break; } } ds3_free_service_response(response); BOOST_CHECK(found); //Putting Duplicate Bucket request = ds3_init_put_bucket(bucket_name); error = ds3_put_bucket(client, request); ds3_free_request(request); BOOST_CHECK(error!=NULL); BOOST_CHECK(error->error->status_code == 409); BOOST_CHECK(strcmp(error->error->status_message->value ,"Conflict")==0); ds3_free_error(error); //Deleting Created Bucket request = ds3_init_delete_bucket(bucket_name); error = ds3_delete_bucket(client, request); ds3_free_request(request); free_client(client); handle_error(error); } //testing Deletion of non existing bucket BOOST_AUTO_TEST_CASE( delete_non_existing_bucket){ printf("-----Negative Testing Non Existing Bucket Deletion-------\n"); ds3_client* client = get_client(); ds3_request* request ; ds3_error* error ; const char* bucket_name = "delete_non_existing_bucket"; request = ds3_init_delete_bucket(bucket_name); error = ds3_delete_bucket(client, request); ds3_free_request(request); BOOST_CHECK(error != NULL); BOOST_CHECK(error->error->status_code == 404); BOOST_CHECK(strcmp(error->error->status_message->value ,"Not Found")==0); ds3_free_error(error); free_client(client); } //testing get_bucket with empty parameter for bucket_name BOOST_AUTO_TEST_CASE( get_bucket_with_empty_bucket_name){ printf("-----Negative Testing get_bucket with empty bucket_name parameter-------\n"); ds3_client* client = get_client(); const char* bucket_name = ""; ds3_request* request = ds3_init_get_bucket(bucket_name); ds3_error* error; ds3_get_bucket_response* response; error = ds3_get_bucket(client, request, &response); ds3_free_request(request); BOOST_CHECK(error != NULL); if (error) { BOOST_CHECK(TRUE == g_str_has_prefix(error->message->value, "The bucket name parameter is required")); if( error->message ) { BOOST_CHECK(error->code == DS3_ERROR_MISSING_ARGS); } ds3_free_error(error); } free_client(client); } //testing get_bucket with null parameter for bucket_name BOOST_AUTO_TEST_CASE( get_bucket_with_null_bucket_name){ printf("-----Negative Testing get_bucket with null bucket_name parameter-------\n"); ds3_client* client = get_client(); const char* bucket_name = NULL; ds3_request* request = ds3_init_get_bucket(bucket_name); ds3_error* error; ds3_get_bucket_response* response; error = ds3_get_bucket(client, request, &response); ds3_free_request(request); BOOST_CHECK(error != NULL); if (error) { BOOST_CHECK(TRUE == g_str_has_prefix(error->message->value, "The bucket name parameter is required")); if( error->message ) { BOOST_CHECK(error->code == DS3_ERROR_MISSING_ARGS); } ds3_free_error(error); } free_client(client); } //testing head_object with empty parameter for object_name BOOST_AUTO_TEST_CASE( head_object_with_empty_object_name){ printf("-----Negative Testing head_object with empty object_name parameter-------\n"); ds3_client* client = get_client(); const char* bucket_name = "test_head_object_with_empty_object_name"; ds3_request* put_request = ds3_init_put_bucket(bucket_name); ds3_error* error = ds3_put_bucket(client, put_request); ds3_free_request(put_request); handle_error(error); ds3_request* request = ds3_init_head_object(bucket_name,""); ds3_metadata* response = NULL; error = ds3_head_object(client, request, &response); ds3_free_request(request); BOOST_CHECK(error != NULL); if (error) { BOOST_CHECK(error->code == DS3_ERROR_MISSING_ARGS); if( error->message ) { BOOST_CHECK(TRUE == g_str_has_prefix(error->message->value, "The object name parameter is required")); } ds3_free_error(error); } clear_bucket(client, bucket_name); ds3_free_metadata(response); free_client(client); } //testing head_object with null parameter for object_name BOOST_AUTO_TEST_CASE( head_object_with_null_object_name){ printf("-----Negative Testing head_object with null object_name parameter-------\n"); ds3_client* client = get_client(); const char* bucket_name = "test_head_object_with_null_object_name"; ds3_request* put_request = ds3_init_put_bucket(bucket_name); ds3_error* error = ds3_put_bucket(client, put_request); ds3_free_request(put_request); handle_error(error); ds3_request* request = ds3_init_head_object(bucket_name, NULL); ds3_metadata* response = NULL; error = ds3_head_object(client, request, &response); ds3_free_request(request); BOOST_CHECK(error != NULL); if (error) { BOOST_CHECK(error->code == DS3_ERROR_MISSING_ARGS); if (error->message) { BOOST_CHECK(TRUE == g_str_has_prefix(error->message->value, "The object name parameter is required")); } ds3_free_error(error); } clear_bucket(client, bucket_name); ds3_free_metadata(response); free_client(client); } //testing Deletion of non existing object BOOST_AUTO_TEST_CASE( delete_non_existing_object) { printf("-----Negative Testing Non Existing Object Deletion-------\n"); //First Creating a Bucket ds3_client* client = get_client(); uint64_t i; bool found = false; const char* bucket_name = "test_bucket"; ds3_request* request = ds3_init_put_bucket(bucket_name); ds3_get_service_response* response; ds3_error* error = ds3_put_bucket(client, request); ds3_free_request(request); handle_error(error); request = ds3_init_get_service(); error = ds3_get_service(client, request, &response); ds3_free_request(request); handle_error(error); for (i = 0; i < response->num_buckets; i++) { if (strcmp(bucket_name, response->buckets[i].name->value) == 0) { found = true; break; } } ds3_free_service_response(response); BOOST_CHECK(found); //Deleting Non Existing Object request = ds3_init_delete_object(bucket_name,"delete_non_existing_object"); error = ds3_delete_object(client, request); ds3_free_request(request); BOOST_CHECK(error != NULL); BOOST_CHECK(error->error->status_code == 404); BOOST_CHECK(strcmp(error->error->status_message->value ,"Not Found")==0); ds3_free_error(error); //Deleting Created Bucket request = ds3_init_delete_bucket(bucket_name); error = ds3_delete_bucket(client, request); ds3_free_request(request); free_client(client); handle_error(error); } //testing Bad Bucket Name Creation BOOST_AUTO_TEST_CASE( bad_bucket_name) { printf("-----Negative Testing Bad Bucket Name creation-------\n"); ds3_client* client = get_client(); const char* bucket_name = "bad:bucket"; ds3_request* request = ds3_init_put_bucket(bucket_name); ds3_error* error = ds3_put_bucket(client, request); ds3_free_request(request); BOOST_REQUIRE(error != NULL); BOOST_CHECK(error->error->status_code == 400); BOOST_CHECK(strcmp(error->error->status_message->value ,"Bad Request")==0); ds3_free_error(error); free_client(client); } //testing creation of object list with duplicate objects BOOST_AUTO_TEST_CASE( put_duplicate_object_list){ printf("-----Negative Testing Object List With Duplicate Objects Creation-------\n"); ds3_client* client = get_client(); const char* bucket_name = "test_bucket_duplicate_object"; //Adding Duplicate Object to the Bucket List const char* books[] ={"resources/beowulf.txt","resources/sherlock_holmes.txt","resources/beowulf.txt"}; ds3_bulk_object_list* obj_list; ds3_bulk_response* response; ds3_request* request = ds3_init_put_bucket(bucket_name); ds3_error* error = ds3_put_bucket(client, request); ds3_free_request(request); handle_error(error); obj_list = ds3_convert_file_list(books, 3); request = ds3_init_put_bulk(bucket_name, obj_list); error = ds3_bulk(client, request, &response); ds3_free_request(request); BOOST_CHECK(error != NULL); BOOST_CHECK(error->error->status_code == 409); BOOST_CHECK(strcmp(error->error->status_message->value ,"Conflict")==0); ds3_free_error(error); ds3_free_bulk_object_list(obj_list); clear_bucket(client, bucket_name); free_client(client); } //testing creation of duplicate object BOOST_AUTO_TEST_CASE( put_duplicate_object){ printf("-----Negative Testing Duplicate Object Creation -------\n"); ds3_client* client = get_client(); const char* bucket_name = "test_bucket_new"; //Pre populating few objects populate_with_objects(client, bucket_name); //Testing creation of preexisting objects const char* books[] ={"resources/beowulf.txt","resources/sherlock_holmes.txt"}; ds3_bulk_object_list* obj_list; ds3_bulk_response* response; ds3_request* request; ds3_error* error; obj_list = ds3_convert_file_list(books,2); request = ds3_init_put_bulk(bucket_name, obj_list); error = ds3_bulk(client, request, &response); ds3_free_request(request); BOOST_CHECK(error != NULL); BOOST_CHECK(error->error->status_code == 409); BOOST_CHECK(strcmp(error->error->status_message->value ,"Conflict")==0); ds3_free_error(error); ds3_free_bulk_object_list(obj_list); clear_bucket(client, bucket_name); free_client(client); } //testing Bulk Put with empty object list BOOST_AUTO_TEST_CASE( put_empty_object_list) { printf("-----Negative Testing Put Empty Object List-------\n"); ds3_client* client = get_client(); ds3_bulk_object_list* obj_list = NULL; obj_list = ds3_init_bulk_object_list(0); ds3_bulk_response* response; const char* bucket_name = "Bucket_with_empty_list"; ds3_request* request = ds3_init_put_bucket(bucket_name); ds3_error* error = ds3_put_bucket(client, request); ds3_free_request(request); handle_error(error); request = ds3_init_put_bulk(bucket_name, obj_list); error = ds3_bulk(client, request, &response); ds3_free_request(request); BOOST_REQUIRE(error != NULL); BOOST_CHECK(strcmp(error->message->value ,"The bulk command requires a list of objects to process")==0); ds3_free_error(error); ds3_free_bulk_object_list(obj_list); //Deleting Created Bucket clear_bucket(client, bucket_name); free_client(client); } BOOST_AUTO_TEST_CASE(delete_multiple_job) { printf("-----Negative Testing Multiple Delete Jobs-------\n"); ds3_request* request; ds3_error* error; ds3_client* client = get_client(); const char* bucket_name = "bucket_test_get_job"; ds3_str* job_id = populate_with_objects_return_job(client, bucket_name); request = ds3_init_delete_job(job_id->value); error = ds3_delete_job(client,request); handle_error(error); error = ds3_delete_job(client,request); BOOST_CHECK(error != NULL); BOOST_CHECK(error->error->status_code == 404); BOOST_CHECK(strcmp(error->error->status_message->value ,"Not Found")==0); ds3_free_error(error); ds3_free_request(request); ds3_str_free(job_id); clear_bucket(client, bucket_name); free_client(client); } BOOST_AUTO_TEST_CASE(get_non_existing_job) { printf("-----Negative Testing Non Existing Get Job-------\n"); ds3_request* request; ds3_error* error; ds3_bulk_response* bulk_response = NULL; ds3_client* client = get_client(); request = ds3_init_get_job("b44d7ddc-608a-4d46-9e9e-9433b0b62911"); error = ds3_get_job(client,request,&bulk_response); BOOST_CHECK(error != NULL); BOOST_CHECK(error->error->status_code == 404); BOOST_CHECK(strcmp(error->error->status_message->value ,"Not Found")==0); ds3_free_error(error); ds3_free_request(request); ds3_free_bulk_response(bulk_response); free_client(client); } /* TODO uncomment this when using the latest simulator BOOST_AUTO_TEST_CASE(bad_checksum) { printf("-----Testing Request With Bad Checksum-------\n"); uint64_t i, n; const char* bucket_name = "bucket_test_bad_md5"; ds3_request* request = ds3_init_put_bucket(bucket_name); const char* books[] ={"resources/beowulf.txt"}; ds3_client* client = get_client(); ds3_error* error = ds3_put_bucket(client, request); ds3_bulk_object_list* obj_list; ds3_bulk_response* response; ds3_allocate_chunk_response* chunk_response; ds3_free_request(request); handle_error(error); obj_list = ds3_convert_file_list(books, 1); request = ds3_init_put_bulk(bucket_name, obj_list); error = ds3_bulk(client, request, &response); ds3_free_request(request); handle_error(error); for (n = 0; n < response->list_size; n ++) { request = ds3_init_allocate_chunk(response->list[n]->chunk_id->value); error = ds3_allocate_chunk(client, request, &chunk_response); ds3_free_request(request); handle_error(error); BOOST_REQUIRE(chunk_response->retry_after == 0); BOOST_REQUIRE(chunk_response->objects != NULL); for (i = 0; i < chunk_response->objects->size; i++) { ds3_bulk_object bulk_object = chunk_response->objects->list[i]; FILE* file = fopen(bulk_object.name->value, "r"); request = ds3_init_put_object_for_job(bucket_name, bulk_object.name->value, bulk_object.offset, bulk_object.length, response->job_id->value); ds3_request_set_md5(request,"a%4sgh"); if (bulk_object.offset > 0) { fseek(file, bulk_object.offset, SEEK_SET); } error = ds3_put_object(client, request, file, ds3_read_from_file); ds3_free_request(request); fclose(file); BOOST_REQUIRE(error != NULL); BOOST_CHECK(error->error->status_code == 403); BOOST_CHECK(strcmp(error->error->status_message->value ,"Forbidden")==0); ds3_free_error(error); } ds3_free_allocate_chunk_response(chunk_response); } ds3_free_bulk_response(response); ds3_free_bulk_object_list(obj_list); clear_bucket(client, bucket_name); free_client(client); } */
#include <cstdio> #include <vtkCellArray.h> #include <vtkFloatArray.h> #include <vtkPoints.h> #include "proctor/proctor.h" #include "proctor/detector.h" #include "proctor/scanning_model_source.h" #include "proctor/confusion_matrix.h" #ifdef _MSC_VER # define snprintf _snprintf #endif namespace pcl { namespace proctor { IndicesPtr Proctor::randomSubset(int n, int r) { IndicesPtr subset (new vector<int>()); vector<int> bag (n); for (int i = 0; i < n; i++) bag[i] = i; int edge = n; subset->resize(r); for (int i = 0; i < r; i++) { int pick = rand() % edge; (*subset)[i] = bag[pick]; bag[pick] = bag[--edge]; } return subset; } void Proctor::train(Detector &detector) { source_->getModelIDs(model_ids_); cout << "Proctor beginning training" << endl; cout << "[models]" << endl; //for (int mi = 0; mi < num_model_ids && mi < Config::num_models; mi++) { timer.start(); const int num_model_ids = model_ids_.size(); #pragma omp parallel for for (int mi = 0; mi < Config::num_models; mi++) { std::string model_id = model_ids_[mi]; cout << "Begin scanning model " << mi << " (" << model_id << ")" << endl; Scene *scene = new Scene(model_id, source_->getTrainingModel(model_id)); cout << "Finished scanning model " << mi << " (" << model_id << ")" << endl; cout << endl; cout << "Begin training model " << mi << " (" << model_id << ")" << endl; // TODO Time the training phase detector.train(*scene); cout << "Finished training model " << mi << " (" << model_id << ")" << endl; cout << endl; } timer.stop(OBTAIN_CLOUD_TRAINING); cout << "Proctor finished training" << endl; } double Proctor::test(Detector &detector, unsigned int seed) { srand(seed); source_->resetTestGenerator(); // run the tests memset(confusion, 0, sizeof(confusion)); std::map<std::string, std::map<std::string, int> > guesses; ConfusionMatrix confusion_matrix; int num_model_ids = model_ids_.size(); //#pragma omp parallel for for (int ni = 0; num_model_ids > 0 && ni < Config::num_trials; ni++) { cout << "[test " << ni << "]" << endl; std::string truth_id = model_ids_[ni % model_ids_.size()]; std::map<std::string, int>& guesses_for_id = guesses[truth_id]; timer.start(); PointCloud<PointNormal>::Ptr test_cloud = source_->getTestModel(truth_id); timer.stop(OBTAIN_CLOUD_TESTING); cout << "scanned model " << truth_id << endl; timer.start(); try { Scene test_scene(truth_id, test_cloud); //std::string guessed_id = detector.query(test_scene, classifier[ni], registration[ni]); std::string guessed_id = detector.query(test_scene); guesses_for_id[guessed_id] += 1; confusion_matrix.increment(truth_id, guessed_id); cout << "detector guessed " << guessed_id << endl; } catch (exception &e) { cout << "Detector exception" << endl; cout << e.what() << endl; //memset(classifier[ni], 0, sizeof(classifier[ni])); //memset(registration[ni], 0, sizeof(registration[ni])); } timer.stop(DETECTOR_TEST); cout << endl; } printConfusionMatrix(confusion_matrix); return confusion_matrix.trace(); } typedef struct { int ni; int mi; double distance; } Detection; bool operator<(const Detection &a, const Detection &b) { return a.distance < b.distance; } void Proctor::printPrecisionRecall() { //vector<Detection> detections; //Detection d; //for (d.ni = 0; d.ni < Config::num_trials; d.ni++) { //for (d.mi = 0; d.mi < Config::num_models; d.mi++) { //d.distance = registration[d.ni][d.mi]; //if (!d.distance) continue; // did not attempt registration on this model //detections.push_back(d); //} //} //sort(detections.begin(), detections.end()); //int correct = 0; //for (unsigned int di = 0; di < detections.size(); di++) { //if (detections[di].mi == scenes[detections[di].ni].mi) { //correct++; //printf( //"%.6f %.6f %g\n", //double(correct) / double(di + 1), //double(correct) / double(Config::num_trials), //detections[di].distance //); //} //} } void Proctor::printClassifierStats() { //float avg = 0; // average rank of correct id //int area = 0; // area under curve of cumulative histogram //for (int ni = 0; ni < Config::num_trials; ni++) { //int answer = scenes[ni].mi; //float votes = classifier[ni][answer]; //// figure out the rank in this trial //int rank = 1; //int tie = 0; //for (int mi = 0; mi < Config::num_models; mi++) { //if (classifier[ni][mi] > votes) rank++; //else if (classifier[ni][mi] == votes) tie++; //} //// contribute to average rank //avg += rank + float(tie) / 2; //// contribute to area under curve //area += Config::num_models - rank + 1; //} //avg /= Config::num_trials; //printf("average vote rank of correct model: %0.2f\n", avg); //printf("area under cumulative histogram of correct model rank: %d\n", area); } void Proctor::printTimer() { printf( "obtain training clouds: %10.3f sec\n" "obtain testing clouds: %10.3f sec\n" "detector training: %10.3f sec\n" "detector testing: %10.3f sec\n", timer[OBTAIN_CLOUD_TRAINING], timer[OBTAIN_CLOUD_TESTING], timer[DETECTOR_TRAIN], timer[DETECTOR_TEST] ); } void Proctor::printResults(Detector &detector) { // precision-recall printf("[precision-recall]\n"); printPrecisionRecall(); // classifier stats printf("[classifier stats]\n"); printClassifierStats(); // timing printf("[timing]\n"); printTimer(); printf("[detector timing]\n"); detector.printTimer(); } void Proctor::printConfusionMatrix(ConfusionMatrix &matrix) { // correct percentage printf("[overview]\n"); printf("%d of %d correct (%.2f%%)\n", matrix.trace(), matrix.total(), float(matrix.trace()) / matrix.total() * 100); cout << endl; cout << "[confusion matrix]" << endl; matrix.printMatrix(); cout << endl; } } } Fix the bounds for parallelization via OpenMP git-svn-id: e7ea667a1d39a4453c4efcc4ba7bca3d620c3f19@4470 a9d63959-f2ad-4865-b262-bf0e56cfafb6 #include <cstdio> #include <algorithm> #include <vtkCellArray.h> #include <vtkFloatArray.h> #include <vtkPoints.h> #include "proctor/proctor.h" #include "proctor/detector.h" #include "proctor/scanning_model_source.h" #include "proctor/confusion_matrix.h" #ifdef _MSC_VER # define snprintf _snprintf #endif namespace pcl { namespace proctor { IndicesPtr Proctor::randomSubset(int n, int r) { IndicesPtr subset (new vector<int>()); vector<int> bag (n); for (int i = 0; i < n; i++) bag[i] = i; int edge = n; subset->resize(r); for (int i = 0; i < r; i++) { int pick = rand() % edge; (*subset)[i] = bag[pick]; bag[pick] = bag[--edge]; } return subset; } void Proctor::train(Detector &detector) { source_->getModelIDs(model_ids_); cout << "Proctor beginning training" << endl; cout << "[models]" << endl; timer.start(); const int num_model_ids = std::min((int) model_ids_.size(), num_models_); #pragma omp parallel for for (int mi = 0; mi < num_model_ids; mi++) { std::string model_id = model_ids_[mi]; cout << "Begin scanning model " << mi << " (" << model_id << ")" << endl; Scene *scene = new Scene(model_id, source_->getTrainingModel(model_id)); cout << "Finished scanning model " << mi << " (" << model_id << ")" << endl; cout << endl; cout << "Begin training model " << mi << " (" << model_id << ")" << endl; // TODO Time the training phase detector.train(*scene); cout << "Finished training model " << mi << " (" << model_id << ")" << endl; cout << endl; } timer.stop(OBTAIN_CLOUD_TRAINING); cout << "Proctor finished training" << endl; } double Proctor::test(Detector &detector, unsigned int seed) { srand(seed); source_->resetTestGenerator(); std::map<std::string, std::map<std::string, int> > guesses; ConfusionMatrix confusion_matrix; int num_model_ids = std::min((int) model_ids_.size(), num_models_); if (num_model_ids == 0) assert(false); //#pragma omp parallel for for (int ni = 0; ni < num_trials_; ni++) { cout << "[test " << ni << "]" << endl; std::string truth_id = model_ids_[ni % num_model_ids]; std::map<std::string, int>& guesses_for_id = guesses[truth_id]; timer.start(); PointCloud<PointNormal>::Ptr test_cloud = source_->getTestModel(truth_id); timer.stop(OBTAIN_CLOUD_TESTING); cout << "scanned model " << truth_id << endl; timer.start(); try { Scene test_scene(truth_id, test_cloud); //std::string guessed_id = detector.query(test_scene, classifier[ni], registration[ni]); std::string guessed_id = detector.query(test_scene); guesses_for_id[guessed_id] += 1; confusion_matrix.increment(truth_id, guessed_id); cout << "detector guessed " << guessed_id << endl; } catch (exception &e) { cout << "Detector exception" << endl; cout << e.what() << endl; //memset(classifier[ni], 0, sizeof(classifier[ni])); //memset(registration[ni], 0, sizeof(registration[ni])); } timer.stop(DETECTOR_TEST); cout << endl; } printConfusionMatrix(confusion_matrix); return confusion_matrix.trace(); } typedef struct { int ni; int mi; double distance; } Detection; bool operator<(const Detection &a, const Detection &b) { return a.distance < b.distance; } void Proctor::printPrecisionRecall() { //vector<Detection> detections; //Detection d; //for (d.ni = 0; d.ni < Config::num_trials; d.ni++) { //for (d.mi = 0; d.mi < Config::num_models; d.mi++) { //d.distance = registration[d.ni][d.mi]; //if (!d.distance) continue; // did not attempt registration on this model //detections.push_back(d); //} //} //sort(detections.begin(), detections.end()); //int correct = 0; //for (unsigned int di = 0; di < detections.size(); di++) { //if (detections[di].mi == scenes[detections[di].ni].mi) { //correct++; //printf( //"%.6f %.6f %g\n", //double(correct) / double(di + 1), //double(correct) / double(Config::num_trials), //detections[di].distance //); //} //} } void Proctor::printClassifierStats() { //float avg = 0; // average rank of correct id //int area = 0; // area under curve of cumulative histogram //for (int ni = 0; ni < Config::num_trials; ni++) { //int answer = scenes[ni].mi; //float votes = classifier[ni][answer]; //// figure out the rank in this trial //int rank = 1; //int tie = 0; //for (int mi = 0; mi < Config::num_models; mi++) { //if (classifier[ni][mi] > votes) rank++; //else if (classifier[ni][mi] == votes) tie++; //} //// contribute to average rank //avg += rank + float(tie) / 2; //// contribute to area under curve //area += Config::num_models - rank + 1; //} //avg /= Config::num_trials; //printf("average vote rank of correct model: %0.2f\n", avg); //printf("area under cumulative histogram of correct model rank: %d\n", area); } void Proctor::printTimer() { printf( "obtain training clouds: %10.3f sec\n" "obtain testing clouds: %10.3f sec\n" "detector training: %10.3f sec\n" "detector testing: %10.3f sec\n", timer[OBTAIN_CLOUD_TRAINING], timer[OBTAIN_CLOUD_TESTING], timer[DETECTOR_TRAIN], timer[DETECTOR_TEST] ); } void Proctor::printResults(Detector &detector) { // precision-recall printf("[precision-recall]\n"); printPrecisionRecall(); // classifier stats printf("[classifier stats]\n"); printClassifierStats(); // timing printf("[timing]\n"); printTimer(); printf("[detector timing]\n"); detector.printTimer(); } void Proctor::printConfusionMatrix(ConfusionMatrix &matrix) { // correct percentage printf("[overview]\n"); printf("%d of %d correct (%.2f%%)\n", matrix.trace(), matrix.total(), float(matrix.trace()) / matrix.total() * 100); cout << endl; cout << "[confusion matrix]" << endl; matrix.printMatrix(); cout << endl; } } }
// This file is part of The New Aspell // Copyright (C) 2002 by Kevin Atkinson under the GNU LGPL license // version 2.0 or 2.1. You should have received a copy of the LGPL // license along with this library if you did not you can find // it at http://www.gnu.org/. #include "checker_string.hpp" #include "speller.hpp" #include "document_checker.hpp" #include "copy_ptr-t.hpp" static int get_line(FILE * in, CharVector & d) { d.resize(0); int i; while ((i = getc(in)), i != EOF) { d.push_back(static_cast<char>(i)); if (i == '\n') break; } return d.size(); } CheckerString::CheckerString(Speller * speller, FILE * in, FILE * out, int num_lines) : in_(in), out_(out), speller_(speller) { lines_.reserve(num_lines + 1); for (; num_lines > 0; --num_lines) { lines_.resize(lines_.size() + 1); int s = get_line(in_, lines_.back()); if (s == 0) break; } if (lines_.back().size() != 0) lines_.resize(lines_.size() + 1); end_ = lines_.end() - 1; cur_line_ = lines_.begin(); diff = 0; has_repl_ = false; checker_.reset(new_document_checker(speller, 0, 0)); checker_->process(cur_line_->data(), cur_line_->size()); } CheckerString::~CheckerString() { for (cur_line_ = first_line(); !off_end(cur_line_); next_line(cur_line_)) { fwrite(cur_line_->data(), cur_line_->size(), 1, out_); cur_line_->resize(0); } if (in_ != stdin) fclose(in_); if (out_ != stdout && out_ != stdout) fclose(out_); } bool CheckerString::read_next_line() { if (feof(in_)) return false; Lines::iterator next = end_; inc(next); if (next == cur_line_) return false; int s = get_line(in_, *end_); if (s == 0) return false; end_ = next; if (end_->size() > 0) fwrite(end_->data(), end_->size(), 1, out_); end_->resize(0); return true; } bool CheckerString::next_misspelling() { if (off_end(cur_line_)) return false; if (has_repl_) { has_repl_ = false; CharVector word; bool correct = speller_->check(get_word(word)); if (!correct) return true; diff_ += word_size_ - tok_.len; word_size_ = 0; } while ((tok_ = checker_->next_misspelling()).len == 0) { next_line(cur_line_); diff_ = 0; if (off_end(cur_line_)) return false; checker_->process(cur_line_->data(), cur_line_->size()); } word_size_ = tok_.len; word_begin_ = cur_line_->begin() + tok_.offset + diff_; return true; } void CheckerString::replace(ParmString repl) { assert(word_size_ > 0); int offset = word_begin_ - cur_line_->begin(); cur_line_->replace(word_begin_, word_begin_ + word_size_, repl.str(), repl.str() + repl.size()); word_begin_ = cur_line_->begin() + offset; word_size_ = repl.size(); has_repl_ = true; } int dist(CheckerString::Iterator smaller, CheckerString::Iterator larger) { if (smaller.line_ == larger.line_) return larger.i_ - smaller.i_; int d = 0; d += smaller.line_->end() - smaller.i_; smaller.cs_->inc(smaller.line_); while (smaller.line_ != larger.line_) { d += smaller.line_->size(); smaller.cs_->inc(smaller.line_); } d += larger.i_ - larger.line_->begin() + 1; return d; } Fix compile error from previous bug fix! // This file is part of The New Aspell // Copyright (C) 2002 by Kevin Atkinson under the GNU LGPL license // version 2.0 or 2.1. You should have received a copy of the LGPL // license along with this library if you did not you can find // it at http://www.gnu.org/. #include "checker_string.hpp" #include "speller.hpp" #include "document_checker.hpp" #include "copy_ptr-t.hpp" static int get_line(FILE * in, CharVector & d) { d.resize(0); int i; while ((i = getc(in)), i != EOF) { d.push_back(static_cast<char>(i)); if (i == '\n') break; } return d.size(); } CheckerString::CheckerString(Speller * speller, FILE * in, FILE * out, int num_lines) : in_(in), out_(out), speller_(speller) { lines_.reserve(num_lines + 1); for (; num_lines > 0; --num_lines) { lines_.resize(lines_.size() + 1); int s = get_line(in_, lines_.back()); if (s == 0) break; } if (lines_.back().size() != 0) lines_.resize(lines_.size() + 1); end_ = lines_.end() - 1; cur_line_ = lines_.begin(); diff_ = 0; has_repl_ = false; checker_.reset(new_document_checker(speller, 0, 0)); checker_->process(cur_line_->data(), cur_line_->size()); } CheckerString::~CheckerString() { for (cur_line_ = first_line(); !off_end(cur_line_); next_line(cur_line_)) { fwrite(cur_line_->data(), cur_line_->size(), 1, out_); cur_line_->resize(0); } if (in_ != stdin) fclose(in_); if (out_ != stdout && out_ != stdout) fclose(out_); } bool CheckerString::read_next_line() { if (feof(in_)) return false; Lines::iterator next = end_; inc(next); if (next == cur_line_) return false; int s = get_line(in_, *end_); if (s == 0) return false; end_ = next; if (end_->size() > 0) fwrite(end_->data(), end_->size(), 1, out_); end_->resize(0); return true; } bool CheckerString::next_misspelling() { if (off_end(cur_line_)) return false; if (has_repl_) { has_repl_ = false; CharVector word; bool correct = speller_->check(get_word(word)); if (!correct) return true; diff_ += word_size_ - tok_.len; word_size_ = 0; } while ((tok_ = checker_->next_misspelling()).len == 0) { next_line(cur_line_); diff_ = 0; if (off_end(cur_line_)) return false; checker_->process(cur_line_->data(), cur_line_->size()); } word_size_ = tok_.len; word_begin_ = cur_line_->begin() + tok_.offset + diff_; return true; } void CheckerString::replace(ParmString repl) { assert(word_size_ > 0); int offset = word_begin_ - cur_line_->begin(); cur_line_->replace(word_begin_, word_begin_ + word_size_, repl.str(), repl.str() + repl.size()); word_begin_ = cur_line_->begin() + offset; word_size_ = repl.size(); has_repl_ = true; } int dist(CheckerString::Iterator smaller, CheckerString::Iterator larger) { if (smaller.line_ == larger.line_) return larger.i_ - smaller.i_; int d = 0; d += smaller.line_->end() - smaller.i_; smaller.cs_->inc(smaller.line_); while (smaller.line_ != larger.line_) { d += smaller.line_->size(); smaller.cs_->inc(smaller.line_); } d += larger.i_ - larger.line_->begin() + 1; return d; }
// Copyright 2011 the V8 project authors. All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "v8.h" #if defined(V8_TARGET_ARCH_MIPS) #include "codegen.h" #include "debug.h" #include "deoptimizer.h" #include "full-codegen.h" #include "runtime.h" namespace v8 { namespace internal { #define __ ACCESS_MASM(masm) void Builtins::Generate_Adaptor(MacroAssembler* masm, CFunctionId id, BuiltinExtraArguments extra_args) { // ----------- S t a t e ------------- // -- a0 : number of arguments excluding receiver // -- a1 : called function (only guaranteed when // -- extra_args requires it) // -- cp : context // -- sp[0] : last argument // -- ... // -- sp[4 * (argc - 1)] : first argument // -- sp[4 * agrc] : receiver // ----------------------------------- // Insert extra arguments. int num_extra_args = 0; if (extra_args == NEEDS_CALLED_FUNCTION) { num_extra_args = 1; __ push(a1); } else { ASSERT(extra_args == NO_EXTRA_ARGUMENTS); } // JumpToExternalReference expects a0 to contain the number of arguments // including the receiver and the extra arguments. __ Addu(a0, a0, Operand(num_extra_args + 1)); __ JumpToExternalReference(ExternalReference(id, masm->isolate())); } // Load the built-in Array function from the current context. static void GenerateLoadArrayFunction(MacroAssembler* masm, Register result) { // Load the global context. __ lw(result, MemOperand(cp, Context::SlotOffset(Context::GLOBAL_INDEX))); __ lw(result, FieldMemOperand(result, GlobalObject::kGlobalContextOffset)); // Load the Array function from the global context. __ lw(result, MemOperand(result, Context::SlotOffset(Context::ARRAY_FUNCTION_INDEX))); } // Allocate an empty JSArray. The allocated array is put into the result // register. An elements backing store is allocated with size initial_capacity // and filled with the hole values. static void AllocateEmptyJSArray(MacroAssembler* masm, Register array_function, Register result, Register scratch1, Register scratch2, Register scratch3, Label* gc_required) { const int initial_capacity = JSArray::kPreallocatedArrayElements; STATIC_ASSERT(initial_capacity >= 0); // Load the initial map from the array function. __ lw(scratch1, FieldMemOperand(array_function, JSFunction::kPrototypeOrInitialMapOffset)); // Allocate the JSArray object together with space for a fixed array with the // requested elements. int size = JSArray::kSize; if (initial_capacity > 0) { size += FixedArray::SizeFor(initial_capacity); } __ AllocateInNewSpace(size, result, scratch2, scratch3, gc_required, TAG_OBJECT); // Allocated the JSArray. Now initialize the fields except for the elements // array. // result: JSObject // scratch1: initial map // scratch2: start of next object __ sw(scratch1, FieldMemOperand(result, JSObject::kMapOffset)); __ LoadRoot(scratch1, Heap::kEmptyFixedArrayRootIndex); __ sw(scratch1, FieldMemOperand(result, JSArray::kPropertiesOffset)); // Field JSArray::kElementsOffset is initialized later. __ mov(scratch3, zero_reg); __ sw(scratch3, FieldMemOperand(result, JSArray::kLengthOffset)); if (initial_capacity == 0) { __ sw(scratch1, FieldMemOperand(result, JSArray::kElementsOffset)); return; } // Calculate the location of the elements array and set elements array member // of the JSArray. // result: JSObject // scratch2: start of next object __ Addu(scratch1, result, Operand(JSArray::kSize)); __ sw(scratch1, FieldMemOperand(result, JSArray::kElementsOffset)); // Clear the heap tag on the elements array. __ And(scratch1, scratch1, Operand(~kHeapObjectTagMask)); // Initialize the FixedArray and fill it with holes. FixedArray length is // stored as a smi. // result: JSObject // scratch1: elements array (untagged) // scratch2: start of next object __ LoadRoot(scratch3, Heap::kFixedArrayMapRootIndex); STATIC_ASSERT(0 * kPointerSize == FixedArray::kMapOffset); __ sw(scratch3, MemOperand(scratch1)); __ Addu(scratch1, scratch1, kPointerSize); __ li(scratch3, Operand(Smi::FromInt(initial_capacity))); STATIC_ASSERT(1 * kPointerSize == FixedArray::kLengthOffset); __ sw(scratch3, MemOperand(scratch1)); __ Addu(scratch1, scratch1, kPointerSize); // Fill the FixedArray with the hole value. Inline the code if short. STATIC_ASSERT(2 * kPointerSize == FixedArray::kHeaderSize); __ LoadRoot(scratch3, Heap::kTheHoleValueRootIndex); static const int kLoopUnfoldLimit = 4; if (initial_capacity <= kLoopUnfoldLimit) { for (int i = 0; i < initial_capacity; i++) { __ sw(scratch3, MemOperand(scratch1, i * kPointerSize)); } } else { Label loop, entry; __ Addu(scratch2, scratch1, Operand(initial_capacity * kPointerSize)); __ Branch(&entry); __ bind(&loop); __ sw(scratch3, MemOperand(scratch1)); __ Addu(scratch1, scratch1, kPointerSize); __ bind(&entry); __ Branch(&loop, lt, scratch1, Operand(scratch2)); } } // Allocate a JSArray with the number of elements stored in a register. The // register array_function holds the built-in Array function and the register // array_size holds the size of the array as a smi. The allocated array is put // into the result register and beginning and end of the FixedArray elements // storage is put into registers elements_array_storage and elements_array_end // (see below for when that is not the case). If the parameter fill_with_holes // is true the allocated elements backing store is filled with the hole values // otherwise it is left uninitialized. When the backing store is filled the // register elements_array_storage is scratched. static void AllocateJSArray(MacroAssembler* masm, Register array_function, // Array function. Register array_size, // As a smi, cannot be 0. Register result, Register elements_array_storage, Register elements_array_end, Register scratch1, Register scratch2, bool fill_with_hole, Label* gc_required) { // Load the initial map from the array function. __ lw(elements_array_storage, FieldMemOperand(array_function, JSFunction::kPrototypeOrInitialMapOffset)); if (FLAG_debug_code) { // Assert that array size is not zero. __ Assert( ne, "array size is unexpectedly 0", array_size, Operand(zero_reg)); } // Allocate the JSArray object together with space for a FixedArray with the // requested number of elements. STATIC_ASSERT(kSmiTagSize == 1 && kSmiTag == 0); __ li(elements_array_end, (JSArray::kSize + FixedArray::kHeaderSize) / kPointerSize); __ sra(scratch1, array_size, kSmiTagSize); __ Addu(elements_array_end, elements_array_end, scratch1); __ AllocateInNewSpace( elements_array_end, result, scratch1, scratch2, gc_required, static_cast<AllocationFlags>(TAG_OBJECT | SIZE_IN_WORDS)); // Allocated the JSArray. Now initialize the fields except for the elements // array. // result: JSObject // elements_array_storage: initial map // array_size: size of array (smi) __ sw(elements_array_storage, FieldMemOperand(result, JSObject::kMapOffset)); __ LoadRoot(elements_array_storage, Heap::kEmptyFixedArrayRootIndex); __ sw(elements_array_storage, FieldMemOperand(result, JSArray::kPropertiesOffset)); // Field JSArray::kElementsOffset is initialized later. __ sw(array_size, FieldMemOperand(result, JSArray::kLengthOffset)); // Calculate the location of the elements array and set elements array member // of the JSArray. // result: JSObject // array_size: size of array (smi) __ Addu(elements_array_storage, result, Operand(JSArray::kSize)); __ sw(elements_array_storage, FieldMemOperand(result, JSArray::kElementsOffset)); // Clear the heap tag on the elements array. __ And(elements_array_storage, elements_array_storage, Operand(~kHeapObjectTagMask)); // Initialize the fixed array and fill it with holes. FixedArray length is // stored as a smi. // result: JSObject // elements_array_storage: elements array (untagged) // array_size: size of array (smi) __ LoadRoot(scratch1, Heap::kFixedArrayMapRootIndex); ASSERT_EQ(0 * kPointerSize, FixedArray::kMapOffset); __ sw(scratch1, MemOperand(elements_array_storage)); __ Addu(elements_array_storage, elements_array_storage, kPointerSize); // Length of the FixedArray is the number of pre-allocated elements if // the actual JSArray has length 0 and the size of the JSArray for non-empty // JSArrays. The length of a FixedArray is stored as a smi. STATIC_ASSERT(kSmiTag == 0); ASSERT_EQ(1 * kPointerSize, FixedArray::kLengthOffset); __ sw(array_size, MemOperand(elements_array_storage)); __ Addu(elements_array_storage, elements_array_storage, kPointerSize); // Calculate elements array and elements array end. // result: JSObject // elements_array_storage: elements array element storage // array_size: smi-tagged size of elements array STATIC_ASSERT(kSmiTag == 0 && kSmiTagSize < kPointerSizeLog2); __ sll(elements_array_end, array_size, kPointerSizeLog2 - kSmiTagSize); __ Addu(elements_array_end, elements_array_storage, elements_array_end); // Fill the allocated FixedArray with the hole value if requested. // result: JSObject // elements_array_storage: elements array element storage // elements_array_end: start of next object if (fill_with_hole) { Label loop, entry; __ LoadRoot(scratch1, Heap::kTheHoleValueRootIndex); __ Branch(&entry); __ bind(&loop); __ sw(scratch1, MemOperand(elements_array_storage)); __ Addu(elements_array_storage, elements_array_storage, kPointerSize); __ bind(&entry); __ Branch(&loop, lt, elements_array_storage, Operand(elements_array_end)); } } // Create a new array for the built-in Array function. This function allocates // the JSArray object and the FixedArray elements array and initializes these. // If the Array cannot be constructed in native code the runtime is called. This // function assumes the following state: // a0: argc // a1: constructor (built-in Array function) // ra: return address // sp[0]: last argument // This function is used for both construct and normal calls of Array. The only // difference between handling a construct call and a normal call is that for a // construct call the constructor function in a1 needs to be preserved for // entering the generic code. In both cases argc in a0 needs to be preserved. // Both registers are preserved by this code so no need to differentiate between // construct call and normal call. static void ArrayNativeCode(MacroAssembler* masm, Label* call_generic_code) { Counters* counters = masm->isolate()->counters(); Label argc_one_or_more, argc_two_or_more, not_empty_array, empty_array; // Check for array construction with zero arguments or one. __ Branch(&argc_one_or_more, ne, a0, Operand(zero_reg)); // Handle construction of an empty array. __ bind(&empty_array); AllocateEmptyJSArray(masm, a1, a2, a3, t0, t1, call_generic_code); __ IncrementCounter(counters->array_function_native(), 1, a3, t0); // Setup return value, remove receiver from stack and return. __ mov(v0, a2); __ Addu(sp, sp, Operand(kPointerSize)); __ Ret(); // Check for one argument. Bail out if argument is not smi or if it is // negative. __ bind(&argc_one_or_more); __ Branch(&argc_two_or_more, ne, a0, Operand(1)); STATIC_ASSERT(kSmiTag == 0); __ lw(a2, MemOperand(sp)); // Get the argument from the stack. __ Branch(&not_empty_array, ne, a2, Operand(zero_reg)); __ Drop(1); // Adjust stack. __ mov(a0, zero_reg); // Treat this as a call with argc of zero. __ Branch(&empty_array); __ bind(&not_empty_array); __ And(a3, a2, Operand(kIntptrSignBit | kSmiTagMask)); __ Branch(call_generic_code, eq, a3, Operand(zero_reg)); // Handle construction of an empty array of a certain size. Bail out if size // is too large to actually allocate an elements array. STATIC_ASSERT(kSmiTag == 0); __ Branch(call_generic_code, Ugreater_equal, a2, Operand(JSObject::kInitialMaxFastElementArray << kSmiTagSize)); // a0: argc // a1: constructor // a2: array_size (smi) // sp[0]: argument AllocateJSArray(masm, a1, a2, a3, t0, t1, t2, t3, true, call_generic_code); __ IncrementCounter(counters->array_function_native(), 1, a2, t0); // Setup return value, remove receiver and argument from stack and return. __ mov(v0, a3); __ Addu(sp, sp, Operand(2 * kPointerSize)); __ Ret(); // Handle construction of an array from a list of arguments. __ bind(&argc_two_or_more); __ sll(a2, a0, kSmiTagSize); // Convert argc to a smi. // a0: argc // a1: constructor // a2: array_size (smi) // sp[0]: last argument AllocateJSArray(masm, a1, a2, a3, t0, t1, t2, t3, false, call_generic_code); __ IncrementCounter(counters->array_function_native(), 1, a2, t2); // Fill arguments as array elements. Copy from the top of the stack (last // element) to the array backing store filling it backwards. Note: // elements_array_end points after the backing store. // a0: argc // a3: JSArray // t0: elements_array storage start (untagged) // t1: elements_array_end (untagged) // sp[0]: last argument Label loop, entry; __ Branch(USE_DELAY_SLOT, &entry); __ mov(t3, sp); __ bind(&loop); __ lw(a2, MemOperand(t3)); __ Addu(t3, t3, kPointerSize); if (FLAG_smi_only_arrays) { __ JumpIfNotSmi(a2, call_generic_code); } __ Addu(t1, t1, -kPointerSize); __ sw(a2, MemOperand(t1)); __ bind(&entry); __ Branch(&loop, lt, t0, Operand(t1)); __ mov(sp, t3); // Remove caller arguments and receiver from the stack, setup return value and // return. // a0: argc // a3: JSArray // sp[0]: receiver __ Addu(sp, sp, Operand(kPointerSize)); __ mov(v0, a3); __ Ret(); } void Builtins::Generate_ArrayCode(MacroAssembler* masm) { // ----------- S t a t e ------------- // -- a0 : number of arguments // -- ra : return address // -- sp[...]: constructor arguments // ----------------------------------- Label generic_array_code; // Get the Array function. GenerateLoadArrayFunction(masm, a1); if (FLAG_debug_code) { // Initial map for the builtin Array functions should be maps. __ lw(a2, FieldMemOperand(a1, JSFunction::kPrototypeOrInitialMapOffset)); __ And(t0, a2, Operand(kSmiTagMask)); __ Assert(ne, "Unexpected initial map for Array function (1)", t0, Operand(zero_reg)); __ GetObjectType(a2, a3, t0); __ Assert(eq, "Unexpected initial map for Array function (2)", t0, Operand(MAP_TYPE)); } // Run the native code for the Array function called as a normal function. ArrayNativeCode(masm, &generic_array_code); // Jump to the generic array code if the specialized code cannot handle // the construction. __ bind(&generic_array_code); Handle<Code> array_code = masm->isolate()->builtins()->ArrayCodeGeneric(); __ Jump(array_code, RelocInfo::CODE_TARGET); } void Builtins::Generate_ArrayConstructCode(MacroAssembler* masm) { // ----------- S t a t e ------------- // -- a0 : number of arguments // -- a1 : constructor function // -- ra : return address // -- sp[...]: constructor arguments // ----------------------------------- Label generic_constructor; if (FLAG_debug_code) { // The array construct code is only set for the builtin and internal // Array functions which always have a map. // Initial map for the builtin Array function should be a map. __ lw(a2, FieldMemOperand(a1, JSFunction::kPrototypeOrInitialMapOffset)); __ And(t0, a2, Operand(kSmiTagMask)); __ Assert(ne, "Unexpected initial map for Array function (3)", t0, Operand(zero_reg)); __ GetObjectType(a2, a3, t0); __ Assert(eq, "Unexpected initial map for Array function (4)", t0, Operand(MAP_TYPE)); } // Run the native code for the Array function called as a constructor. ArrayNativeCode(masm, &generic_constructor); // Jump to the generic construct code in case the specialized code cannot // handle the construction. __ bind(&generic_constructor); Handle<Code> generic_construct_stub = masm->isolate()->builtins()->JSConstructStubGeneric(); __ Jump(generic_construct_stub, RelocInfo::CODE_TARGET); } void Builtins::Generate_StringConstructCode(MacroAssembler* masm) { // ----------- S t a t e ------------- // -- a0 : number of arguments // -- a1 : constructor function // -- ra : return address // -- sp[(argc - n - 1) * 4] : arg[n] (zero based) // -- sp[argc * 4] : receiver // ----------------------------------- Counters* counters = masm->isolate()->counters(); __ IncrementCounter(counters->string_ctor_calls(), 1, a2, a3); Register function = a1; if (FLAG_debug_code) { __ LoadGlobalFunction(Context::STRING_FUNCTION_INDEX, a2); __ Assert(eq, "Unexpected String function", function, Operand(a2)); } // Load the first arguments in a0 and get rid of the rest. Label no_arguments; __ Branch(&no_arguments, eq, a0, Operand(zero_reg)); // First args = sp[(argc - 1) * 4]. __ Subu(a0, a0, Operand(1)); __ sll(a0, a0, kPointerSizeLog2); __ Addu(sp, a0, sp); __ lw(a0, MemOperand(sp)); // sp now point to args[0], drop args[0] + receiver. __ Drop(2); Register argument = a2; Label not_cached, argument_is_string; NumberToStringStub::GenerateLookupNumberStringCache( masm, a0, // Input. argument, // Result. a3, // Scratch. t0, // Scratch. t1, // Scratch. false, // Is it a Smi? &not_cached); __ IncrementCounter(counters->string_ctor_cached_number(), 1, a3, t0); __ bind(&argument_is_string); // ----------- S t a t e ------------- // -- a2 : argument converted to string // -- a1 : constructor function // -- ra : return address // ----------------------------------- Label gc_required; __ AllocateInNewSpace(JSValue::kSize, v0, // Result. a3, // Scratch. t0, // Scratch. &gc_required, TAG_OBJECT); // Initialising the String Object. Register map = a3; __ LoadGlobalFunctionInitialMap(function, map, t0); if (FLAG_debug_code) { __ lbu(t0, FieldMemOperand(map, Map::kInstanceSizeOffset)); __ Assert(eq, "Unexpected string wrapper instance size", t0, Operand(JSValue::kSize >> kPointerSizeLog2)); __ lbu(t0, FieldMemOperand(map, Map::kUnusedPropertyFieldsOffset)); __ Assert(eq, "Unexpected unused properties of string wrapper", t0, Operand(zero_reg)); } __ sw(map, FieldMemOperand(v0, HeapObject::kMapOffset)); __ LoadRoot(a3, Heap::kEmptyFixedArrayRootIndex); __ sw(a3, FieldMemOperand(v0, JSObject::kPropertiesOffset)); __ sw(a3, FieldMemOperand(v0, JSObject::kElementsOffset)); __ sw(argument, FieldMemOperand(v0, JSValue::kValueOffset)); // Ensure the object is fully initialized. STATIC_ASSERT(JSValue::kSize == 4 * kPointerSize); __ Ret(); // The argument was not found in the number to string cache. Check // if it's a string already before calling the conversion builtin. Label convert_argument; __ bind(&not_cached); __ JumpIfSmi(a0, &convert_argument); // Is it a String? __ lw(a2, FieldMemOperand(a0, HeapObject::kMapOffset)); __ lbu(a3, FieldMemOperand(a2, Map::kInstanceTypeOffset)); STATIC_ASSERT(kNotStringTag != 0); __ And(t0, a3, Operand(kIsNotStringMask)); __ Branch(&convert_argument, ne, t0, Operand(zero_reg)); __ mov(argument, a0); __ IncrementCounter(counters->string_ctor_conversions(), 1, a3, t0); __ Branch(&argument_is_string); // Invoke the conversion builtin and put the result into a2. __ bind(&convert_argument); __ push(function); // Preserve the function. __ IncrementCounter(counters->string_ctor_conversions(), 1, a3, t0); { FrameScope scope(masm, StackFrame::INTERNAL); __ push(v0); __ InvokeBuiltin(Builtins::TO_STRING, CALL_FUNCTION); } __ pop(function); __ mov(argument, v0); __ Branch(&argument_is_string); // Load the empty string into a2, remove the receiver from the // stack, and jump back to the case where the argument is a string. __ bind(&no_arguments); __ LoadRoot(argument, Heap::kEmptyStringRootIndex); __ Drop(1); __ Branch(&argument_is_string); // At this point the argument is already a string. Call runtime to // create a string wrapper. __ bind(&gc_required); __ IncrementCounter(counters->string_ctor_gc_required(), 1, a3, t0); { FrameScope scope(masm, StackFrame::INTERNAL); __ push(argument); __ CallRuntime(Runtime::kNewStringWrapper, 1); } __ Ret(); } void Builtins::Generate_JSConstructCall(MacroAssembler* masm) { // ----------- S t a t e ------------- // -- a0 : number of arguments // -- a1 : constructor function // -- ra : return address // -- sp[...]: constructor arguments // ----------------------------------- Label slow, non_function_call; // Check that the function is not a smi. __ JumpIfSmi(a1, &non_function_call); // Check that the function is a JSFunction. __ GetObjectType(a1, a2, a2); __ Branch(&slow, ne, a2, Operand(JS_FUNCTION_TYPE)); // Jump to the function-specific construct stub. __ lw(a2, FieldMemOperand(a1, JSFunction::kSharedFunctionInfoOffset)); __ lw(a2, FieldMemOperand(a2, SharedFunctionInfo::kConstructStubOffset)); __ Addu(t9, a2, Operand(Code::kHeaderSize - kHeapObjectTag)); __ Jump(t9); // a0: number of arguments // a1: called object // a2: object type Label do_call; __ bind(&slow); __ Branch(&non_function_call, ne, a2, Operand(JS_FUNCTION_PROXY_TYPE)); __ GetBuiltinEntry(a3, Builtins::CALL_FUNCTION_PROXY_AS_CONSTRUCTOR); __ jmp(&do_call); __ bind(&non_function_call); __ GetBuiltinEntry(a3, Builtins::CALL_NON_FUNCTION_AS_CONSTRUCTOR); __ bind(&do_call); // CALL_NON_FUNCTION expects the non-function constructor as receiver // (instead of the original receiver from the call site). The receiver is // stack element argc. // Set expected number of arguments to zero (not changing a0). __ mov(a2, zero_reg); __ SetCallKind(t1, CALL_AS_METHOD); __ Jump(masm->isolate()->builtins()->ArgumentsAdaptorTrampoline(), RelocInfo::CODE_TARGET); } static void Generate_JSConstructStubHelper(MacroAssembler* masm, bool is_api_function, bool count_constructions) { // Should never count constructions for api objects. ASSERT(!is_api_function || !count_constructions); Isolate* isolate = masm->isolate(); // ----------- S t a t e ------------- // -- a0 : number of arguments // -- a1 : constructor function // -- ra : return address // -- sp[...]: constructor arguments // ----------------------------------- // Enter a construct frame. { FrameScope scope(masm, StackFrame::CONSTRUCT); // Preserve the two incoming parameters on the stack. __ sll(a0, a0, kSmiTagSize); // Tag arguments count. __ MultiPushReversed(a0.bit() | a1.bit()); // Use t7 to hold undefined, which is used in several places below. __ LoadRoot(t7, Heap::kUndefinedValueRootIndex); Label rt_call, allocated; // Try to allocate the object without transitioning into C code. If any of // the preconditions is not met, the code bails out to the runtime call. if (FLAG_inline_new) { Label undo_allocation; #ifdef ENABLE_DEBUGGER_SUPPORT ExternalReference debug_step_in_fp = ExternalReference::debug_step_in_fp_address(isolate); __ li(a2, Operand(debug_step_in_fp)); __ lw(a2, MemOperand(a2)); __ Branch(&rt_call, ne, a2, Operand(zero_reg)); #endif // Load the initial map and verify that it is in fact a map. // a1: constructor function __ lw(a2, FieldMemOperand(a1, JSFunction::kPrototypeOrInitialMapOffset)); __ JumpIfSmi(a2, &rt_call); __ GetObjectType(a2, a3, t4); __ Branch(&rt_call, ne, t4, Operand(MAP_TYPE)); // Check that the constructor is not constructing a JSFunction (see // comments in Runtime_NewObject in runtime.cc). In which case the // initial map's instance type would be JS_FUNCTION_TYPE. // a1: constructor function // a2: initial map __ lbu(a3, FieldMemOperand(a2, Map::kInstanceTypeOffset)); __ Branch(&rt_call, eq, a3, Operand(JS_FUNCTION_TYPE)); if (count_constructions) { Label allocate; // Decrease generous allocation count. __ lw(a3, FieldMemOperand(a1, JSFunction::kSharedFunctionInfoOffset)); MemOperand constructor_count = FieldMemOperand(a3, SharedFunctionInfo::kConstructionCountOffset); __ lbu(t0, constructor_count); __ Subu(t0, t0, Operand(1)); __ sb(t0, constructor_count); __ Branch(&allocate, ne, t0, Operand(zero_reg)); __ Push(a1, a2); __ push(a1); // Constructor. // The call will replace the stub, so the countdown is only done once. __ CallRuntime(Runtime::kFinalizeInstanceSize, 1); __ pop(a2); __ pop(a1); __ bind(&allocate); } // Now allocate the JSObject on the heap. // a1: constructor function // a2: initial map __ lbu(a3, FieldMemOperand(a2, Map::kInstanceSizeOffset)); __ AllocateInNewSpace(a3, t4, t5, t6, &rt_call, SIZE_IN_WORDS); // Allocated the JSObject, now initialize the fields. Map is set to // initial map and properties and elements are set to empty fixed array. // a1: constructor function // a2: initial map // a3: object size // t4: JSObject (not tagged) __ LoadRoot(t6, Heap::kEmptyFixedArrayRootIndex); __ mov(t5, t4); __ sw(a2, MemOperand(t5, JSObject::kMapOffset)); __ sw(t6, MemOperand(t5, JSObject::kPropertiesOffset)); __ sw(t6, MemOperand(t5, JSObject::kElementsOffset)); __ Addu(t5, t5, Operand(3*kPointerSize)); ASSERT_EQ(0 * kPointerSize, JSObject::kMapOffset); ASSERT_EQ(1 * kPointerSize, JSObject::kPropertiesOffset); ASSERT_EQ(2 * kPointerSize, JSObject::kElementsOffset); // Fill all the in-object properties with appropriate filler. // a1: constructor function // a2: initial map // a3: object size (in words) // t4: JSObject (not tagged) // t5: First in-object property of JSObject (not tagged) __ sll(t0, a3, kPointerSizeLog2); __ addu(t6, t4, t0); // End of object. ASSERT_EQ(3 * kPointerSize, JSObject::kHeaderSize); __ LoadRoot(t7, Heap::kUndefinedValueRootIndex); if (count_constructions) { __ lw(a0, FieldMemOperand(a2, Map::kInstanceSizesOffset)); __ Ext(a0, a0, Map::kPreAllocatedPropertyFieldsByte * kBitsPerByte, kBitsPerByte); __ sll(t0, a0, kPointerSizeLog2); __ addu(a0, t5, t0); // a0: offset of first field after pre-allocated fields if (FLAG_debug_code) { __ Assert(le, "Unexpected number of pre-allocated property fields.", a0, Operand(t6)); } __ InitializeFieldsWithFiller(t5, a0, t7); // To allow for truncation. __ LoadRoot(t7, Heap::kOnePointerFillerMapRootIndex); } __ InitializeFieldsWithFiller(t5, t6, t7); // Add the object tag to make the JSObject real, so that we can continue // and jump into the continuation code at any time from now on. Any // failures need to undo the allocation, so that the heap is in a // consistent state and verifiable. __ Addu(t4, t4, Operand(kHeapObjectTag)); // Check if a non-empty properties array is needed. Continue with // allocated object if not fall through to runtime call if it is. // a1: constructor function // t4: JSObject // t5: start of next object (not tagged) __ lbu(a3, FieldMemOperand(a2, Map::kUnusedPropertyFieldsOffset)); // The field instance sizes contains both pre-allocated property fields // and in-object properties. __ lw(a0, FieldMemOperand(a2, Map::kInstanceSizesOffset)); __ Ext(t6, a0, Map::kPreAllocatedPropertyFieldsByte * kBitsPerByte, kBitsPerByte); __ Addu(a3, a3, Operand(t6)); __ Ext(t6, a0, Map::kInObjectPropertiesByte * kBitsPerByte, kBitsPerByte); __ subu(a3, a3, t6); // Done if no extra properties are to be allocated. __ Branch(&allocated, eq, a3, Operand(zero_reg)); __ Assert(greater_equal, "Property allocation count failed.", a3, Operand(zero_reg)); // Scale the number of elements by pointer size and add the header for // FixedArrays to the start of the next object calculation from above. // a1: constructor // a3: number of elements in properties array // t4: JSObject // t5: start of next object __ Addu(a0, a3, Operand(FixedArray::kHeaderSize / kPointerSize)); __ AllocateInNewSpace( a0, t5, t6, a2, &undo_allocation, static_cast<AllocationFlags>(RESULT_CONTAINS_TOP | SIZE_IN_WORDS)); // Initialize the FixedArray. // a1: constructor // a3: number of elements in properties array (un-tagged) // t4: JSObject // t5: start of next object __ LoadRoot(t6, Heap::kFixedArrayMapRootIndex); __ mov(a2, t5); __ sw(t6, MemOperand(a2, JSObject::kMapOffset)); __ sll(a0, a3, kSmiTagSize); __ sw(a0, MemOperand(a2, FixedArray::kLengthOffset)); __ Addu(a2, a2, Operand(2 * kPointerSize)); ASSERT_EQ(0 * kPointerSize, JSObject::kMapOffset); ASSERT_EQ(1 * kPointerSize, FixedArray::kLengthOffset); // Initialize the fields to undefined. // a1: constructor // a2: First element of FixedArray (not tagged) // a3: number of elements in properties array // t4: JSObject // t5: FixedArray (not tagged) __ sll(t3, a3, kPointerSizeLog2); __ addu(t6, a2, t3); // End of object. ASSERT_EQ(2 * kPointerSize, FixedArray::kHeaderSize); { Label loop, entry; if (count_constructions) { __ LoadRoot(t7, Heap::kUndefinedValueRootIndex); } else if (FLAG_debug_code) { __ LoadRoot(t8, Heap::kUndefinedValueRootIndex); __ Assert(eq, "Undefined value not loaded.", t7, Operand(t8)); } __ jmp(&entry); __ bind(&loop); __ sw(t7, MemOperand(a2)); __ addiu(a2, a2, kPointerSize); __ bind(&entry); __ Branch(&loop, less, a2, Operand(t6)); } // Store the initialized FixedArray into the properties field of // the JSObject. // a1: constructor function // t4: JSObject // t5: FixedArray (not tagged) __ Addu(t5, t5, Operand(kHeapObjectTag)); // Add the heap tag. __ sw(t5, FieldMemOperand(t4, JSObject::kPropertiesOffset)); // Continue with JSObject being successfully allocated. // a1: constructor function // a4: JSObject __ jmp(&allocated); // Undo the setting of the new top so that the heap is verifiable. For // example, the map's unused properties potentially do not match the // allocated objects unused properties. // t4: JSObject (previous new top) __ bind(&undo_allocation); __ UndoAllocationInNewSpace(t4, t5); } __ bind(&rt_call); // Allocate the new receiver object using the runtime call. // a1: constructor function __ push(a1); // Argument for Runtime_NewObject. __ CallRuntime(Runtime::kNewObject, 1); __ mov(t4, v0); // Receiver for constructor call allocated. // t4: JSObject __ bind(&allocated); __ push(t4); // Push the function and the allocated receiver from the stack. // sp[0]: receiver (newly allocated object) // sp[1]: constructor function // sp[2]: number of arguments (smi-tagged) __ lw(a1, MemOperand(sp, kPointerSize)); __ MultiPushReversed(a1.bit() | t4.bit()); // Reload the number of arguments from the stack. // a1: constructor function // sp[0]: receiver // sp[1]: constructor function // sp[2]: receiver // sp[3]: constructor function // sp[4]: number of arguments (smi-tagged) __ lw(a3, MemOperand(sp, 4 * kPointerSize)); // Setup pointer to last argument. __ Addu(a2, fp, Operand(StandardFrameConstants::kCallerSPOffset)); // Setup number of arguments for function call below. __ srl(a0, a3, kSmiTagSize); // Copy arguments and receiver to the expression stack. // a0: number of arguments // a1: constructor function // a2: address of last argument (caller sp) // a3: number of arguments (smi-tagged) // sp[0]: receiver // sp[1]: constructor function // sp[2]: receiver // sp[3]: constructor function // sp[4]: number of arguments (smi-tagged) Label loop, entry; __ jmp(&entry); __ bind(&loop); __ sll(t0, a3, kPointerSizeLog2 - kSmiTagSize); __ Addu(t0, a2, Operand(t0)); __ lw(t1, MemOperand(t0)); __ push(t1); __ bind(&entry); __ Addu(a3, a3, Operand(-2)); __ Branch(&loop, greater_equal, a3, Operand(zero_reg)); // Call the function. // a0: number of arguments // a1: constructor function if (is_api_function) { __ lw(cp, FieldMemOperand(a1, JSFunction::kContextOffset)); Handle<Code> code = masm->isolate()->builtins()->HandleApiCallConstruct(); ParameterCount expected(0); __ InvokeCode(code, expected, expected, RelocInfo::CODE_TARGET, CALL_FUNCTION, CALL_AS_METHOD); } else { ParameterCount actual(a0); __ InvokeFunction(a1, actual, CALL_FUNCTION, NullCallWrapper(), CALL_AS_METHOD); } // Pop the function from the stack. // v0: result // sp[0]: constructor function // sp[2]: receiver // sp[3]: constructor function // sp[4]: number of arguments (smi-tagged) __ Pop(); // Restore context from the frame. __ lw(cp, MemOperand(fp, StandardFrameConstants::kContextOffset)); // If the result is an object (in the ECMA sense), we should get rid // of the receiver and use the result; see ECMA-262 section 13.2.2-7 // on page 74. Label use_receiver, exit; // If the result is a smi, it is *not* an object in the ECMA sense. // v0: result // sp[0]: receiver (newly allocated object) // sp[1]: constructor function // sp[2]: number of arguments (smi-tagged) __ JumpIfSmi(v0, &use_receiver); // If the type of the result (stored in its map) is less than // FIRST_SPEC_OBJECT_TYPE, it is not an object in the ECMA sense. __ GetObjectType(v0, a3, a3); __ Branch(&exit, greater_equal, a3, Operand(FIRST_SPEC_OBJECT_TYPE)); // Throw away the result of the constructor invocation and use the // on-stack receiver as the result. __ bind(&use_receiver); __ lw(v0, MemOperand(sp)); // Remove receiver from the stack, remove caller arguments, and // return. __ bind(&exit); // v0: result // sp[0]: receiver (newly allocated object) // sp[1]: constructor function // sp[2]: number of arguments (smi-tagged) __ lw(a1, MemOperand(sp, 2 * kPointerSize)); // Leave construct frame. } __ sll(t0, a1, kPointerSizeLog2 - 1); __ Addu(sp, sp, t0); __ Addu(sp, sp, kPointerSize); __ IncrementCounter(isolate->counters()->constructed_objects(), 1, a1, a2); __ Ret(); } void Builtins::Generate_JSConstructStubCountdown(MacroAssembler* masm) { Generate_JSConstructStubHelper(masm, false, true); } void Builtins::Generate_JSConstructStubGeneric(MacroAssembler* masm) { Generate_JSConstructStubHelper(masm, false, false); } void Builtins::Generate_JSConstructStubApi(MacroAssembler* masm) { Generate_JSConstructStubHelper(masm, true, false); } static void Generate_JSEntryTrampolineHelper(MacroAssembler* masm, bool is_construct) { // Called from JSEntryStub::GenerateBody // ----------- S t a t e ------------- // -- a0: code entry // -- a1: function // -- a2: reveiver_pointer // -- a3: argc // -- s0: argv // ----------------------------------- // Clear the context before we push it when entering the JS frame. __ mov(cp, zero_reg); // Enter an internal frame. { FrameScope scope(masm, StackFrame::INTERNAL); // Set up the context from the function argument. __ lw(cp, FieldMemOperand(a1, JSFunction::kContextOffset)); // Set up the roots register. ExternalReference roots_array_start = ExternalReference::roots_array_start(masm->isolate()); __ li(s6, Operand(roots_array_start)); // Push the function and the receiver onto the stack. __ Push(a1, a2); // Copy arguments to the stack in a loop. // a3: argc // s0: argv, ie points to first arg Label loop, entry; __ sll(t0, a3, kPointerSizeLog2); __ addu(t2, s0, t0); __ b(&entry); __ nop(); // Branch delay slot nop. // t2 points past last arg. __ bind(&loop); __ lw(t0, MemOperand(s0)); // Read next parameter. __ addiu(s0, s0, kPointerSize); __ lw(t0, MemOperand(t0)); // Dereference handle. __ push(t0); // Push parameter. __ bind(&entry); __ Branch(&loop, ne, s0, Operand(t2)); // Initialize all JavaScript callee-saved registers, since they will be seen // by the garbage collector as part of handlers. __ LoadRoot(t0, Heap::kUndefinedValueRootIndex); __ mov(s1, t0); __ mov(s2, t0); __ mov(s3, t0); __ mov(s4, t0); __ mov(s5, t0); // s6 holds the root address. Do not clobber. // s7 is cp. Do not init. // Invoke the code and pass argc as a0. __ mov(a0, a3); if (is_construct) { __ Call(masm->isolate()->builtins()->JSConstructCall()); } else { ParameterCount actual(a0); __ InvokeFunction(a1, actual, CALL_FUNCTION, NullCallWrapper(), CALL_AS_METHOD); } // Leave internal frame. } __ Jump(ra); } void Builtins::Generate_JSEntryTrampoline(MacroAssembler* masm) { Generate_JSEntryTrampolineHelper(masm, false); } void Builtins::Generate_JSConstructEntryTrampoline(MacroAssembler* masm) { Generate_JSEntryTrampolineHelper(masm, true); } void Builtins::Generate_LazyCompile(MacroAssembler* masm) { // Enter an internal frame. { FrameScope scope(masm, StackFrame::INTERNAL); // Preserve the function. __ push(a1); // Push call kind information. __ push(t1); // Push the function on the stack as the argument to the runtime function. __ push(a1); // Call the runtime function. __ CallRuntime(Runtime::kLazyCompile, 1); // Calculate the entry point. __ addiu(t9, v0, Code::kHeaderSize - kHeapObjectTag); // Restore call kind information. __ pop(t1); // Restore saved function. __ pop(a1); // Tear down temporary frame. } // Do a tail-call of the compiled function. __ Jump(t9); } void Builtins::Generate_LazyRecompile(MacroAssembler* masm) { // Enter an internal frame. { FrameScope scope(masm, StackFrame::INTERNAL); // Preserve the function. __ push(a1); // Push call kind information. __ push(t1); // Push the function on the stack as the argument to the runtime function. __ push(a1); __ CallRuntime(Runtime::kLazyRecompile, 1); // Calculate the entry point. __ Addu(t9, v0, Operand(Code::kHeaderSize - kHeapObjectTag)); // Restore call kind information. __ pop(t1); // Restore saved function. __ pop(a1); // Tear down temporary frame. } // Do a tail-call of the compiled function. __ Jump(t9); } static void Generate_NotifyDeoptimizedHelper(MacroAssembler* masm, Deoptimizer::BailoutType type) { { FrameScope scope(masm, StackFrame::INTERNAL); // Pass the function and deoptimization type to the runtime system. __ li(a0, Operand(Smi::FromInt(static_cast<int>(type)))); __ push(a0); __ CallRuntime(Runtime::kNotifyDeoptimized, 1); } // Get the full codegen state from the stack and untag it -> t2. __ lw(t2, MemOperand(sp, 0 * kPointerSize)); __ SmiUntag(t2); // Switch on the state. Label with_tos_register, unknown_state; __ Branch(&with_tos_register, ne, t2, Operand(FullCodeGenerator::NO_REGISTERS)); __ Addu(sp, sp, Operand(1 * kPointerSize)); // Remove state. __ Ret(); __ bind(&with_tos_register); __ lw(v0, MemOperand(sp, 1 * kPointerSize)); __ Branch(&unknown_state, ne, t2, Operand(FullCodeGenerator::TOS_REG)); __ Addu(sp, sp, Operand(2 * kPointerSize)); // Remove state. __ Ret(); __ bind(&unknown_state); __ stop("no cases left"); } void Builtins::Generate_NotifyDeoptimized(MacroAssembler* masm) { Generate_NotifyDeoptimizedHelper(masm, Deoptimizer::EAGER); } void Builtins::Generate_NotifyLazyDeoptimized(MacroAssembler* masm) { Generate_NotifyDeoptimizedHelper(masm, Deoptimizer::LAZY); } void Builtins::Generate_NotifyOSR(MacroAssembler* masm) { // For now, we are relying on the fact that Runtime::NotifyOSR // doesn't do any garbage collection which allows us to save/restore // the registers without worrying about which of them contain // pointers. This seems a bit fragile. RegList saved_regs = (kJSCallerSaved | kCalleeSaved | ra.bit() | fp.bit()) & ~sp.bit(); __ MultiPush(saved_regs); { FrameScope scope(masm, StackFrame::INTERNAL); __ CallRuntime(Runtime::kNotifyOSR, 0); } __ MultiPop(saved_regs); __ Ret(); } void Builtins::Generate_OnStackReplacement(MacroAssembler* masm) { CpuFeatures::TryForceFeatureScope scope(VFP3); if (!CpuFeatures::IsSupported(FPU)) { __ Abort("Unreachable code: Cannot optimize without FPU support."); return; } // Lookup the function in the JavaScript frame and push it as an // argument to the on-stack replacement function. __ lw(a0, MemOperand(fp, JavaScriptFrameConstants::kFunctionOffset)); { FrameScope scope(masm, StackFrame::INTERNAL); __ push(a0); __ CallRuntime(Runtime::kCompileForOnStackReplacement, 1); } // If the result was -1 it means that we couldn't optimize the // function. Just return and continue in the unoptimized version. __ Ret(eq, v0, Operand(Smi::FromInt(-1))); // Untag the AST id and push it on the stack. __ SmiUntag(v0); __ push(v0); // Generate the code for doing the frame-to-frame translation using // the deoptimizer infrastructure. Deoptimizer::EntryGenerator generator(masm, Deoptimizer::OSR); generator.Generate(); } void Builtins::Generate_FunctionCall(MacroAssembler* masm) { // 1. Make sure we have at least one argument. // a0: actual number of arguments { Label done; __ Branch(&done, ne, a0, Operand(zero_reg)); __ LoadRoot(t2, Heap::kUndefinedValueRootIndex); __ push(t2); __ Addu(a0, a0, Operand(1)); __ bind(&done); } // 2. Get the function to call (passed as receiver) from the stack, check // if it is a function. // a0: actual number of arguments Label slow, non_function; __ sll(at, a0, kPointerSizeLog2); __ addu(at, sp, at); __ lw(a1, MemOperand(at)); __ JumpIfSmi(a1, &non_function); __ GetObjectType(a1, a2, a2); __ Branch(&slow, ne, a2, Operand(JS_FUNCTION_TYPE)); // 3a. Patch the first argument if necessary when calling a function. // a0: actual number of arguments // a1: function Label shift_arguments; __ li(t0, Operand(0, RelocInfo::NONE)); // Indicate regular JS_FUNCTION. { Label convert_to_object, use_global_receiver, patch_receiver; // Change context eagerly in case we need the global receiver. __ lw(cp, FieldMemOperand(a1, JSFunction::kContextOffset)); // Do not transform the receiver for strict mode functions. __ lw(a2, FieldMemOperand(a1, JSFunction::kSharedFunctionInfoOffset)); __ lw(a3, FieldMemOperand(a2, SharedFunctionInfo::kCompilerHintsOffset)); __ And(t3, a3, Operand(1 << (SharedFunctionInfo::kStrictModeFunction + kSmiTagSize))); __ Branch(&shift_arguments, ne, t3, Operand(zero_reg)); // Do not transform the receiver for native (Compilerhints already in a3). __ And(t3, a3, Operand(1 << (SharedFunctionInfo::kNative + kSmiTagSize))); __ Branch(&shift_arguments, ne, t3, Operand(zero_reg)); // Compute the receiver in non-strict mode. // Load first argument in a2. a2 = -kPointerSize(sp + n_args << 2). __ sll(at, a0, kPointerSizeLog2); __ addu(a2, sp, at); __ lw(a2, MemOperand(a2, -kPointerSize)); // a0: actual number of arguments // a1: function // a2: first argument __ JumpIfSmi(a2, &convert_to_object, t2); __ LoadRoot(a3, Heap::kUndefinedValueRootIndex); __ Branch(&use_global_receiver, eq, a2, Operand(a3)); __ LoadRoot(a3, Heap::kNullValueRootIndex); __ Branch(&use_global_receiver, eq, a2, Operand(a3)); STATIC_ASSERT(LAST_SPEC_OBJECT_TYPE == LAST_TYPE); __ GetObjectType(a2, a3, a3); __ Branch(&shift_arguments, ge, a3, Operand(FIRST_SPEC_OBJECT_TYPE)); __ bind(&convert_to_object); // Enter an internal frame in order to preserve argument count. { FrameScope scope(masm, StackFrame::INTERNAL); __ sll(a0, a0, kSmiTagSize); // Smi tagged. __ push(a0); __ push(a2); __ InvokeBuiltin(Builtins::TO_OBJECT, CALL_FUNCTION); __ mov(a2, v0); __ pop(a0); __ sra(a0, a0, kSmiTagSize); // Un-tag. // Leave internal frame. } // Restore the function to a1, and the flag to t0. __ sll(at, a0, kPointerSizeLog2); __ addu(at, sp, at); __ lw(a1, MemOperand(at)); __ li(t0, Operand(0, RelocInfo::NONE)); __ Branch(&patch_receiver); // Use the global receiver object from the called function as the // receiver. __ bind(&use_global_receiver); const int kGlobalIndex = Context::kHeaderSize + Context::GLOBAL_INDEX * kPointerSize; __ lw(a2, FieldMemOperand(cp, kGlobalIndex)); __ lw(a2, FieldMemOperand(a2, GlobalObject::kGlobalContextOffset)); __ lw(a2, FieldMemOperand(a2, kGlobalIndex)); __ lw(a2, FieldMemOperand(a2, GlobalObject::kGlobalReceiverOffset)); __ bind(&patch_receiver); __ sll(at, a0, kPointerSizeLog2); __ addu(a3, sp, at); __ sw(a2, MemOperand(a3, -kPointerSize)); __ Branch(&shift_arguments); } // 3b. Check for function proxy. __ bind(&slow); __ li(t0, Operand(1, RelocInfo::NONE)); // Indicate function proxy. __ Branch(&shift_arguments, eq, a2, Operand(JS_FUNCTION_PROXY_TYPE)); __ bind(&non_function); __ li(t0, Operand(2, RelocInfo::NONE)); // Indicate non-function. // 3c. Patch the first argument when calling a non-function. The // CALL_NON_FUNCTION builtin expects the non-function callee as // receiver, so overwrite the first argument which will ultimately // become the receiver. // a0: actual number of arguments // a1: function // t0: call type (0: JS function, 1: function proxy, 2: non-function) __ sll(at, a0, kPointerSizeLog2); __ addu(a2, sp, at); __ sw(a1, MemOperand(a2, -kPointerSize)); // 4. Shift arguments and return address one slot down on the stack // (overwriting the original receiver). Adjust argument count to make // the original first argument the new receiver. // a0: actual number of arguments // a1: function // t0: call type (0: JS function, 1: function proxy, 2: non-function) __ bind(&shift_arguments); { Label loop; // Calculate the copy start address (destination). Copy end address is sp. __ sll(at, a0, kPointerSizeLog2); __ addu(a2, sp, at); __ bind(&loop); __ lw(at, MemOperand(a2, -kPointerSize)); __ sw(at, MemOperand(a2)); __ Subu(a2, a2, Operand(kPointerSize)); __ Branch(&loop, ne, a2, Operand(sp)); // Adjust the actual number of arguments and remove the top element // (which is a copy of the last argument). __ Subu(a0, a0, Operand(1)); __ Pop(); } // 5a. Call non-function via tail call to CALL_NON_FUNCTION builtin, // or a function proxy via CALL_FUNCTION_PROXY. // a0: actual number of arguments // a1: function // t0: call type (0: JS function, 1: function proxy, 2: non-function) { Label function, non_proxy; __ Branch(&function, eq, t0, Operand(zero_reg)); // Expected number of arguments is 0 for CALL_NON_FUNCTION. __ mov(a2, zero_reg); __ SetCallKind(t1, CALL_AS_METHOD); __ Branch(&non_proxy, ne, t0, Operand(1)); __ push(a1); // Re-add proxy object as additional argument. __ Addu(a0, a0, Operand(1)); __ GetBuiltinEntry(a3, Builtins::CALL_FUNCTION_PROXY); __ Jump(masm->isolate()->builtins()->ArgumentsAdaptorTrampoline(), RelocInfo::CODE_TARGET); __ bind(&non_proxy); __ GetBuiltinEntry(a3, Builtins::CALL_NON_FUNCTION); __ Jump(masm->isolate()->builtins()->ArgumentsAdaptorTrampoline(), RelocInfo::CODE_TARGET); __ bind(&function); } // 5b. Get the code to call from the function and check that the number of // expected arguments matches what we're providing. If so, jump // (tail-call) to the code in register edx without checking arguments. // a0: actual number of arguments // a1: function __ lw(a3, FieldMemOperand(a1, JSFunction::kSharedFunctionInfoOffset)); __ lw(a2, FieldMemOperand(a3, SharedFunctionInfo::kFormalParameterCountOffset)); __ sra(a2, a2, kSmiTagSize); __ lw(a3, FieldMemOperand(a1, JSFunction::kCodeEntryOffset)); __ SetCallKind(t1, CALL_AS_METHOD); // Check formal and actual parameter counts. __ Jump(masm->isolate()->builtins()->ArgumentsAdaptorTrampoline(), RelocInfo::CODE_TARGET, ne, a2, Operand(a0)); ParameterCount expected(0); __ InvokeCode(a3, expected, expected, JUMP_FUNCTION, NullCallWrapper(), CALL_AS_METHOD); } void Builtins::Generate_FunctionApply(MacroAssembler* masm) { const int kIndexOffset = -5 * kPointerSize; const int kLimitOffset = -4 * kPointerSize; const int kArgsOffset = 2 * kPointerSize; const int kRecvOffset = 3 * kPointerSize; const int kFunctionOffset = 4 * kPointerSize; { FrameScope frame_scope(masm, StackFrame::INTERNAL); __ lw(a0, MemOperand(fp, kFunctionOffset)); // Get the function. __ push(a0); __ lw(a0, MemOperand(fp, kArgsOffset)); // Get the args array. __ push(a0); // Returns (in v0) number of arguments to copy to stack as Smi. __ InvokeBuiltin(Builtins::APPLY_PREPARE, CALL_FUNCTION); // Check the stack for overflow. We are not trying to catch // interruptions (e.g. debug break and preemption) here, so the "real stack // limit" is checked. Label okay; __ LoadRoot(a2, Heap::kRealStackLimitRootIndex); // Make a2 the space we have left. The stack might already be overflowed // here which will cause a2 to become negative. __ subu(a2, sp, a2); // Check if the arguments will overflow the stack. __ sll(t3, v0, kPointerSizeLog2 - kSmiTagSize); __ Branch(&okay, gt, a2, Operand(t3)); // Signed comparison. // Out of stack space. __ lw(a1, MemOperand(fp, kFunctionOffset)); __ push(a1); __ push(v0); __ InvokeBuiltin(Builtins::APPLY_OVERFLOW, CALL_FUNCTION); // End of stack check. // Push current limit and index. __ bind(&okay); __ push(v0); // Limit. __ mov(a1, zero_reg); // Initial index. __ push(a1); // Get the receiver. __ lw(a0, MemOperand(fp, kRecvOffset)); // Check that the function is a JS function (otherwise it must be a proxy). Label push_receiver; __ lw(a1, MemOperand(fp, kFunctionOffset)); __ GetObjectType(a1, a2, a2); __ Branch(&push_receiver, ne, a2, Operand(JS_FUNCTION_TYPE)); // Change context eagerly to get the right global object if necessary. __ lw(cp, FieldMemOperand(a1, JSFunction::kContextOffset)); // Load the shared function info while the function is still in a1. __ lw(a2, FieldMemOperand(a1, JSFunction::kSharedFunctionInfoOffset)); // Compute the receiver. // Do not transform the receiver for strict mode functions. Label call_to_object, use_global_receiver; __ lw(a2, FieldMemOperand(a2, SharedFunctionInfo::kCompilerHintsOffset)); __ And(t3, a2, Operand(1 << (SharedFunctionInfo::kStrictModeFunction + kSmiTagSize))); __ Branch(&push_receiver, ne, t3, Operand(zero_reg)); // Do not transform the receiver for native (Compilerhints already in a2). __ And(t3, a2, Operand(1 << (SharedFunctionInfo::kNative + kSmiTagSize))); __ Branch(&push_receiver, ne, t3, Operand(zero_reg)); // Compute the receiver in non-strict mode. __ JumpIfSmi(a0, &call_to_object); __ LoadRoot(a1, Heap::kNullValueRootIndex); __ Branch(&use_global_receiver, eq, a0, Operand(a1)); __ LoadRoot(a2, Heap::kUndefinedValueRootIndex); __ Branch(&use_global_receiver, eq, a0, Operand(a2)); // Check if the receiver is already a JavaScript object. // a0: receiver STATIC_ASSERT(LAST_SPEC_OBJECT_TYPE == LAST_TYPE); __ GetObjectType(a0, a1, a1); __ Branch(&push_receiver, ge, a1, Operand(FIRST_SPEC_OBJECT_TYPE)); // Convert the receiver to a regular object. // a0: receiver __ bind(&call_to_object); __ push(a0); __ InvokeBuiltin(Builtins::TO_OBJECT, CALL_FUNCTION); __ mov(a0, v0); // Put object in a0 to match other paths to push_receiver. __ Branch(&push_receiver); // Use the current global receiver object as the receiver. __ bind(&use_global_receiver); const int kGlobalOffset = Context::kHeaderSize + Context::GLOBAL_INDEX * kPointerSize; __ lw(a0, FieldMemOperand(cp, kGlobalOffset)); __ lw(a0, FieldMemOperand(a0, GlobalObject::kGlobalContextOffset)); __ lw(a0, FieldMemOperand(a0, kGlobalOffset)); __ lw(a0, FieldMemOperand(a0, GlobalObject::kGlobalReceiverOffset)); // Push the receiver. // a0: receiver __ bind(&push_receiver); __ push(a0); // Copy all arguments from the array to the stack. Label entry, loop; __ lw(a0, MemOperand(fp, kIndexOffset)); __ Branch(&entry); // Load the current argument from the arguments array and push it to the // stack. // a0: current argument index __ bind(&loop); __ lw(a1, MemOperand(fp, kArgsOffset)); __ push(a1); __ push(a0); // Call the runtime to access the property in the arguments array. __ CallRuntime(Runtime::kGetProperty, 2); __ push(v0); // Use inline caching to access the arguments. __ lw(a0, MemOperand(fp, kIndexOffset)); __ Addu(a0, a0, Operand(1 << kSmiTagSize)); __ sw(a0, MemOperand(fp, kIndexOffset)); // Test if the copy loop has finished copying all the elements from the // arguments object. __ bind(&entry); __ lw(a1, MemOperand(fp, kLimitOffset)); __ Branch(&loop, ne, a0, Operand(a1)); // Invoke the function. Label call_proxy; ParameterCount actual(a0); __ sra(a0, a0, kSmiTagSize); __ lw(a1, MemOperand(fp, kFunctionOffset)); __ GetObjectType(a1, a2, a2); __ Branch(&call_proxy, ne, a2, Operand(JS_FUNCTION_TYPE)); __ InvokeFunction(a1, actual, CALL_FUNCTION, NullCallWrapper(), CALL_AS_METHOD); frame_scope.GenerateLeaveFrame(); __ Ret(USE_DELAY_SLOT); __ Addu(sp, sp, Operand(3 * kPointerSize)); // In delay slot. // Invoke the function proxy. __ bind(&call_proxy); __ push(a1); // Add function proxy as last argument. __ Addu(a0, a0, Operand(1)); __ li(a2, Operand(0, RelocInfo::NONE)); __ SetCallKind(t1, CALL_AS_METHOD); __ GetBuiltinEntry(a3, Builtins::CALL_FUNCTION_PROXY); __ Call(masm->isolate()->builtins()->ArgumentsAdaptorTrampoline(), RelocInfo::CODE_TARGET); // Tear down the internal frame and remove function, receiver and args. } __ Ret(USE_DELAY_SLOT); __ Addu(sp, sp, Operand(3 * kPointerSize)); // In delay slot. } static void EnterArgumentsAdaptorFrame(MacroAssembler* masm) { __ sll(a0, a0, kSmiTagSize); __ li(t0, Operand(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR))); __ MultiPush(a0.bit() | a1.bit() | t0.bit() | fp.bit() | ra.bit()); __ Addu(fp, sp, Operand(3 * kPointerSize)); } static void LeaveArgumentsAdaptorFrame(MacroAssembler* masm) { // ----------- S t a t e ------------- // -- v0 : result being passed through // ----------------------------------- // Get the number of arguments passed (as a smi), tear down the frame and // then tear down the parameters. __ lw(a1, MemOperand(fp, -3 * kPointerSize)); __ mov(sp, fp); __ MultiPop(fp.bit() | ra.bit()); __ sll(t0, a1, kPointerSizeLog2 - kSmiTagSize); __ Addu(sp, sp, t0); // Adjust for the receiver. __ Addu(sp, sp, Operand(kPointerSize)); } void Builtins::Generate_ArgumentsAdaptorTrampoline(MacroAssembler* masm) { // State setup as expected by MacroAssembler::InvokePrologue. // ----------- S t a t e ------------- // -- a0: actual arguments count // -- a1: function (passed through to callee) // -- a2: expected arguments count // -- a3: callee code entry // -- t1: call kind information // ----------------------------------- Label invoke, dont_adapt_arguments; Label enough, too_few; __ Branch(&dont_adapt_arguments, eq, a2, Operand(SharedFunctionInfo::kDontAdaptArgumentsSentinel)); // We use Uless as the number of argument should always be greater than 0. __ Branch(&too_few, Uless, a0, Operand(a2)); { // Enough parameters: actual >= expected. // a0: actual number of arguments as a smi // a1: function // a2: expected number of arguments // a3: code entry to call __ bind(&enough); EnterArgumentsAdaptorFrame(masm); // Calculate copy start address into a0 and copy end address into a2. __ sll(a0, a0, kPointerSizeLog2 - kSmiTagSize); __ Addu(a0, fp, a0); // Adjust for return address and receiver. __ Addu(a0, a0, Operand(2 * kPointerSize)); // Compute copy end address. __ sll(a2, a2, kPointerSizeLog2); __ subu(a2, a0, a2); // Copy the arguments (including the receiver) to the new stack frame. // a0: copy start address // a1: function // a2: copy end address // a3: code entry to call Label copy; __ bind(&copy); __ lw(t0, MemOperand(a0)); __ push(t0); __ Branch(USE_DELAY_SLOT, &copy, ne, a0, Operand(a2)); __ addiu(a0, a0, -kPointerSize); // In delay slot. __ jmp(&invoke); } { // Too few parameters: Actual < expected. __ bind(&too_few); EnterArgumentsAdaptorFrame(masm); // TODO(MIPS): Optimize these loops. // Calculate copy start address into a0 and copy end address is fp. // a0: actual number of arguments as a smi // a1: function // a2: expected number of arguments // a3: code entry to call __ sll(a0, a0, kPointerSizeLog2 - kSmiTagSize); __ Addu(a0, fp, a0); // Adjust for return address and receiver. __ Addu(a0, a0, Operand(2 * kPointerSize)); // Compute copy end address. Also adjust for return address. __ Addu(t3, fp, kPointerSize); // Copy the arguments (including the receiver) to the new stack frame. // a0: copy start address // a1: function // a2: expected number of arguments // a3: code entry to call // t3: copy end address Label copy; __ bind(&copy); __ lw(t0, MemOperand(a0)); // Adjusted above for return addr and receiver. __ push(t0); __ Subu(a0, a0, kPointerSize); __ Branch(&copy, ne, a0, Operand(t3)); // Fill the remaining expected arguments with undefined. // a1: function // a2: expected number of arguments // a3: code entry to call __ LoadRoot(t0, Heap::kUndefinedValueRootIndex); __ sll(t2, a2, kPointerSizeLog2); __ Subu(a2, fp, Operand(t2)); __ Addu(a2, a2, Operand(-4 * kPointerSize)); // Adjust for frame. Label fill; __ bind(&fill); __ push(t0); __ Branch(&fill, ne, sp, Operand(a2)); } // Call the entry point. __ bind(&invoke); __ Call(a3); // Exit frame and return. LeaveArgumentsAdaptorFrame(masm); __ Ret(); // ------------------------------------------- // Don't adapt arguments. // ------------------------------------------- __ bind(&dont_adapt_arguments); __ Jump(a3); } #undef __ } } // namespace v8::internal #endif // V8_TARGET_ARCH_MIPS MIPS: Ensure that InternalArrays remain InternalArrays regardless of how they are constructed. Port r10306 (9141da8e) BUG= TEST= Review URL: http://codereview.chromium.org/9080001 Patch from Gergely Kis <gergely@homejinni.com>. git-svn-id: b158db1e4b4ab85d4c9e510fdef4b1e8c614b15b@10325 ce2b1a6d-e550-0410-aec6-3dcde31c8c00 // Copyright 2012 the V8 project authors. All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "v8.h" #if defined(V8_TARGET_ARCH_MIPS) #include "codegen.h" #include "debug.h" #include "deoptimizer.h" #include "full-codegen.h" #include "runtime.h" namespace v8 { namespace internal { #define __ ACCESS_MASM(masm) void Builtins::Generate_Adaptor(MacroAssembler* masm, CFunctionId id, BuiltinExtraArguments extra_args) { // ----------- S t a t e ------------- // -- a0 : number of arguments excluding receiver // -- a1 : called function (only guaranteed when // -- extra_args requires it) // -- cp : context // -- sp[0] : last argument // -- ... // -- sp[4 * (argc - 1)] : first argument // -- sp[4 * agrc] : receiver // ----------------------------------- // Insert extra arguments. int num_extra_args = 0; if (extra_args == NEEDS_CALLED_FUNCTION) { num_extra_args = 1; __ push(a1); } else { ASSERT(extra_args == NO_EXTRA_ARGUMENTS); } // JumpToExternalReference expects a0 to contain the number of arguments // including the receiver and the extra arguments. __ Addu(a0, a0, Operand(num_extra_args + 1)); __ JumpToExternalReference(ExternalReference(id, masm->isolate())); } // Load the built-in InternalArray function from the current context. static void GenerateLoadInternalArrayFunction(MacroAssembler* masm, Register result) { // Load the global context. __ lw(result, MemOperand(cp, Context::SlotOffset(Context::GLOBAL_INDEX))); __ lw(result, FieldMemOperand(result, GlobalObject::kGlobalContextOffset)); // Load the InternalArray function from the global context. __ lw(result, MemOperand(result, Context::SlotOffset( Context::INTERNAL_ARRAY_FUNCTION_INDEX))); } // Load the built-in Array function from the current context. static void GenerateLoadArrayFunction(MacroAssembler* masm, Register result) { // Load the global context. __ lw(result, MemOperand(cp, Context::SlotOffset(Context::GLOBAL_INDEX))); __ lw(result, FieldMemOperand(result, GlobalObject::kGlobalContextOffset)); // Load the Array function from the global context. __ lw(result, MemOperand(result, Context::SlotOffset(Context::ARRAY_FUNCTION_INDEX))); } // Allocate an empty JSArray. The allocated array is put into the result // register. An elements backing store is allocated with size initial_capacity // and filled with the hole values. static void AllocateEmptyJSArray(MacroAssembler* masm, Register array_function, Register result, Register scratch1, Register scratch2, Register scratch3, Label* gc_required) { const int initial_capacity = JSArray::kPreallocatedArrayElements; STATIC_ASSERT(initial_capacity >= 0); // Load the initial map from the array function. __ lw(scratch1, FieldMemOperand(array_function, JSFunction::kPrototypeOrInitialMapOffset)); // Allocate the JSArray object together with space for a fixed array with the // requested elements. int size = JSArray::kSize; if (initial_capacity > 0) { size += FixedArray::SizeFor(initial_capacity); } __ AllocateInNewSpace(size, result, scratch2, scratch3, gc_required, TAG_OBJECT); // Allocated the JSArray. Now initialize the fields except for the elements // array. // result: JSObject // scratch1: initial map // scratch2: start of next object __ sw(scratch1, FieldMemOperand(result, JSObject::kMapOffset)); __ LoadRoot(scratch1, Heap::kEmptyFixedArrayRootIndex); __ sw(scratch1, FieldMemOperand(result, JSArray::kPropertiesOffset)); // Field JSArray::kElementsOffset is initialized later. __ mov(scratch3, zero_reg); __ sw(scratch3, FieldMemOperand(result, JSArray::kLengthOffset)); if (initial_capacity == 0) { __ sw(scratch1, FieldMemOperand(result, JSArray::kElementsOffset)); return; } // Calculate the location of the elements array and set elements array member // of the JSArray. // result: JSObject // scratch2: start of next object __ Addu(scratch1, result, Operand(JSArray::kSize)); __ sw(scratch1, FieldMemOperand(result, JSArray::kElementsOffset)); // Clear the heap tag on the elements array. __ And(scratch1, scratch1, Operand(~kHeapObjectTagMask)); // Initialize the FixedArray and fill it with holes. FixedArray length is // stored as a smi. // result: JSObject // scratch1: elements array (untagged) // scratch2: start of next object __ LoadRoot(scratch3, Heap::kFixedArrayMapRootIndex); STATIC_ASSERT(0 * kPointerSize == FixedArray::kMapOffset); __ sw(scratch3, MemOperand(scratch1)); __ Addu(scratch1, scratch1, kPointerSize); __ li(scratch3, Operand(Smi::FromInt(initial_capacity))); STATIC_ASSERT(1 * kPointerSize == FixedArray::kLengthOffset); __ sw(scratch3, MemOperand(scratch1)); __ Addu(scratch1, scratch1, kPointerSize); // Fill the FixedArray with the hole value. Inline the code if short. STATIC_ASSERT(2 * kPointerSize == FixedArray::kHeaderSize); __ LoadRoot(scratch3, Heap::kTheHoleValueRootIndex); static const int kLoopUnfoldLimit = 4; if (initial_capacity <= kLoopUnfoldLimit) { for (int i = 0; i < initial_capacity; i++) { __ sw(scratch3, MemOperand(scratch1, i * kPointerSize)); } } else { Label loop, entry; __ Addu(scratch2, scratch1, Operand(initial_capacity * kPointerSize)); __ Branch(&entry); __ bind(&loop); __ sw(scratch3, MemOperand(scratch1)); __ Addu(scratch1, scratch1, kPointerSize); __ bind(&entry); __ Branch(&loop, lt, scratch1, Operand(scratch2)); } } // Allocate a JSArray with the number of elements stored in a register. The // register array_function holds the built-in Array function and the register // array_size holds the size of the array as a smi. The allocated array is put // into the result register and beginning and end of the FixedArray elements // storage is put into registers elements_array_storage and elements_array_end // (see below for when that is not the case). If the parameter fill_with_holes // is true the allocated elements backing store is filled with the hole values // otherwise it is left uninitialized. When the backing store is filled the // register elements_array_storage is scratched. static void AllocateJSArray(MacroAssembler* masm, Register array_function, // Array function. Register array_size, // As a smi, cannot be 0. Register result, Register elements_array_storage, Register elements_array_end, Register scratch1, Register scratch2, bool fill_with_hole, Label* gc_required) { // Load the initial map from the array function. __ lw(elements_array_storage, FieldMemOperand(array_function, JSFunction::kPrototypeOrInitialMapOffset)); if (FLAG_debug_code) { // Assert that array size is not zero. __ Assert( ne, "array size is unexpectedly 0", array_size, Operand(zero_reg)); } // Allocate the JSArray object together with space for a FixedArray with the // requested number of elements. STATIC_ASSERT(kSmiTagSize == 1 && kSmiTag == 0); __ li(elements_array_end, (JSArray::kSize + FixedArray::kHeaderSize) / kPointerSize); __ sra(scratch1, array_size, kSmiTagSize); __ Addu(elements_array_end, elements_array_end, scratch1); __ AllocateInNewSpace( elements_array_end, result, scratch1, scratch2, gc_required, static_cast<AllocationFlags>(TAG_OBJECT | SIZE_IN_WORDS)); // Allocated the JSArray. Now initialize the fields except for the elements // array. // result: JSObject // elements_array_storage: initial map // array_size: size of array (smi) __ sw(elements_array_storage, FieldMemOperand(result, JSObject::kMapOffset)); __ LoadRoot(elements_array_storage, Heap::kEmptyFixedArrayRootIndex); __ sw(elements_array_storage, FieldMemOperand(result, JSArray::kPropertiesOffset)); // Field JSArray::kElementsOffset is initialized later. __ sw(array_size, FieldMemOperand(result, JSArray::kLengthOffset)); // Calculate the location of the elements array and set elements array member // of the JSArray. // result: JSObject // array_size: size of array (smi) __ Addu(elements_array_storage, result, Operand(JSArray::kSize)); __ sw(elements_array_storage, FieldMemOperand(result, JSArray::kElementsOffset)); // Clear the heap tag on the elements array. __ And(elements_array_storage, elements_array_storage, Operand(~kHeapObjectTagMask)); // Initialize the fixed array and fill it with holes. FixedArray length is // stored as a smi. // result: JSObject // elements_array_storage: elements array (untagged) // array_size: size of array (smi) __ LoadRoot(scratch1, Heap::kFixedArrayMapRootIndex); ASSERT_EQ(0 * kPointerSize, FixedArray::kMapOffset); __ sw(scratch1, MemOperand(elements_array_storage)); __ Addu(elements_array_storage, elements_array_storage, kPointerSize); // Length of the FixedArray is the number of pre-allocated elements if // the actual JSArray has length 0 and the size of the JSArray for non-empty // JSArrays. The length of a FixedArray is stored as a smi. STATIC_ASSERT(kSmiTag == 0); ASSERT_EQ(1 * kPointerSize, FixedArray::kLengthOffset); __ sw(array_size, MemOperand(elements_array_storage)); __ Addu(elements_array_storage, elements_array_storage, kPointerSize); // Calculate elements array and elements array end. // result: JSObject // elements_array_storage: elements array element storage // array_size: smi-tagged size of elements array STATIC_ASSERT(kSmiTag == 0 && kSmiTagSize < kPointerSizeLog2); __ sll(elements_array_end, array_size, kPointerSizeLog2 - kSmiTagSize); __ Addu(elements_array_end, elements_array_storage, elements_array_end); // Fill the allocated FixedArray with the hole value if requested. // result: JSObject // elements_array_storage: elements array element storage // elements_array_end: start of next object if (fill_with_hole) { Label loop, entry; __ LoadRoot(scratch1, Heap::kTheHoleValueRootIndex); __ Branch(&entry); __ bind(&loop); __ sw(scratch1, MemOperand(elements_array_storage)); __ Addu(elements_array_storage, elements_array_storage, kPointerSize); __ bind(&entry); __ Branch(&loop, lt, elements_array_storage, Operand(elements_array_end)); } } // Create a new array for the built-in Array function. This function allocates // the JSArray object and the FixedArray elements array and initializes these. // If the Array cannot be constructed in native code the runtime is called. This // function assumes the following state: // a0: argc // a1: constructor (built-in Array function) // ra: return address // sp[0]: last argument // This function is used for both construct and normal calls of Array. The only // difference between handling a construct call and a normal call is that for a // construct call the constructor function in a1 needs to be preserved for // entering the generic code. In both cases argc in a0 needs to be preserved. // Both registers are preserved by this code so no need to differentiate between // construct call and normal call. static void ArrayNativeCode(MacroAssembler* masm, Label* call_generic_code) { Counters* counters = masm->isolate()->counters(); Label argc_one_or_more, argc_two_or_more, not_empty_array, empty_array; // Check for array construction with zero arguments or one. __ Branch(&argc_one_or_more, ne, a0, Operand(zero_reg)); // Handle construction of an empty array. __ bind(&empty_array); AllocateEmptyJSArray(masm, a1, a2, a3, t0, t1, call_generic_code); __ IncrementCounter(counters->array_function_native(), 1, a3, t0); // Setup return value, remove receiver from stack and return. __ mov(v0, a2); __ Addu(sp, sp, Operand(kPointerSize)); __ Ret(); // Check for one argument. Bail out if argument is not smi or if it is // negative. __ bind(&argc_one_or_more); __ Branch(&argc_two_or_more, ne, a0, Operand(1)); STATIC_ASSERT(kSmiTag == 0); __ lw(a2, MemOperand(sp)); // Get the argument from the stack. __ Branch(&not_empty_array, ne, a2, Operand(zero_reg)); __ Drop(1); // Adjust stack. __ mov(a0, zero_reg); // Treat this as a call with argc of zero. __ Branch(&empty_array); __ bind(&not_empty_array); __ And(a3, a2, Operand(kIntptrSignBit | kSmiTagMask)); __ Branch(call_generic_code, eq, a3, Operand(zero_reg)); // Handle construction of an empty array of a certain size. Bail out if size // is too large to actually allocate an elements array. STATIC_ASSERT(kSmiTag == 0); __ Branch(call_generic_code, Ugreater_equal, a2, Operand(JSObject::kInitialMaxFastElementArray << kSmiTagSize)); // a0: argc // a1: constructor // a2: array_size (smi) // sp[0]: argument AllocateJSArray(masm, a1, a2, a3, t0, t1, t2, t3, true, call_generic_code); __ IncrementCounter(counters->array_function_native(), 1, a2, t0); // Setup return value, remove receiver and argument from stack and return. __ mov(v0, a3); __ Addu(sp, sp, Operand(2 * kPointerSize)); __ Ret(); // Handle construction of an array from a list of arguments. __ bind(&argc_two_or_more); __ sll(a2, a0, kSmiTagSize); // Convert argc to a smi. // a0: argc // a1: constructor // a2: array_size (smi) // sp[0]: last argument AllocateJSArray(masm, a1, a2, a3, t0, t1, t2, t3, false, call_generic_code); __ IncrementCounter(counters->array_function_native(), 1, a2, t2); // Fill arguments as array elements. Copy from the top of the stack (last // element) to the array backing store filling it backwards. Note: // elements_array_end points after the backing store. // a0: argc // a3: JSArray // t0: elements_array storage start (untagged) // t1: elements_array_end (untagged) // sp[0]: last argument Label loop, entry; __ Branch(USE_DELAY_SLOT, &entry); __ mov(t3, sp); __ bind(&loop); __ lw(a2, MemOperand(t3)); __ Addu(t3, t3, kPointerSize); if (FLAG_smi_only_arrays) { __ JumpIfNotSmi(a2, call_generic_code); } __ Addu(t1, t1, -kPointerSize); __ sw(a2, MemOperand(t1)); __ bind(&entry); __ Branch(&loop, lt, t0, Operand(t1)); __ mov(sp, t3); // Remove caller arguments and receiver from the stack, setup return value and // return. // a0: argc // a3: JSArray // sp[0]: receiver __ Addu(sp, sp, Operand(kPointerSize)); __ mov(v0, a3); __ Ret(); } void Builtins::Generate_InternalArrayCode(MacroAssembler* masm) { // ----------- S t a t e ------------- // -- a0 : number of arguments // -- ra : return address // -- sp[...]: constructor arguments // ----------------------------------- Label generic_array_code, one_or_more_arguments, two_or_more_arguments; // Get the InternalArray function. GenerateLoadInternalArrayFunction(masm, a1); if (FLAG_debug_code) { // Initial map for the builtin InternalArray functions should be maps. __ lw(a2, FieldMemOperand(a1, JSFunction::kPrototypeOrInitialMapOffset)); __ And(t0, a2, Operand(kSmiTagMask)); __ Assert(ne, "Unexpected initial map for InternalArray function", t0, Operand(zero_reg)); __ GetObjectType(a2, a3, t0); __ Assert(eq, "Unexpected initial map for InternalArray function", t0, Operand(MAP_TYPE)); } // Run the native code for the InternalArray function called as a normal // function. ArrayNativeCode(masm, &generic_array_code); // Jump to the generic array code if the specialized code cannot handle the // construction. __ bind(&generic_array_code); Handle<Code> array_code = masm->isolate()->builtins()->ArrayCodeGeneric(); __ Jump(array_code, RelocInfo::CODE_TARGET); } void Builtins::Generate_ArrayCode(MacroAssembler* masm) { // ----------- S t a t e ------------- // -- a0 : number of arguments // -- ra : return address // -- sp[...]: constructor arguments // ----------------------------------- Label generic_array_code; // Get the Array function. GenerateLoadArrayFunction(masm, a1); if (FLAG_debug_code) { // Initial map for the builtin Array functions should be maps. __ lw(a2, FieldMemOperand(a1, JSFunction::kPrototypeOrInitialMapOffset)); __ And(t0, a2, Operand(kSmiTagMask)); __ Assert(ne, "Unexpected initial map for Array function (1)", t0, Operand(zero_reg)); __ GetObjectType(a2, a3, t0); __ Assert(eq, "Unexpected initial map for Array function (2)", t0, Operand(MAP_TYPE)); } // Run the native code for the Array function called as a normal function. ArrayNativeCode(masm, &generic_array_code); // Jump to the generic array code if the specialized code cannot handle // the construction. __ bind(&generic_array_code); Handle<Code> array_code = masm->isolate()->builtins()->ArrayCodeGeneric(); __ Jump(array_code, RelocInfo::CODE_TARGET); } void Builtins::Generate_ArrayConstructCode(MacroAssembler* masm) { // ----------- S t a t e ------------- // -- a0 : number of arguments // -- a1 : constructor function // -- ra : return address // -- sp[...]: constructor arguments // ----------------------------------- Label generic_constructor; if (FLAG_debug_code) { // The array construct code is only set for the builtin and internal // Array functions which always have a map. // Initial map for the builtin Array function should be a map. __ lw(a2, FieldMemOperand(a1, JSFunction::kPrototypeOrInitialMapOffset)); __ And(t0, a2, Operand(kSmiTagMask)); __ Assert(ne, "Unexpected initial map for Array function (3)", t0, Operand(zero_reg)); __ GetObjectType(a2, a3, t0); __ Assert(eq, "Unexpected initial map for Array function (4)", t0, Operand(MAP_TYPE)); } // Run the native code for the Array function called as a constructor. ArrayNativeCode(masm, &generic_constructor); // Jump to the generic construct code in case the specialized code cannot // handle the construction. __ bind(&generic_constructor); Handle<Code> generic_construct_stub = masm->isolate()->builtins()->JSConstructStubGeneric(); __ Jump(generic_construct_stub, RelocInfo::CODE_TARGET); } void Builtins::Generate_StringConstructCode(MacroAssembler* masm) { // ----------- S t a t e ------------- // -- a0 : number of arguments // -- a1 : constructor function // -- ra : return address // -- sp[(argc - n - 1) * 4] : arg[n] (zero based) // -- sp[argc * 4] : receiver // ----------------------------------- Counters* counters = masm->isolate()->counters(); __ IncrementCounter(counters->string_ctor_calls(), 1, a2, a3); Register function = a1; if (FLAG_debug_code) { __ LoadGlobalFunction(Context::STRING_FUNCTION_INDEX, a2); __ Assert(eq, "Unexpected String function", function, Operand(a2)); } // Load the first arguments in a0 and get rid of the rest. Label no_arguments; __ Branch(&no_arguments, eq, a0, Operand(zero_reg)); // First args = sp[(argc - 1) * 4]. __ Subu(a0, a0, Operand(1)); __ sll(a0, a0, kPointerSizeLog2); __ Addu(sp, a0, sp); __ lw(a0, MemOperand(sp)); // sp now point to args[0], drop args[0] + receiver. __ Drop(2); Register argument = a2; Label not_cached, argument_is_string; NumberToStringStub::GenerateLookupNumberStringCache( masm, a0, // Input. argument, // Result. a3, // Scratch. t0, // Scratch. t1, // Scratch. false, // Is it a Smi? &not_cached); __ IncrementCounter(counters->string_ctor_cached_number(), 1, a3, t0); __ bind(&argument_is_string); // ----------- S t a t e ------------- // -- a2 : argument converted to string // -- a1 : constructor function // -- ra : return address // ----------------------------------- Label gc_required; __ AllocateInNewSpace(JSValue::kSize, v0, // Result. a3, // Scratch. t0, // Scratch. &gc_required, TAG_OBJECT); // Initialising the String Object. Register map = a3; __ LoadGlobalFunctionInitialMap(function, map, t0); if (FLAG_debug_code) { __ lbu(t0, FieldMemOperand(map, Map::kInstanceSizeOffset)); __ Assert(eq, "Unexpected string wrapper instance size", t0, Operand(JSValue::kSize >> kPointerSizeLog2)); __ lbu(t0, FieldMemOperand(map, Map::kUnusedPropertyFieldsOffset)); __ Assert(eq, "Unexpected unused properties of string wrapper", t0, Operand(zero_reg)); } __ sw(map, FieldMemOperand(v0, HeapObject::kMapOffset)); __ LoadRoot(a3, Heap::kEmptyFixedArrayRootIndex); __ sw(a3, FieldMemOperand(v0, JSObject::kPropertiesOffset)); __ sw(a3, FieldMemOperand(v0, JSObject::kElementsOffset)); __ sw(argument, FieldMemOperand(v0, JSValue::kValueOffset)); // Ensure the object is fully initialized. STATIC_ASSERT(JSValue::kSize == 4 * kPointerSize); __ Ret(); // The argument was not found in the number to string cache. Check // if it's a string already before calling the conversion builtin. Label convert_argument; __ bind(&not_cached); __ JumpIfSmi(a0, &convert_argument); // Is it a String? __ lw(a2, FieldMemOperand(a0, HeapObject::kMapOffset)); __ lbu(a3, FieldMemOperand(a2, Map::kInstanceTypeOffset)); STATIC_ASSERT(kNotStringTag != 0); __ And(t0, a3, Operand(kIsNotStringMask)); __ Branch(&convert_argument, ne, t0, Operand(zero_reg)); __ mov(argument, a0); __ IncrementCounter(counters->string_ctor_conversions(), 1, a3, t0); __ Branch(&argument_is_string); // Invoke the conversion builtin and put the result into a2. __ bind(&convert_argument); __ push(function); // Preserve the function. __ IncrementCounter(counters->string_ctor_conversions(), 1, a3, t0); { FrameScope scope(masm, StackFrame::INTERNAL); __ push(v0); __ InvokeBuiltin(Builtins::TO_STRING, CALL_FUNCTION); } __ pop(function); __ mov(argument, v0); __ Branch(&argument_is_string); // Load the empty string into a2, remove the receiver from the // stack, and jump back to the case where the argument is a string. __ bind(&no_arguments); __ LoadRoot(argument, Heap::kEmptyStringRootIndex); __ Drop(1); __ Branch(&argument_is_string); // At this point the argument is already a string. Call runtime to // create a string wrapper. __ bind(&gc_required); __ IncrementCounter(counters->string_ctor_gc_required(), 1, a3, t0); { FrameScope scope(masm, StackFrame::INTERNAL); __ push(argument); __ CallRuntime(Runtime::kNewStringWrapper, 1); } __ Ret(); } void Builtins::Generate_JSConstructCall(MacroAssembler* masm) { // ----------- S t a t e ------------- // -- a0 : number of arguments // -- a1 : constructor function // -- ra : return address // -- sp[...]: constructor arguments // ----------------------------------- Label slow, non_function_call; // Check that the function is not a smi. __ JumpIfSmi(a1, &non_function_call); // Check that the function is a JSFunction. __ GetObjectType(a1, a2, a2); __ Branch(&slow, ne, a2, Operand(JS_FUNCTION_TYPE)); // Jump to the function-specific construct stub. __ lw(a2, FieldMemOperand(a1, JSFunction::kSharedFunctionInfoOffset)); __ lw(a2, FieldMemOperand(a2, SharedFunctionInfo::kConstructStubOffset)); __ Addu(t9, a2, Operand(Code::kHeaderSize - kHeapObjectTag)); __ Jump(t9); // a0: number of arguments // a1: called object // a2: object type Label do_call; __ bind(&slow); __ Branch(&non_function_call, ne, a2, Operand(JS_FUNCTION_PROXY_TYPE)); __ GetBuiltinEntry(a3, Builtins::CALL_FUNCTION_PROXY_AS_CONSTRUCTOR); __ jmp(&do_call); __ bind(&non_function_call); __ GetBuiltinEntry(a3, Builtins::CALL_NON_FUNCTION_AS_CONSTRUCTOR); __ bind(&do_call); // CALL_NON_FUNCTION expects the non-function constructor as receiver // (instead of the original receiver from the call site). The receiver is // stack element argc. // Set expected number of arguments to zero (not changing a0). __ mov(a2, zero_reg); __ SetCallKind(t1, CALL_AS_METHOD); __ Jump(masm->isolate()->builtins()->ArgumentsAdaptorTrampoline(), RelocInfo::CODE_TARGET); } static void Generate_JSConstructStubHelper(MacroAssembler* masm, bool is_api_function, bool count_constructions) { // Should never count constructions for api objects. ASSERT(!is_api_function || !count_constructions); Isolate* isolate = masm->isolate(); // ----------- S t a t e ------------- // -- a0 : number of arguments // -- a1 : constructor function // -- ra : return address // -- sp[...]: constructor arguments // ----------------------------------- // Enter a construct frame. { FrameScope scope(masm, StackFrame::CONSTRUCT); // Preserve the two incoming parameters on the stack. __ sll(a0, a0, kSmiTagSize); // Tag arguments count. __ MultiPushReversed(a0.bit() | a1.bit()); // Use t7 to hold undefined, which is used in several places below. __ LoadRoot(t7, Heap::kUndefinedValueRootIndex); Label rt_call, allocated; // Try to allocate the object without transitioning into C code. If any of // the preconditions is not met, the code bails out to the runtime call. if (FLAG_inline_new) { Label undo_allocation; #ifdef ENABLE_DEBUGGER_SUPPORT ExternalReference debug_step_in_fp = ExternalReference::debug_step_in_fp_address(isolate); __ li(a2, Operand(debug_step_in_fp)); __ lw(a2, MemOperand(a2)); __ Branch(&rt_call, ne, a2, Operand(zero_reg)); #endif // Load the initial map and verify that it is in fact a map. // a1: constructor function __ lw(a2, FieldMemOperand(a1, JSFunction::kPrototypeOrInitialMapOffset)); __ JumpIfSmi(a2, &rt_call); __ GetObjectType(a2, a3, t4); __ Branch(&rt_call, ne, t4, Operand(MAP_TYPE)); // Check that the constructor is not constructing a JSFunction (see // comments in Runtime_NewObject in runtime.cc). In which case the // initial map's instance type would be JS_FUNCTION_TYPE. // a1: constructor function // a2: initial map __ lbu(a3, FieldMemOperand(a2, Map::kInstanceTypeOffset)); __ Branch(&rt_call, eq, a3, Operand(JS_FUNCTION_TYPE)); if (count_constructions) { Label allocate; // Decrease generous allocation count. __ lw(a3, FieldMemOperand(a1, JSFunction::kSharedFunctionInfoOffset)); MemOperand constructor_count = FieldMemOperand(a3, SharedFunctionInfo::kConstructionCountOffset); __ lbu(t0, constructor_count); __ Subu(t0, t0, Operand(1)); __ sb(t0, constructor_count); __ Branch(&allocate, ne, t0, Operand(zero_reg)); __ Push(a1, a2); __ push(a1); // Constructor. // The call will replace the stub, so the countdown is only done once. __ CallRuntime(Runtime::kFinalizeInstanceSize, 1); __ pop(a2); __ pop(a1); __ bind(&allocate); } // Now allocate the JSObject on the heap. // a1: constructor function // a2: initial map __ lbu(a3, FieldMemOperand(a2, Map::kInstanceSizeOffset)); __ AllocateInNewSpace(a3, t4, t5, t6, &rt_call, SIZE_IN_WORDS); // Allocated the JSObject, now initialize the fields. Map is set to // initial map and properties and elements are set to empty fixed array. // a1: constructor function // a2: initial map // a3: object size // t4: JSObject (not tagged) __ LoadRoot(t6, Heap::kEmptyFixedArrayRootIndex); __ mov(t5, t4); __ sw(a2, MemOperand(t5, JSObject::kMapOffset)); __ sw(t6, MemOperand(t5, JSObject::kPropertiesOffset)); __ sw(t6, MemOperand(t5, JSObject::kElementsOffset)); __ Addu(t5, t5, Operand(3*kPointerSize)); ASSERT_EQ(0 * kPointerSize, JSObject::kMapOffset); ASSERT_EQ(1 * kPointerSize, JSObject::kPropertiesOffset); ASSERT_EQ(2 * kPointerSize, JSObject::kElementsOffset); // Fill all the in-object properties with appropriate filler. // a1: constructor function // a2: initial map // a3: object size (in words) // t4: JSObject (not tagged) // t5: First in-object property of JSObject (not tagged) __ sll(t0, a3, kPointerSizeLog2); __ addu(t6, t4, t0); // End of object. ASSERT_EQ(3 * kPointerSize, JSObject::kHeaderSize); __ LoadRoot(t7, Heap::kUndefinedValueRootIndex); if (count_constructions) { __ lw(a0, FieldMemOperand(a2, Map::kInstanceSizesOffset)); __ Ext(a0, a0, Map::kPreAllocatedPropertyFieldsByte * kBitsPerByte, kBitsPerByte); __ sll(t0, a0, kPointerSizeLog2); __ addu(a0, t5, t0); // a0: offset of first field after pre-allocated fields if (FLAG_debug_code) { __ Assert(le, "Unexpected number of pre-allocated property fields.", a0, Operand(t6)); } __ InitializeFieldsWithFiller(t5, a0, t7); // To allow for truncation. __ LoadRoot(t7, Heap::kOnePointerFillerMapRootIndex); } __ InitializeFieldsWithFiller(t5, t6, t7); // Add the object tag to make the JSObject real, so that we can continue // and jump into the continuation code at any time from now on. Any // failures need to undo the allocation, so that the heap is in a // consistent state and verifiable. __ Addu(t4, t4, Operand(kHeapObjectTag)); // Check if a non-empty properties array is needed. Continue with // allocated object if not fall through to runtime call if it is. // a1: constructor function // t4: JSObject // t5: start of next object (not tagged) __ lbu(a3, FieldMemOperand(a2, Map::kUnusedPropertyFieldsOffset)); // The field instance sizes contains both pre-allocated property fields // and in-object properties. __ lw(a0, FieldMemOperand(a2, Map::kInstanceSizesOffset)); __ Ext(t6, a0, Map::kPreAllocatedPropertyFieldsByte * kBitsPerByte, kBitsPerByte); __ Addu(a3, a3, Operand(t6)); __ Ext(t6, a0, Map::kInObjectPropertiesByte * kBitsPerByte, kBitsPerByte); __ subu(a3, a3, t6); // Done if no extra properties are to be allocated. __ Branch(&allocated, eq, a3, Operand(zero_reg)); __ Assert(greater_equal, "Property allocation count failed.", a3, Operand(zero_reg)); // Scale the number of elements by pointer size and add the header for // FixedArrays to the start of the next object calculation from above. // a1: constructor // a3: number of elements in properties array // t4: JSObject // t5: start of next object __ Addu(a0, a3, Operand(FixedArray::kHeaderSize / kPointerSize)); __ AllocateInNewSpace( a0, t5, t6, a2, &undo_allocation, static_cast<AllocationFlags>(RESULT_CONTAINS_TOP | SIZE_IN_WORDS)); // Initialize the FixedArray. // a1: constructor // a3: number of elements in properties array (un-tagged) // t4: JSObject // t5: start of next object __ LoadRoot(t6, Heap::kFixedArrayMapRootIndex); __ mov(a2, t5); __ sw(t6, MemOperand(a2, JSObject::kMapOffset)); __ sll(a0, a3, kSmiTagSize); __ sw(a0, MemOperand(a2, FixedArray::kLengthOffset)); __ Addu(a2, a2, Operand(2 * kPointerSize)); ASSERT_EQ(0 * kPointerSize, JSObject::kMapOffset); ASSERT_EQ(1 * kPointerSize, FixedArray::kLengthOffset); // Initialize the fields to undefined. // a1: constructor // a2: First element of FixedArray (not tagged) // a3: number of elements in properties array // t4: JSObject // t5: FixedArray (not tagged) __ sll(t3, a3, kPointerSizeLog2); __ addu(t6, a2, t3); // End of object. ASSERT_EQ(2 * kPointerSize, FixedArray::kHeaderSize); { Label loop, entry; if (count_constructions) { __ LoadRoot(t7, Heap::kUndefinedValueRootIndex); } else if (FLAG_debug_code) { __ LoadRoot(t8, Heap::kUndefinedValueRootIndex); __ Assert(eq, "Undefined value not loaded.", t7, Operand(t8)); } __ jmp(&entry); __ bind(&loop); __ sw(t7, MemOperand(a2)); __ addiu(a2, a2, kPointerSize); __ bind(&entry); __ Branch(&loop, less, a2, Operand(t6)); } // Store the initialized FixedArray into the properties field of // the JSObject. // a1: constructor function // t4: JSObject // t5: FixedArray (not tagged) __ Addu(t5, t5, Operand(kHeapObjectTag)); // Add the heap tag. __ sw(t5, FieldMemOperand(t4, JSObject::kPropertiesOffset)); // Continue with JSObject being successfully allocated. // a1: constructor function // a4: JSObject __ jmp(&allocated); // Undo the setting of the new top so that the heap is verifiable. For // example, the map's unused properties potentially do not match the // allocated objects unused properties. // t4: JSObject (previous new top) __ bind(&undo_allocation); __ UndoAllocationInNewSpace(t4, t5); } __ bind(&rt_call); // Allocate the new receiver object using the runtime call. // a1: constructor function __ push(a1); // Argument for Runtime_NewObject. __ CallRuntime(Runtime::kNewObject, 1); __ mov(t4, v0); // Receiver for constructor call allocated. // t4: JSObject __ bind(&allocated); __ push(t4); // Push the function and the allocated receiver from the stack. // sp[0]: receiver (newly allocated object) // sp[1]: constructor function // sp[2]: number of arguments (smi-tagged) __ lw(a1, MemOperand(sp, kPointerSize)); __ MultiPushReversed(a1.bit() | t4.bit()); // Reload the number of arguments from the stack. // a1: constructor function // sp[0]: receiver // sp[1]: constructor function // sp[2]: receiver // sp[3]: constructor function // sp[4]: number of arguments (smi-tagged) __ lw(a3, MemOperand(sp, 4 * kPointerSize)); // Setup pointer to last argument. __ Addu(a2, fp, Operand(StandardFrameConstants::kCallerSPOffset)); // Setup number of arguments for function call below. __ srl(a0, a3, kSmiTagSize); // Copy arguments and receiver to the expression stack. // a0: number of arguments // a1: constructor function // a2: address of last argument (caller sp) // a3: number of arguments (smi-tagged) // sp[0]: receiver // sp[1]: constructor function // sp[2]: receiver // sp[3]: constructor function // sp[4]: number of arguments (smi-tagged) Label loop, entry; __ jmp(&entry); __ bind(&loop); __ sll(t0, a3, kPointerSizeLog2 - kSmiTagSize); __ Addu(t0, a2, Operand(t0)); __ lw(t1, MemOperand(t0)); __ push(t1); __ bind(&entry); __ Addu(a3, a3, Operand(-2)); __ Branch(&loop, greater_equal, a3, Operand(zero_reg)); // Call the function. // a0: number of arguments // a1: constructor function if (is_api_function) { __ lw(cp, FieldMemOperand(a1, JSFunction::kContextOffset)); Handle<Code> code = masm->isolate()->builtins()->HandleApiCallConstruct(); ParameterCount expected(0); __ InvokeCode(code, expected, expected, RelocInfo::CODE_TARGET, CALL_FUNCTION, CALL_AS_METHOD); } else { ParameterCount actual(a0); __ InvokeFunction(a1, actual, CALL_FUNCTION, NullCallWrapper(), CALL_AS_METHOD); } // Pop the function from the stack. // v0: result // sp[0]: constructor function // sp[2]: receiver // sp[3]: constructor function // sp[4]: number of arguments (smi-tagged) __ Pop(); // Restore context from the frame. __ lw(cp, MemOperand(fp, StandardFrameConstants::kContextOffset)); // If the result is an object (in the ECMA sense), we should get rid // of the receiver and use the result; see ECMA-262 section 13.2.2-7 // on page 74. Label use_receiver, exit; // If the result is a smi, it is *not* an object in the ECMA sense. // v0: result // sp[0]: receiver (newly allocated object) // sp[1]: constructor function // sp[2]: number of arguments (smi-tagged) __ JumpIfSmi(v0, &use_receiver); // If the type of the result (stored in its map) is less than // FIRST_SPEC_OBJECT_TYPE, it is not an object in the ECMA sense. __ GetObjectType(v0, a3, a3); __ Branch(&exit, greater_equal, a3, Operand(FIRST_SPEC_OBJECT_TYPE)); // Throw away the result of the constructor invocation and use the // on-stack receiver as the result. __ bind(&use_receiver); __ lw(v0, MemOperand(sp)); // Remove receiver from the stack, remove caller arguments, and // return. __ bind(&exit); // v0: result // sp[0]: receiver (newly allocated object) // sp[1]: constructor function // sp[2]: number of arguments (smi-tagged) __ lw(a1, MemOperand(sp, 2 * kPointerSize)); // Leave construct frame. } __ sll(t0, a1, kPointerSizeLog2 - 1); __ Addu(sp, sp, t0); __ Addu(sp, sp, kPointerSize); __ IncrementCounter(isolate->counters()->constructed_objects(), 1, a1, a2); __ Ret(); } void Builtins::Generate_JSConstructStubCountdown(MacroAssembler* masm) { Generate_JSConstructStubHelper(masm, false, true); } void Builtins::Generate_JSConstructStubGeneric(MacroAssembler* masm) { Generate_JSConstructStubHelper(masm, false, false); } void Builtins::Generate_JSConstructStubApi(MacroAssembler* masm) { Generate_JSConstructStubHelper(masm, true, false); } static void Generate_JSEntryTrampolineHelper(MacroAssembler* masm, bool is_construct) { // Called from JSEntryStub::GenerateBody // ----------- S t a t e ------------- // -- a0: code entry // -- a1: function // -- a2: reveiver_pointer // -- a3: argc // -- s0: argv // ----------------------------------- // Clear the context before we push it when entering the JS frame. __ mov(cp, zero_reg); // Enter an internal frame. { FrameScope scope(masm, StackFrame::INTERNAL); // Set up the context from the function argument. __ lw(cp, FieldMemOperand(a1, JSFunction::kContextOffset)); // Set up the roots register. ExternalReference roots_array_start = ExternalReference::roots_array_start(masm->isolate()); __ li(s6, Operand(roots_array_start)); // Push the function and the receiver onto the stack. __ Push(a1, a2); // Copy arguments to the stack in a loop. // a3: argc // s0: argv, ie points to first arg Label loop, entry; __ sll(t0, a3, kPointerSizeLog2); __ addu(t2, s0, t0); __ b(&entry); __ nop(); // Branch delay slot nop. // t2 points past last arg. __ bind(&loop); __ lw(t0, MemOperand(s0)); // Read next parameter. __ addiu(s0, s0, kPointerSize); __ lw(t0, MemOperand(t0)); // Dereference handle. __ push(t0); // Push parameter. __ bind(&entry); __ Branch(&loop, ne, s0, Operand(t2)); // Initialize all JavaScript callee-saved registers, since they will be seen // by the garbage collector as part of handlers. __ LoadRoot(t0, Heap::kUndefinedValueRootIndex); __ mov(s1, t0); __ mov(s2, t0); __ mov(s3, t0); __ mov(s4, t0); __ mov(s5, t0); // s6 holds the root address. Do not clobber. // s7 is cp. Do not init. // Invoke the code and pass argc as a0. __ mov(a0, a3); if (is_construct) { __ Call(masm->isolate()->builtins()->JSConstructCall()); } else { ParameterCount actual(a0); __ InvokeFunction(a1, actual, CALL_FUNCTION, NullCallWrapper(), CALL_AS_METHOD); } // Leave internal frame. } __ Jump(ra); } void Builtins::Generate_JSEntryTrampoline(MacroAssembler* masm) { Generate_JSEntryTrampolineHelper(masm, false); } void Builtins::Generate_JSConstructEntryTrampoline(MacroAssembler* masm) { Generate_JSEntryTrampolineHelper(masm, true); } void Builtins::Generate_LazyCompile(MacroAssembler* masm) { // Enter an internal frame. { FrameScope scope(masm, StackFrame::INTERNAL); // Preserve the function. __ push(a1); // Push call kind information. __ push(t1); // Push the function on the stack as the argument to the runtime function. __ push(a1); // Call the runtime function. __ CallRuntime(Runtime::kLazyCompile, 1); // Calculate the entry point. __ addiu(t9, v0, Code::kHeaderSize - kHeapObjectTag); // Restore call kind information. __ pop(t1); // Restore saved function. __ pop(a1); // Tear down temporary frame. } // Do a tail-call of the compiled function. __ Jump(t9); } void Builtins::Generate_LazyRecompile(MacroAssembler* masm) { // Enter an internal frame. { FrameScope scope(masm, StackFrame::INTERNAL); // Preserve the function. __ push(a1); // Push call kind information. __ push(t1); // Push the function on the stack as the argument to the runtime function. __ push(a1); __ CallRuntime(Runtime::kLazyRecompile, 1); // Calculate the entry point. __ Addu(t9, v0, Operand(Code::kHeaderSize - kHeapObjectTag)); // Restore call kind information. __ pop(t1); // Restore saved function. __ pop(a1); // Tear down temporary frame. } // Do a tail-call of the compiled function. __ Jump(t9); } static void Generate_NotifyDeoptimizedHelper(MacroAssembler* masm, Deoptimizer::BailoutType type) { { FrameScope scope(masm, StackFrame::INTERNAL); // Pass the function and deoptimization type to the runtime system. __ li(a0, Operand(Smi::FromInt(static_cast<int>(type)))); __ push(a0); __ CallRuntime(Runtime::kNotifyDeoptimized, 1); } // Get the full codegen state from the stack and untag it -> t2. __ lw(t2, MemOperand(sp, 0 * kPointerSize)); __ SmiUntag(t2); // Switch on the state. Label with_tos_register, unknown_state; __ Branch(&with_tos_register, ne, t2, Operand(FullCodeGenerator::NO_REGISTERS)); __ Addu(sp, sp, Operand(1 * kPointerSize)); // Remove state. __ Ret(); __ bind(&with_tos_register); __ lw(v0, MemOperand(sp, 1 * kPointerSize)); __ Branch(&unknown_state, ne, t2, Operand(FullCodeGenerator::TOS_REG)); __ Addu(sp, sp, Operand(2 * kPointerSize)); // Remove state. __ Ret(); __ bind(&unknown_state); __ stop("no cases left"); } void Builtins::Generate_NotifyDeoptimized(MacroAssembler* masm) { Generate_NotifyDeoptimizedHelper(masm, Deoptimizer::EAGER); } void Builtins::Generate_NotifyLazyDeoptimized(MacroAssembler* masm) { Generate_NotifyDeoptimizedHelper(masm, Deoptimizer::LAZY); } void Builtins::Generate_NotifyOSR(MacroAssembler* masm) { // For now, we are relying on the fact that Runtime::NotifyOSR // doesn't do any garbage collection which allows us to save/restore // the registers without worrying about which of them contain // pointers. This seems a bit fragile. RegList saved_regs = (kJSCallerSaved | kCalleeSaved | ra.bit() | fp.bit()) & ~sp.bit(); __ MultiPush(saved_regs); { FrameScope scope(masm, StackFrame::INTERNAL); __ CallRuntime(Runtime::kNotifyOSR, 0); } __ MultiPop(saved_regs); __ Ret(); } void Builtins::Generate_OnStackReplacement(MacroAssembler* masm) { CpuFeatures::TryForceFeatureScope scope(VFP3); if (!CpuFeatures::IsSupported(FPU)) { __ Abort("Unreachable code: Cannot optimize without FPU support."); return; } // Lookup the function in the JavaScript frame and push it as an // argument to the on-stack replacement function. __ lw(a0, MemOperand(fp, JavaScriptFrameConstants::kFunctionOffset)); { FrameScope scope(masm, StackFrame::INTERNAL); __ push(a0); __ CallRuntime(Runtime::kCompileForOnStackReplacement, 1); } // If the result was -1 it means that we couldn't optimize the // function. Just return and continue in the unoptimized version. __ Ret(eq, v0, Operand(Smi::FromInt(-1))); // Untag the AST id and push it on the stack. __ SmiUntag(v0); __ push(v0); // Generate the code for doing the frame-to-frame translation using // the deoptimizer infrastructure. Deoptimizer::EntryGenerator generator(masm, Deoptimizer::OSR); generator.Generate(); } void Builtins::Generate_FunctionCall(MacroAssembler* masm) { // 1. Make sure we have at least one argument. // a0: actual number of arguments { Label done; __ Branch(&done, ne, a0, Operand(zero_reg)); __ LoadRoot(t2, Heap::kUndefinedValueRootIndex); __ push(t2); __ Addu(a0, a0, Operand(1)); __ bind(&done); } // 2. Get the function to call (passed as receiver) from the stack, check // if it is a function. // a0: actual number of arguments Label slow, non_function; __ sll(at, a0, kPointerSizeLog2); __ addu(at, sp, at); __ lw(a1, MemOperand(at)); __ JumpIfSmi(a1, &non_function); __ GetObjectType(a1, a2, a2); __ Branch(&slow, ne, a2, Operand(JS_FUNCTION_TYPE)); // 3a. Patch the first argument if necessary when calling a function. // a0: actual number of arguments // a1: function Label shift_arguments; __ li(t0, Operand(0, RelocInfo::NONE)); // Indicate regular JS_FUNCTION. { Label convert_to_object, use_global_receiver, patch_receiver; // Change context eagerly in case we need the global receiver. __ lw(cp, FieldMemOperand(a1, JSFunction::kContextOffset)); // Do not transform the receiver for strict mode functions. __ lw(a2, FieldMemOperand(a1, JSFunction::kSharedFunctionInfoOffset)); __ lw(a3, FieldMemOperand(a2, SharedFunctionInfo::kCompilerHintsOffset)); __ And(t3, a3, Operand(1 << (SharedFunctionInfo::kStrictModeFunction + kSmiTagSize))); __ Branch(&shift_arguments, ne, t3, Operand(zero_reg)); // Do not transform the receiver for native (Compilerhints already in a3). __ And(t3, a3, Operand(1 << (SharedFunctionInfo::kNative + kSmiTagSize))); __ Branch(&shift_arguments, ne, t3, Operand(zero_reg)); // Compute the receiver in non-strict mode. // Load first argument in a2. a2 = -kPointerSize(sp + n_args << 2). __ sll(at, a0, kPointerSizeLog2); __ addu(a2, sp, at); __ lw(a2, MemOperand(a2, -kPointerSize)); // a0: actual number of arguments // a1: function // a2: first argument __ JumpIfSmi(a2, &convert_to_object, t2); __ LoadRoot(a3, Heap::kUndefinedValueRootIndex); __ Branch(&use_global_receiver, eq, a2, Operand(a3)); __ LoadRoot(a3, Heap::kNullValueRootIndex); __ Branch(&use_global_receiver, eq, a2, Operand(a3)); STATIC_ASSERT(LAST_SPEC_OBJECT_TYPE == LAST_TYPE); __ GetObjectType(a2, a3, a3); __ Branch(&shift_arguments, ge, a3, Operand(FIRST_SPEC_OBJECT_TYPE)); __ bind(&convert_to_object); // Enter an internal frame in order to preserve argument count. { FrameScope scope(masm, StackFrame::INTERNAL); __ sll(a0, a0, kSmiTagSize); // Smi tagged. __ push(a0); __ push(a2); __ InvokeBuiltin(Builtins::TO_OBJECT, CALL_FUNCTION); __ mov(a2, v0); __ pop(a0); __ sra(a0, a0, kSmiTagSize); // Un-tag. // Leave internal frame. } // Restore the function to a1, and the flag to t0. __ sll(at, a0, kPointerSizeLog2); __ addu(at, sp, at); __ lw(a1, MemOperand(at)); __ li(t0, Operand(0, RelocInfo::NONE)); __ Branch(&patch_receiver); // Use the global receiver object from the called function as the // receiver. __ bind(&use_global_receiver); const int kGlobalIndex = Context::kHeaderSize + Context::GLOBAL_INDEX * kPointerSize; __ lw(a2, FieldMemOperand(cp, kGlobalIndex)); __ lw(a2, FieldMemOperand(a2, GlobalObject::kGlobalContextOffset)); __ lw(a2, FieldMemOperand(a2, kGlobalIndex)); __ lw(a2, FieldMemOperand(a2, GlobalObject::kGlobalReceiverOffset)); __ bind(&patch_receiver); __ sll(at, a0, kPointerSizeLog2); __ addu(a3, sp, at); __ sw(a2, MemOperand(a3, -kPointerSize)); __ Branch(&shift_arguments); } // 3b. Check for function proxy. __ bind(&slow); __ li(t0, Operand(1, RelocInfo::NONE)); // Indicate function proxy. __ Branch(&shift_arguments, eq, a2, Operand(JS_FUNCTION_PROXY_TYPE)); __ bind(&non_function); __ li(t0, Operand(2, RelocInfo::NONE)); // Indicate non-function. // 3c. Patch the first argument when calling a non-function. The // CALL_NON_FUNCTION builtin expects the non-function callee as // receiver, so overwrite the first argument which will ultimately // become the receiver. // a0: actual number of arguments // a1: function // t0: call type (0: JS function, 1: function proxy, 2: non-function) __ sll(at, a0, kPointerSizeLog2); __ addu(a2, sp, at); __ sw(a1, MemOperand(a2, -kPointerSize)); // 4. Shift arguments and return address one slot down on the stack // (overwriting the original receiver). Adjust argument count to make // the original first argument the new receiver. // a0: actual number of arguments // a1: function // t0: call type (0: JS function, 1: function proxy, 2: non-function) __ bind(&shift_arguments); { Label loop; // Calculate the copy start address (destination). Copy end address is sp. __ sll(at, a0, kPointerSizeLog2); __ addu(a2, sp, at); __ bind(&loop); __ lw(at, MemOperand(a2, -kPointerSize)); __ sw(at, MemOperand(a2)); __ Subu(a2, a2, Operand(kPointerSize)); __ Branch(&loop, ne, a2, Operand(sp)); // Adjust the actual number of arguments and remove the top element // (which is a copy of the last argument). __ Subu(a0, a0, Operand(1)); __ Pop(); } // 5a. Call non-function via tail call to CALL_NON_FUNCTION builtin, // or a function proxy via CALL_FUNCTION_PROXY. // a0: actual number of arguments // a1: function // t0: call type (0: JS function, 1: function proxy, 2: non-function) { Label function, non_proxy; __ Branch(&function, eq, t0, Operand(zero_reg)); // Expected number of arguments is 0 for CALL_NON_FUNCTION. __ mov(a2, zero_reg); __ SetCallKind(t1, CALL_AS_METHOD); __ Branch(&non_proxy, ne, t0, Operand(1)); __ push(a1); // Re-add proxy object as additional argument. __ Addu(a0, a0, Operand(1)); __ GetBuiltinEntry(a3, Builtins::CALL_FUNCTION_PROXY); __ Jump(masm->isolate()->builtins()->ArgumentsAdaptorTrampoline(), RelocInfo::CODE_TARGET); __ bind(&non_proxy); __ GetBuiltinEntry(a3, Builtins::CALL_NON_FUNCTION); __ Jump(masm->isolate()->builtins()->ArgumentsAdaptorTrampoline(), RelocInfo::CODE_TARGET); __ bind(&function); } // 5b. Get the code to call from the function and check that the number of // expected arguments matches what we're providing. If so, jump // (tail-call) to the code in register edx without checking arguments. // a0: actual number of arguments // a1: function __ lw(a3, FieldMemOperand(a1, JSFunction::kSharedFunctionInfoOffset)); __ lw(a2, FieldMemOperand(a3, SharedFunctionInfo::kFormalParameterCountOffset)); __ sra(a2, a2, kSmiTagSize); __ lw(a3, FieldMemOperand(a1, JSFunction::kCodeEntryOffset)); __ SetCallKind(t1, CALL_AS_METHOD); // Check formal and actual parameter counts. __ Jump(masm->isolate()->builtins()->ArgumentsAdaptorTrampoline(), RelocInfo::CODE_TARGET, ne, a2, Operand(a0)); ParameterCount expected(0); __ InvokeCode(a3, expected, expected, JUMP_FUNCTION, NullCallWrapper(), CALL_AS_METHOD); } void Builtins::Generate_FunctionApply(MacroAssembler* masm) { const int kIndexOffset = -5 * kPointerSize; const int kLimitOffset = -4 * kPointerSize; const int kArgsOffset = 2 * kPointerSize; const int kRecvOffset = 3 * kPointerSize; const int kFunctionOffset = 4 * kPointerSize; { FrameScope frame_scope(masm, StackFrame::INTERNAL); __ lw(a0, MemOperand(fp, kFunctionOffset)); // Get the function. __ push(a0); __ lw(a0, MemOperand(fp, kArgsOffset)); // Get the args array. __ push(a0); // Returns (in v0) number of arguments to copy to stack as Smi. __ InvokeBuiltin(Builtins::APPLY_PREPARE, CALL_FUNCTION); // Check the stack for overflow. We are not trying to catch // interruptions (e.g. debug break and preemption) here, so the "real stack // limit" is checked. Label okay; __ LoadRoot(a2, Heap::kRealStackLimitRootIndex); // Make a2 the space we have left. The stack might already be overflowed // here which will cause a2 to become negative. __ subu(a2, sp, a2); // Check if the arguments will overflow the stack. __ sll(t3, v0, kPointerSizeLog2 - kSmiTagSize); __ Branch(&okay, gt, a2, Operand(t3)); // Signed comparison. // Out of stack space. __ lw(a1, MemOperand(fp, kFunctionOffset)); __ push(a1); __ push(v0); __ InvokeBuiltin(Builtins::APPLY_OVERFLOW, CALL_FUNCTION); // End of stack check. // Push current limit and index. __ bind(&okay); __ push(v0); // Limit. __ mov(a1, zero_reg); // Initial index. __ push(a1); // Get the receiver. __ lw(a0, MemOperand(fp, kRecvOffset)); // Check that the function is a JS function (otherwise it must be a proxy). Label push_receiver; __ lw(a1, MemOperand(fp, kFunctionOffset)); __ GetObjectType(a1, a2, a2); __ Branch(&push_receiver, ne, a2, Operand(JS_FUNCTION_TYPE)); // Change context eagerly to get the right global object if necessary. __ lw(cp, FieldMemOperand(a1, JSFunction::kContextOffset)); // Load the shared function info while the function is still in a1. __ lw(a2, FieldMemOperand(a1, JSFunction::kSharedFunctionInfoOffset)); // Compute the receiver. // Do not transform the receiver for strict mode functions. Label call_to_object, use_global_receiver; __ lw(a2, FieldMemOperand(a2, SharedFunctionInfo::kCompilerHintsOffset)); __ And(t3, a2, Operand(1 << (SharedFunctionInfo::kStrictModeFunction + kSmiTagSize))); __ Branch(&push_receiver, ne, t3, Operand(zero_reg)); // Do not transform the receiver for native (Compilerhints already in a2). __ And(t3, a2, Operand(1 << (SharedFunctionInfo::kNative + kSmiTagSize))); __ Branch(&push_receiver, ne, t3, Operand(zero_reg)); // Compute the receiver in non-strict mode. __ JumpIfSmi(a0, &call_to_object); __ LoadRoot(a1, Heap::kNullValueRootIndex); __ Branch(&use_global_receiver, eq, a0, Operand(a1)); __ LoadRoot(a2, Heap::kUndefinedValueRootIndex); __ Branch(&use_global_receiver, eq, a0, Operand(a2)); // Check if the receiver is already a JavaScript object. // a0: receiver STATIC_ASSERT(LAST_SPEC_OBJECT_TYPE == LAST_TYPE); __ GetObjectType(a0, a1, a1); __ Branch(&push_receiver, ge, a1, Operand(FIRST_SPEC_OBJECT_TYPE)); // Convert the receiver to a regular object. // a0: receiver __ bind(&call_to_object); __ push(a0); __ InvokeBuiltin(Builtins::TO_OBJECT, CALL_FUNCTION); __ mov(a0, v0); // Put object in a0 to match other paths to push_receiver. __ Branch(&push_receiver); // Use the current global receiver object as the receiver. __ bind(&use_global_receiver); const int kGlobalOffset = Context::kHeaderSize + Context::GLOBAL_INDEX * kPointerSize; __ lw(a0, FieldMemOperand(cp, kGlobalOffset)); __ lw(a0, FieldMemOperand(a0, GlobalObject::kGlobalContextOffset)); __ lw(a0, FieldMemOperand(a0, kGlobalOffset)); __ lw(a0, FieldMemOperand(a0, GlobalObject::kGlobalReceiverOffset)); // Push the receiver. // a0: receiver __ bind(&push_receiver); __ push(a0); // Copy all arguments from the array to the stack. Label entry, loop; __ lw(a0, MemOperand(fp, kIndexOffset)); __ Branch(&entry); // Load the current argument from the arguments array and push it to the // stack. // a0: current argument index __ bind(&loop); __ lw(a1, MemOperand(fp, kArgsOffset)); __ push(a1); __ push(a0); // Call the runtime to access the property in the arguments array. __ CallRuntime(Runtime::kGetProperty, 2); __ push(v0); // Use inline caching to access the arguments. __ lw(a0, MemOperand(fp, kIndexOffset)); __ Addu(a0, a0, Operand(1 << kSmiTagSize)); __ sw(a0, MemOperand(fp, kIndexOffset)); // Test if the copy loop has finished copying all the elements from the // arguments object. __ bind(&entry); __ lw(a1, MemOperand(fp, kLimitOffset)); __ Branch(&loop, ne, a0, Operand(a1)); // Invoke the function. Label call_proxy; ParameterCount actual(a0); __ sra(a0, a0, kSmiTagSize); __ lw(a1, MemOperand(fp, kFunctionOffset)); __ GetObjectType(a1, a2, a2); __ Branch(&call_proxy, ne, a2, Operand(JS_FUNCTION_TYPE)); __ InvokeFunction(a1, actual, CALL_FUNCTION, NullCallWrapper(), CALL_AS_METHOD); frame_scope.GenerateLeaveFrame(); __ Ret(USE_DELAY_SLOT); __ Addu(sp, sp, Operand(3 * kPointerSize)); // In delay slot. // Invoke the function proxy. __ bind(&call_proxy); __ push(a1); // Add function proxy as last argument. __ Addu(a0, a0, Operand(1)); __ li(a2, Operand(0, RelocInfo::NONE)); __ SetCallKind(t1, CALL_AS_METHOD); __ GetBuiltinEntry(a3, Builtins::CALL_FUNCTION_PROXY); __ Call(masm->isolate()->builtins()->ArgumentsAdaptorTrampoline(), RelocInfo::CODE_TARGET); // Tear down the internal frame and remove function, receiver and args. } __ Ret(USE_DELAY_SLOT); __ Addu(sp, sp, Operand(3 * kPointerSize)); // In delay slot. } static void EnterArgumentsAdaptorFrame(MacroAssembler* masm) { __ sll(a0, a0, kSmiTagSize); __ li(t0, Operand(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR))); __ MultiPush(a0.bit() | a1.bit() | t0.bit() | fp.bit() | ra.bit()); __ Addu(fp, sp, Operand(3 * kPointerSize)); } static void LeaveArgumentsAdaptorFrame(MacroAssembler* masm) { // ----------- S t a t e ------------- // -- v0 : result being passed through // ----------------------------------- // Get the number of arguments passed (as a smi), tear down the frame and // then tear down the parameters. __ lw(a1, MemOperand(fp, -3 * kPointerSize)); __ mov(sp, fp); __ MultiPop(fp.bit() | ra.bit()); __ sll(t0, a1, kPointerSizeLog2 - kSmiTagSize); __ Addu(sp, sp, t0); // Adjust for the receiver. __ Addu(sp, sp, Operand(kPointerSize)); } void Builtins::Generate_ArgumentsAdaptorTrampoline(MacroAssembler* masm) { // State setup as expected by MacroAssembler::InvokePrologue. // ----------- S t a t e ------------- // -- a0: actual arguments count // -- a1: function (passed through to callee) // -- a2: expected arguments count // -- a3: callee code entry // -- t1: call kind information // ----------------------------------- Label invoke, dont_adapt_arguments; Label enough, too_few; __ Branch(&dont_adapt_arguments, eq, a2, Operand(SharedFunctionInfo::kDontAdaptArgumentsSentinel)); // We use Uless as the number of argument should always be greater than 0. __ Branch(&too_few, Uless, a0, Operand(a2)); { // Enough parameters: actual >= expected. // a0: actual number of arguments as a smi // a1: function // a2: expected number of arguments // a3: code entry to call __ bind(&enough); EnterArgumentsAdaptorFrame(masm); // Calculate copy start address into a0 and copy end address into a2. __ sll(a0, a0, kPointerSizeLog2 - kSmiTagSize); __ Addu(a0, fp, a0); // Adjust for return address and receiver. __ Addu(a0, a0, Operand(2 * kPointerSize)); // Compute copy end address. __ sll(a2, a2, kPointerSizeLog2); __ subu(a2, a0, a2); // Copy the arguments (including the receiver) to the new stack frame. // a0: copy start address // a1: function // a2: copy end address // a3: code entry to call Label copy; __ bind(&copy); __ lw(t0, MemOperand(a0)); __ push(t0); __ Branch(USE_DELAY_SLOT, &copy, ne, a0, Operand(a2)); __ addiu(a0, a0, -kPointerSize); // In delay slot. __ jmp(&invoke); } { // Too few parameters: Actual < expected. __ bind(&too_few); EnterArgumentsAdaptorFrame(masm); // TODO(MIPS): Optimize these loops. // Calculate copy start address into a0 and copy end address is fp. // a0: actual number of arguments as a smi // a1: function // a2: expected number of arguments // a3: code entry to call __ sll(a0, a0, kPointerSizeLog2 - kSmiTagSize); __ Addu(a0, fp, a0); // Adjust for return address and receiver. __ Addu(a0, a0, Operand(2 * kPointerSize)); // Compute copy end address. Also adjust for return address. __ Addu(t3, fp, kPointerSize); // Copy the arguments (including the receiver) to the new stack frame. // a0: copy start address // a1: function // a2: expected number of arguments // a3: code entry to call // t3: copy end address Label copy; __ bind(&copy); __ lw(t0, MemOperand(a0)); // Adjusted above for return addr and receiver. __ push(t0); __ Subu(a0, a0, kPointerSize); __ Branch(&copy, ne, a0, Operand(t3)); // Fill the remaining expected arguments with undefined. // a1: function // a2: expected number of arguments // a3: code entry to call __ LoadRoot(t0, Heap::kUndefinedValueRootIndex); __ sll(t2, a2, kPointerSizeLog2); __ Subu(a2, fp, Operand(t2)); __ Addu(a2, a2, Operand(-4 * kPointerSize)); // Adjust for frame. Label fill; __ bind(&fill); __ push(t0); __ Branch(&fill, ne, sp, Operand(a2)); } // Call the entry point. __ bind(&invoke); __ Call(a3); // Exit frame and return. LeaveArgumentsAdaptorFrame(masm); __ Ret(); // ------------------------------------------- // Don't adapt arguments. // ------------------------------------------- __ bind(&dont_adapt_arguments); __ Jump(a3); } #undef __ } } // namespace v8::internal #endif // V8_TARGET_ARCH_MIPS
/* * Copyright (C) 2006 Tommi Maekitalo * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * As a special exception, you may use this file as part of a free * software library without restriction. Specifically, if other files * instantiate templates or use macros or inline functions from this * file, or you compile this file and link it with other files to * produce an executable, this file does not by itself cause the * resulting executable to be covered by the GNU General Public * License. This exception does not however invalidate any other * reasons why the executable file might be covered by the GNU Library * General Public License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "tnt/process.h" #include "tnt/tntconfig.h" #include <cxxtools/systemerror.h> #include <cxxtools/posix/fork.h> #include <pwd.h> #include <grp.h> #include <cxxtools/log.h> #include <vector> #include <fstream> #include <errno.h> #include <signal.h> log_define("tntnet.process") namespace { tnt::Process* theProcess = 0; void sigEnd(int) { signal(SIGTERM, sigEnd); if (theProcess) theProcess->shutdown(); } void sigReload(int) { signal(SIGHUP, sigReload); if (theProcess) theProcess->restart(); } void setGroup(const std::string& group) { struct group * gr = ::getgrnam(group.c_str()); if (gr == 0) throw std::runtime_error("unknown group " + group); log_debug("change group to " << group << '(' << gr->gr_gid << ')'); int ret = ::setgid(gr->gr_gid); if (ret != 0) throw cxxtools::SystemError("setgid"); } void setUser(const std::string& user) { struct passwd * pw = getpwnam(user.c_str()); if (pw == 0) throw std::runtime_error("unknown user " + user); log_debug("change user to " << user << '(' << pw->pw_uid << ')'); int ret = ::setuid(pw->pw_uid); if (ret != 0) throw cxxtools::SystemError("getuid"); } void setDir(const std::string& dir) { log_debug("chdir(" << dir << ')'); if (::chdir(dir.c_str()) == -1) throw cxxtools::SystemError("chdir"); } void setRootdir(const std::string& dir) { if (!::chroot(dir.c_str()) == -1) throw cxxtools::SystemError("chroot"); } class PidFile { std::string pidFileName; public: PidFile(const std::string& pidFileName, pid_t pid); ~PidFile(); void releasePidFile() { pidFileName.clear(); } }; PidFile::PidFile(const std::string& pidFileName_, pid_t pid) : pidFileName(pidFileName_) { if (pidFileName.empty()) return; if (pidFileName[0] != '/') { // prepend current working-directory to pidfilename if not absolute std::vector<char> buf(256); const char* cwd; while (true) { cwd = ::getcwd(&buf[0], buf.size()); if (cwd) break; else if (errno == ERANGE) buf.resize(buf.size() * 2); else throw cxxtools::SystemError("getcwd"); } pidFileName = std::string(cwd) + '/' + pidFileName; log_debug("pidfile=" << pidFileName); } std::ofstream pidfile(pidFileName.c_str()); if (pidfile.fail()) throw std::runtime_error("unable to open pid-file " + pidFileName); pidfile << pid; if (pidfile.fail()) throw std::runtime_error("error writing to pid-file " + pidFileName); } PidFile::~PidFile() { if (!pidFileName.empty()) ::unlink(pidFileName.c_str()); } void closeStdHandles(const std::string& errorLog = std::string()) { if (::freopen("/dev/null", "r", stdin) == 0) throw cxxtools::SystemError("freopen(stdin)"); if (::freopen("/dev/null", "w", stdout) == 0) throw cxxtools::SystemError("freopen(stdout)"); if (!errorLog.empty()) { if (::freopen(errorLog.c_str(), "a+", stderr) == 0) throw cxxtools::SystemError("freopen(stderr)"); } } } namespace tnt { Process::Process() { theProcess = this; } Process::~Process() { if (theProcess == this) theProcess = 0; } void Process::runMonitor(cxxtools::posix::Pipe& mainPipe) { log_debug("run monitor"); // setsid if (setsid() == -1) throw cxxtools::SystemError("setsid"); bool first = true; while (true) { cxxtools::posix::Pipe monitorPipe; cxxtools::posix::Fork fork; if (fork.child()) { // worker-process log_debug("close read-fd of monitor-pipe"); monitorPipe.closeReadFd(); initWorker(); if (first) { log_debug("signal initialization ready"); mainPipe.write('1'); log_debug("close write-fd of main-pipe"); mainPipe.closeWriteFd(); } log_debug("close standard-handles"); closeStdHandles(tnt::TntConfig::it().errorLog); exitRestart = false; log_debug("do work"); doWork(); // normal shutdown if (exitRestart) log_debug("restart"); else { log_debug("signal shutdown"); monitorPipe.write('s'); } return; } // monitor-process log_debug("write pid " << fork.getPid() << " to \"" << tnt::TntConfig::it().pidfile << '"'); PidFile p(tnt::TntConfig::it().pidfile, fork.getPid()); if (first) { log_debug("close standard-handles"); closeStdHandles(); first = false; } monitorPipe.closeWriteFd(); try { log_debug("monitor child"); char dummy; size_t c = monitorPipe.read(&dummy, 1); if (c > 0) { log_debug("child terminated normally"); return; } log_debug("nothing read from monitor-pipe - restart child"); } catch (const cxxtools::SystemError&) { log_debug("child exited without notification"); } log_debug("wait for child-termination"); fork.wait(); ::sleep(1); } } void Process::initWorker() { log_debug("init worker"); log_debug("onInit"); onInit(); if (!tnt::TntConfig::it().group.empty()) { log_debug("set group to \"" << tnt::TntConfig::it().group << '"'); ::setGroup(tnt::TntConfig::it().group); } if (!tnt::TntConfig::it().user.empty()) { log_debug("set user to \"" << tnt::TntConfig::it().user << '"'); ::setUser(tnt::TntConfig::it().user); } if (!tnt::TntConfig::it().dir.empty()) { log_debug("set dir to \"" << tnt::TntConfig::it().dir << '"'); ::setDir(tnt::TntConfig::it().dir); } if (!tnt::TntConfig::it().chrootdir.empty()) { log_debug("change root to \"" << tnt::TntConfig::it().chrootdir << '"'); ::setRootdir(tnt::TntConfig::it().chrootdir); } signal(SIGTERM, sigEnd); signal(SIGINT, sigEnd); signal(SIGHUP, sigReload); } void Process::run() { if (tnt::TntConfig::it().daemon) { log_debug("run daemon-mode"); // We receive the writing-end of the notify pipe. // After successful initialization we need to write a byte to this fd. cxxtools::posix::Pipe mainPipe; cxxtools::posix::Fork fork; if (fork.parent()) { log_debug("close write-fd of main-pipe"); mainPipe.closeWriteFd(); log_debug("wait for child to initialize"); mainPipe.read(); log_debug("child initialized"); fork.setNowait(); } else { log_debug("close read-fd of main-pipe"); mainPipe.closeReadFd(); runMonitor(mainPipe); } } else { log_debug("run"); initWorker(); log_debug("do work"); doWork(); } } void Process::shutdown() { doShutdown(); } void Process::restart() { exitRestart = true; doShutdown(); } } ignore exception message "lost connection to peer" when killing the monitor process before the worker process in daemon mode git-svn-id: cc913a7f7b4e3b8bac01cff72f0fc87362e4d502@1418 8dd45c8f-be11-0410-86c3-e0da43b70fc1 /* * Copyright (C) 2006 Tommi Maekitalo * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * As a special exception, you may use this file as part of a free * software library without restriction. Specifically, if other files * instantiate templates or use macros or inline functions from this * file, or you compile this file and link it with other files to * produce an executable, this file does not by itself cause the * resulting executable to be covered by the GNU General Public * License. This exception does not however invalidate any other * reasons why the executable file might be covered by the GNU Library * General Public License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "tnt/process.h" #include "tnt/tntconfig.h" #include <cxxtools/systemerror.h> #include <cxxtools/posix/fork.h> #include <pwd.h> #include <grp.h> #include <cxxtools/log.h> #include <vector> #include <fstream> #include <errno.h> #include <signal.h> log_define("tntnet.process") namespace { tnt::Process* theProcess = 0; void sigEnd(int) { signal(SIGTERM, sigEnd); if (theProcess) theProcess->shutdown(); } void sigReload(int) { signal(SIGHUP, sigReload); if (theProcess) theProcess->restart(); } void setGroup(const std::string& group) { struct group * gr = ::getgrnam(group.c_str()); if (gr == 0) throw std::runtime_error("unknown group " + group); log_debug("change group to " << group << '(' << gr->gr_gid << ')'); int ret = ::setgid(gr->gr_gid); if (ret != 0) throw cxxtools::SystemError("setgid"); } void setUser(const std::string& user) { struct passwd * pw = getpwnam(user.c_str()); if (pw == 0) throw std::runtime_error("unknown user " + user); log_debug("change user to " << user << '(' << pw->pw_uid << ')'); int ret = ::setuid(pw->pw_uid); if (ret != 0) throw cxxtools::SystemError("getuid"); } void setDir(const std::string& dir) { log_debug("chdir(" << dir << ')'); if (::chdir(dir.c_str()) == -1) throw cxxtools::SystemError("chdir"); } void setRootdir(const std::string& dir) { if (!::chroot(dir.c_str()) == -1) throw cxxtools::SystemError("chroot"); } class PidFile { std::string pidFileName; public: PidFile(const std::string& pidFileName, pid_t pid); ~PidFile(); void releasePidFile() { pidFileName.clear(); } }; PidFile::PidFile(const std::string& pidFileName_, pid_t pid) : pidFileName(pidFileName_) { if (pidFileName.empty()) return; if (pidFileName[0] != '/') { // prepend current working-directory to pidfilename if not absolute std::vector<char> buf(256); const char* cwd; while (true) { cwd = ::getcwd(&buf[0], buf.size()); if (cwd) break; else if (errno == ERANGE) buf.resize(buf.size() * 2); else throw cxxtools::SystemError("getcwd"); } pidFileName = std::string(cwd) + '/' + pidFileName; log_debug("pidfile=" << pidFileName); } std::ofstream pidfile(pidFileName.c_str()); if (pidfile.fail()) throw std::runtime_error("unable to open pid-file " + pidFileName); pidfile << pid; if (pidfile.fail()) throw std::runtime_error("error writing to pid-file " + pidFileName); } PidFile::~PidFile() { if (!pidFileName.empty()) ::unlink(pidFileName.c_str()); } void closeStdHandles(const std::string& errorLog = std::string()) { if (::freopen("/dev/null", "r", stdin) == 0) throw cxxtools::SystemError("freopen(stdin)"); if (::freopen("/dev/null", "w", stdout) == 0) throw cxxtools::SystemError("freopen(stdout)"); if (!errorLog.empty()) { if (::freopen(errorLog.c_str(), "a+", stderr) == 0) throw cxxtools::SystemError("freopen(stderr)"); } } } namespace tnt { Process::Process() { theProcess = this; } Process::~Process() { if (theProcess == this) theProcess = 0; } void Process::runMonitor(cxxtools::posix::Pipe& mainPipe) { log_debug("run monitor"); // setsid if (setsid() == -1) throw cxxtools::SystemError("setsid"); bool first = true; while (true) { cxxtools::posix::Pipe monitorPipe; cxxtools::posix::Fork fork; if (fork.child()) { // worker-process log_debug("close read-fd of monitor-pipe"); monitorPipe.closeReadFd(); initWorker(); if (first) { log_debug("signal initialization ready"); mainPipe.write('1'); log_debug("close write-fd of main-pipe"); mainPipe.closeWriteFd(); } log_debug("close standard-handles"); closeStdHandles(tnt::TntConfig::it().errorLog); exitRestart = false; log_debug("do work"); doWork(); // normal shutdown if (exitRestart) log_debug("restart"); else { log_debug("signal shutdown"); try { monitorPipe.write('s'); } catch (const std::exception& e) { log_debug("ingore exception from monitor pipe: " << e.what()); } } return; } // monitor-process log_debug("write pid " << fork.getPid() << " to \"" << tnt::TntConfig::it().pidfile << '"'); PidFile p(tnt::TntConfig::it().pidfile, fork.getPid()); if (first) { log_debug("close standard-handles"); closeStdHandles(); first = false; } monitorPipe.closeWriteFd(); try { log_debug("monitor child"); char dummy; size_t c = monitorPipe.read(&dummy, 1); if (c > 0) { log_debug("child terminated normally"); return; } log_debug("nothing read from monitor-pipe - restart child"); } catch (const cxxtools::SystemError&) { log_debug("child exited without notification"); } log_debug("wait for child-termination"); fork.wait(); ::sleep(1); } } void Process::initWorker() { log_debug("init worker"); log_debug("onInit"); onInit(); if (!tnt::TntConfig::it().group.empty()) { log_debug("set group to \"" << tnt::TntConfig::it().group << '"'); ::setGroup(tnt::TntConfig::it().group); } if (!tnt::TntConfig::it().user.empty()) { log_debug("set user to \"" << tnt::TntConfig::it().user << '"'); ::setUser(tnt::TntConfig::it().user); } if (!tnt::TntConfig::it().dir.empty()) { log_debug("set dir to \"" << tnt::TntConfig::it().dir << '"'); ::setDir(tnt::TntConfig::it().dir); } if (!tnt::TntConfig::it().chrootdir.empty()) { log_debug("change root to \"" << tnt::TntConfig::it().chrootdir << '"'); ::setRootdir(tnt::TntConfig::it().chrootdir); } signal(SIGTERM, sigEnd); signal(SIGINT, sigEnd); signal(SIGHUP, sigReload); } void Process::run() { if (tnt::TntConfig::it().daemon) { log_debug("run daemon-mode"); // We receive the writing-end of the notify pipe. // After successful initialization we need to write a byte to this fd. cxxtools::posix::Pipe mainPipe; cxxtools::posix::Fork fork; if (fork.parent()) { log_debug("close write-fd of main-pipe"); mainPipe.closeWriteFd(); log_debug("wait for child to initialize"); mainPipe.read(); log_debug("child initialized"); fork.setNowait(); } else { log_debug("close read-fd of main-pipe"); mainPipe.closeReadFd(); runMonitor(mainPipe); } } else { log_debug("run"); initWorker(); log_debug("do work"); doWork(); } } void Process::shutdown() { doShutdown(); } void Process::restart() { exitRestart = true; doShutdown(); } }
/*++ Copyright (c) 2012 Microsoft Corporation Module Name: fpa2bv_approx_tactic.cpp Abstract: Tactic that converts floating points to bit-vectors lazily Author: Aleksander Zeljic 2012-11-15 Notes: --*/ #include"tactical.h" #include"cooperate.h" #include"ref_util.h" #include"th_rewriter.h" #include"bit_blaster_rewriter.h" #include"bit_blaster_model_converter.h" #include"model_v2_pp.h" #include"goal2sat.h" #include"sat_solver.h" #include"fpa_decl_plugin.h" #include"fpa2bv_converter_prec.h" #include"fpa2bv_rewriter_prec.h" #include"fpa2bv_approx_tactic.h" #include"const_intro_rewriter.h" #include"ctx_simplify_tactic.h" #include"filter_model_converter.h" #include <list> #include <queue> #include <math.h> #include<iostream> #define K_MIN 10 #define K_PERCENTAGE 0.3 #define PREC_INCREMENT 20 #define ERR_OP 0 // struct pair { expr * exp; double quotient;// mpf * }; bool isinfinite(double x) { #ifdef _WIN32 int c = _fpclass(x); return c == _FPCLASS_PINF || c == _FPCLASS_NINF; #else return fpclassify(x) == FP_INFINITE; #endif } class fpa2bv_approx_tactic: public tactic { struct imp { ast_manager & m; goal2sat m_goal2sat; sat2goal m_sat2goal; params_ref m_params; unsigned m_num_steps; bool m_proofs_enabled; bool m_produce_models; bool m_produce_unsat_cores; bool m_cancel; fpa_approximation_mode m_mode; ast_manager * m_temp_manager; model_ref m_fpa_model; fpa_util m_float_util; imp(ast_manager & _m, params_ref const & p, fpa_approximation_mode mode) : m(_m), m_params(p), m_proofs_enabled(false), m_produce_models(false), m_produce_unsat_cores(false), m_cancel(false), m_mode(mode), m_temp_manager(0), m_float_util(_m) { } void updt_params(params_ref const & p) { m_params = p; } void set_cancel(bool f) { //If f is true stop everything m_cancel = f; } void init_precision_mapping(func_decl_ref_vector const & cnsts, obj_map<func_decl, unsigned> & map, obj_map<func_decl, app*> & const2term_map) { for (unsigned i = 0; i < cnsts.size(); i++) { if (const2term_map.contains(cnsts[i]) || m_mode == FPAA_SMALL_FLOATS) map.insert_if_not_there(cnsts.get(i), 0); else map.insert_if_not_there(cnsts.get(i), MAX_PRECISION); } } bool proof_guided_refinement( goal_ref const & g, func_decl_ref_vector const & cnsts, obj_map<func_decl, unsigned> & cnst2prec_map, obj_map<func_decl, unsigned> & new_map) { // We have no model. Let's just increase precision of everything. bool res = false; for (unsigned i = 0; i < cnsts.size(); i++) { unsigned old = cnst2prec_map.find(cnsts.get(i)); unsigned n = old + PREC_INCREMENT; if (old >= MAX_PRECISION) n = MAX_PRECISION; else { if (n > MAX_PRECISION) n = MAX_PRECISION; res = true; } new_map.insert(cnsts.get(i), n); } return res; } void boolean_comparison_of_models(goal_ref g, model_ref const & mdl, model_ref const & full_mdl, obj_map<func_decl, app*> & cnst2term_map, obj_map<expr,int>& count) { std::queue<expr*> to_traverse; app * cur; int cur_cnt; expr_ref mdl_eval(m), full_eval(m); for (unsigned i=0; i < g->size(); i++){ mdl->eval(g->form(i),mdl_eval,true); full_mdl->eval(g->form(i),full_eval,true); //Push only if the full model evaluates to false, or if the models differ? if (!m.is_true(full_eval)) // m.is_true(full_eval) != m.is_true(mdl_eval) to_traverse.push(g->form(i)); } while (to_traverse.size() > 0) { cur = to_app(to_traverse.front()); #ifdef Z3DEBUG std::cout<<"Analyze - traversing: "<<mk_ismt2_pp(cur,m)<<std::endl; std::cout.flush(); #endif if (m_float_util.is_rm(cur) || m_float_util.is_numeral(cur)) { to_traverse.pop(); continue; } else if(!m.is_bool(cur)){ //Push and add potential counter to the map for the descendants //Inserting children in the count map //Count will contain only introduced constants not other expressions if (count.contains(cur) ){ cur_cnt = count.find(cur); count.remove(cur); count.insert(cur,1+cur_cnt); } else if(cnst2term_map.contains(cur->get_decl())) count.insert(cur,1); if(cnst2term_map.contains(cur->get_decl())) to_traverse.push(cnst2term_map.find(cur->get_decl())); for(unsigned i=0;i<cur->get_num_args();i++) { if(m_float_util.is_rm(cur->get_arg(i)) || m_float_util.is_numeral(cur->get_arg(i))) continue; to_traverse.push(cur->get_arg(i)); } } else { //Comparing boolean values from the model and the expanded model mdl->eval(cur,mdl_eval,true); full_mdl->eval(cur,full_eval,true); if (m.is_true(full_eval) != m.is_true(mdl_eval)) { //queue arguments for(unsigned i=0; i < cur->get_num_args(); i++) to_traverse.push(cur->get_arg(i)); } } to_traverse.pop(); } #ifdef Z3DEBUG std::cout<<"Expression count"<<std::endl; for(obj_map<expr,int>::iterator it = count.begin(); it!= count.end(); it++) { std::cout<<mk_ismt2_pp(it->m_key,m)<<":"<<it->m_value<<std::endl; } std::cout<<"-------------------------"<<std::endl; std::cout.flush(); #endif } //Equality as assignment? void fix_cnst2cnst_equalities(goal_ref const & g,model_ref & full_mdl) { app * eq; #ifdef Z3DEBUG std::cout<<"Fixing trivial equalities"<<std::endl; #endif for (unsigned i=0; i<g->size();i++) { eq = to_app(g->form(i)); if (eq->get_family_id() == m.get_basic_family_id() && eq->get_decl_kind() == OP_EQ){ //eq is in fact an equality app * lhs = to_app(eq->get_arg(0)); app * rhs = to_app(eq->get_arg(1)); expr * lhs_e,*rhs_e,*exp, *exp_e; app *other = NULL; if(lhs->get_num_args()==0 && rhs ->get_num_args()==0){ //over constants lhs_e = full_mdl->get_const_interp(lhs->get_decl()); rhs_e = full_mdl->get_const_interp(rhs->get_decl()); // != would work as well, to make sure they are not both NULL, //and could simplify later checks if(lhs_e != rhs_e) { //SASSERT(lhs_e || rhs_e); //and one is registered in the full model while the other is not if(!lhs_e){// && rhs_e){ other = lhs; exp_e = rhs_e; exp = rhs; } else { // if(!rhs_e && lhs_e){ other = rhs; exp_e = lhs_e; exp = lhs; } full_mdl->register_decl(other->get_decl(),exp_e); #ifdef Z3DEBUG std::cout<<mk_ismt2_pp(eq,m)<<" : "<<"assigning "<<mk_ismt2_pp(other,m)<< " value of "<<mk_ismt2_pp(exp,m)<<":"<<mk_ismt2_pp(exp_e,m)<<std::endl; #endif } } } } } void obtain_values( app * rhs, model_ref const & mdl, model_ref & full_mdl, mpf_manager & mpf_mngr, obj_map<func_decl,app*> & cnst2term_map, obj_map<expr, bool> & precise_op, obj_map<expr, mpf*> & actual_value, obj_map<expr, double> & err_est, mpf_rounding_mode & rm, bool & precise_children, bool & seen_all_children, bool & children_have_finite_err, mpf * arg_val, mpf * est_arg_val //expr_ref * arg_e ){ expr_ref arg_e[] = { expr_ref(m), expr_ref(m), expr_ref(m), expr_ref(m) }; unsigned i=0; //Set rounding mode if (rhs->get_num_args() > 0 && m_float_util.is_rm(rhs->get_arg(0))) { expr_ref rm_val(m); mdl->eval(rhs->get_arg(0), rm_val, true); m_float_util.is_rm_numeral(rm_val, rm); i = 1; } //Collect argument values for (; i < rhs->get_num_args(); i++) { expr * arg = rhs->get_arg(i); if (is_app(arg) && to_app(arg)->get_num_args() == 0) { if (precise_op.contains(arg)) { precise_children &= precise_op.find(arg); } else if (!cnst2term_map.contains(to_app(arg)->get_decl())) { /* that's okay */ } else { #ifdef Z3DEBUG std::cout << "Not seen all children of " << mk_ismt2_pp(rhs, m) << " (spec. " << mk_ismt2_pp(arg, m) << ")" << std::endl; #endif precise_children = false; seen_all_children = false; break; } } // Value from small model mdl->eval(arg, arg_e[i],true); m_float_util.is_numeral(arg_e[i], arg_val[i]); if( children_have_finite_err && err_est.contains(arg) && isinfinite(err_est.find(arg))) children_have_finite_err=false; if (actual_value.contains(arg)) mpf_mngr.set(est_arg_val[i], *actual_value.find(arg)); else if (seen_all_children && is_app(arg) && to_app(arg)->get_num_args()==0) { //We have seen all children so if it is a constant and not in actual_value then //it is an input variable and its est_val is the same as actual value mpf * tmp = alloc(mpf); mpf_mngr.set(*tmp, arg_val[i]); actual_value.insert(arg, tmp); mpf_mngr.set(est_arg_val[i], *tmp); } else std::cout << "Estimated value missing: " << mk_ismt2_pp(arg,m) << std::endl; } } void full_semantics_eval( app * rhs, mpf_manager & mpf_mngr, mpf_rounding_mode & rm, mpf * arg_val, mpf * est_arg_val, mpf & rhs_value, mpf & est_rhs_value){ switch (rhs->get_decl()->get_decl_kind()) { case OP_FPA_ADD: mpf_mngr.add(rm, arg_val[1], arg_val[2], rhs_value); mpf_mngr.add(rm, est_arg_val[1], est_arg_val[2], est_rhs_value); break; case OP_FPA_SUB: mpf_mngr.sub(rm, arg_val[1], arg_val[2], rhs_value); mpf_mngr.sub(rm, est_arg_val[1], est_arg_val[2], est_rhs_value); break; case OP_FPA_NEG: mpf_mngr.neg(arg_val[0], rhs_value); mpf_mngr.neg(est_arg_val[0], est_rhs_value);//Does it even make sense to look at this? break; case OP_FPA_MUL: mpf_mngr.mul(rm, arg_val[1], arg_val[2], rhs_value); mpf_mngr.mul(rm, est_arg_val[1], est_arg_val[2], est_rhs_value); break; case OP_FPA_DIV: mpf_mngr.div(rm, arg_val[1], arg_val[2], rhs_value); mpf_mngr.div(rm, est_arg_val[1], est_arg_val[2], est_rhs_value); break; case OP_FPA_REM: mpf_mngr.rem(arg_val[0], arg_val[1], rhs_value); mpf_mngr.rem(est_arg_val[0], est_arg_val[1], est_rhs_value); break; case OP_FPA_FMA: mpf_mngr.fused_mul_add(rm, arg_val[1], arg_val[2], arg_val[3], rhs_value); mpf_mngr.fused_mul_add(rm, est_arg_val[1], est_arg_val[2], est_arg_val[3], est_rhs_value); break; case OP_FPA_SQRT: mpf_mngr.sqrt(rm, arg_val[1], rhs_value); mpf_mngr.sqrt(rm, est_arg_val[1], est_rhs_value); break; case OP_FPA_TO_FP: { unsigned ebits = rhs->get_decl()->get_parameter(0).get_int(); unsigned sbits = rhs->get_decl()->get_parameter(1).get_int(); mpf_mngr.set(rhs_value, ebits, sbits, rm, arg_val[1]); mpf_mngr.set(est_rhs_value, ebits, sbits, rm, est_arg_val[1]); break; } case OP_FPA_ABS: { mpf_mngr.abs(arg_val[0], rhs_value); mpf_mngr.abs(est_arg_val[0], est_rhs_value); break; } default: NOT_IMPLEMENTED_YET(); break; } } void evaluate_constant( app * rhs, model_ref const & mdl, mpf_manager & mpf_mngr, obj_map<expr, mpf*> & actual_value, mpf & rhs_value, mpf & est_rhs_value){ expr_ref exp(m); mdl->eval(rhs, exp, true); m_float_util.is_numeral(exp, rhs_value); //OLD:is_value if (actual_value.contains(rhs)) mpf_mngr.set(est_rhs_value, *actual_value.find(rhs)); else { mpf * tmp = alloc(mpf); mpf_mngr.set(*tmp, rhs_value); actual_value.insert(rhs, tmp); mpf_mngr.set(est_rhs_value, rhs_value); } } void calculate_error( expr_ref & lhs, mpf_manager & mpf_mngr, obj_map<expr, bool> & precise_op, obj_map<expr, double> & err_est, mpf & lhs_value, mpf & est_rhs_value, bool children_have_finite_err){ mpf err, rel_err; if (!mpf_mngr.eq(lhs_value, est_rhs_value) && !(mpf_mngr.is_nan(lhs_value) && mpf_mngr.is_nan(est_rhs_value))) { #ifdef Z3DEBUG std::cout << "Increasing precision of " << mk_ismt2_pp(lhs, m) << " because " << mk_ismt2_pp(lhs, m) << " != " << mpf_mngr.to_string(est_rhs_value) << std::endl; #endif //TODO: smarter adjustment to be implemented precise_op.insert(lhs, false); if (mpf_mngr.is_regular(lhs_value) && mpf_mngr.is_regular(est_rhs_value)) { mpf_mngr.sub(MPF_ROUND_TOWARD_ZERO, est_rhs_value, lhs_value, err); mpf_mngr.div(MPF_ROUND_TOWARD_ZERO, err, lhs_value, rel_err); mpf_mngr.abs(rel_err); } else// One of the two is a special value; in this case the relative error is +INF mpf_mngr.mk_pinf(11, 53, rel_err); if(children_have_finite_err) err_est.insert(lhs, mpf_mngr.to_double(rel_err)); #ifdef Z3DEBUG std::cout << "Error estimate: "<<mpf_mngr.to_string(rel_err) << std::endl; #endif } else { #ifdef Z3DEBUG std::cout << mk_ismt2_pp(lhs, m) << " is precise." << std::endl; #endif precise_op.insert(lhs, true); } #ifdef Z3DEBUG std::cout << "****************************" << std::endl; #endif } bool evaluate_model(goal_ref const & g, model_ref & mdl){ bool is_model = true; expr_ref res(m); for (unsigned j = 0; j < g->size(); j++) { mdl->eval(g->form(j), res, true); if (!m.is_true(res)) { std::cout << "Failed: " << mk_ismt2_pp(g->form(j), m) << std::endl; std::cout << "Evaluates to: " << mk_ismt2_pp(res, m) << std::endl; is_model=false; } } return is_model; } void evaluate_and_patch( func_decl_ref_vector const & cnsts, model_ref const & mdl, model_ref & full_mdl, goal_ref const & g, obj_map<func_decl,app*> & cnst2term_map, obj_map<expr, double> & err_est) { mpf_manager & mpf_mngr = m_float_util.fm(); expr_ref lhs(m), lhs_eval(m); app * rhs; mpf arg_val[4]; //First argument can be rounding mode mpf est_arg_val[4]; mpf lhs_value, rhs_value, est_rhs_value; mpf_rounding_mode rm; mpf err, rel_err; obj_map<expr, bool> precise_op; obj_map<expr, mpf*> actual_value; while (precise_op.size() != cnst2term_map.size()) for(unsigned i=0;i<cnsts.size();i++) if(cnst2term_map.contains(cnsts.get(i))) { lhs = m.mk_const(cnsts.get(i)); rhs = cnst2term_map.find(cnsts.get(i)); if (precise_op.contains(lhs))//already visited, skip return; mdl->eval(lhs, lhs_eval, true); if (m_float_util.is_numeral(lhs_eval, lhs_value)) {//OLD:is_value bool precise_children = true; bool seen_all_children = true; bool children_have_finite_err = true; obtain_values(rhs, mdl, full_mdl,mpf_mngr,cnst2term_map,precise_op,actual_value, err_est, rm, precise_children, seen_all_children, children_have_finite_err, arg_val, est_arg_val ); if (seen_all_children) {//If some arguments are not evaluated yet, skip if (rhs->get_num_args() == 0) evaluate_constant(rhs,mdl,mpf_mngr,actual_value, rhs_value, est_rhs_value); else full_semantics_eval(rhs,mpf_mngr,rm,arg_val,est_arg_val, rhs_value, est_rhs_value); full_mdl->register_decl((to_app(lhs))->get_decl(), m_float_util.mk_value(est_rhs_value)); #ifdef Z3DEBUG std::cout << "Assigning " << mk_ismt2_pp(lhs, m) << " value " << mpf_mngr.to_string(est_rhs_value) << std::endl << "Values of " << mk_ismt2_pp(lhs, m) << std::endl << "Precise children: " << ((precise_children) ? "True" : "False") << std::endl << "Lhs: " << mk_ismt2_pp(lhs_eval, m) << std::endl << "Model: " << mpf_mngr.to_string(rhs_value) << std::endl << "Estimate: " << mpf_mngr.to_string(est_rhs_value) << std::endl; #endif calculate_error(lhs,mpf_mngr,precise_op,err_est,lhs_value,est_rhs_value,children_have_finite_err); if (!actual_value.contains(lhs)) { mpf * tmp = alloc(mpf); mpf_mngr.set(*tmp, est_rhs_value); actual_value.insert(lhs, tmp); } if (!precise_children && !precise_op.contains(lhs)) { std::cout << mk_ismt2_pp(lhs, m) << " is imprecise because some children are imprecise." << std::endl; precise_op.insert(lhs, false); } } } } for (obj_map<expr, mpf *>::iterator it = actual_value.begin(); it != actual_value.end(); it++) mpf_mngr.del(*it->m_value); mpf_mngr.del(err); mpf_mngr.del(rel_err); mpf_mngr.del(lhs_value); mpf_mngr.del(rhs_value); mpf_mngr.del(est_rhs_value); for (unsigned i = 0; i < 4; i++) { mpf_mngr.del(arg_val[i]); mpf_mngr.del(est_arg_val[i]); } } bool precise_model_reconstruction( model_ref const & mdl, model_ref & full_mdl, goal_ref const & g, obj_map<expr, double> & err_est,//mpf* func_decl_ref_vector const & cnsts, obj_map<func_decl, app*> & cnst2term_map) { #ifdef Z3DEBUG std::cout << "Attempting to patch small-float model" << std::endl; #endif expr_ref res(m); bool is_model=true; //Evaluation of the model using full fpa semantics and construction of the full model evaluate_and_patch(cnsts, mdl, full_mdl, g, cnst2term_map, err_est); #ifdef Z3DEBUG std::cout<<std::endl<<"Printing err_est map"<<std::endl; for(obj_map<expr,double>::iterator it = err_est.begin(); it!= err_est.end(); it++) { std::cout<<mk_ismt2_pp(it->m_key,m)<<":"<<it->m_value<<std::endl; } std::cout<<"-------------------------"<<std::endl; std::cout.flush(); #endif //Assigning values when input_cnst = intro_cnst; fix_cnst2cnst_equalities(g,full_mdl); //Completing the model with values for input variables for (unsigned j=0; j < mdl->get_num_constants(); j++) { if (!cnst2term_map.contains(mdl->get_constant(j)) && !full_mdl->get_const_interp(mdl->get_constant(j))) { mdl->eval(mdl->get_constant(j), res); full_mdl->register_decl(mdl->get_constant(j), res); } } //Evaluate the full model is_model = evaluate_model(g,full_mdl); return is_model; } void calculate_relative_error( obj_map<expr, double> & err_est, obj_map<expr, int> & expr_count, obj_map<expr, double> & err_ratio_map) { unsigned num_args=0; expr_ref exp(m); double out_err,cur,err_ratio, avg_err; //AZ: Currently ignoring the expr_count, since it was blocking consideration of some expressions for (obj_map<expr, double>::iterator it = err_est.begin(); it != err_est.end(); it++) { // if any ancestor node has an error current node will be in expr_count. /*if (!expr_count.contains(it->m_key)) continue;*/ exp = it->m_key; out_err = it->m_value; num_args = to_app(exp)->get_num_args(); // Calculate average error of input params avg_err = 0.0; if (num_args > 0) { for (unsigned i=0; i<num_args; i++) { expr * arg = to_app(exp)->get_arg(i); if (err_est.contains(arg)) { cur = err_est.find(arg); avg_err = avg_err + cur; } } avg_err = avg_err/num_args; } // Relative error when input error exists, otherwise just output error err_ratio = fabs((avg_err != (double) 0)? out_err / avg_err : out_err); if(expr_count.contains(exp)) { if(ERR_OP) err_ratio *= 1 + expr_count.find(exp); else err_ratio += expr_count.find(exp); } err_ratio_map.insert(exp, err_ratio); } TRACE("fpa2bv_approx", tout << "ERROR RATIO MAP: " << std::endl; for (obj_map<expr, double>::iterator it = err_ratio_map.begin();// mpf* it != err_ratio_map.end(); it++) tout << mk_ismt2_pp(it->m_key, m) << ": " <<it->m_value<< std::endl; ); #ifdef Z3DEBUG std::cout<<"Error ratio:"<<std::endl; for (obj_map<expr, double>::iterator it = err_ratio_map.begin();//mpf* it != err_ratio_map.end(); it++) std::cout<< mk_ismt2_pp(it->m_key, m) << ": " << it->m_value<< std::endl; std::cout.flush(); #endif } void rank_terms(obj_map<expr, double> & err_ratio_map, std::list <struct pair *> & ranked_terms) { unsigned kth = (unsigned)(err_ratio_map.size()*K_PERCENTAGE); if (kth<10) kth=K_MIN; SASSERT(!err_ratio_map.empty()); //Insertion sort the error ratios, keeping only the k highest elements obj_map<expr, double>::iterator it = err_ratio_map.begin(); struct pair * p = new struct pair(); p->exp=it->m_key; p->quotient=it->m_value; ranked_terms.push_front(p); for (it++; it != err_ratio_map.end(); it++) { if (ranked_terms.size()<kth || it->m_value >= ranked_terms.back()->quotient) { std::list<struct pair *>::iterator pos = ranked_terms.begin(); while (pos!=ranked_terms.end() && it->m_value <= ranked_terms.back()->quotient) pos++; struct pair * p = new struct pair(); p->exp=it->m_key; p->quotient=it->m_value; ranked_terms.insert(pos, p); if (ranked_terms.size() > kth) { delete ranked_terms.back(); ranked_terms.pop_back(); } } } } void increase_precision( std::list <struct pair *> & ranked_terms, func_decl_ref_vector const & cnsts, obj_map<func_decl, unsigned> & cnst2prec_map, obj_map<func_decl, app*> & cnst2term_map, obj_map<func_decl, unsigned> & new_map){ //Refine chosen terms and find the any input 'variables' which are //its immediate arguments and refine them as well #ifdef Z3DEBUG std::cout<<"Increasing precision:"<<std::endl; #endif for(std::list<struct pair *>::iterator itp = ranked_terms.begin(); itp != ranked_terms.end(); itp++) { app * cur = to_app((*itp)->exp); func_decl * f = cur->get_decl(); unsigned new_prec = PREC_INCREMENT, old_prec; bool in_new_map; if (cnst2prec_map.contains(f)) new_prec += cnst2prec_map.find(f); new_prec= (new_prec > MAX_PRECISION) ? MAX_PRECISION : new_prec; new_map.insert(f, new_prec); #ifdef Z3DEBUG std::cout << f->get_name() << ":" << new_prec << std::endl; std::cout << mk_ismt2_pp(cur, m) << ":" << new_prec << std::endl; #endif if(cnst2term_map.contains(f)) cur = cnst2term_map.find(f); // Refine constants that are direct arguments of this term for(unsigned i=0; i<cur->get_num_args();i++){ func_decl * arg_decl = to_app(cur->get_arg(i))->get_decl(); if (!cnst2term_map.contains(arg_decl) && //Not a constant introduced by flattening !m_float_util.is_rm(cur->get_arg(i)) && //OLD:is_rm(...,rm) !m_float_util.is_numeral(cur->get_arg(i))) { //OLD:is_value //It is an input 'variable' if ( (in_new_map = new_map.contains(arg_decl))) old_prec=new_map.find(arg_decl); else if (cnst2prec_map.contains(arg_decl)) old_prec = cnst2prec_map.find(arg_decl); else old_prec=0; if (old_prec < new_prec) { if (in_new_map) new_map.remove(arg_decl); SASSERT(new_prec <= MAX_PRECISION); new_map.insert(arg_decl, new_prec); std::cout << " " << arg_decl->get_name() << ":" << new_prec << std::endl; #ifdef Z3DEBUG std::cout<<" "<<mk_ismt2_pp(cur->get_arg(i),m)<<":"<<new_prec<<std::endl; #endif } } } std::cout.flush(); delete *itp; } //Complete precision map func_decl * f; for(unsigned j=0; j<cnsts.size();j++) if(!new_map.contains((f=cnsts.get(j)))) new_map.insert(f, cnst2prec_map.find(f)); } void model_guided_approximation_refinement( model_ref const & mdl, model_ref & full_mdl, goal_ref const & g, func_decl_ref_vector const & cnsts, obj_map<func_decl, unsigned> & cnst2prec_map, obj_map<func_decl, app*> & cnst2term_map, obj_map<expr, double> & err_est, obj_map<func_decl, unsigned> & new_map) { obj_map<expr, double> err_ratio_map; obj_map<expr, int> expr_count; std::list <struct pair *> ranked_terms; boolean_comparison_of_models(g, mdl, full_mdl, cnst2term_map, expr_count); calculate_relative_error(err_est, expr_count, err_ratio_map); rank_terms (err_ratio_map,ranked_terms); increase_precision(ranked_terms,cnsts,cnst2prec_map,cnst2term_map,new_map); } void simplify(goal_ref mg) { ast_manager &m = mg->m(); // CMW: <--- We use the manager of the goal, so this works for any manager. expr_ref new_curr(m); proof_ref new_pr(m); th_rewriter simplifier(m, m_params); // CMW: we need to eliminate AND expressions. params_ref elim_and(m_params); elim_and.set_bool("elim_and", true); // elim_and.set_uint("max_depth", 1); // CMW: This number can have a big impact on performance, either way. simplifier.updt_params(elim_and); SASSERT(mg->is_well_sorted()); TRACE("before_simplifier", mg->display(tout);); m_num_steps = 0; if (mg->inconsistent()) return; for (unsigned idx = 0; idx < mg->size(); idx++) { if (mg->inconsistent()) break; expr * curr = mg->form(idx); simplifier(curr, new_curr, new_pr); m_num_steps += simplifier.get_num_steps(); if (mg->proofs_enabled()) { proof * pr = mg->pr(idx); new_pr = m.mk_modus_ponens(pr, new_pr); } mg->update(idx, new_curr, new_pr, mg->dep(idx)); } TRACE("after_simplifier_bug", mg->display(tout);); mg->elim_redundancies(); TRACE("after_simplifier", mg->display(tout);); TRACE("after_simplifier_detail", mg->display_with_dependencies(tout);); SASSERT(mg->is_well_sorted()); } bool fully_encoded(obj_map<func_decl, unsigned> const & precision_map) { for (obj_map<func_decl, unsigned>::iterator it = precision_map.begin(); it != precision_map.end(); it++) if (it->m_value < MAX_PRECISION) return false; return true; } void bitblast(goal_ref const & g, fpa2bv_converter_prec & fpa2bv, bit_blaster_rewriter & bv2bool, obj_map<func_decl,unsigned> & const2prec_map, sat::solver & solver, atom2bool_var & map) { // CMW: This is all done using the temporary manager! expr_ref new_curr(*m_temp_manager); proof_ref new_pr(*m_temp_manager); std::cout.flush(); SASSERT(g->is_well_sorted()); //fpa2bv fpa2bv_rewriter_prec fpa2bv_rw(*m_temp_manager, fpa2bv, m_params); fpa2bv_rw.m_cfg.set_mappings(&const2prec_map); m_num_steps = 0; unsigned size = g->size(); for (unsigned idx = 0; idx < size; idx++) { if (g->inconsistent()) break; expr * curr = g->form(idx); #ifdef Z3DEBUG std::cout<<mk_ismt2_pp(curr,m)<<std::endl; std::cout.flush(); #endif fpa2bv_rw(curr, new_curr, new_pr); m_num_steps += fpa2bv_rw.get_num_steps(); if (m_proofs_enabled) { proof * pr = g->pr(idx); new_pr = m_temp_manager->mk_modus_ponens(pr, new_pr); } g->update(idx, new_curr, new_pr, g->dep(idx)); SASSERT(g->is_well_sorted()); } //Adding the equalities that fix bits for(unsigned i=0;i<fpa2bv.m_extra_assertions.size();i++) g->assert_expr(fpa2bv.m_extra_assertions.get(i)); SASSERT(g->is_well_sorted()); simplify(g); //Bitblasting TRACE("before_bit_blaster", g->display(tout);); m_num_steps = 0; size = g->size(); for (unsigned idx = 0; idx < size; idx++) { if (g->inconsistent()) break; expr * curr = g->form(idx); bv2bool(curr, new_curr, new_pr); m_num_steps += bv2bool.get_num_steps(); if (m_proofs_enabled) { proof * pr = g->pr(idx); new_pr = m_temp_manager->mk_modus_ponens(pr, new_pr); } g->update(idx, new_curr, new_pr, g->dep(idx)); } g->inc_depth(); simplify(g); TRACE("before_sat_solver", g->display(tout);); g->elim_redundancies(); goal2sat::dep2asm_map d2am ; m_goal2sat(*g, m_params, solver, map, d2am , false); TRACE("sat_solver_unknown", tout << "interpreted_atoms: " << map.interpreted_atoms() << "\n"; atom2bool_var::iterator it = map.begin(); atom2bool_var::iterator end = map.end(); for (; it != end; ++it) { if (!is_uninterp_const(it->m_key)) tout << mk_ismt2_pp(it->m_key, *m_temp_manager) << "\n"; }); CASSERT("sat_solver", solver.check_invariant()); IF_VERBOSE(TACTIC_VERBOSITY_LVL, solver.display_status(verbose_stream());); TRACE("sat_dimacs", solver.display_dimacs(tout);); } model_ref get_fpa_model(goal_ref const & g, fpa2bv_converter_prec & fpa2bv, bit_blaster_rewriter & bv2bool, sat::solver & solver, atom2bool_var & map) { // CMW: This is all done using the temporary manager, until at the very end we translate the model back to this->m. model_ref md = alloc(model, *m_temp_manager); sat::model const & ll_m = solver.get_model(); TRACE("sat_tactic", for (unsigned i = 0; i < ll_m.size(); i++) tout << i << ":" << ll_m[i] << " "; tout << "\n";); atom2bool_var::iterator it = map.begin(); atom2bool_var::iterator end = map.end(); for (; it != end; ++it) { expr * n = it->m_key; sat::bool_var v = it->m_value; if (is_app(n) && to_app(n)->get_decl()->get_arity() != 0) continue; TRACE("sat_tactic", tout << "extracting value of " << mk_ismt2_pp(n, *m_temp_manager) << "\nvar: " << v << "\n";); switch (sat::value_at(v, ll_m)) { case l_true: md->register_decl(to_app(n)->get_decl(), m_temp_manager->mk_true()); break; case l_false: md->register_decl(to_app(n)->get_decl(), m_temp_manager->mk_false()); break; default: break; } } TRACE("sat_tactic", model_v2_pp(tout, *md);); model_converter_ref bb_mc = mk_bit_blaster_model_converter(*m_temp_manager, bv2bool.const2bits()); model_converter_ref bv_mc = mk_fpa2bv_prec_model_converter(*m_temp_manager, fpa2bv.const2bv(), fpa2bv.rm_const2bv()); bb_mc->operator()(md, 0); bv_mc->operator()(md, 0); #ifdef Z3DEBUG std::cout << "Model: " << std::endl; for (unsigned i = 0 ; i < md->get_num_constants(); i++) { func_decl * d = md->get_constant(i); std::cout << d->get_name() << " = " << mk_ismt2_pp(md->get_const_interp(d), *m_temp_manager) << std::endl; } #endif // md is in terms of the temporary manager. ast_translation translator(*m_temp_manager, this->m); return md->translate(translator); } void encode_fpa_terms( goal_ref const & g, obj_map<func_decl,app*> & const2term_map) { for (obj_map<func_decl, app*>::iterator it = const2term_map.begin(); it!=const2term_map.end(); it++) { expr_ref q(m); #ifdef Z3DEBUG std::cout << "Adding " << it->m_key->get_name() << " = " << mk_ismt2_pp(it->m_value, m) << std::endl; #endif q = m.mk_eq(m.mk_const(it->m_key), it->m_value); g->assert_expr(q); } } lbool approximate_model_construction(goal_ref & g, obj_map<func_decl, unsigned> & const2prec_map) { lbool r = l_undef; // CMW: The following will introduce lots of stuff that we don't need (e.g., symbols) // To save memory, we use a separate, new manager that we can throw away afterwards. m_temp_manager = alloc(ast_manager, PGM_DISABLED); { ast_translation translator(m, *m_temp_manager); goal_ref ng = g->translate(translator); obj_map<func_decl, unsigned> const2prec_map_tm; for (obj_map<func_decl, unsigned>::iterator it = const2prec_map.begin(); it!=const2prec_map.end(); it++) const2prec_map_tm.insert(translator(it->m_key), it->m_value); sat::solver sat_solver(m_params, 0); atom2bool_var atom_map(*m_temp_manager); { tactic_report report_i("fpa2bv_approx_before_bitblaster", *ng); } fpa2bv_converter_prec fpa2bv(*m_temp_manager, m_mode); bit_blaster_rewriter bv2bool(*m_temp_manager, m_params); bitblast(ng, fpa2bv, bv2bool, const2prec_map_tm, sat_solver, atom_map); { tactic_report report_i("fpa2bv_approx_after_bitblaster", *ng); } std::cout << "Iteration variables: " << sat_solver.num_vars() << std::endl; std::cout << "Iteration clauses: " << sat_solver.num_clauses() << std::endl; r = sat_solver.check(); if (r == l_true) { // we need to get the model and translate it back to m. m_fpa_model = get_fpa_model(ng, fpa2bv, bv2bool, sat_solver, atom_map).get(); } else m_fpa_model = 0; // CMW: translator, etc, gets destroyed here, so all references // to temporary expressions are gone. } dealloc(m_temp_manager); m_temp_manager = 0; return r; } void lift( goal_ref const & g, func_decl_ref_vector & constants, obj_map<func_decl, app*> * const2term_map ) { expr_ref new_new_curr(m); expr_ref new_curr(m); proof_ref new_pr(m); simplify(g); //Renaming subexpressions using new constants const_intro_rewriter const_rewriter(m, m_params); for (unsigned idx = 0; idx < g->size(); idx++) { if (g->inconsistent()) break; expr * curr = g->form(idx); const_rewriter(curr, new_curr, new_pr); //Introduces constants that replace subexpressions m_num_steps += const_rewriter.get_num_steps(); if (m_proofs_enabled) { proof * pr = g->pr(idx); new_pr = m.mk_modus_ponens(pr, new_pr); } g->update(idx, new_curr, new_pr, g->dep(idx)); } constants.set(const_rewriter.m_cfg.m_introduced_consts); const2term_map->swap(const_rewriter.m_cfg.m_const2term_map); // Note: Ideally, we would directly encode them. For now we're lazy and just add equalities // and we rely on fpa2bv_converter_prec to `magically' recognize the equalities we added. { tactic_report report_i("fpa2bv_approx_before_fpa_terms", *(g.get())); } encode_fpa_terms(g, *const2term_map); SASSERT(g.get()->is_well_sorted()); } void verify_precise_model( goal_ref const & g, model_ref & full_mdl, func_decl_ref_vector & constants, obj_map<func_decl, app*> & const2term_map, model_converter_ref & mc, goal_ref_buffer & result ){ expr_ref res(m); for (unsigned j = 0; j < g->size(); j++) { full_mdl->eval(g->form(j), res, true); if (!m.is_true(res)) { std::cout << "Failed: " << mk_ismt2_pp(g->form(j), m) << std::endl; std::cout << "Evaluates to: " << mk_ismt2_pp(res, m) << std::endl; } SASSERT(m.is_true(res)); } std::cout << "Full model: " << std::endl; for (unsigned i = 0 ; i < full_mdl->get_num_decls(); i++) { func_decl * d = full_mdl->get_decl(i); if(constants.contains(d)) std::cout << d->get_name() << " = " << mk_ismt2_pp(full_mdl->get_const_interp(d), m) << std::endl; } std::cout.flush(); result.back()->reset(); // Filter all the constants we introduced earlier from the model. filter_model_converter * fmc = alloc(filter_model_converter, m); for (obj_map<func_decl, app*>::iterator it = const2term_map.begin(); it != const2term_map.end(); it++) fmc->insert(it->m_key); mc = concat(fmc, model2model_converter(m_fpa_model.get())); } void setup_options(goal_ref const & g){ SASSERT(g->is_well_sorted()); fail_if_proof_generation("fpa2bv_approx", g); fail_if_unsat_core_generation("fpa2bv_approx", g); m_proofs_enabled = g->proofs_enabled(); m_produce_models = g->models_enabled(); m_produce_unsat_cores = g->unsat_core_enabled(); m_num_steps = 0; } void print_constants(func_decl_ref_vector & constants, obj_map<func_decl, unsigned> & const2prec_map){ #ifdef Z3DEBUG for(unsigned i=0;i<constants.size();i++) { func_decl * q = constants.get(i); std::cout<<q->get_name()<<":"<<const2prec_map.find(q)<<std::endl; } #endif } virtual void operator()(goal_ref const & g, goal_ref_buffer & result, model_converter_ref & mc, proof_converter_ref & pc, expr_dependency_ref & core) { bool solved=false; mc = 0; pc = 0; core = 0; obj_map<func_decl, unsigned> const2prec_map; obj_map<func_decl, unsigned> next_const2prec_map; func_decl_ref_vector constants(m); obj_map<func_decl, app*> const2term_map; lbool r = l_true; unsigned iteration_cnt = 0; stopwatch sw; tactic_report report("fpa2bv_approx", *g); TRACE("fpa2bv_approx", tout << "BEFORE: " << std::endl; g->display(tout);); result.reset(); result.push_back(g.get()); SASSERT(g->is_well_sorted()); if (g->inconsistent()) return; lift(g, constants, &const2term_map); init_precision_mapping(constants, const2prec_map, const2term_map); std::cout << "Simplified goal:" << std::endl; g->display(std::cout); while (!solved && !m_cancel) { std::cout << "=============== Starting iteration " << ++iteration_cnt << std::endl; sw.reset(); sw.start(); // Copy the goal goal_ref mg(alloc(goal, g->m(),g->proofs_enabled(),g->models_enabled(),g->unsat_core_enabled())); mg->copy_from(*g.get()); tactic_report report_i("fpa2bv_approx_i", *mg); print_constants(constants, const2prec_map); TRACE("fpa2bv_approx_goal_i", mg->display(tout); ); r = approximate_model_construction(mg, const2prec_map); std::cout << "Approximation is " << (r==l_true?"SAT":r==l_false?"UNSAT":"UNKNOWN") << std::endl; if (r == l_true) { model_ref full_mdl = alloc(model, m); obj_map<expr, double> err_est; solved = precise_model_reconstruction(m_fpa_model, full_mdl, mg, err_est, constants, const2term_map); std::cout<<"Patching of the model "<<((solved)?"succeeded":"failed")<<std::endl; std::cout.flush(); if (!solved) model_guided_approximation_refinement(m_fpa_model, full_mdl, mg, constants, const2prec_map, const2term_map, err_est, next_const2prec_map); else verify_precise_model(g,full_mdl,constants,const2term_map,mc,result); } else if (r == l_false) { if(!proof_guided_refinement(g, constants, const2prec_map, next_const2prec_map)) {// Refinement failed -> This is unsat. solved = true; result.back()->reset(); result.back()->assert_expr(m.mk_false()); } } else { // CMW: When the sat solver comes back with `unknown', what shall we do? // AZ: Blindly refine? m_cancel = true; } const2prec_map.swap(next_const2prec_map); next_const2prec_map.reset(); std::cout << "Iteration time: " << sw.get_current_seconds() << std::endl; } std::cout << "=============== Terminating " << std::endl; dec_ref_map_key_values(m, const2term_map); std::cout << "Iteration count: " << iteration_cnt << std::endl; } }; imp * m_imp; params_ref m_params; public: fpa2bv_approx_tactic(ast_manager & m, params_ref const & p) : m_params(p){ m_imp = alloc(imp, m, p, FPAA_DEFAULT_MODE); } virtual tactic * translate(ast_manager & m) { return alloc(fpa2bv_approx_tactic, m, m_params); } virtual ~fpa2bv_approx_tactic() { dealloc(m_imp); } virtual void updt_params(params_ref const & p) { m_params = p; m_imp->updt_params(p); } virtual void collect_param_descrs(param_descrs & r) { } virtual void operator()(goal_ref const & in, goal_ref_buffer & result, model_converter_ref & mc, proof_converter_ref & pc, expr_dependency_ref & core) { (*m_imp)(in, result, mc, pc, core); } virtual void cleanup() { ast_manager & m = m_imp->m; imp * d = m_imp; #pragma omp critical (tactic_cancel) { d = m_imp; } dealloc(d); d = alloc(imp, m, m_params, FPAA_DEFAULT_MODE); #pragma omp critical (tactic_cancel) { m_imp = d; } } protected: virtual void set_cancel(bool f) { if (m_imp) m_imp->set_cancel(f); } }; tactic * mk_fpa2bv_approx_tactic(ast_manager & m, params_ref const & p) { return and_then(clean(alloc(fpa2bv_approx_tactic, m, p)), mk_fail_if_undecided_tactic()); } Buggy version, a full model is found but evaluation finds it to be invalid. /*++ Copyright (c) 2012 Microsoft Corporation Module Name: fpa2bv_approx_tactic.cpp Abstract: Tactic that converts floating points to bit-vectors lazily Author: Aleksander Zeljic 2012-11-15 Notes: --*/ #include"tactical.h" #include"cooperate.h" #include"ref_util.h" #include"th_rewriter.h" #include"bit_blaster_rewriter.h" #include"bit_blaster_model_converter.h" #include"model_v2_pp.h" #include"goal2sat.h" #include"sat_solver.h" #include"fpa_decl_plugin.h" #include"fpa2bv_converter_prec.h" #include"fpa2bv_rewriter_prec.h" #include"fpa2bv_approx_tactic.h" #include"const_intro_rewriter.h" #include"ctx_simplify_tactic.h" #include"filter_model_converter.h" #include <list> #include <queue> #include <math.h> #include<iostream> #define K_MIN 10 #define K_PERCENTAGE 0.3 #define PREC_INCREMENT 20 #define ERR_OP 0 // struct pair { expr * exp; double quotient;// mpf * }; bool isinfinite(double x) { #ifdef _WIN32 int c = _fpclass(x); return c == _FPCLASS_PINF || c == _FPCLASS_NINF; #else return fpclassify(x) == FP_INFINITE; #endif } class fpa2bv_approx_tactic: public tactic { struct imp { ast_manager & m; goal2sat m_goal2sat; sat2goal m_sat2goal; params_ref m_params; unsigned m_num_steps; bool m_proofs_enabled; bool m_produce_models; bool m_produce_unsat_cores; bool m_cancel; fpa_approximation_mode m_mode; ast_manager * m_temp_manager; model_ref m_fpa_model; fpa_util m_float_util; imp(ast_manager & _m, params_ref const & p, fpa_approximation_mode mode) : m(_m), m_params(p), m_proofs_enabled(false), m_produce_models(false), m_produce_unsat_cores(false), m_cancel(false), m_mode(mode), m_temp_manager(0), m_float_util(_m) { } void updt_params(params_ref const & p) { m_params = p; } void set_cancel(bool f) { //If f is true stop everything m_cancel = f; } void init_precision_mapping(func_decl_ref_vector const & cnsts, obj_map<func_decl, unsigned> & map, obj_map<func_decl, app*> & const2term_map) { for (unsigned i = 0; i < cnsts.size(); i++) { if (const2term_map.contains(cnsts.get(i)) || m_mode == FPAA_SMALL_FLOATS) map.insert_if_not_there(cnsts.get(i), 0); else map.insert_if_not_there(cnsts.get(i), MAX_PRECISION); } } bool proof_guided_refinement( goal_ref const & g, func_decl_ref_vector const & cnsts, obj_map<func_decl, unsigned> & cnst2prec_map, obj_map<func_decl, unsigned> & new_map) { // We have no model. Let's just increase precision of everything. bool res = false; for (unsigned i = 0; i < cnsts.size(); i++) { unsigned old = cnst2prec_map.find(cnsts.get(i)); unsigned n = old + PREC_INCREMENT; if (old >= MAX_PRECISION) n = MAX_PRECISION; else { if (n > MAX_PRECISION) n = MAX_PRECISION; res = true; } new_map.insert(cnsts.get(i), n); } return res; } void boolean_comparison_of_models(goal_ref g, model_ref const & mdl, model_ref const & full_mdl, obj_map<func_decl, app*> & cnst2term_map, obj_map<expr,int>& count) { std::queue<expr*> to_traverse; app * cur; int cur_cnt; expr_ref mdl_eval(m), full_eval(m); for (unsigned i=0; i < g->size(); i++){ mdl->eval(g->form(i),mdl_eval,true); full_mdl->eval(g->form(i),full_eval,true); //Push only if the full model evaluates to false, or if the models differ? if (!m.is_true(full_eval)) // m.is_true(full_eval) != m.is_true(mdl_eval) to_traverse.push(g->form(i)); } while (to_traverse.size() > 0) { cur = to_app(to_traverse.front()); #ifdef Z3DEBUG std::cout<<"Analyze - traversing: "<<mk_ismt2_pp(cur,m)<<std::endl; std::cout.flush(); #endif if (m_float_util.is_rm(cur) || m_float_util.is_numeral(cur)) { to_traverse.pop(); continue; } else if(!m.is_bool(cur)){ //Push and add potential counter to the map for the descendants //Inserting children in the count map //Count will contain only introduced constants not other expressions if (count.contains(cur) ){ cur_cnt = count.find(cur); count.remove(cur); count.insert(cur,1+cur_cnt); } else if(cnst2term_map.contains(cur->get_decl())) count.insert(cur,1); if(cnst2term_map.contains(cur->get_decl())) to_traverse.push(cnst2term_map.find(cur->get_decl())); for(unsigned i=0;i<cur->get_num_args();i++) { if(m_float_util.is_rm(cur->get_arg(i)) || m_float_util.is_numeral(cur->get_arg(i))) continue; to_traverse.push(cur->get_arg(i)); } } else { //Comparing boolean values from the model and the expanded model mdl->eval(cur,mdl_eval,true); full_mdl->eval(cur,full_eval,true); if (m.is_true(full_eval) != m.is_true(mdl_eval)) { //queue arguments for(unsigned i=0; i < cur->get_num_args(); i++) to_traverse.push(cur->get_arg(i)); } } to_traverse.pop(); } #ifdef Z3DEBUG std::cout<<"Expression count"<<std::endl; for(obj_map<expr,int>::iterator it = count.begin(); it!= count.end(); it++) { std::cout<<mk_ismt2_pp(it->m_key,m)<<":"<<it->m_value<<std::endl; } std::cout<<"-------------------------"<<std::endl; std::cout.flush(); #endif } //Equality as assignment? void fix_cnst2cnst_equalities(goal_ref const & g,model_ref & full_mdl) { app * eq; #ifdef Z3DEBUG std::cout<<"Fixing trivial equalities"<<std::endl; #endif for (unsigned i=0; i<g->size();i++) { eq = to_app(g->form(i)); if (eq->get_family_id() == m.get_basic_family_id() && eq->get_decl_kind() == OP_EQ){ //eq is in fact an equality app * lhs = to_app(eq->get_arg(0)); app * rhs = to_app(eq->get_arg(1)); expr * lhs_e,*rhs_e,*exp, *exp_e; app *other = NULL; if(lhs->get_num_args()==0 && rhs ->get_num_args()==0){ //over constants lhs_e = full_mdl->get_const_interp(lhs->get_decl()); rhs_e = full_mdl->get_const_interp(rhs->get_decl()); // != would work as well, to make sure they are not both NULL, //and could simplify later checks if(lhs_e != rhs_e) { //SASSERT(lhs_e || rhs_e); //and one is registered in the full model while the other is not if(!lhs_e){// && rhs_e){ other = lhs; exp_e = rhs_e; exp = rhs; } else { // if(!rhs_e && lhs_e){ other = rhs; exp_e = lhs_e; exp = lhs; } full_mdl->register_decl(other->get_decl(),exp_e); #ifdef Z3DEBUG std::cout<<mk_ismt2_pp(eq,m)<<" : "<<"assigning "<<mk_ismt2_pp(other,m)<< " value of "<<mk_ismt2_pp(exp,m)<<":"<<mk_ismt2_pp(exp_e,m)<<std::endl; #endif } } } } } void obtain_values( app * rhs, model_ref const & mdl, model_ref & full_mdl, mpf_manager & mpf_mngr, obj_map<func_decl,app*> & cnst2term_map, obj_map<expr, bool> & precise_op, obj_map<expr, mpf*> & actual_value, obj_map<expr, double> & err_est, mpf_rounding_mode & rm, bool & precise_children, bool & seen_all_children, bool & children_have_finite_err, mpf * arg_val, mpf * est_arg_val //expr_ref * arg_e ){ expr_ref arg_e[] = { expr_ref(m), expr_ref(m), expr_ref(m), expr_ref(m) }; unsigned i=0; //Set rounding mode if (rhs->get_num_args() > 0 && m_float_util.is_rm(rhs->get_arg(0))) { expr_ref rm_val(m); mdl->eval(rhs->get_arg(0), rm_val, true); m_float_util.is_rm_numeral(rm_val, rm); i = 1; } //Collect argument values for (; i < rhs->get_num_args(); i++) { expr * arg = rhs->get_arg(i); if (is_app(arg) && to_app(arg)->get_num_args() == 0) { if (precise_op.contains(arg)) { precise_children &= precise_op.find(arg); } else if (!cnst2term_map.contains(to_app(arg)->get_decl())) { /* that's okay */ } else { #ifdef Z3DEBUG std::cout << "Not seen all children of " << mk_ismt2_pp(rhs, m) << " (spec. " << mk_ismt2_pp(arg, m) << ")" << std::endl; #endif precise_children = false; seen_all_children = false; break; } } // Value from small model mdl->eval(arg, arg_e[i],true); m_float_util.is_numeral(arg_e[i], arg_val[i]); if( children_have_finite_err && err_est.contains(arg) && isinfinite(err_est.find(arg))) children_have_finite_err=false; if (actual_value.contains(arg)) mpf_mngr.set(est_arg_val[i], *actual_value.find(arg)); else if (seen_all_children && is_app(arg) && to_app(arg)->get_num_args()==0) { //We have seen all children so if it is a constant and not in actual_value then //it is an input variable and its est_val is the same as actual value mpf * tmp = alloc(mpf); mpf_mngr.set(*tmp, arg_val[i]); actual_value.insert(arg, tmp); mpf_mngr.set(est_arg_val[i], *tmp); } else std::cout << "Estimated value missing: " << mk_ismt2_pp(arg,m) << std::endl; } } void full_semantics_eval( app * rhs, mpf_manager & mpf_mngr, mpf_rounding_mode & rm, mpf * arg_val, mpf * est_arg_val, mpf & rhs_value, mpf & est_rhs_value){ switch (rhs->get_decl()->get_decl_kind()) { case OP_FPA_ADD: mpf_mngr.add(rm, arg_val[1], arg_val[2], rhs_value); mpf_mngr.add(rm, est_arg_val[1], est_arg_val[2], est_rhs_value); break; case OP_FPA_SUB: mpf_mngr.sub(rm, arg_val[1], arg_val[2], rhs_value); mpf_mngr.sub(rm, est_arg_val[1], est_arg_val[2], est_rhs_value); break; case OP_FPA_NEG: mpf_mngr.neg(arg_val[0], rhs_value); mpf_mngr.neg(est_arg_val[0], est_rhs_value);//Does it even make sense to look at this? break; case OP_FPA_MUL: mpf_mngr.mul(rm, arg_val[1], arg_val[2], rhs_value); mpf_mngr.mul(rm, est_arg_val[1], est_arg_val[2], est_rhs_value); break; case OP_FPA_DIV: mpf_mngr.div(rm, arg_val[1], arg_val[2], rhs_value); mpf_mngr.div(rm, est_arg_val[1], est_arg_val[2], est_rhs_value); break; case OP_FPA_REM: mpf_mngr.rem(arg_val[0], arg_val[1], rhs_value); mpf_mngr.rem(est_arg_val[0], est_arg_val[1], est_rhs_value); break; case OP_FPA_FMA: mpf_mngr.fused_mul_add(rm, arg_val[1], arg_val[2], arg_val[3], rhs_value); mpf_mngr.fused_mul_add(rm, est_arg_val[1], est_arg_val[2], est_arg_val[3], est_rhs_value); break; case OP_FPA_SQRT: mpf_mngr.sqrt(rm, arg_val[1], rhs_value); mpf_mngr.sqrt(rm, est_arg_val[1], est_rhs_value); break; case OP_FPA_TO_FP: { unsigned ebits = rhs->get_decl()->get_parameter(0).get_int(); unsigned sbits = rhs->get_decl()->get_parameter(1).get_int(); mpf_mngr.set(rhs_value, ebits, sbits, rm, arg_val[1]); mpf_mngr.set(est_rhs_value, ebits, sbits, rm, est_arg_val[1]); break; } case OP_FPA_ABS: { mpf_mngr.abs(arg_val[0], rhs_value); mpf_mngr.abs(est_arg_val[0], est_rhs_value); break; } default: NOT_IMPLEMENTED_YET(); break; } } void evaluate_constant( app * rhs, model_ref const & mdl, mpf_manager & mpf_mngr, obj_map<expr, mpf*> & actual_value, mpf & rhs_value, mpf & est_rhs_value){ expr_ref exp(m); mdl->eval(rhs, exp, true); m_float_util.is_numeral(exp, rhs_value); //OLD:is_value if (actual_value.contains(rhs)) mpf_mngr.set(est_rhs_value, *actual_value.find(rhs)); else { mpf * tmp = alloc(mpf); mpf_mngr.set(*tmp, rhs_value); actual_value.insert(rhs, tmp); mpf_mngr.set(est_rhs_value, rhs_value); } } void calculate_error( expr_ref & lhs, mpf_manager & mpf_mngr, obj_map<expr, bool> & precise_op, obj_map<expr, double> & err_est, mpf & lhs_value, mpf & est_rhs_value, bool children_have_finite_err){ mpf err, rel_err; if (!mpf_mngr.eq(lhs_value, est_rhs_value) && !(mpf_mngr.is_nan(lhs_value) && mpf_mngr.is_nan(est_rhs_value))) { #ifdef Z3DEBUG std::cout << "Increasing precision of " << mk_ismt2_pp(lhs, m) << " because " << mk_ismt2_pp(lhs, m) << " != " << mpf_mngr.to_string(est_rhs_value) << std::endl; #endif //TODO: smarter adjustment to be implemented precise_op.insert(lhs, false); if (mpf_mngr.is_regular(lhs_value) && mpf_mngr.is_regular(est_rhs_value)) { mpf_mngr.sub(MPF_ROUND_TOWARD_ZERO, est_rhs_value, lhs_value, err); mpf_mngr.div(MPF_ROUND_TOWARD_ZERO, err, lhs_value, rel_err); mpf_mngr.abs(rel_err); } else// One of the two is a special value; in this case the relative error is +INF mpf_mngr.mk_pinf(11, 53, rel_err); if(children_have_finite_err) err_est.insert(lhs, mpf_mngr.to_double(rel_err)); #ifdef Z3DEBUG std::cout << "Error estimate: "<<mpf_mngr.to_string(rel_err) << std::endl; #endif } else { #ifdef Z3DEBUG std::cout << mk_ismt2_pp(lhs, m) << " is precise." << std::endl; #endif precise_op.insert(lhs, true); } #ifdef Z3DEBUG std::cout << "****************************" << std::endl; #endif } bool evaluate_model(goal_ref const & g, model_ref & mdl){ bool is_model = true; expr_ref res(m); for (unsigned j = 0; j < g->size(); j++) { mdl->eval(g->form(j), res, true); if (!m.is_true(res)) { std::cout << "Failed: " << mk_ismt2_pp(g->form(j), m) << std::endl; std::cout << "Evaluates to: " << mk_ismt2_pp(res, m) << std::endl; is_model=false; } } return is_model; } void evaluate_and_patch( func_decl_ref_vector const & cnsts, model_ref const & mdl, model_ref & full_mdl, goal_ref const & g, obj_map<func_decl,app*> & cnst2term_map, obj_map<expr, double> & err_est) { mpf_manager & mpf_mngr = m_float_util.fm(); expr_ref lhs(m), lhs_eval(m); app * rhs; mpf arg_val[4]; //First argument can be rounding mode mpf est_arg_val[4]; mpf lhs_value, rhs_value, est_rhs_value; mpf_rounding_mode rm; mpf err, rel_err; obj_map<expr, bool> precise_op; obj_map<expr, mpf*> actual_value; while (precise_op.size() != cnst2term_map.size()) for(unsigned i=0;i<cnsts.size();i++) if(cnst2term_map.contains(cnsts.get(i))) { lhs = m.mk_const(cnsts.get(i)); rhs = cnst2term_map.find(cnsts.get(i)); if (precise_op.contains(lhs))//already visited, skip return; mdl->eval(lhs, lhs_eval, true); if (m_float_util.is_numeral(lhs_eval, lhs_value)) {//OLD:is_value bool precise_children = true; bool seen_all_children = true; bool children_have_finite_err = true; obtain_values(rhs, mdl, full_mdl,mpf_mngr,cnst2term_map,precise_op,actual_value, err_est, rm, precise_children, seen_all_children, children_have_finite_err, arg_val, est_arg_val ); if (seen_all_children) {//If some arguments are not evaluated yet, skip if (rhs->get_num_args() == 0) evaluate_constant(rhs,mdl,mpf_mngr,actual_value, rhs_value, est_rhs_value); else full_semantics_eval(rhs,mpf_mngr,rm,arg_val,est_arg_val, rhs_value, est_rhs_value); if (mpf_mngr.eq(rhs_value, est_rhs_value)) { full_mdl->register_decl((to_app(lhs))->get_decl(), m_float_util.mk_value(est_rhs_value)); precise_op.insert(lhs, true); } else { full_mdl->register_decl((to_app(lhs))->get_decl(), m_float_util.mk_value(est_rhs_value)); #ifdef Z3DEBUG std::cout << "Assigning " << mk_ismt2_pp(lhs, m) << " value " << mpf_mngr.to_string(est_rhs_value) << std::endl << "Values of " << mk_ismt2_pp(lhs, m) << std::endl << "Precise children: " << ((precise_children) ? "True" : "False") << std::endl << "Lhs: " << mk_ismt2_pp(lhs_eval, m) << std::endl << "Model: " << mpf_mngr.to_string(rhs_value) << std::endl << "Estimate: " << mpf_mngr.to_string(est_rhs_value) << std::endl; #endif calculate_error(lhs,mpf_mngr,precise_op,err_est,lhs_value,est_rhs_value,children_have_finite_err); } if (!actual_value.contains(lhs)) { mpf * tmp = alloc(mpf); mpf_mngr.set(*tmp, est_rhs_value); actual_value.insert(lhs, tmp); } if (!precise_children && !precise_op.contains(lhs)) { std::cout << mk_ismt2_pp(lhs, m) << " is imprecise because some children are imprecise." << std::endl; precise_op.insert(lhs, false); } } } } for (obj_map<expr, mpf *>::iterator it = actual_value.begin(); it != actual_value.end(); it++) mpf_mngr.del(*it->m_value); mpf_mngr.del(err); mpf_mngr.del(rel_err); mpf_mngr.del(lhs_value); mpf_mngr.del(rhs_value); mpf_mngr.del(est_rhs_value); for (unsigned i = 0; i < 4; i++) { mpf_mngr.del(arg_val[i]); mpf_mngr.del(est_arg_val[i]); } } bool precise_model_reconstruction( model_ref const & mdl, model_ref & full_mdl, goal_ref const & g, obj_map<expr, double> & err_est,//mpf* func_decl_ref_vector const & cnsts, obj_map<func_decl, app*> & cnst2term_map) { #ifdef Z3DEBUG std::cout << "Attempting to patch small-float model" << std::endl; #endif expr_ref res(m); bool is_model=true; //Evaluation of the model using full fpa semantics and construction of the full model evaluate_and_patch(cnsts, mdl, full_mdl, g, cnst2term_map, err_est); #ifdef Z3DEBUG std::cout<<std::endl<<"Printing err_est map"<<std::endl; for(obj_map<expr,double>::iterator it = err_est.begin(); it!= err_est.end(); it++) { std::cout<<mk_ismt2_pp(it->m_key,m)<<":"<<it->m_value<<std::endl; } std::cout<<"-------------------------"<<std::endl; std::cout.flush(); #endif //Assigning values when input_cnst = intro_cnst; fix_cnst2cnst_equalities(g,full_mdl); //Completing the model with values for input variables for (unsigned j=0; j < mdl->get_num_constants(); j++) { if (!cnst2term_map.contains(mdl->get_constant(j)) && !full_mdl->get_const_interp(mdl->get_constant(j))) { mdl->eval(mdl->get_constant(j), res); full_mdl->register_decl(mdl->get_constant(j), res); } } //Evaluate the full model is_model = evaluate_model(g,full_mdl); return is_model; } void calculate_relative_error( obj_map<expr, double> & err_est, obj_map<expr, int> & expr_count, obj_map<expr, double> & err_ratio_map) { unsigned num_args=0; expr_ref exp(m); double out_err,cur,err_ratio, avg_err; //AZ: Currently ignoring the expr_count, since it was blocking consideration of some expressions for (obj_map<expr, double>::iterator it = err_est.begin(); it != err_est.end(); it++) { // if any ancestor node has an error current node will be in expr_count. /*if (!expr_count.contains(it->m_key)) continue;*/ exp = it->m_key; out_err = it->m_value; num_args = to_app(exp)->get_num_args(); // Calculate average error of input params avg_err = 0.0; if (num_args > 0) { for (unsigned i=0; i<num_args; i++) { expr * arg = to_app(exp)->get_arg(i); if (err_est.contains(arg)) { cur = err_est.find(arg); avg_err = avg_err + cur; } } avg_err = avg_err/num_args; } // Relative error when input error exists, otherwise just output error err_ratio = fabs((avg_err != (double) 0)? out_err / avg_err : out_err); if(expr_count.contains(exp)) { if(ERR_OP) err_ratio *= 1 + expr_count.find(exp); else err_ratio += expr_count.find(exp); } err_ratio_map.insert(exp, err_ratio); } TRACE("fpa2bv_approx", tout << "ERROR RATIO MAP: " << std::endl; for (obj_map<expr, double>::iterator it = err_ratio_map.begin();// mpf* it != err_ratio_map.end(); it++) tout << mk_ismt2_pp(it->m_key, m) << ": " <<it->m_value<< std::endl; ); #ifdef Z3DEBUG std::cout<<"Error ratio:"<<std::endl; for (obj_map<expr, double>::iterator it = err_ratio_map.begin();//mpf* it != err_ratio_map.end(); it++) std::cout<< mk_ismt2_pp(it->m_key, m) << ": " << it->m_value<< std::endl; std::cout.flush(); #endif } void rank_terms(obj_map<expr, double> & err_ratio_map, std::list <struct pair *> & ranked_terms) { unsigned kth = (unsigned)(err_ratio_map.size()*K_PERCENTAGE); if (kth<10) kth=K_MIN; SASSERT(!err_ratio_map.empty()); //Insertion sort the error ratios, keeping only the k highest elements obj_map<expr, double>::iterator it = err_ratio_map.begin(); struct pair * p = new struct pair(); p->exp=it->m_key; p->quotient=it->m_value; ranked_terms.push_front(p); for (it++; it != err_ratio_map.end(); it++) { if (ranked_terms.size()<kth || it->m_value >= ranked_terms.back()->quotient) { std::list<struct pair *>::iterator pos = ranked_terms.begin(); while (pos!=ranked_terms.end() && it->m_value <= ranked_terms.back()->quotient) pos++; struct pair * p = new struct pair(); p->exp=it->m_key; p->quotient=it->m_value; ranked_terms.insert(pos, p); if (ranked_terms.size() > kth) { delete ranked_terms.back(); ranked_terms.pop_back(); } } } } void increase_precision( std::list <struct pair *> & ranked_terms, func_decl_ref_vector const & cnsts, obj_map<func_decl, unsigned> & cnst2prec_map, obj_map<func_decl, app*> & cnst2term_map, obj_map<func_decl, unsigned> & new_map){ //Refine chosen terms and find the any input 'variables' which are //its immediate arguments and refine them as well #ifdef Z3DEBUG std::cout<<"Increasing precision:"<<std::endl; #endif for(std::list<struct pair *>::iterator itp = ranked_terms.begin(); itp != ranked_terms.end(); itp++) { app * cur = to_app((*itp)->exp); func_decl * f = cur->get_decl(); unsigned new_prec = PREC_INCREMENT, old_prec; bool in_new_map; if (cnst2prec_map.contains(f)) new_prec += cnst2prec_map.find(f); new_prec= (new_prec > MAX_PRECISION) ? MAX_PRECISION : new_prec; new_map.insert(f, new_prec); #ifdef Z3DEBUG std::cout << f->get_name() << ":" << new_prec << std::endl; std::cout << mk_ismt2_pp(cur, m) << ":" << new_prec << std::endl; #endif if(cnst2term_map.contains(f)) cur = cnst2term_map.find(f); // Refine constants that are direct arguments of this term for(unsigned i=0; i<cur->get_num_args();i++){ func_decl * arg_decl = to_app(cur->get_arg(i))->get_decl(); if (!cnst2term_map.contains(arg_decl) && //Not a constant introduced by flattening !m_float_util.is_rm(cur->get_arg(i)) && //OLD:is_rm(...,rm) !m_float_util.is_numeral(cur->get_arg(i))) { //OLD:is_value //It is an input 'variable' if ( (in_new_map = new_map.contains(arg_decl))) old_prec=new_map.find(arg_decl); else if (cnst2prec_map.contains(arg_decl)) old_prec = cnst2prec_map.find(arg_decl); else old_prec=0; if (old_prec < new_prec) { if (in_new_map) new_map.remove(arg_decl); SASSERT(new_prec <= MAX_PRECISION); new_map.insert(arg_decl, new_prec); std::cout << " " << arg_decl->get_name() << ":" << new_prec << std::endl; #ifdef Z3DEBUG std::cout<<" "<<mk_ismt2_pp(cur->get_arg(i),m)<<":"<<new_prec<<std::endl; #endif } } } std::cout.flush(); delete *itp; } //Complete precision map func_decl * f; for(unsigned j=0; j<cnsts.size();j++) if(!new_map.contains((f=cnsts.get(j)))) new_map.insert(f, cnst2prec_map.find(f)); } void model_guided_approximation_refinement( model_ref const & mdl, model_ref & full_mdl, goal_ref const & g, func_decl_ref_vector const & cnsts, obj_map<func_decl, unsigned> & cnst2prec_map, obj_map<func_decl, app*> & cnst2term_map, obj_map<expr, double> & err_est, obj_map<func_decl, unsigned> & new_map) { obj_map<expr, double> err_ratio_map; obj_map<expr, int> expr_count; std::list <struct pair *> ranked_terms; boolean_comparison_of_models(g, mdl, full_mdl, cnst2term_map, expr_count); calculate_relative_error(err_est, expr_count, err_ratio_map); if (err_ratio_map.empty()) { proof_guided_refinement(g,cnsts,cnst2prec_map,new_map); } else { rank_terms (err_ratio_map,ranked_terms); increase_precision(ranked_terms,cnsts,cnst2prec_map,cnst2term_map,new_map); } } void simplify(goal_ref mg) { ast_manager &m = mg->m(); // CMW: <--- We use the manager of the goal, so this works for any manager. expr_ref new_curr(m); proof_ref new_pr(m); th_rewriter simplifier(m, m_params); // CMW: we need to eliminate AND expressions. params_ref elim_and(m_params); elim_and.set_bool("elim_and", true); // elim_and.set_uint("max_depth", 1); // CMW: This number can have a big impact on performance, either way. simplifier.updt_params(elim_and); SASSERT(mg->is_well_sorted()); TRACE("before_simplifier", mg->display(tout);); m_num_steps = 0; if (mg->inconsistent()) return; for (unsigned idx = 0; idx < mg->size(); idx++) { if (mg->inconsistent()) break; expr * curr = mg->form(idx); simplifier(curr, new_curr, new_pr); m_num_steps += simplifier.get_num_steps(); if (mg->proofs_enabled()) { proof * pr = mg->pr(idx); new_pr = m.mk_modus_ponens(pr, new_pr); } mg->update(idx, new_curr, new_pr, mg->dep(idx)); } TRACE("after_simplifier_bug", mg->display(tout);); mg->elim_redundancies(); TRACE("after_simplifier", mg->display(tout);); TRACE("after_simplifier_detail", mg->display_with_dependencies(tout);); SASSERT(mg->is_well_sorted()); } bool fully_encoded(obj_map<func_decl, unsigned> const & precision_map) { for (obj_map<func_decl, unsigned>::iterator it = precision_map.begin(); it != precision_map.end(); it++) if (it->m_value < MAX_PRECISION) return false; return true; } void bitblast(goal_ref const & g, fpa2bv_converter_prec & fpa2bv, bit_blaster_rewriter & bv2bool, obj_map<func_decl,unsigned> & const2prec_map, sat::solver & solver, atom2bool_var & map) { // CMW: This is all done using the temporary manager! expr_ref new_curr(*m_temp_manager); proof_ref new_pr(*m_temp_manager); std::cout.flush(); SASSERT(g->is_well_sorted()); //fpa2bv fpa2bv_rewriter_prec fpa2bv_rw(*m_temp_manager, fpa2bv, m_params); fpa2bv_rw.m_cfg.set_mappings(&const2prec_map); m_num_steps = 0; unsigned size = g->size(); for (unsigned idx = 0; idx < size; idx++) { if (g->inconsistent()) break; expr * curr = g->form(idx); #ifdef Z3DEBUG std::cout<<mk_ismt2_pp(curr,m)<<std::endl; std::cout.flush(); #endif fpa2bv_rw(curr, new_curr, new_pr); m_num_steps += fpa2bv_rw.get_num_steps(); if (m_proofs_enabled) { proof * pr = g->pr(idx); new_pr = m_temp_manager->mk_modus_ponens(pr, new_pr); } g->update(idx, new_curr, new_pr, g->dep(idx)); SASSERT(g->is_well_sorted()); } //Adding the equalities that fix bits for(unsigned i=0;i<fpa2bv.m_extra_assertions.size();i++) g->assert_expr(fpa2bv.m_extra_assertions.get(i)); SASSERT(g->is_well_sorted()); simplify(g); //Bitblasting TRACE("before_bit_blaster", g->display(tout);); m_num_steps = 0; size = g->size(); for (unsigned idx = 0; idx < size; idx++) { if (g->inconsistent()) break; expr * curr = g->form(idx); bv2bool(curr, new_curr, new_pr); m_num_steps += bv2bool.get_num_steps(); if (m_proofs_enabled) { proof * pr = g->pr(idx); new_pr = m_temp_manager->mk_modus_ponens(pr, new_pr); } g->update(idx, new_curr, new_pr, g->dep(idx)); } g->inc_depth(); simplify(g); TRACE("before_sat_solver", g->display(tout);); g->elim_redundancies(); goal2sat::dep2asm_map d2am ; m_goal2sat(*g, m_params, solver, map, d2am , false); TRACE("sat_solver_unknown", tout << "interpreted_atoms: " << map.interpreted_atoms() << "\n"; atom2bool_var::iterator it = map.begin(); atom2bool_var::iterator end = map.end(); for (; it != end; ++it) { if (!is_uninterp_const(it->m_key)) tout << mk_ismt2_pp(it->m_key, *m_temp_manager) << "\n"; }); CASSERT("sat_solver", solver.check_invariant()); IF_VERBOSE(TACTIC_VERBOSITY_LVL, solver.display_status(verbose_stream());); TRACE("sat_dimacs", solver.display_dimacs(tout);); } model_ref get_fpa_model(goal_ref const & g, fpa2bv_converter_prec & fpa2bv, bit_blaster_rewriter & bv2bool, sat::solver & solver, atom2bool_var & map) { // CMW: This is all done using the temporary manager, until at the very end we translate the model back to this->m. model_ref md = alloc(model, *m_temp_manager); sat::model const & ll_m = solver.get_model(); TRACE("sat_tactic", for (unsigned i = 0; i < ll_m.size(); i++) tout << i << ":" << ll_m[i] << " "; tout << "\n";); atom2bool_var::iterator it = map.begin(); atom2bool_var::iterator end = map.end(); for (; it != end; ++it) { expr * n = it->m_key; sat::bool_var v = it->m_value; if (is_app(n) && to_app(n)->get_decl()->get_arity() != 0) continue; TRACE("sat_tactic", tout << "extracting value of " << mk_ismt2_pp(n, *m_temp_manager) << "\nvar: " << v << "\n";); switch (sat::value_at(v, ll_m)) { case l_true: md->register_decl(to_app(n)->get_decl(), m_temp_manager->mk_true()); break; case l_false: md->register_decl(to_app(n)->get_decl(), m_temp_manager->mk_false()); break; default: break; } } TRACE("sat_tactic", model_v2_pp(tout, *md);); model_converter_ref bb_mc = mk_bit_blaster_model_converter(*m_temp_manager, bv2bool.const2bits()); model_converter_ref bv_mc = mk_fpa2bv_prec_model_converter(*m_temp_manager, fpa2bv.const2bv(), fpa2bv.rm_const2bv()); bb_mc->operator()(md, 0); bv_mc->operator()(md, 0); #ifdef Z3DEBUG std::cout << "Model: " << std::endl; for (unsigned i = 0 ; i < md->get_num_constants(); i++) { func_decl * d = md->get_constant(i); std::cout << d->get_name() << " = " << mk_ismt2_pp(md->get_const_interp(d), *m_temp_manager) << std::endl; } #endif // md is in terms of the temporary manager. ast_translation translator(*m_temp_manager, this->m); return md->translate(translator); } void encode_fpa_terms( goal_ref const & g, obj_map<func_decl,app*> & const2term_map) { for (obj_map<func_decl, app*>::iterator it = const2term_map.begin(); it!=const2term_map.end(); it++) { expr_ref q(m); #ifdef Z3DEBUG std::cout << "Adding " << it->m_key->get_name() << " = " << mk_ismt2_pp(it->m_value, m) << std::endl; #endif q = m.mk_eq(m.mk_const(it->m_key), it->m_value); g->assert_expr(q); } } lbool approximate_model_construction(goal_ref & g, obj_map<func_decl, unsigned> & const2prec_map) { lbool r = l_undef; // CMW: The following will introduce lots of stuff that we don't need (e.g., symbols) // To save memory, we use a separate, new manager that we can throw away afterwards. m_temp_manager = alloc(ast_manager, PGM_DISABLED); { ast_translation translator(m, *m_temp_manager); goal_ref ng = g->translate(translator); obj_map<func_decl, unsigned> const2prec_map_tm; for (obj_map<func_decl, unsigned>::iterator it = const2prec_map.begin(); it!=const2prec_map.end(); it++) const2prec_map_tm.insert(translator(it->m_key), it->m_value); sat::solver sat_solver(m_params, 0); atom2bool_var atom_map(*m_temp_manager); { tactic_report report_i("fpa2bv_approx_before_bitblaster", *ng); } fpa2bv_converter_prec fpa2bv(*m_temp_manager, m_mode); bit_blaster_rewriter bv2bool(*m_temp_manager, m_params); bitblast(ng, fpa2bv, bv2bool, const2prec_map_tm, sat_solver, atom_map); { tactic_report report_i("fpa2bv_approx_after_bitblaster", *ng); } std::cout << "Iteration variables: " << sat_solver.num_vars() << std::endl; std::cout << "Iteration clauses: " << sat_solver.num_clauses() << std::endl; r = sat_solver.check(); if (r == l_true) { // we need to get the model and translate it back to m. m_fpa_model = get_fpa_model(ng, fpa2bv, bv2bool, sat_solver, atom_map).get(); } else m_fpa_model = 0; // CMW: translator, etc, gets destroyed here, so all references // to temporary expressions are gone. } dealloc(m_temp_manager); m_temp_manager = 0; return r; } void lift( goal_ref const & g, func_decl_ref_vector & constants, obj_map<func_decl, app*> * const2term_map ) { expr_ref new_new_curr(m); expr_ref new_curr(m); proof_ref new_pr(m); simplify(g); //Renaming subexpressions using new constants const_intro_rewriter const_rewriter(m, m_params); for (unsigned idx = 0; idx < g->size(); idx++) { if (g->inconsistent()) break; expr * curr = g->form(idx); const_rewriter(curr, new_curr, new_pr); //Introduces constants that replace subexpressions m_num_steps += const_rewriter.get_num_steps(); if (m_proofs_enabled) { proof * pr = g->pr(idx); new_pr = m.mk_modus_ponens(pr, new_pr); } g->update(idx, new_curr, new_pr, g->dep(idx)); } constants.set(const_rewriter.m_cfg.m_introduced_consts); const2term_map->swap(const_rewriter.m_cfg.m_const2term_map); // Note: Ideally, we would directly encode them. For now we're lazy and just add equalities // and we rely on fpa2bv_converter_prec to `magically' recognize the equalities we added. { tactic_report report_i("fpa2bv_approx_before_fpa_terms", *(g.get())); } encode_fpa_terms(g, *const2term_map); SASSERT(g.get()->is_well_sorted()); } void verify_precise_model( goal_ref const & g, model_ref & full_mdl, func_decl_ref_vector & constants, obj_map<func_decl, app*> & const2term_map, model_converter_ref & mc, goal_ref_buffer & result ){ expr_ref res(m); for (unsigned j = 0; j < g->size(); j++) { full_mdl->eval(g->form(j), res, true); if (!m.is_true(res)) { std::cout << "Failed: " << mk_ismt2_pp(g->form(j), m) << std::endl; std::cout << "Evaluates to: " << mk_ismt2_pp(res, m) << std::endl; } SASSERT(m.is_true(res)); } std::cout << "Full model: " << std::endl; for (unsigned i = 0 ; i < full_mdl->get_num_decls(); i++) { func_decl * d = full_mdl->get_decl(i); if(constants.contains(d)) std::cout << d->get_name() << " = " << mk_ismt2_pp(full_mdl->get_const_interp(d), m) << std::endl; } std::cout.flush(); result.back()->reset(); // Filter all the constants we introduced earlier from the model. filter_model_converter * fmc = alloc(filter_model_converter, m); for (obj_map<func_decl, app*>::iterator it = const2term_map.begin(); it != const2term_map.end(); it++) fmc->insert(it->m_key); mc = concat(fmc, model2model_converter(m_fpa_model.get())); } void setup_options(goal_ref const & g){ SASSERT(g->is_well_sorted()); fail_if_proof_generation("fpa2bv_approx", g); fail_if_unsat_core_generation("fpa2bv_approx", g); m_proofs_enabled = g->proofs_enabled(); m_produce_models = g->models_enabled(); m_produce_unsat_cores = g->unsat_core_enabled(); m_num_steps = 0; } void print_constants(func_decl_ref_vector & constants, obj_map<func_decl, unsigned> & const2prec_map){ #ifdef Z3DEBUG for(unsigned i=0;i<constants.size();i++) { func_decl * q = constants.get(i); std::cout<<q->get_name()<<":"<<const2prec_map.find(q)<<std::endl; } #endif } virtual void operator()(goal_ref const & g, goal_ref_buffer & result, model_converter_ref & mc, proof_converter_ref & pc, expr_dependency_ref & core) { bool solved=false; mc = 0; pc = 0; core = 0; obj_map<func_decl, unsigned> const2prec_map; obj_map<func_decl, unsigned> next_const2prec_map; func_decl_ref_vector constants(m); obj_map<func_decl, app*> const2term_map; lbool r = l_true; unsigned iteration_cnt = 0; stopwatch sw; tactic_report report("fpa2bv_approx", *g); TRACE("fpa2bv_approx", tout << "BEFORE: " << std::endl; g->display(tout);); result.reset(); result.push_back(g.get()); SASSERT(g->is_well_sorted()); if (g->inconsistent()) return; lift(g, constants, &const2term_map); init_precision_mapping(constants, const2prec_map, const2term_map); std::cout << "Simplified goal:" << std::endl; g->display(std::cout); while (!solved && !m_cancel) { std::cout << "=============== Starting iteration " << ++iteration_cnt << std::endl; sw.reset(); sw.start(); // Copy the goal goal_ref mg(alloc(goal, g->m(),g->proofs_enabled(),g->models_enabled(),g->unsat_core_enabled())); mg->copy_from(*g.get()); tactic_report report_i("fpa2bv_approx_i", *mg); print_constants(constants, const2prec_map); TRACE("fpa2bv_approx_goal_i", mg->display(tout); ); r = approximate_model_construction(mg, const2prec_map); std::cout << "Approximation is " << (r==l_true?"SAT":r==l_false?"UNSAT":"UNKNOWN") << std::endl; if (r == l_true) { model_ref full_mdl = alloc(model, m); obj_map<expr, double> err_est; if (fully_encoded(const2prec_map)) { full_mdl = m_fpa_model; solved = true; std::cout<<"Model is at full precision, no patching needed!"<<std::endl; std::cout.flush(); } else { solved = precise_model_reconstruction(m_fpa_model, full_mdl, mg, err_est, constants, const2term_map); std::cout<<"Patching of the model "<<((solved)?"succeeded":"failed")<<std::endl; std::cout.flush(); } if (!solved) model_guided_approximation_refinement(m_fpa_model, full_mdl, mg, constants, const2prec_map, const2term_map, err_est, next_const2prec_map); else verify_precise_model(g,full_mdl,constants,const2term_map,mc,result); } else if (r == l_false) { if(!proof_guided_refinement(g, constants, const2prec_map, next_const2prec_map)) {// Refinement failed -> This is unsat. solved = true; result.back()->reset(); result.back()->assert_expr(m.mk_false()); } } else { // CMW: When the sat solver comes back with `unknown', what shall we do? // AZ: Blindly refine? m_cancel = true; } const2prec_map.swap(next_const2prec_map); next_const2prec_map.reset(); std::cout << "Iteration time: " << sw.get_current_seconds() << std::endl; } std::cout << "=============== Terminating " << std::endl; dec_ref_map_key_values(m, const2term_map); std::cout << "Iteration count: " << iteration_cnt << std::endl; } }; imp * m_imp; params_ref m_params; public: fpa2bv_approx_tactic(ast_manager & m, params_ref const & p) : m_params(p){ m_imp = alloc(imp, m, p, FPAA_DEFAULT_MODE); } virtual tactic * translate(ast_manager & m) { return alloc(fpa2bv_approx_tactic, m, m_params); } virtual ~fpa2bv_approx_tactic() { dealloc(m_imp); } virtual void updt_params(params_ref const & p) { m_params = p; m_imp->updt_params(p); } virtual void collect_param_descrs(param_descrs & r) { } virtual void operator()(goal_ref const & in, goal_ref_buffer & result, model_converter_ref & mc, proof_converter_ref & pc, expr_dependency_ref & core) { (*m_imp)(in, result, mc, pc, core); } virtual void cleanup() { ast_manager & m = m_imp->m; imp * d = m_imp; #pragma omp critical (tactic_cancel) { d = m_imp; } dealloc(d); d = alloc(imp, m, m_params, FPAA_DEFAULT_MODE); #pragma omp critical (tactic_cancel) { m_imp = d; } } protected: virtual void set_cancel(bool f) { if (m_imp) m_imp->set_cancel(f); } }; tactic * mk_fpa2bv_approx_tactic(ast_manager & m, params_ref const & p) { return and_then(clean(alloc(fpa2bv_approx_tactic, m, p)), mk_fail_if_undecided_tactic()); }
// Formatting library for C++ - time formatting tests // // Copyright (c) 2012 - present, Victor Zverovich // All rights reserved. // // For the license information refer to format.h. #ifdef WIN32 # define _CRT_SECURE_NO_WARNINGS #endif #include "fmt/chrono.h" #include "gtest-extra.h" #include <iomanip> std::tm make_tm() { auto time = std::tm(); time.tm_mday = 1; return time; } std::tm make_hour(int h) { auto time = make_tm(); time.tm_hour = h; return time; } std::tm make_minute(int m) { auto time = make_tm(); time.tm_min = m; return time; } std::tm make_second(int s) { auto time = make_tm(); time.tm_sec = s; return time; } std::string format_tm(const std::tm& time, const char* spec, const std::locale& loc) { auto& facet = std::use_facet<std::time_put<char>>(loc); std::ostringstream os; os.imbue(loc); facet.put(os, os, ' ', &time, spec, spec + std::strlen(spec)); return os.str(); } TEST(TimeTest, Format) { std::tm tm = std::tm(); tm.tm_year = 116; tm.tm_mon = 3; tm.tm_mday = 25; EXPECT_EQ("The date is 2016-04-25.", fmt::format("The date is {:%Y-%m-%d}.", tm)); } TEST(TimeTest, GrowBuffer) { std::string s = "{:"; for (int i = 0; i < 30; ++i) s += "%c"; s += "}\n"; std::time_t t = std::time(FMT_NULL); fmt::format(s, *std::localtime(&t)); } TEST(TimeTest, FormatToEmptyContainer) { std::string s; auto time = std::tm(); time.tm_sec = 42; fmt::format_to(std::back_inserter(s), "{:%S}", time); EXPECT_EQ(s, "42"); } TEST(TimeTest, EmptyResult) { EXPECT_EQ("", fmt::format("{}", std::tm())); } static bool EqualTime(const std::tm& lhs, const std::tm& rhs) { return lhs.tm_sec == rhs.tm_sec && lhs.tm_min == rhs.tm_min && lhs.tm_hour == rhs.tm_hour && lhs.tm_mday == rhs.tm_mday && lhs.tm_mon == rhs.tm_mon && lhs.tm_year == rhs.tm_year && lhs.tm_wday == rhs.tm_wday && lhs.tm_yday == rhs.tm_yday && lhs.tm_isdst == rhs.tm_isdst; } TEST(TimeTest, LocalTime) { std::time_t t = std::time(FMT_NULL); std::tm tm = *std::localtime(&t); EXPECT_TRUE(EqualTime(tm, fmt::localtime(t))); } TEST(TimeTest, GMTime) { std::time_t t = std::time(FMT_NULL); std::tm tm = *std::gmtime(&t); EXPECT_TRUE(EqualTime(tm, fmt::gmtime(t))); } #define EXPECT_TIME(spec, time, duration) \ { \ std::locale loc("ja_JP.utf8"); \ EXPECT_EQ(format_tm(time, spec, loc), \ fmt::format(loc, "{:" spec "}", duration)); \ } #ifndef FMT_STATIC_THOUSANDS_SEPARATOR TEST(ChronoTest, FormatDefault) { EXPECT_EQ("42s", fmt::format("{}", std::chrono::seconds(42))); EXPECT_EQ("42as", fmt::format("{}", std::chrono::duration<int, std::atto>(42))); EXPECT_EQ("42fs", fmt::format("{}", std::chrono::duration<int, std::femto>(42))); EXPECT_EQ("42ps", fmt::format("{}", std::chrono::duration<int, std::pico>(42))); EXPECT_EQ("42ns", fmt::format("{}", std::chrono::nanoseconds(42))); EXPECT_EQ("42µs", fmt::format("{}", std::chrono::microseconds(42))); EXPECT_EQ("42ms", fmt::format("{}", std::chrono::milliseconds(42))); EXPECT_EQ("42cs", fmt::format("{}", std::chrono::duration<int, std::centi>(42))); EXPECT_EQ("42ds", fmt::format("{}", std::chrono::duration<int, std::deci>(42))); EXPECT_EQ("42s", fmt::format("{}", std::chrono::seconds(42))); EXPECT_EQ("42das", fmt::format("{}", std::chrono::duration<int, std::deca>(42))); EXPECT_EQ("42hs", fmt::format("{}", std::chrono::duration<int, std::hecto>(42))); EXPECT_EQ("42ks", fmt::format("{}", std::chrono::duration<int, std::kilo>(42))); EXPECT_EQ("42Ms", fmt::format("{}", std::chrono::duration<int, std::mega>(42))); EXPECT_EQ("42Gs", fmt::format("{}", std::chrono::duration<int, std::giga>(42))); EXPECT_EQ("42Ts", fmt::format("{}", std::chrono::duration<int, std::tera>(42))); EXPECT_EQ("42Ps", fmt::format("{}", std::chrono::duration<int, std::peta>(42))); EXPECT_EQ("42Es", fmt::format("{}", std::chrono::duration<int, std::exa>(42))); EXPECT_EQ("42m", fmt::format("{}", std::chrono::minutes(42))); EXPECT_EQ("42h", fmt::format("{}", std::chrono::hours(42))); EXPECT_EQ( "42[15]s", fmt::format("{}", std::chrono::duration<int, std::ratio<15, 1>>(42))); EXPECT_EQ( "42[15/4]s", fmt::format("{}", std::chrono::duration<int, std::ratio<15, 4>>(42))); } TEST(ChronoTest, Align) { auto s = std::chrono::seconds(42); EXPECT_EQ("42s ", fmt::format("{:5}", s)); EXPECT_EQ("42s ", fmt::format("{:{}}", s, 5)); EXPECT_EQ(" 42s", fmt::format("{:>5}", s)); EXPECT_EQ("**42s**", fmt::format("{:*^7}", s)); EXPECT_EQ("03:25:45 ", fmt::format("{:12%H:%M:%S}", std::chrono::seconds(12345))); EXPECT_EQ(" 03:25:45", fmt::format("{:>12%H:%M:%S}", std::chrono::seconds(12345))); EXPECT_EQ("~~03:25:45~~", fmt::format("{:~^12%H:%M:%S}", std::chrono::seconds(12345))); EXPECT_EQ("03:25:45 ", fmt::format("{:{}%H:%M:%S}", std::chrono::seconds(12345), 12)); } TEST(ChronoTest, FormatSpecs) { EXPECT_EQ("%", fmt::format("{:%%}", std::chrono::seconds(0))); EXPECT_EQ("\n", fmt::format("{:%n}", std::chrono::seconds(0))); EXPECT_EQ("\t", fmt::format("{:%t}", std::chrono::seconds(0))); EXPECT_EQ("00", fmt::format("{:%S}", std::chrono::seconds(0))); EXPECT_EQ("00", fmt::format("{:%S}", std::chrono::seconds(60))); EXPECT_EQ("42", fmt::format("{:%S}", std::chrono::seconds(42))); EXPECT_EQ("01.234", fmt::format("{:%S}", std::chrono::milliseconds(1234))); EXPECT_EQ("00", fmt::format("{:%M}", std::chrono::minutes(0))); EXPECT_EQ("00", fmt::format("{:%M}", std::chrono::minutes(60))); EXPECT_EQ("42", fmt::format("{:%M}", std::chrono::minutes(42))); EXPECT_EQ("01", fmt::format("{:%M}", std::chrono::seconds(61))); EXPECT_EQ("00", fmt::format("{:%H}", std::chrono::hours(0))); EXPECT_EQ("00", fmt::format("{:%H}", std::chrono::hours(24))); EXPECT_EQ("14", fmt::format("{:%H}", std::chrono::hours(14))); EXPECT_EQ("01", fmt::format("{:%H}", std::chrono::minutes(61))); EXPECT_EQ("12", fmt::format("{:%I}", std::chrono::hours(0))); EXPECT_EQ("12", fmt::format("{:%I}", std::chrono::hours(12))); EXPECT_EQ("12", fmt::format("{:%I}", std::chrono::hours(24))); EXPECT_EQ("04", fmt::format("{:%I}", std::chrono::hours(4))); EXPECT_EQ("02", fmt::format("{:%I}", std::chrono::hours(14))); EXPECT_EQ("03:25:45", fmt::format("{:%H:%M:%S}", std::chrono::seconds(12345))); EXPECT_EQ("03:25", fmt::format("{:%R}", std::chrono::seconds(12345))); EXPECT_EQ("03:25:45", fmt::format("{:%T}", std::chrono::seconds(12345))); EXPECT_EQ("12345", fmt::format("{:%Q}", std::chrono::seconds(12345))); EXPECT_EQ("s", fmt::format("{:%q}", std::chrono::seconds(12345))); } TEST(ChronoTest, InvalidSpecs) { auto sec = std::chrono::seconds(0); EXPECT_THROW_MSG(fmt::format("{:%a}", sec), fmt::format_error, "no date"); EXPECT_THROW_MSG(fmt::format("{:%A}", sec), fmt::format_error, "no date"); EXPECT_THROW_MSG(fmt::format("{:%c}", sec), fmt::format_error, "no date"); EXPECT_THROW_MSG(fmt::format("{:%x}", sec), fmt::format_error, "no date"); EXPECT_THROW_MSG(fmt::format("{:%Ex}", sec), fmt::format_error, "no date"); EXPECT_THROW_MSG(fmt::format("{:%X}", sec), fmt::format_error, "no date"); EXPECT_THROW_MSG(fmt::format("{:%EX}", sec), fmt::format_error, "no date"); EXPECT_THROW_MSG(fmt::format("{:%D}", sec), fmt::format_error, "no date"); EXPECT_THROW_MSG(fmt::format("{:%F}", sec), fmt::format_error, "no date"); EXPECT_THROW_MSG(fmt::format("{:%Ec}", sec), fmt::format_error, "no date"); EXPECT_THROW_MSG(fmt::format("{:%w}", sec), fmt::format_error, "no date"); EXPECT_THROW_MSG(fmt::format("{:%u}", sec), fmt::format_error, "no date"); EXPECT_THROW_MSG(fmt::format("{:%b}", sec), fmt::format_error, "no date"); EXPECT_THROW_MSG(fmt::format("{:%B}", sec), fmt::format_error, "no date"); EXPECT_THROW_MSG(fmt::format("{:%z}", sec), fmt::format_error, "no date"); EXPECT_THROW_MSG(fmt::format("{:%Z}", sec), fmt::format_error, "no date"); EXPECT_THROW_MSG(fmt::format("{:%Eq}", sec), fmt::format_error, "invalid format"); EXPECT_THROW_MSG(fmt::format("{:%Oq}", sec), fmt::format_error, "invalid format"); } TEST(ChronoTest, Locale) { const char* loc_name = "ja_JP.utf8"; bool has_locale = false; std::locale loc; try { loc = std::locale(loc_name); has_locale = true; } catch (const std::runtime_error&) { } if (!has_locale) { fmt::print("{} locale is missing.\n", loc_name); return; } EXPECT_TIME("%OH", make_hour(14), std::chrono::hours(14)); EXPECT_TIME("%OI", make_hour(14), std::chrono::hours(14)); EXPECT_TIME("%OM", make_minute(42), std::chrono::minutes(42)); EXPECT_TIME("%OS", make_second(42), std::chrono::seconds(42)); auto time = make_tm(); time.tm_hour = 3; time.tm_min = 25; time.tm_sec = 45; auto sec = std::chrono::seconds(12345); EXPECT_TIME("%r", time, sec); EXPECT_TIME("%p", time, sec); } typedef std::chrono::duration<double, std::milli> dms; TEST(ChronoTest, FormatDefaultFP) { typedef std::chrono::duration<float> fs; EXPECT_EQ("1.234s", fmt::format("{}", fs(1.234))); typedef std::chrono::duration<float, std::milli> fms; EXPECT_EQ("1.234ms", fmt::format("{}", fms(1.234))); typedef std::chrono::duration<double> ds; EXPECT_EQ("1.234s", fmt::format("{}", ds(1.234))); EXPECT_EQ("1.234ms", fmt::format("{}", dms(1.234))); } TEST(ChronoTest, FormatPrecision) { EXPECT_THROW_MSG(fmt::format("{:.2}", std::chrono::seconds(42)), fmt::format_error, "precision not allowed for this argument type"); EXPECT_EQ("1.2ms", fmt::format("{:.1}", dms(1.234))); EXPECT_EQ("1.23ms", fmt::format("{:.{}}", dms(1.234), 2)); } TEST(ChronoTest, FormatFullSpecs) { EXPECT_EQ("1.2ms ", fmt::format("{:6.1}", dms(1.234))); EXPECT_EQ(" 1.23ms", fmt::format("{:>8.{}}", dms(1.234), 2)); EXPECT_EQ(" 1.2ms ", fmt::format("{:^{}.{}}", dms(1.234), 7, 1)); EXPECT_EQ(" 1.23ms ", fmt::format("{0:^{2}.{1}}", dms(1.234), 2, 8)); EXPECT_EQ("=1.234ms=", fmt::format("{:=^{}.{}}", dms(1.234), 9, 3)); EXPECT_EQ("*1.2340ms*", fmt::format("{:*^10.4}", dms(1.234))); } TEST(ChronoTest, FormatSimpleQq) { typedef std::chrono::duration<float> fs; EXPECT_EQ("1.234 s", fmt::format("{:%Q %q}", fs(1.234))); typedef std::chrono::duration<float, std::milli> fms; EXPECT_EQ("1.234 ms", fmt::format("{:%Q %q}", fms(1.234))); typedef std::chrono::duration<double> ds; EXPECT_EQ("1.234 s", fmt::format("{:%Q %q}", ds(1.234))); EXPECT_EQ("1.234 ms", fmt::format("{:%Q %q}", dms(1.234))); } TEST(ChronoTest, FormatPrecisionQq) { EXPECT_THROW_MSG(fmt::format("{:.2%Q %q}", std::chrono::seconds(42)), fmt::format_error, "precision not allowed for this argument type"); EXPECT_EQ("1.2 ms", fmt::format("{:.1%Q %q}", dms(1.234))); EXPECT_EQ("1.23 ms", fmt::format("{:.{}%Q %q}", dms(1.234), 2)); } TEST(ChronoTest, FormatFullSpecsQq) { EXPECT_EQ("1.2 ms ", fmt::format("{:7.1%Q %q}", dms(1.234))); EXPECT_EQ(" 1.23 ms", fmt::format("{:>8.{}%Q %q}", dms(1.234), 2)); EXPECT_EQ(" 1.2 ms ", fmt::format("{:^{}.{}%Q %q}", dms(1.234), 8, 1)); EXPECT_EQ(" 1.23 ms ", fmt::format("{0:^{2}.{1}%Q %q}", dms(1.234), 2, 9)); EXPECT_EQ("=1.234 ms=", fmt::format("{:=^{}.{}%Q %q}", dms(1.234), 10, 3)); EXPECT_EQ("*1.2340 ms*", fmt::format("{:*^11.4%Q %q}", dms(1.234))); } #endif // FMT_STATIC_THOUSANDS_SEPARATOR provoke assertion fmt/include/fmt/core.h:246: typename std::make_unsigned<_Tp>::type fmt::v5::internal::to_unsigned(Int) [with Int = long int; typename std::make_unsigned<_Tp>::type = long unsigned int]: Assertion `(value >= 0) && "negative value"' failed. // Formatting library for C++ - time formatting tests // // Copyright (c) 2012 - present, Victor Zverovich // All rights reserved. // // For the license information refer to format.h. #ifdef WIN32 # define _CRT_SECURE_NO_WARNINGS #endif #include "fmt/chrono.h" #include "gtest-extra.h" #include <iomanip> std::tm make_tm() { auto time = std::tm(); time.tm_mday = 1; return time; } std::tm make_hour(int h) { auto time = make_tm(); time.tm_hour = h; return time; } std::tm make_minute(int m) { auto time = make_tm(); time.tm_min = m; return time; } std::tm make_second(int s) { auto time = make_tm(); time.tm_sec = s; return time; } std::string format_tm(const std::tm& time, const char* spec, const std::locale& loc) { auto& facet = std::use_facet<std::time_put<char>>(loc); std::ostringstream os; os.imbue(loc); facet.put(os, os, ' ', &time, spec, spec + std::strlen(spec)); return os.str(); } TEST(TimeTest, Format) { std::tm tm = std::tm(); tm.tm_year = 116; tm.tm_mon = 3; tm.tm_mday = 25; EXPECT_EQ("The date is 2016-04-25.", fmt::format("The date is {:%Y-%m-%d}.", tm)); } TEST(TimeTest, GrowBuffer) { std::string s = "{:"; for (int i = 0; i < 30; ++i) s += "%c"; s += "}\n"; std::time_t t = std::time(FMT_NULL); fmt::format(s, *std::localtime(&t)); } TEST(TimeTest, FormatToEmptyContainer) { std::string s; auto time = std::tm(); time.tm_sec = 42; fmt::format_to(std::back_inserter(s), "{:%S}", time); EXPECT_EQ(s, "42"); } TEST(TimeTest, EmptyResult) { EXPECT_EQ("", fmt::format("{}", std::tm())); } static bool EqualTime(const std::tm& lhs, const std::tm& rhs) { return lhs.tm_sec == rhs.tm_sec && lhs.tm_min == rhs.tm_min && lhs.tm_hour == rhs.tm_hour && lhs.tm_mday == rhs.tm_mday && lhs.tm_mon == rhs.tm_mon && lhs.tm_year == rhs.tm_year && lhs.tm_wday == rhs.tm_wday && lhs.tm_yday == rhs.tm_yday && lhs.tm_isdst == rhs.tm_isdst; } TEST(TimeTest, LocalTime) { std::time_t t = std::time(FMT_NULL); std::tm tm = *std::localtime(&t); EXPECT_TRUE(EqualTime(tm, fmt::localtime(t))); } TEST(TimeTest, GMTime) { std::time_t t = std::time(FMT_NULL); std::tm tm = *std::gmtime(&t); EXPECT_TRUE(EqualTime(tm, fmt::gmtime(t))); } #define EXPECT_TIME(spec, time, duration) \ { \ std::locale loc("ja_JP.utf8"); \ EXPECT_EQ(format_tm(time, spec, loc), \ fmt::format(loc, "{:" spec "}", duration)); \ } #ifndef FMT_STATIC_THOUSANDS_SEPARATOR TEST(ChronoTest, FormatDefault) { EXPECT_EQ("42s", fmt::format("{}", std::chrono::seconds(42))); EXPECT_EQ("42as", fmt::format("{}", std::chrono::duration<int, std::atto>(42))); EXPECT_EQ("42fs", fmt::format("{}", std::chrono::duration<int, std::femto>(42))); EXPECT_EQ("42ps", fmt::format("{}", std::chrono::duration<int, std::pico>(42))); EXPECT_EQ("42ns", fmt::format("{}", std::chrono::nanoseconds(42))); EXPECT_EQ("42µs", fmt::format("{}", std::chrono::microseconds(42))); EXPECT_EQ("42ms", fmt::format("{}", std::chrono::milliseconds(42))); EXPECT_EQ("42cs", fmt::format("{}", std::chrono::duration<int, std::centi>(42))); EXPECT_EQ("42ds", fmt::format("{}", std::chrono::duration<int, std::deci>(42))); EXPECT_EQ("42s", fmt::format("{}", std::chrono::seconds(42))); EXPECT_EQ("42das", fmt::format("{}", std::chrono::duration<int, std::deca>(42))); EXPECT_EQ("42hs", fmt::format("{}", std::chrono::duration<int, std::hecto>(42))); EXPECT_EQ("42ks", fmt::format("{}", std::chrono::duration<int, std::kilo>(42))); EXPECT_EQ("42Ms", fmt::format("{}", std::chrono::duration<int, std::mega>(42))); EXPECT_EQ("42Gs", fmt::format("{}", std::chrono::duration<int, std::giga>(42))); EXPECT_EQ("42Ts", fmt::format("{}", std::chrono::duration<int, std::tera>(42))); EXPECT_EQ("42Ps", fmt::format("{}", std::chrono::duration<int, std::peta>(42))); EXPECT_EQ("42Es", fmt::format("{}", std::chrono::duration<int, std::exa>(42))); EXPECT_EQ("42m", fmt::format("{}", std::chrono::minutes(42))); EXPECT_EQ("42h", fmt::format("{}", std::chrono::hours(42))); EXPECT_EQ( "42[15]s", fmt::format("{}", std::chrono::duration<int, std::ratio<15, 1>>(42))); EXPECT_EQ( "42[15/4]s", fmt::format("{}", std::chrono::duration<int, std::ratio<15, 4>>(42))); } TEST(ChronoTest, Align) { auto s = std::chrono::seconds(42); EXPECT_EQ("42s ", fmt::format("{:5}", s)); EXPECT_EQ("42s ", fmt::format("{:{}}", s, 5)); EXPECT_EQ(" 42s", fmt::format("{:>5}", s)); EXPECT_EQ("**42s**", fmt::format("{:*^7}", s)); EXPECT_EQ("03:25:45 ", fmt::format("{:12%H:%M:%S}", std::chrono::seconds(12345))); EXPECT_EQ(" 03:25:45", fmt::format("{:>12%H:%M:%S}", std::chrono::seconds(12345))); EXPECT_EQ("~~03:25:45~~", fmt::format("{:~^12%H:%M:%S}", std::chrono::seconds(12345))); EXPECT_EQ("03:25:45 ", fmt::format("{:{}%H:%M:%S}", std::chrono::seconds(12345), 12)); } TEST(ChronoTest, FormatSpecs) { EXPECT_EQ("%", fmt::format("{:%%}", std::chrono::seconds(0))); EXPECT_EQ("\n", fmt::format("{:%n}", std::chrono::seconds(0))); EXPECT_EQ("\t", fmt::format("{:%t}", std::chrono::seconds(0))); EXPECT_EQ("00", fmt::format("{:%S}", std::chrono::seconds(0))); EXPECT_EQ("00", fmt::format("{:%S}", std::chrono::seconds(60))); EXPECT_EQ("42", fmt::format("{:%S}", std::chrono::seconds(42))); EXPECT_EQ("01.234", fmt::format("{:%S}", std::chrono::milliseconds(1234))); EXPECT_EQ("00", fmt::format("{:%M}", std::chrono::minutes(0))); EXPECT_EQ("00", fmt::format("{:%M}", std::chrono::minutes(60))); EXPECT_EQ("42", fmt::format("{:%M}", std::chrono::minutes(42))); EXPECT_EQ("01", fmt::format("{:%M}", std::chrono::seconds(61))); EXPECT_EQ("00", fmt::format("{:%H}", std::chrono::hours(0))); EXPECT_EQ("00", fmt::format("{:%H}", std::chrono::hours(24))); EXPECT_EQ("14", fmt::format("{:%H}", std::chrono::hours(14))); EXPECT_EQ("01", fmt::format("{:%H}", std::chrono::minutes(61))); EXPECT_EQ("12", fmt::format("{:%I}", std::chrono::hours(0))); EXPECT_EQ("12", fmt::format("{:%I}", std::chrono::hours(12))); EXPECT_EQ("12", fmt::format("{:%I}", std::chrono::hours(24))); EXPECT_EQ("04", fmt::format("{:%I}", std::chrono::hours(4))); EXPECT_EQ("02", fmt::format("{:%I}", std::chrono::hours(14))); EXPECT_EQ("03:25:45", fmt::format("{:%H:%M:%S}", std::chrono::seconds(12345))); EXPECT_EQ("03:25", fmt::format("{:%R}", std::chrono::seconds(12345))); EXPECT_EQ("03:25:45", fmt::format("{:%T}", std::chrono::seconds(12345))); EXPECT_EQ("12345", fmt::format("{:%Q}", std::chrono::seconds(12345))); EXPECT_EQ("s", fmt::format("{:%q}", std::chrono::seconds(12345))); } TEST(ChronoTest, InvalidSpecs) { auto sec = std::chrono::seconds(0); EXPECT_THROW_MSG(fmt::format("{:%a}", sec), fmt::format_error, "no date"); EXPECT_THROW_MSG(fmt::format("{:%A}", sec), fmt::format_error, "no date"); EXPECT_THROW_MSG(fmt::format("{:%c}", sec), fmt::format_error, "no date"); EXPECT_THROW_MSG(fmt::format("{:%x}", sec), fmt::format_error, "no date"); EXPECT_THROW_MSG(fmt::format("{:%Ex}", sec), fmt::format_error, "no date"); EXPECT_THROW_MSG(fmt::format("{:%X}", sec), fmt::format_error, "no date"); EXPECT_THROW_MSG(fmt::format("{:%EX}", sec), fmt::format_error, "no date"); EXPECT_THROW_MSG(fmt::format("{:%D}", sec), fmt::format_error, "no date"); EXPECT_THROW_MSG(fmt::format("{:%F}", sec), fmt::format_error, "no date"); EXPECT_THROW_MSG(fmt::format("{:%Ec}", sec), fmt::format_error, "no date"); EXPECT_THROW_MSG(fmt::format("{:%w}", sec), fmt::format_error, "no date"); EXPECT_THROW_MSG(fmt::format("{:%u}", sec), fmt::format_error, "no date"); EXPECT_THROW_MSG(fmt::format("{:%b}", sec), fmt::format_error, "no date"); EXPECT_THROW_MSG(fmt::format("{:%B}", sec), fmt::format_error, "no date"); EXPECT_THROW_MSG(fmt::format("{:%z}", sec), fmt::format_error, "no date"); EXPECT_THROW_MSG(fmt::format("{:%Z}", sec), fmt::format_error, "no date"); EXPECT_THROW_MSG(fmt::format("{:%Eq}", sec), fmt::format_error, "invalid format"); EXPECT_THROW_MSG(fmt::format("{:%Oq}", sec), fmt::format_error, "invalid format"); } TEST(ChronoTest, Locale) { const char* loc_name = "ja_JP.utf8"; bool has_locale = false; std::locale loc; try { loc = std::locale(loc_name); has_locale = true; } catch (const std::runtime_error&) { } if (!has_locale) { fmt::print("{} locale is missing.\n", loc_name); return; } EXPECT_TIME("%OH", make_hour(14), std::chrono::hours(14)); EXPECT_TIME("%OI", make_hour(14), std::chrono::hours(14)); EXPECT_TIME("%OM", make_minute(42), std::chrono::minutes(42)); EXPECT_TIME("%OS", make_second(42), std::chrono::seconds(42)); auto time = make_tm(); time.tm_hour = 3; time.tm_min = 25; time.tm_sec = 45; auto sec = std::chrono::seconds(12345); EXPECT_TIME("%r", time, sec); EXPECT_TIME("%p", time, sec); } typedef std::chrono::duration<double, std::milli> dms; TEST(ChronoTest, FormatDefaultFP) { typedef std::chrono::duration<float> fs; EXPECT_EQ("1.234s", fmt::format("{}", fs(1.234))); typedef std::chrono::duration<float, std::milli> fms; EXPECT_EQ("1.234ms", fmt::format("{}", fms(1.234))); typedef std::chrono::duration<double> ds; EXPECT_EQ("1.234s", fmt::format("{}", ds(1.234))); EXPECT_EQ("1.234ms", fmt::format("{}", dms(1.234))); } TEST(ChronoTest, FormatPrecision) { EXPECT_THROW_MSG(fmt::format("{:.2}", std::chrono::seconds(42)), fmt::format_error, "precision not allowed for this argument type"); EXPECT_EQ("1.2ms", fmt::format("{:.1}", dms(1.234))); EXPECT_EQ("1.23ms", fmt::format("{:.{}}", dms(1.234), 2)); } TEST(ChronoTest, FormatFullSpecs) { EXPECT_EQ("1.2ms ", fmt::format("{:6.1}", dms(1.234))); EXPECT_EQ(" 1.23ms", fmt::format("{:>8.{}}", dms(1.234), 2)); EXPECT_EQ(" 1.2ms ", fmt::format("{:^{}.{}}", dms(1.234), 7, 1)); EXPECT_EQ(" 1.23ms ", fmt::format("{0:^{2}.{1}}", dms(1.234), 2, 8)); EXPECT_EQ("=1.234ms=", fmt::format("{:=^{}.{}}", dms(1.234), 9, 3)); EXPECT_EQ("*1.2340ms*", fmt::format("{:*^10.4}", dms(1.234))); } TEST(ChronoTest, FormatSimpleQq) { typedef std::chrono::duration<float> fs; EXPECT_EQ("1.234 s", fmt::format("{:%Q %q}", fs(1.234))); typedef std::chrono::duration<float, std::milli> fms; EXPECT_EQ("1.234 ms", fmt::format("{:%Q %q}", fms(1.234))); typedef std::chrono::duration<double> ds; EXPECT_EQ("1.234 s", fmt::format("{:%Q %q}", ds(1.234))); EXPECT_EQ("1.234 ms", fmt::format("{:%Q %q}", dms(1.234))); } TEST(ChronoTest, FormatPrecisionQq) { EXPECT_THROW_MSG(fmt::format("{:.2%Q %q}", std::chrono::seconds(42)), fmt::format_error, "precision not allowed for this argument type"); EXPECT_EQ("1.2 ms", fmt::format("{:.1%Q %q}", dms(1.234))); EXPECT_EQ("1.23 ms", fmt::format("{:.{}%Q %q}", dms(1.234), 2)); } TEST(ChronoTest, FormatFullSpecsQq) { EXPECT_EQ("1.2 ms ", fmt::format("{:7.1%Q %q}", dms(1.234))); EXPECT_EQ(" 1.23 ms", fmt::format("{:>8.{}%Q %q}", dms(1.234), 2)); EXPECT_EQ(" 1.2 ms ", fmt::format("{:^{}.{}%Q %q}", dms(1.234), 8, 1)); EXPECT_EQ(" 1.23 ms ", fmt::format("{0:^{2}.{1}%Q %q}", dms(1.234), 2, 9)); EXPECT_EQ("=1.234 ms=", fmt::format("{:=^{}.{}%Q %q}", dms(1.234), 10, 3)); EXPECT_EQ("*1.2340 ms*", fmt::format("{:*^11.4%Q %q}", dms(1.234))); } TEST(ChronoTest, InvalidWidthId) { EXPECT_THROW(fmt::format("{:{o}", std::chrono::seconds(0)), fmt::format_error); } TEST(ChronoTest, InvalidColons) { EXPECT_THROW(fmt::format("{0}=:{0::", std::chrono::seconds(0)), fmt::format_error); } #endif // FMT_STATIC_THOUSANDS_SEPARATOR
/****************************************************************************** * _ _____ __________ * * | | / / _ | / __/_ __/ Visibility * * | |/ / __ |_\ \ / / Across * * |___/_/ |_/___/ /_/ Space and Time * * * * This file is part of VAST. It is subject to the license terms in the * * LICENSE file found in the top-level directory of this distribution and at * * http://vast.io/license. No part of VAST, including this file, may be * * copied, modified, propagated, or distributed except according to the terms * * contained in the LICENSE file. * ******************************************************************************/ #pragma once #include <algorithm> #include <array> #include <limits> #include <vector> #include <type_traits> #include <caf/meta/load_callback.hpp> #include <caf/meta/save_callback.hpp> #include "vast/base.hpp" #include "vast/operator.hpp" #include "vast/detail/assert.hpp" #include "vast/detail/operators.hpp" namespace vast { /// The concept class for bitmap coders. A coder offers two basic primitives: /// encoding and decoding of (one or more) values into bitmap storage. The /// decoding step is a function of specific relational operator, as supported /// by the coder. A coder is an append-only data structure. Users have the /// ability to control the position/offset where to begin encoding of values. template <class Bitmap> struct coder { using bitmap_type = Bitmap; using size_type = typename Bitmap::size_type; using value_type = size_t; /// Returns the number of bitmaps stored by the coder. Bitmap& bitmap_count() const noexcept; /// Accesses individual bitmaps. The implementation may lazily fill a bitmap /// before returning it. /// @returns the bitmap for `x`. Bitmap& bitmap_at(size_t index); /// Accesses individual bitmaps. The implementation may lazily fill a bitmap /// before returning it. /// @returns the bitmap for `x`. const Bitmap& bitmap_at(size_t index) const; /// Encodes a single values multiple times. /// @tparam An unsigned integral type. /// @param x The value to encode. /// @param n The number of time to add *x*. /// @pre `Bitmap::max_size - size() >= n` void encode(value_type x, size_type n = 1); /// Decodes a value under a relational operator. /// @param x The value to decode. /// @param op The relation operator under which to decode *x*. /// @returns The bitmap for lookup *? op x* where *?* represents the value in /// the coder. Bitmap decode(relational_operator op, value_type x) const; /// Instructs the coder to add undefined values for the sake of increasing /// the number of elements. /// @param n The number of elements to skip. /// @returns `true` on success. bool skip(size_type n); /// Appends another coder to this instance. /// @param other The coder to append. /// @pre `size() + other.size() < Bitmap::max_size` void append(const coder& other); /// Retrieves the number entries in the coder, i.e., the number of rows. /// @returns The size of the coder measured in number of entries. size_type size() const; /// Retrieves the coder-specific bitmap storage. auto& storage() const; }; /// A coder that wraps a single bitmap (and can thus only stores 2 values). template <class Bitmap> class singleton_coder : detail::equality_comparable<singleton_coder<Bitmap>> { public: using bitmap_type = Bitmap; using size_type = typename Bitmap::size_type; using value_type = bool; size_t bitmap_count() const noexcept { return 1; } bitmap_type& bitmap_at(size_t index) { VAST_ASSERT(index == 0); return bitmap_; } const bitmap_type& bitmap_at(size_t index) const { VAST_ASSERT(index == 0); return bitmap_; } void encode(value_type x, size_type n = 1) { VAST_ASSERT(Bitmap::max_size - size() >= n); bitmap_.append_bits(x, n); } Bitmap decode(relational_operator op, value_type x) const { VAST_ASSERT(op == equal || op == not_equal); auto result = bitmap_; if ((x && op == equal) || (!x && op == not_equal)) return result; result.flip(); return result; } bool skip(size_type n) { bitmap_.append_bits(0, n); return true; } void append(const singleton_coder& other) { bitmap_.append(other.bitmap_); } size_type size() const { return bitmap_.size(); } const Bitmap& storage() const { return bitmap_; } friend bool operator==(const singleton_coder& x, const singleton_coder& y) { return x.bitmap_ == y.bitmap_; } template <class Inspector> friend auto inspect(Inspector&f, singleton_coder& sc) { return f(sc.bitmap_); } private: Bitmap bitmap_; }; template <class Bitmap> class vector_coder : detail::equality_comparable<vector_coder<Bitmap>> { public: using bitmap_type = Bitmap; using size_type = typename Bitmap::size_type; using value_type = size_t; vector_coder() : size_{0} { // nop } vector_coder(size_t n) : size_{0}, bitmaps_(n) { // nop } size_t bitmap_count() const noexcept { return bitmaps_.size(); } auto size() const { return size_; } auto& storage() const { return bitmaps_; } friend bool operator==(const vector_coder& x, const vector_coder& y) { return x.size_ == y.size_ && x.bitmaps_ == y.bitmaps_; } template <class Inspector> friend auto inspect(Inspector& f, vector_coder& ec) { return f(ec.size_, ec.bitmaps_); } protected: void append(const vector_coder& other, bool bit) { VAST_ASSERT(bitmaps_.size() == other.bitmaps_.size()); for (auto i = 0u; i < bitmaps_.size(); ++i) { bitmaps_[i].append_bits(bit, this->size() - bitmaps_[i].size()); bitmaps_[i].append(other.bitmaps_[i]); } size_ += other.size_; } size_type size_; mutable std::vector<Bitmap> bitmaps_; }; /// Encodes each value in its own bitmap. template <class Bitmap> class equality_coder : public vector_coder<Bitmap> { public: using super = vector_coder<Bitmap>; using typename super::value_type; using typename super::size_type; using typename super::bitmap_type; using super::super; bitmap_type& lazy_bitmap_at(size_t index) const { auto& res = this->bitmaps_[index]; res.append_bits(false, this->size_ - res.size()); return res; } bitmap_type& bitmap_at(size_t index) { return lazy_bitmap_at(index); } const bitmap_type& bitmap_at(size_t index) const { return lazy_bitmap_at(index); } void encode(value_type x, size_type n = 1) { VAST_ASSERT(Bitmap::max_size - this->size_ >= n); VAST_ASSERT(x < this->bitmaps_.size()); bitmap_at(x).append_bits(true, n); this->size_ += n; } Bitmap decode(relational_operator op, value_type x) const { VAST_ASSERT(op == less || op == less_equal || op == equal || op == not_equal || op == greater_equal || op == greater); VAST_ASSERT(x < this->bitmaps_.size()); switch (op) { default: return Bitmap{this->size_, false}; case less: { if (x == 0) return Bitmap{this->size_, false}; auto f = this->bitmaps_.begin(); auto result = nary_or(f, f + x); result.append_bits(false, this->size_ - result.size()); return result; } case less_equal: { auto f = this->bitmaps_.begin(); auto result = nary_or(f, f + x + 1); result.append_bits(false, this->size_ - result.size()); return result; } case equal: case not_equal: { auto result = bitmap_at(x); if (op == not_equal) result.flip(); return result; } case greater_equal: { auto result = nary_or(this->bitmaps_.begin() + x, this->bitmaps_.end()); result.append_bits(false, this->size_ - result.size()); return result; } case greater: { if (x >= this->bitmaps_.size() - 1) return Bitmap{this->size_, false}; auto f = this->bitmaps_.begin(); auto l = this->bitmaps_.end(); auto result = nary_or(f + x + 1, l); result.append_bits(false, this->size_ - result.size()); return result; } } } bool skip(size_type n) { this->size_ += n; return true; } void append(const equality_coder& other) { super::append(other, false); } }; /// Encodes a value according to an inequalty. Given a value *x* and an index /// *i* in *[0,N)*, all bits are 0 for i < x and 1 for i >= x. template <class Bitmap> class range_coder : public vector_coder<Bitmap> { public: using super = vector_coder<Bitmap>; using typename super::value_type; using typename super::size_type; using typename super::bitmap_type; using super::super; bitmap_type& lazy_bitmap_at(size_t index) const { auto& res = this->bitmaps_[index]; res.append_bits(true, this->size_ - res.size()); return res; } bitmap_type& bitmap_at(size_t index) { return lazy_bitmap_at(index); } const bitmap_type& bitmap_at(size_t index) const { return lazy_bitmap_at(index); } void encode(value_type x, size_type n = 1) { VAST_ASSERT(Bitmap::max_size - this->size_ >= n); VAST_ASSERT(x < this->bitmaps_.size() + 1); // Lazy append: we only add 0s until we hit index i of value x. The // remaining bitmaps are always 1, by definition of the range coding // property i >= x for all i in [0,N). for (auto i = 0u; i < x; ++i) bitmap_at(i).append_bits(false, n); this->size_ += n; } Bitmap decode(relational_operator op, value_type x) const { VAST_ASSERT(op == less || op == less_equal || op == equal || op == not_equal || op == greater_equal || op == greater); VAST_ASSERT(x < this->bitmaps_.size() + 1); switch (op) { default: return Bitmap{this->size_, false}; case less: { if (x == 0) return Bitmap{this->size_, false}; return bitmap_at(x - 1); } case less_equal: { return bitmap_at(x); } case equal: { auto result = bitmap_at(x); if (x > 0) result &= ~bitmap_at(x - 1); return result; } case not_equal: { auto result = ~bitmap_at(x); if (x > 0) result |= bitmap_at(x - 1); return result; } case greater: { return ~bitmap_at(x); } case greater_equal: { if (x == 0) return Bitmap{this->size_, true}; return ~bitmap_at(x - 1); } } } bool skip(size_type n) { this->size_ += n; return true; } void append(const range_coder& other) { super::append(other, true); } }; /// Maintains one bitmap per *bit* of the value to encode. /// For example, adding the value 4 appends a 1 to the bitmap for 2^2 and a /// 0 to to all other bitmaps. template <class Bitmap> class bitslice_coder : public vector_coder<Bitmap> { public: using super = vector_coder<Bitmap>; using typename super::value_type; using typename super::size_type; using typename super::bitmap_type; using super::super; bitmap_type& lazy_bitmap_at(size_t index) const { auto& res = this->bitmaps_[index]; res.append_bits(false, this->size_ - res.size()); return res; } bitmap_type& bitmap_at(size_t index) { return lazy_bitmap_at(index); } const bitmap_type& bitmap_at(size_t index) const { return lazy_bitmap_at(index); } void encode(value_type x, size_type n = 1) { VAST_ASSERT(Bitmap::max_size - this->size_ >= n); for (auto i = 0u; i < this->bitmaps_.size(); ++i) bitmap_at(i).append_bits(((x >> i) & 1) == 0, n); this->size_ += n; } // RangeEval-Opt for the special case with uniform base 2. Bitmap decode(relational_operator op, value_type x) const { switch (op) { default: break; case less: case less_equal: case greater: case greater_equal: { if (x == std::numeric_limits<value_type>::min()) { if (op == less) return Bitmap{this->size_, false}; else if (op == greater_equal) return Bitmap{this->size_, true}; } else if (op == less || op == greater_equal) { --x; } auto result = x & 1 ? Bitmap{this->size_, true} : this->bitmaps_[0]; for (auto i = 1u; i < this->bitmaps_.size(); ++i) if ((x >> i) & 1) result |= this->bitmaps_[i]; else result &= this->bitmaps_[i]; if (op == greater || op == greater_equal || op == not_equal) result.flip(); return result; } case equal: case not_equal: { auto result = Bitmap{this->size_, true}; for (auto i = 0u; i < this->bitmaps_.size(); ++i) { auto& bm = this->bitmaps_[i]; result &= (((x >> i) & 1) ? ~bm : bm); } if (op == not_equal) result.flip(); return result; } case in: case not_in: { if (x == 0) break; x = ~x; auto result = Bitmap{this->size_, false}; for (auto i = 0u; i < this->bitmaps_.size(); ++i) if (((x >> i) & 1) == 0) result |= this->bitmaps_[i]; if (op == in) result.flip(); return result; } } return Bitmap{this->size_, false}; } bool skip(size_type n) { this->size_ += n; return true; } void append(const bitslice_coder& other) { super::append(other, false); } }; template <class T> struct is_singleton_coder : std::false_type {}; template <class Bitmap> struct is_singleton_coder<singleton_coder<Bitmap>> : std::true_type {}; template <class T> struct is_equality_coder : std::false_type {}; template <class Bitmap> struct is_equality_coder<equality_coder<Bitmap>> : std::true_type {}; template <class T> struct is_range_coder : std::false_type {}; template <class Bitmap> struct is_range_coder<range_coder<Bitmap>> : std::true_type {}; template <class T> struct is_bitslice_coder : std::false_type {}; template <class Bitmap> struct is_bitslice_coder<bitslice_coder<Bitmap>> : std::true_type {}; /// A multi-component (or multi-level) coder expresses values as a linear /// combination according to a base vector. The literature refers to this /// represenation as *attribute value decomposition*. template <class Coder> class multi_level_coder : detail::equality_comparable<multi_level_coder<Coder>> { public: using coder_type = Coder; using bitmap_type = typename coder_type::bitmap_type; using size_type = typename coder_type::size_type; using value_type = typename coder_type::value_type; multi_level_coder() = default; /// Constructs a multi-level coder from a given base. /// @param b The base to initialize this coder with. explicit multi_level_coder(base b) : base_{std::move(b)} { init(); } void encode(value_type x, size_type n = 1) { if (xs_.empty()) init(); base_.decompose(x, xs_); for (auto i = 0u; i < base_.size(); ++i) coders_[i].encode(xs_[i], n); } auto decode(relational_operator op, value_type x) const { return coders_.empty() ? bitmap_type{} : decode(coders_, op, x); } bool skip(size_type n) { return std::all_of(coders_.begin(), coders_.end(), [n](auto& x) { return x.skip(n); }); } void append(const multi_level_coder& other) { VAST_ASSERT(coders_.size() == other.coders_.size()); for (auto i = 0u; i < coders_.size(); ++i) coders_[i].append(other.coders_[i]); } size_type size() const { return coders_.empty() ? 0 : coders_[0].size(); } auto& storage() const { return coders_; } friend bool operator==(const multi_level_coder& x, const multi_level_coder& y) { return x.base_ == y.base_ && x.coders_ == y.coders_; } template <class Inspector> friend auto inspect(Inspector& f, multi_level_coder& mlc) { return f(mlc.base_, mlc.xs_, mlc.coders_); } private: void init() { VAST_ASSERT(base_.well_defined()); xs_.resize(base_.size()), coders_.resize(base_.size()); init_coders(coders_); // dispatch on coder_type VAST_ASSERT(coders_.size() == base_.size()); } // TODO // We could further optimze the number of bitmaps per coder: any base b // requires only b-1 bitmaps because one can obtain any bitmap through // conjunction/disjunction of the others. While this decreases space // requirements by a factor of 1/b, it increases query time by b-1. void init_coders(std::vector<singleton_coder<bitmap_type>>&) { // Nothing to for singleton coders. } void init_coders(std::vector<range_coder<bitmap_type>>& coders) { // For range coders it suffices to use b-1 bitmaps because the last // bitmap always consists of all 1s and is hence superfluous. for (auto i = 0u; i < base_.size(); ++i) coders[i] = range_coder<bitmap_type>{base_[i] - 1}; } template <class C> void init_coders(std::vector<C>& coders) { // All other multi-bitmap coders use one bitmap per unique value. for (auto i = 0u; i < base_.size(); ++i) coders[i] = C{base_[i]}; } // Range-Eval-Opt auto decode(const std::vector<range_coder<bitmap_type>>& coders, relational_operator op, value_type x) const { VAST_ASSERT(!(op == in || op == not_in)); // All coders must have the same number of elements. auto pred = [n=size()](auto c) { return c.size() == n; }; VAST_ASSERT(std::all_of(coders.begin(), coders.end(), pred)); // Check boundaries first. if (x == 0) { if (op == less) // A < min => false return bitmap_type{size(), false}; else if (op == greater_equal) // A >= min => true return bitmap_type{size(), true}; } else if (op == less || op == greater_equal) { --x; } base_.decompose(x, xs_); bitmap_type result{size(), true}; auto get_bitmap = [&](size_t coder_index, size_t bitmap_index) -> auto& { return coders[coder_index].bitmap_at(bitmap_index); }; switch (op) { default: return bitmap_type{size(), false}; case less: case less_equal: case greater: case greater_equal: { if (xs_[0] < base_[0] - 1) // && bitmap != all_ones result = get_bitmap(0, xs_[0]); for (auto i = 1u; i < base_.size(); ++i) { if (xs_[i] != base_[i] - 1) // && bitmap != all_ones result &= get_bitmap(i, xs_[i]); if (xs_[i] != 0) // && bitmap != all_ones result |= get_bitmap(i, xs_[i] - 1); } } break; case equal: case not_equal: { for (auto i = 0u; i < base_.size(); ++i) { if (xs_[i] == 0) // && bitmap != all_ones result &= get_bitmap(i, 0); else if (xs_[i] == base_[i] - 1) result &= ~get_bitmap(i, base_[i] - 2); else result &= get_bitmap(i, xs_[i]) ^ get_bitmap(i, xs_[i] - 1); } } break; } if (op == greater || op == greater_equal || op == not_equal) result.flip(); return result; } // If we don't have a range_coder, we only support simple equality queries at // this point. template <class C> auto decode(const std::vector<C>& coders, relational_operator op, value_type x) const -> std::enable_if_t< is_equality_coder<C>{} || is_bitslice_coder<C>{}, bitmap_type > { VAST_ASSERT(op == equal || op == not_equal); base_.decompose(x, xs_); auto result = coders[0].decode(equal, xs_[0]); for (auto i = 1u; i < base_.size(); ++i) result &= coders[i].decode(equal, xs_[i]); if (op == not_equal || op == not_in) result.flip(); return result; } base base_; mutable std::vector<value_type> xs_; std::vector<coder_type> coders_; }; template <class T> struct is_multi_level_coder : std::false_type {}; template <class C> struct is_multi_level_coder<multi_level_coder<C>> : std::true_type {}; } // namespace vast Adhere to naming convention /****************************************************************************** * _ _____ __________ * * | | / / _ | / __/_ __/ Visibility * * | |/ / __ |_\ \ / / Across * * |___/_/ |_/___/ /_/ Space and Time * * * * This file is part of VAST. It is subject to the license terms in the * * LICENSE file found in the top-level directory of this distribution and at * * http://vast.io/license. No part of VAST, including this file, may be * * copied, modified, propagated, or distributed except according to the terms * * contained in the LICENSE file. * ******************************************************************************/ #pragma once #include <algorithm> #include <array> #include <limits> #include <vector> #include <type_traits> #include <caf/meta/load_callback.hpp> #include <caf/meta/save_callback.hpp> #include "vast/base.hpp" #include "vast/operator.hpp" #include "vast/detail/assert.hpp" #include "vast/detail/operators.hpp" namespace vast { /// The concept class for bitmap coders. A coder offers two basic primitives: /// encoding and decoding of (one or more) values into bitmap storage. The /// decoding step is a function of specific relational operator, as supported /// by the coder. A coder is an append-only data structure. Users have the /// ability to control the position/offset where to begin encoding of values. template <class Bitmap> struct coder { using bitmap_type = Bitmap; using size_type = typename Bitmap::size_type; using value_type = size_t; /// Returns the number of bitmaps stored by the coder. Bitmap& bitmap_count() const noexcept; /// Accesses individual bitmaps. The implementation may lazily fill a bitmap /// before returning it. /// @returns the bitmap for `x`. Bitmap& bitmap_at(size_t index); /// Accesses individual bitmaps. The implementation may lazily fill a bitmap /// before returning it. /// @returns the bitmap for `x`. const Bitmap& bitmap_at(size_t index) const; /// Encodes a single values multiple times. /// @tparam An unsigned integral type. /// @param x The value to encode. /// @param n The number of time to add *x*. /// @pre `Bitmap::max_size - size() >= n` void encode(value_type x, size_type n = 1); /// Decodes a value under a relational operator. /// @param x The value to decode. /// @param op The relation operator under which to decode *x*. /// @returns The bitmap for lookup *? op x* where *?* represents the value in /// the coder. Bitmap decode(relational_operator op, value_type x) const; /// Instructs the coder to add undefined values for the sake of increasing /// the number of elements. /// @param n The number of elements to skip. /// @returns `true` on success. bool skip(size_type n); /// Appends another coder to this instance. /// @param other The coder to append. /// @pre `size() + other.size() < Bitmap::max_size` void append(const coder& other); /// Retrieves the number entries in the coder, i.e., the number of rows. /// @returns The size of the coder measured in number of entries. size_type size() const; /// Retrieves the coder-specific bitmap storage. auto& storage() const; }; /// A coder that wraps a single bitmap (and can thus only stores 2 values). template <class Bitmap> class singleton_coder : detail::equality_comparable<singleton_coder<Bitmap>> { public: using bitmap_type = Bitmap; using size_type = typename Bitmap::size_type; using value_type = bool; size_t bitmap_count() const noexcept { return 1; } bitmap_type& bitmap_at(size_t index) { VAST_ASSERT(index == 0); return bitmap_; } const bitmap_type& bitmap_at(size_t index) const { VAST_ASSERT(index == 0); return bitmap_; } void encode(value_type x, size_type n = 1) { VAST_ASSERT(Bitmap::max_size - size() >= n); bitmap_.append_bits(x, n); } Bitmap decode(relational_operator op, value_type x) const { VAST_ASSERT(op == equal || op == not_equal); auto result = bitmap_; if ((x && op == equal) || (!x && op == not_equal)) return result; result.flip(); return result; } bool skip(size_type n) { bitmap_.append_bits(0, n); return true; } void append(const singleton_coder& other) { bitmap_.append(other.bitmap_); } size_type size() const { return bitmap_.size(); } const Bitmap& storage() const { return bitmap_; } friend bool operator==(const singleton_coder& x, const singleton_coder& y) { return x.bitmap_ == y.bitmap_; } template <class Inspector> friend auto inspect(Inspector&f, singleton_coder& sc) { return f(sc.bitmap_); } private: Bitmap bitmap_; }; template <class Bitmap> class vector_coder : detail::equality_comparable<vector_coder<Bitmap>> { public: using bitmap_type = Bitmap; using size_type = typename Bitmap::size_type; using value_type = size_t; vector_coder() : size_{0} { // nop } vector_coder(size_t n) : size_{0}, bitmaps_(n) { // nop } size_t bitmap_count() const noexcept { return bitmaps_.size(); } auto size() const { return size_; } auto& storage() const { return bitmaps_; } friend bool operator==(const vector_coder& x, const vector_coder& y) { return x.size_ == y.size_ && x.bitmaps_ == y.bitmaps_; } template <class Inspector> friend auto inspect(Inspector& f, vector_coder& ec) { return f(ec.size_, ec.bitmaps_); } protected: void append(const vector_coder& other, bool bit) { VAST_ASSERT(bitmaps_.size() == other.bitmaps_.size()); for (auto i = 0u; i < bitmaps_.size(); ++i) { bitmaps_[i].append_bits(bit, this->size() - bitmaps_[i].size()); bitmaps_[i].append(other.bitmaps_[i]); } size_ += other.size_; } size_type size_; mutable std::vector<Bitmap> bitmaps_; }; /// Encodes each value in its own bitmap. template <class Bitmap> class equality_coder : public vector_coder<Bitmap> { public: using super = vector_coder<Bitmap>; using typename super::value_type; using typename super::size_type; using typename super::bitmap_type; using super::super; bitmap_type& lazy_bitmap_at(size_t index) const { auto& result = this->bitmaps_[index]; result.append_bits(false, this->size_ - result.size()); return result; } bitmap_type& bitmap_at(size_t index) { return lazy_bitmap_at(index); } const bitmap_type& bitmap_at(size_t index) const { return lazy_bitmap_at(index); } void encode(value_type x, size_type n = 1) { VAST_ASSERT(Bitmap::max_size - this->size_ >= n); VAST_ASSERT(x < this->bitmaps_.size()); bitmap_at(x).append_bits(true, n); this->size_ += n; } Bitmap decode(relational_operator op, value_type x) const { VAST_ASSERT(op == less || op == less_equal || op == equal || op == not_equal || op == greater_equal || op == greater); VAST_ASSERT(x < this->bitmaps_.size()); switch (op) { default: return Bitmap{this->size_, false}; case less: { if (x == 0) return Bitmap{this->size_, false}; auto f = this->bitmaps_.begin(); auto result = nary_or(f, f + x); result.append_bits(false, this->size_ - result.size()); return result; } case less_equal: { auto f = this->bitmaps_.begin(); auto result = nary_or(f, f + x + 1); result.append_bits(false, this->size_ - result.size()); return result; } case equal: case not_equal: { auto result = bitmap_at(x); if (op == not_equal) result.flip(); return result; } case greater_equal: { auto result = nary_or(this->bitmaps_.begin() + x, this->bitmaps_.end()); result.append_bits(false, this->size_ - result.size()); return result; } case greater: { if (x >= this->bitmaps_.size() - 1) return Bitmap{this->size_, false}; auto f = this->bitmaps_.begin(); auto l = this->bitmaps_.end(); auto result = nary_or(f + x + 1, l); result.append_bits(false, this->size_ - result.size()); return result; } } } bool skip(size_type n) { this->size_ += n; return true; } void append(const equality_coder& other) { super::append(other, false); } }; /// Encodes a value according to an inequalty. Given a value *x* and an index /// *i* in *[0,N)*, all bits are 0 for i < x and 1 for i >= x. template <class Bitmap> class range_coder : public vector_coder<Bitmap> { public: using super = vector_coder<Bitmap>; using typename super::value_type; using typename super::size_type; using typename super::bitmap_type; using super::super; bitmap_type& lazy_bitmap_at(size_t index) const { auto& result = this->bitmaps_[index]; result.append_bits(true, this->size_ - result.size()); return result; } bitmap_type& bitmap_at(size_t index) { return lazy_bitmap_at(index); } const bitmap_type& bitmap_at(size_t index) const { return lazy_bitmap_at(index); } void encode(value_type x, size_type n = 1) { VAST_ASSERT(Bitmap::max_size - this->size_ >= n); VAST_ASSERT(x < this->bitmaps_.size() + 1); // Lazy append: we only add 0s until we hit index i of value x. The // remaining bitmaps are always 1, by definition of the range coding // property i >= x for all i in [0,N). for (auto i = 0u; i < x; ++i) bitmap_at(i).append_bits(false, n); this->size_ += n; } Bitmap decode(relational_operator op, value_type x) const { VAST_ASSERT(op == less || op == less_equal || op == equal || op == not_equal || op == greater_equal || op == greater); VAST_ASSERT(x < this->bitmaps_.size() + 1); switch (op) { default: return Bitmap{this->size_, false}; case less: { if (x == 0) return Bitmap{this->size_, false}; return bitmap_at(x - 1); } case less_equal: { return bitmap_at(x); } case equal: { auto result = bitmap_at(x); if (x > 0) result &= ~bitmap_at(x - 1); return result; } case not_equal: { auto result = ~bitmap_at(x); if (x > 0) result |= bitmap_at(x - 1); return result; } case greater: { return ~bitmap_at(x); } case greater_equal: { if (x == 0) return Bitmap{this->size_, true}; return ~bitmap_at(x - 1); } } } bool skip(size_type n) { this->size_ += n; return true; } void append(const range_coder& other) { super::append(other, true); } }; /// Maintains one bitmap per *bit* of the value to encode. /// For example, adding the value 4 appends a 1 to the bitmap for 2^2 and a /// 0 to to all other bitmaps. template <class Bitmap> class bitslice_coder : public vector_coder<Bitmap> { public: using super = vector_coder<Bitmap>; using typename super::value_type; using typename super::size_type; using typename super::bitmap_type; using super::super; bitmap_type& lazy_bitmap_at(size_t index) const { auto& result = this->bitmaps_[index]; result.append_bits(false, this->size_ - result.size()); return result; } bitmap_type& bitmap_at(size_t index) { return lazy_bitmap_at(index); } const bitmap_type& bitmap_at(size_t index) const { return lazy_bitmap_at(index); } void encode(value_type x, size_type n = 1) { VAST_ASSERT(Bitmap::max_size - this->size_ >= n); for (auto i = 0u; i < this->bitmaps_.size(); ++i) bitmap_at(i).append_bits(((x >> i) & 1) == 0, n); this->size_ += n; } // RangeEval-Opt for the special case with uniform base 2. Bitmap decode(relational_operator op, value_type x) const { switch (op) { default: break; case less: case less_equal: case greater: case greater_equal: { if (x == std::numeric_limits<value_type>::min()) { if (op == less) return Bitmap{this->size_, false}; else if (op == greater_equal) return Bitmap{this->size_, true}; } else if (op == less || op == greater_equal) { --x; } auto result = x & 1 ? Bitmap{this->size_, true} : this->bitmaps_[0]; for (auto i = 1u; i < this->bitmaps_.size(); ++i) if ((x >> i) & 1) result |= this->bitmaps_[i]; else result &= this->bitmaps_[i]; if (op == greater || op == greater_equal || op == not_equal) result.flip(); return result; } case equal: case not_equal: { auto result = Bitmap{this->size_, true}; for (auto i = 0u; i < this->bitmaps_.size(); ++i) { auto& bm = this->bitmaps_[i]; result &= (((x >> i) & 1) ? ~bm : bm); } if (op == not_equal) result.flip(); return result; } case in: case not_in: { if (x == 0) break; x = ~x; auto result = Bitmap{this->size_, false}; for (auto i = 0u; i < this->bitmaps_.size(); ++i) if (((x >> i) & 1) == 0) result |= this->bitmaps_[i]; if (op == in) result.flip(); return result; } } return Bitmap{this->size_, false}; } bool skip(size_type n) { this->size_ += n; return true; } void append(const bitslice_coder& other) { super::append(other, false); } }; template <class T> struct is_singleton_coder : std::false_type {}; template <class Bitmap> struct is_singleton_coder<singleton_coder<Bitmap>> : std::true_type {}; template <class T> struct is_equality_coder : std::false_type {}; template <class Bitmap> struct is_equality_coder<equality_coder<Bitmap>> : std::true_type {}; template <class T> struct is_range_coder : std::false_type {}; template <class Bitmap> struct is_range_coder<range_coder<Bitmap>> : std::true_type {}; template <class T> struct is_bitslice_coder : std::false_type {}; template <class Bitmap> struct is_bitslice_coder<bitslice_coder<Bitmap>> : std::true_type {}; /// A multi-component (or multi-level) coder expresses values as a linear /// combination according to a base vector. The literature refers to this /// represenation as *attribute value decomposition*. template <class Coder> class multi_level_coder : detail::equality_comparable<multi_level_coder<Coder>> { public: using coder_type = Coder; using bitmap_type = typename coder_type::bitmap_type; using size_type = typename coder_type::size_type; using value_type = typename coder_type::value_type; multi_level_coder() = default; /// Constructs a multi-level coder from a given base. /// @param b The base to initialize this coder with. explicit multi_level_coder(base b) : base_{std::move(b)} { init(); } void encode(value_type x, size_type n = 1) { if (xs_.empty()) init(); base_.decompose(x, xs_); for (auto i = 0u; i < base_.size(); ++i) coders_[i].encode(xs_[i], n); } auto decode(relational_operator op, value_type x) const { return coders_.empty() ? bitmap_type{} : decode(coders_, op, x); } bool skip(size_type n) { return std::all_of(coders_.begin(), coders_.end(), [n](auto& x) { return x.skip(n); }); } void append(const multi_level_coder& other) { VAST_ASSERT(coders_.size() == other.coders_.size()); for (auto i = 0u; i < coders_.size(); ++i) coders_[i].append(other.coders_[i]); } size_type size() const { return coders_.empty() ? 0 : coders_[0].size(); } auto& storage() const { return coders_; } friend bool operator==(const multi_level_coder& x, const multi_level_coder& y) { return x.base_ == y.base_ && x.coders_ == y.coders_; } template <class Inspector> friend auto inspect(Inspector& f, multi_level_coder& mlc) { return f(mlc.base_, mlc.xs_, mlc.coders_); } private: void init() { VAST_ASSERT(base_.well_defined()); xs_.resize(base_.size()), coders_.resize(base_.size()); init_coders(coders_); // dispatch on coder_type VAST_ASSERT(coders_.size() == base_.size()); } // TODO // We could further optimze the number of bitmaps per coder: any base b // requires only b-1 bitmaps because one can obtain any bitmap through // conjunction/disjunction of the others. While this decreases space // requirements by a factor of 1/b, it increases query time by b-1. void init_coders(std::vector<singleton_coder<bitmap_type>>&) { // Nothing to for singleton coders. } void init_coders(std::vector<range_coder<bitmap_type>>& coders) { // For range coders it suffices to use b-1 bitmaps because the last // bitmap always consists of all 1s and is hence superfluous. for (auto i = 0u; i < base_.size(); ++i) coders[i] = range_coder<bitmap_type>{base_[i] - 1}; } template <class C> void init_coders(std::vector<C>& coders) { // All other multi-bitmap coders use one bitmap per unique value. for (auto i = 0u; i < base_.size(); ++i) coders[i] = C{base_[i]}; } // Range-Eval-Opt auto decode(const std::vector<range_coder<bitmap_type>>& coders, relational_operator op, value_type x) const { VAST_ASSERT(!(op == in || op == not_in)); // All coders must have the same number of elements. auto pred = [n=size()](auto c) { return c.size() == n; }; VAST_ASSERT(std::all_of(coders.begin(), coders.end(), pred)); // Check boundaries first. if (x == 0) { if (op == less) // A < min => false return bitmap_type{size(), false}; else if (op == greater_equal) // A >= min => true return bitmap_type{size(), true}; } else if (op == less || op == greater_equal) { --x; } base_.decompose(x, xs_); bitmap_type result{size(), true}; auto get_bitmap = [&](size_t coder_index, size_t bitmap_index) -> auto& { return coders[coder_index].bitmap_at(bitmap_index); }; switch (op) { default: return bitmap_type{size(), false}; case less: case less_equal: case greater: case greater_equal: { if (xs_[0] < base_[0] - 1) // && bitmap != all_ones result = get_bitmap(0, xs_[0]); for (auto i = 1u; i < base_.size(); ++i) { if (xs_[i] != base_[i] - 1) // && bitmap != all_ones result &= get_bitmap(i, xs_[i]); if (xs_[i] != 0) // && bitmap != all_ones result |= get_bitmap(i, xs_[i] - 1); } } break; case equal: case not_equal: { for (auto i = 0u; i < base_.size(); ++i) { if (xs_[i] == 0) // && bitmap != all_ones result &= get_bitmap(i, 0); else if (xs_[i] == base_[i] - 1) result &= ~get_bitmap(i, base_[i] - 2); else result &= get_bitmap(i, xs_[i]) ^ get_bitmap(i, xs_[i] - 1); } } break; } if (op == greater || op == greater_equal || op == not_equal) result.flip(); return result; } // If we don't have a range_coder, we only support simple equality queries at // this point. template <class C> auto decode(const std::vector<C>& coders, relational_operator op, value_type x) const -> std::enable_if_t< is_equality_coder<C>{} || is_bitslice_coder<C>{}, bitmap_type > { VAST_ASSERT(op == equal || op == not_equal); base_.decompose(x, xs_); auto result = coders[0].decode(equal, xs_[0]); for (auto i = 1u; i < base_.size(); ++i) result &= coders[i].decode(equal, xs_[i]); if (op == not_equal || op == not_in) result.flip(); return result; } base base_; mutable std::vector<value_type> xs_; std::vector<coder_type> coders_; }; template <class T> struct is_multi_level_coder : std::false_type {}; template <class C> struct is_multi_level_coder<multi_level_coder<C>> : std::true_type {}; } // namespace vast
/* Copyright 2015-2019 Egor Yusov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PROPRIETARY RIGHTS. * * In no event and under no legal theory, whether in tort (including negligence), * contract, or otherwise, unless required by applicable law (such as deliberate * and grossly negligent acts) or agreed to in writing, shall any Contributor be * liable for any damages, including any direct, indirect, special, incidental, * or consequential damages of any character arising as a result of this License or * out of the use or inability to use the software (including but not limited to damages * for loss of goodwill, work stoppage, computer failure or malfunction, or any and * all other commercial damages or losses), even if such Contributor has been advised * of the possibility of such damages. */ // This file is derived from the open source project provided by Intel Corportaion that // requires the following notice to be kept: //-------------------------------------------------------------------------------------- // Copyright 2013 Intel Corporation // All Rights Reserved // // Permission is granted to use, copy, distribute and prepare derivative works of this // software for any purpose and without fee, provided, that the above copyright notice // and this statement appear in all copies. Intel makes no representations about the // suitability of this software for any purpose. THIS SOFTWARE IS PROVIDED "AS IS." // INTEL SPECIFICALLY DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, AND ALL LIABILITY, // INCLUDING CONSEQUENTIAL AND OTHER INDIRECT DAMAGES, FOR THE USE OF THIS SOFTWARE, // INCLUDING LIABILITY FOR INFRINGEMENT OF ANY PROPRIETARY RIGHTS, AND INCLUDING THE // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. Intel does not // assume any responsibility for any errors which may appear in this software nor any // responsibility to update it. //-------------------------------------------------------------------------------------- #include "pch.h" #include "LightSctrPostProcess.h" #include "ConvenienceFunctions.h" #include "GraphicsUtilities.h" #include "GraphicsAccessories.h" #include "BasicShaderSourceStreamFactory.h" #include "MapHelper.h" #include "CommonlyUsedStates.h" using namespace Diligent; #define _USE_MATH_DEFINES #include <math.h> static const DepthStencilStateDesc DSS_CmpEqNoWrites { True, // DepthEnable False, // DepthWriteEnable COMPARISON_FUNC_EQUAL // DepthFunc }; // Disable depth testing and always increment stencil value // This depth stencil state is used to mark samples which will undergo further processing // Pixel shader discards pixels that should not be further processed, thus keeping the // stencil value untouched // For instance, pixel shader performing epipolar coordinates generation discards all // sampes, whoose coordinates are outside the screen [-1,1]x[-1,1] area static const DepthStencilStateDesc DSS_IncStencilAlways { False, // DepthEnable False, // DepthWriteEnable COMPARISON_FUNC_LESS, // DepthFunc True, // StencilEnable 0xFF, // StencilReadMask 0xFF, // StencilWriteMask StencilOpDesc { STENCIL_OP_KEEP, // StencilFailOp STENCIL_OP_KEEP, // StencilDepthFailOp STENCIL_OP_INCR_SAT, // StencilPassOp COMPARISON_FUNC_ALWAYS // StencilFunc }, StencilOpDesc { STENCIL_OP_KEEP, // StencilFailOp STENCIL_OP_KEEP, // StencilDepthFailOp STENCIL_OP_INCR_SAT, // StencilPassOp COMPARISON_FUNC_ALWAYS // StencilFunc } }; // Disable depth testing, stencil testing function equal, increment stencil // This state is used to process only those pixels that were marked at the previous pass // All pixels whith different stencil value are discarded from further processing as well // as some pixels can also be discarded during the draw call // For instance, pixel shader marking ray marching samples processes only those pixels which are inside // the screen. It also discards all but those samples that are interpolated from themselves static const DepthStencilStateDesc DSS_StencilEqIncStencil { False, // DepthEnable False, // DepthWriteEnable COMPARISON_FUNC_LESS, // DepthFunc True, // StencilEnable 0xFF, // StencilReadMask 0xFF, // StencilWriteMask StencilOpDesc { STENCIL_OP_KEEP, // StencilFailOp STENCIL_OP_KEEP, // StencilDepthFailOp STENCIL_OP_INCR_SAT, // StencilPassOp COMPARISON_FUNC_EQUAL // StencilFunc }, StencilOpDesc { STENCIL_OP_KEEP, // StencilFailOp STENCIL_OP_KEEP, // StencilDepthFailOp STENCIL_OP_INCR_SAT, // StencilPassOp COMPARISON_FUNC_EQUAL // StencilFunc } }; // Disable depth testing, stencil testing function equal, keep stencil static const DepthStencilStateDesc DSS_StencilEqKeepStencil = { False, // DepthEnable False, // DepthWriteEnable COMPARISON_FUNC_LESS, // DepthFunc True, // StencilEnable 0xFF, // StencilReadMask 0xFF, // StencilWriteMask StencilOpDesc { STENCIL_OP_KEEP, // StencilFailOp STENCIL_OP_KEEP, // StencilDepthFailOp STENCIL_OP_KEEP, // StencilPassOp COMPARISON_FUNC_EQUAL // StencilFunc }, StencilOpDesc { STENCIL_OP_KEEP, // StencilFailOp STENCIL_OP_KEEP, // StencilDepthFailOp STENCIL_OP_KEEP, // StencilPassOp COMPARISON_FUNC_EQUAL // StencilFunc } }; static const BlendStateDesc BS_AdditiveBlend = { False, // AlphaToCoverageEnable False, // IndependentBlendEnable RenderTargetBlendDesc { True, // BlendEnable False, // LogicOperationEnable BLEND_FACTOR_ONE, // SrcBlend BLEND_FACTOR_ONE, // DestBlend BLEND_OPERATION_ADD, // BlendOp BLEND_FACTOR_ONE, // SrcBlendAlpha BLEND_FACTOR_ONE, // DestBlendAlpha BLEND_OPERATION_ADD // BlendOpAlpha } }; static RefCntAutoPtr<IShader> CreateShader(IRenderDevice* pDevice, const Char* FileName, const Char* EntryPoint, SHADER_TYPE Type, const ShaderMacro* Macros, SHADER_VARIABLE_TYPE DefaultVarType, const ShaderVariableDesc* pVarDesc = nullptr, Uint32 NumVars = 0) { ShaderCreationAttribs Attribs; Attribs.EntryPoint = EntryPoint; Attribs.FilePath = FileName; Attribs.Macros = Macros; Attribs.SourceLanguage = SHADER_SOURCE_LANGUAGE_HLSL; Attribs.Desc.ShaderType = Type; Attribs.Desc.Name = EntryPoint; Attribs.Desc.VariableDesc = pVarDesc; Attribs.Desc.NumVariables = NumVars; Attribs.Desc.DefaultVariableType = DefaultVarType; BasicShaderSourceStreamFactory BasicSSSFactory("shaders;shaders\\atmosphere;shaders\\atmosphere\\precompute"); Attribs.pShaderSourceStreamFactory = &BasicSSSFactory; Attribs.UseCombinedTextureSamplers = true; RefCntAutoPtr<IShader> pShader; pDevice->CreateShader( Attribs, &pShader ); return pShader; } LightSctrPostProcess :: LightSctrPostProcess(IRenderDevice* pDevice, IDeviceContext* pContext, TEXTURE_FORMAT BackBufferFmt, TEXTURE_FORMAT DepthBufferFmt, TEXTURE_FORMAT OffscreenBackBufferFmt) : m_BackBufferFmt (BackBufferFmt), m_DepthBufferFmt (DepthBufferFmt), m_OffscreenBackBufferFmt (OffscreenBackBufferFmt), m_bUseCombinedMinMaxTexture(false), m_uiSampleRefinementCSThreadGroupSize(0), // Using small group size is inefficient because a lot of SIMD lanes become idle m_uiSampleRefinementCSMinimumThreadGroupSize(128),// Must be greater than 32 m_uiNumRandomSamplesOnSphere(pDevice->GetDeviceCaps().DevType == DeviceType::OpenGLES ? 64 : 128), m_uiUpToDateResourceFlags(0) { pDevice->CreateResourceMapping(ResourceMappingDesc(), &m_pResMapping); CreateUniformBuffer(pDevice, sizeof( PostProcessingAttribs ), "Postprocessing Attribs CB", &m_pcbPostProcessingAttribs); CreateUniformBuffer(pDevice, sizeof( MiscDynamicParams ), "Misc Dynamic Params CB", &m_pcbMiscParams); { BufferDesc CBDesc; CBDesc.Usage = USAGE_DEFAULT; CBDesc.BindFlags = BIND_UNIFORM_BUFFER; CBDesc.uiSizeInBytes = sizeof(AirScatteringAttribs); BufferData InitData{&m_MediaParams, CBDesc.uiSizeInBytes}; pDevice->CreateBuffer(CBDesc, &InitData, &m_pcbMediaAttribs); } // Add uniform buffers to the shader resource mapping. These buffers will never change. // Note that only buffer objects will stay unchanged, while the buffer contents can be updated. m_pResMapping->AddResource("cbPostProcessingAttribs", m_pcbPostProcessingAttribs, true); m_pResMapping->AddResource("cbParticipatingMediaScatteringParams", m_pcbMediaAttribs, true); m_pResMapping->AddResource("cbMiscDynamicParams", m_pcbMiscParams, true); pDevice->CreateSampler(Sam_LinearClamp, &m_pLinearClampSampler); pDevice->CreateSampler(Sam_PointClamp, &m_pPointClampSampler); { RefCntAutoPtr<IShader> pPrecomputeNetDensityToAtmTopPS; pPrecomputeNetDensityToAtmTopPS = CreateShader(pDevice, "PrecomputeNetDensityToAtmTop.fx", "PrecomputeNetDensityToAtmTopPS", SHADER_TYPE_PIXEL, nullptr, SHADER_VARIABLE_TYPE_STATIC); pPrecomputeNetDensityToAtmTopPS->BindResources(m_pResMapping, BIND_SHADER_RESOURCES_VERIFY_ALL_RESOLVED); TEXTURE_FORMAT RtvFmts[] = {TEX_FORMAT_RG32_FLOAT}; m_pPrecomputeNetDensityToAtmTopPSO = CreateScreenSizeQuadPSO(pDevice, "PrecomputeNetDensityToAtmTopPSO", pPrecomputeNetDensityToAtmTopPS, DSS_DisableDepth, BS_Default, 1, RtvFmts, TEX_FORMAT_UNKNOWN); m_pPrecomputeNetDensityToAtmTopPSO->CreateShaderResourceBinding(&m_pPrecomputeNetDensityToAtmTopSRB, true); } ComputeScatteringCoefficients(pContext); CreatePrecomputedOpticalDepthTexture(pDevice, pContext); CreateAmbientSkyLightTexture(pDevice); // Create sun rendering shaders and PSO { RefCntAutoPtr<IShader> pSunVS = CreateShader(pDevice, "Sun.fx", "SunVS", SHADER_TYPE_VERTEX, nullptr, SHADER_VARIABLE_TYPE_MUTABLE); RefCntAutoPtr<IShader> pSunPS = CreateShader(pDevice, "Sun.fx", "SunPS", SHADER_TYPE_PIXEL, nullptr, SHADER_VARIABLE_TYPE_MUTABLE); PipelineStateDesc PSODesc; PSODesc.Name = "Render Sun"; auto& GraphicsPipeline = PSODesc.GraphicsPipeline; GraphicsPipeline.RasterizerDesc.FillMode = FILL_MODE_SOLID; GraphicsPipeline.RasterizerDesc.CullMode = CULL_MODE_NONE; GraphicsPipeline.RasterizerDesc.FrontCounterClockwise = true; GraphicsPipeline.DepthStencilDesc = DSS_CmpEqNoWrites; GraphicsPipeline.pVS = pSunVS; GraphicsPipeline.pPS = pSunPS; GraphicsPipeline.NumRenderTargets = 1; GraphicsPipeline.RTVFormats[0] = OffscreenBackBufferFmt; GraphicsPipeline.DSVFormat = DepthBufferFmt; GraphicsPipeline.PrimitiveTopology = PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP; pDevice->CreatePipelineState(PSODesc, &m_pRenderSunPSO); } } LightSctrPostProcess :: ~LightSctrPostProcess() { } void LightSctrPostProcess :: OnWindowResize(IRenderDevice* pDevice, Uint32 uiBackBufferWidth, Uint32 uiBackBufferHeight) { m_uiBackBufferWidth = uiBackBufferWidth; m_uiBackBufferHeight = uiBackBufferHeight; // Release all shaders that depend on SCREEN_RESLOUTION shader macro // The shaders will be recreated first time they needed m_pRendedCoordTexPSO.Release(); m_pRendedSliceEndpointsPSO.Release(); m_pRenderSliceUVDirInSM_PSO.Release(); m_pRenderSampleLocationsPSO.Release(); m_pUnwarpEpipolarSctrImgPSO.Release(); m_pUnwarpAndRenderLuminancePSO.Release(); CreateCamSpaceZTexture(pDevice); } void LightSctrPostProcess :: DefineMacros(ShaderMacroHelper &Macros) { // Define common shader macros Macros.AddShaderMacro("NUM_EPIPOLAR_SLICES", m_PostProcessingAttribs.m_uiNumEpipolarSlices); Macros.AddShaderMacro("MAX_SAMPLES_IN_SLICE", m_PostProcessingAttribs.m_uiMaxSamplesInSlice); Macros.AddShaderMacro("OPTIMIZE_SAMPLE_LOCATIONS", m_PostProcessingAttribs.m_bOptimizeSampleLocations); Macros.AddShaderMacro("USE_COMBINED_MIN_MAX_TEXTURE", m_bUseCombinedMinMaxTexture ); Macros.AddShaderMacro("EXTINCTION_EVAL_MODE", m_PostProcessingAttribs.m_uiExtinctionEvalMode ); Macros.AddShaderMacro("ENABLE_LIGHT_SHAFTS", m_PostProcessingAttribs.m_bEnableLightShafts); Macros.AddShaderMacro("MULTIPLE_SCATTERING_MODE", m_PostProcessingAttribs.m_uiMultipleScatteringMode); Macros.AddShaderMacro("SINGLE_SCATTERING_MODE", m_PostProcessingAttribs.m_uiSingleScatteringMode); { std::stringstream ss; ss<<"float2("<<m_uiBackBufferWidth<<".0,"<<m_uiBackBufferHeight<<".0)"; Macros.AddShaderMacro("SCREEN_RESLOUTION", ss.str()); } { std::stringstream ss; ss<<"float4("<<sm_iPrecomputedSctrUDim<<".0," <<sm_iPrecomputedSctrVDim<<".0," <<sm_iPrecomputedSctrWDim<<".0," <<sm_iPrecomputedSctrQDim<<".0)"; Macros.AddShaderMacro("PRECOMPUTED_SCTR_LUT_DIM", ss.str()); } Macros.AddShaderMacro("EARTH_RADIUS", m_MediaParams.fEarthRadius); Macros.AddShaderMacro("ATM_TOP_HEIGHT", m_MediaParams.fAtmTopHeight); Macros.AddShaderMacro("ATM_TOP_RADIUS", m_MediaParams.fAtmTopRadius); { std::stringstream ss; ss<<"float2("<<m_MediaParams.f2ParticleScaleHeight.x<<".0,"<<m_MediaParams.f2ParticleScaleHeight.y<<".0)"; Macros.AddShaderMacro("PARTICLE_SCALE_HEIGHT", ss.str()); } } RefCntAutoPtr<IPipelineState> LightSctrPostProcess :: CreateScreenSizeQuadPSO(IRenderDevice* pDevice, const char* PSOName, IShader* PixelShader, const DepthStencilStateDesc& DSSDesc, const BlendStateDesc& BSDesc, Uint8 NumRTVs, TEXTURE_FORMAT RTVFmts[], TEXTURE_FORMAT DSVFmt) { if (!m_pQuadVS) { m_pQuadVS = CreateShader( pDevice, "ScreenSizeQuadVS.fx", "ScreenSizeQuadVS", SHADER_TYPE_VERTEX, nullptr, SHADER_VARIABLE_TYPE_STATIC ); } PipelineStateDesc PSODesc; PSODesc.Name = PSOName; auto& GraphicsPipeline = PSODesc.GraphicsPipeline; GraphicsPipeline.RasterizerDesc.FillMode = FILL_MODE_SOLID; GraphicsPipeline.RasterizerDesc.CullMode = CULL_MODE_NONE; GraphicsPipeline.RasterizerDesc.FrontCounterClockwise = true; GraphicsPipeline.DepthStencilDesc = DSSDesc; GraphicsPipeline.BlendDesc = BSDesc; GraphicsPipeline.pVS = m_pQuadVS; GraphicsPipeline.pPS = PixelShader; GraphicsPipeline.PrimitiveTopology = PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP; GraphicsPipeline.NumRenderTargets = NumRTVs; GraphicsPipeline.DSVFormat = DSVFmt; for (Uint32 rt=0; rt < NumRTVs; ++rt) GraphicsPipeline.RTVFormats[rt] = RTVFmts[rt]; RefCntAutoPtr<IPipelineState> PSO; pDevice->CreatePipelineState(PSODesc, &PSO); return PSO; } void LightSctrPostProcess::RenderScreenSizeQuad(IDeviceContext* pDeviceContext, IPipelineState* PSO, IShaderResourceBinding* SRB, Uint8 StencilRef, Uint32 NumQuads) { pDeviceContext->SetPipelineState(PSO); pDeviceContext->CommitShaderResources(SRB, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); pDeviceContext->SetStencilRef(StencilRef); DrawAttribs ScreenSizeQuadDrawAttrs; ScreenSizeQuadDrawAttrs.NumVertices = 4; ScreenSizeQuadDrawAttrs.NumInstances = NumQuads; pDeviceContext->Draw(ScreenSizeQuadDrawAttrs); } void LightSctrPostProcess::CreatePrecomputedOpticalDepthTexture(IRenderDevice* pDevice, IDeviceContext* pDeviceContext) { if (!m_ptex2DOccludedNetDensityToAtmTopSRV) { // Create texture if it has not been created yet. // Do not recreate texture if it already exists as this may // break static resource bindings. TextureDesc TexDesc; TexDesc.Name = "Occluded Net Density to Atm Top"; TexDesc.Type = RESOURCE_DIM_TEX_2D; TexDesc.Width = sm_iNumPrecomputedHeights; TexDesc.Height = sm_iNumPrecomputedAngles; TexDesc.Format = TEX_FORMAT_RG32_FLOAT; TexDesc.MipLevels = 1; TexDesc.Usage = USAGE_DEFAULT; TexDesc.BindFlags = BIND_SHADER_RESOURCE | BIND_RENDER_TARGET; RefCntAutoPtr<ITexture> tex2DOccludedNetDensityToAtmTop; pDevice->CreateTexture(TexDesc, nullptr, &tex2DOccludedNetDensityToAtmTop); m_ptex2DOccludedNetDensityToAtmTopSRV = tex2DOccludedNetDensityToAtmTop->GetDefaultView(TEXTURE_VIEW_SHADER_RESOURCE); m_ptex2DOccludedNetDensityToAtmTopSRV->SetSampler(m_pLinearClampSampler); m_ptex2DOccludedNetDensityToAtmTopRTV = tex2DOccludedNetDensityToAtmTop->GetDefaultView(TEXTURE_VIEW_RENDER_TARGET); m_pResMapping->AddResource("g_tex2DOccludedNetDensityToAtmTop", m_ptex2DOccludedNetDensityToAtmTopSRV, false); } ITextureView* pRTVs[] = {m_ptex2DOccludedNetDensityToAtmTopRTV}; pDeviceContext->SetRenderTargets(1, pRTVs, nullptr, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); RenderScreenSizeQuad(pDeviceContext, m_pPrecomputeNetDensityToAtmTopPSO, m_pPrecomputeNetDensityToAtmTopSRB, 0); m_uiUpToDateResourceFlags |= UpToDateResourceFlags::PrecomputedOpticalDepthTex; } void LightSctrPostProcess :: CreateRandomSphereSamplingTexture(IRenderDevice *pDevice) { TextureDesc RandomSphereSamplingTexDesc; RandomSphereSamplingTexDesc.Type = RESOURCE_DIM_TEX_2D; RandomSphereSamplingTexDesc.Width = m_uiNumRandomSamplesOnSphere; RandomSphereSamplingTexDesc.Height = 1; RandomSphereSamplingTexDesc.MipLevels = 1; RandomSphereSamplingTexDesc.Format = TEX_FORMAT_RGBA32_FLOAT; RandomSphereSamplingTexDesc.Usage = USAGE_STATIC; RandomSphereSamplingTexDesc.BindFlags = BIND_SHADER_RESOURCE; std::vector<float4> SphereSampling(m_uiNumRandomSamplesOnSphere); for(Uint32 iSample = 0; iSample < m_uiNumRandomSamplesOnSphere; ++iSample) { float4 &f4Sample = SphereSampling[iSample]; f4Sample.z = ((float)rand()/(float)RAND_MAX) * 2.f - 1.f; float t = ((float)rand()/(float)RAND_MAX) * 2.f * PI; float r = sqrt( std::max(1.f - f4Sample.z*f4Sample.z, 0.f) ); f4Sample.x = r * cos(t); f4Sample.y = r * sin(t); f4Sample.w = 0; } TextureSubResData Mip0Data; Mip0Data.pData = SphereSampling.data(); Mip0Data.Stride = m_uiNumRandomSamplesOnSphere*sizeof( float4 ); TextureData TexData; TexData.NumSubresources = 1; TexData.pSubResources = &Mip0Data; RefCntAutoPtr<ITexture> ptex2DSphereRandomSampling; pDevice->CreateTexture( RandomSphereSamplingTexDesc, &TexData, &ptex2DSphereRandomSampling ); m_ptex2DSphereRandomSamplingSRV = ptex2DSphereRandomSampling->GetDefaultView( TEXTURE_VIEW_SHADER_RESOURCE ); m_ptex2DSphereRandomSamplingSRV->SetSampler(m_pLinearClampSampler); m_pResMapping->AddResource( "g_tex2DSphereRandomSampling", m_ptex2DSphereRandomSamplingSRV, true ); } void LightSctrPostProcess :: CreateAuxTextures(IRenderDevice *pDevice) { TextureDesc TexDesc; TexDesc.Type = RESOURCE_DIM_TEX_2D; TexDesc.MipLevels = 1; TexDesc.Usage = USAGE_DEFAULT; TexDesc.BindFlags = BIND_RENDER_TARGET | BIND_SHADER_RESOURCE; { // MaxSamplesInSlice x NumSlices RG32F texture to store screen-space coordinates // for every epipolar sample TexDesc.Name = "Coordinate Texture"; TexDesc.Width = m_PostProcessingAttribs.m_uiMaxSamplesInSlice; TexDesc.Height = m_PostProcessingAttribs.m_uiNumEpipolarSlices; TexDesc.Format = CoordinateTexFmt; TexDesc.ClearValue.Format = TexDesc.Format; TexDesc.ClearValue.Color[0] = -1e+30f; TexDesc.ClearValue.Color[1] = -1e+30f; TexDesc.ClearValue.Color[2] = -1e+30f; TexDesc.ClearValue.Color[3] = -1e+30f; RefCntAutoPtr<ITexture> tex2DCoordinateTexture; pDevice->CreateTexture(TexDesc, nullptr, &tex2DCoordinateTexture); auto* tex2DCoordinateTextureSRV = tex2DCoordinateTexture->GetDefaultView(TEXTURE_VIEW_SHADER_RESOURCE); m_ptex2DCoordinateTextureRTV = tex2DCoordinateTexture->GetDefaultView(TEXTURE_VIEW_RENDER_TARGET); tex2DCoordinateTextureSRV->SetSampler(m_pLinearClampSampler); m_pResMapping->AddResource("g_tex2DCoordinates", tex2DCoordinateTextureSRV, false); } { // NumSlices x 1 RGBA32F texture to store end point coordinates for every epipolar slice TexDesc.Name = "Slice Endpoints"; TexDesc.Width = m_PostProcessingAttribs.m_uiNumEpipolarSlices; TexDesc.Height = 1; TexDesc.Format = SliceEndpointsFmt; TexDesc.ClearValue.Format = TexDesc.Format; TexDesc.ClearValue.Color[0] = -1e+30f; TexDesc.ClearValue.Color[1] = -1e+30f; TexDesc.ClearValue.Color[2] = -1e+30f; TexDesc.ClearValue.Color[3] = -1e+30f; RefCntAutoPtr<ITexture> tex2DSliceEndpoints; pDevice->CreateTexture(TexDesc, nullptr, &tex2DSliceEndpoints); auto* tex2DSliceEndpointsSRV = tex2DSliceEndpoints->GetDefaultView(TEXTURE_VIEW_SHADER_RESOURCE); m_ptex2DSliceEndpointsRTV = tex2DSliceEndpoints->GetDefaultView(TEXTURE_VIEW_RENDER_TARGET); tex2DSliceEndpointsSRV->SetSampler(m_pLinearClampSampler); m_pResMapping->AddResource("g_tex2DSliceEndPoints", tex2DSliceEndpointsSRV, false); } TexDesc.ClearValue.Format = TEX_FORMAT_UNKNOWN; { TexDesc.Name = "Interpolation Source"; // MaxSamplesInSlice x NumSlices RG16U texture to store two indices from which // the sample should be interpolated, for every epipolar sample TexDesc.Width = m_PostProcessingAttribs.m_uiMaxSamplesInSlice; TexDesc.Height = m_PostProcessingAttribs.m_uiNumEpipolarSlices; // In fact we only need RG16U texture to store interpolation source indices. // However, NVidia GLES does not supported imge load/store operations on this format, // so we have to resort to RGBA32U. TexDesc.Format = InterpolationSourceTexFmt; TexDesc.BindFlags = BIND_UNORDERED_ACCESS | BIND_SHADER_RESOURCE; RefCntAutoPtr<ITexture> tex2DInterpolationSource; pDevice->CreateTexture(TexDesc, nullptr, &tex2DInterpolationSource); auto* tex2DInterpolationSourceSRV = tex2DInterpolationSource->GetDefaultView(TEXTURE_VIEW_SHADER_RESOURCE); auto* tex2DInterpolationSourceUAV = tex2DInterpolationSource->GetDefaultView(TEXTURE_VIEW_UNORDERED_ACCESS); tex2DInterpolationSourceSRV->SetSampler(m_pPointClampSampler); m_pResMapping->AddResource("g_tex2DInterpolationSource", tex2DInterpolationSourceSRV, false); m_pResMapping->AddResource("g_rwtex2DInterpolationSource", tex2DInterpolationSourceUAV, false); } { // MaxSamplesInSlice x NumSlices R32F texture to store camera-space Z coordinate, // for every epipolar sample TexDesc.Name = "Epipolar Cam Space Z"; TexDesc.Format = EpipolarCamSpaceZFmt; TexDesc.BindFlags = BIND_RENDER_TARGET | BIND_SHADER_RESOURCE; RefCntAutoPtr<ITexture> tex2DEpipolarCamSpaceZ; pDevice->CreateTexture(TexDesc, nullptr, &tex2DEpipolarCamSpaceZ); auto* tex2DEpipolarCamSpaceZSRV = tex2DEpipolarCamSpaceZ->GetDefaultView(TEXTURE_VIEW_SHADER_RESOURCE); m_ptex2DEpipolarCamSpaceZRTV = tex2DEpipolarCamSpaceZ->GetDefaultView(TEXTURE_VIEW_RENDER_TARGET); tex2DEpipolarCamSpaceZSRV->SetSampler(m_pLinearClampSampler); m_pResMapping->AddResource("g_tex2DEpipolarCamSpaceZ", tex2DEpipolarCamSpaceZSRV, false); } { // MaxSamplesInSlice x NumSlices RGBA16F texture to store interpolated inscattered light, // for every epipolar sample TexDesc.Name = "Epipolar Inscattering"; TexDesc.Format = EpipolarInsctrTexFmt; constexpr float flt16max = 65504.f; TexDesc.ClearValue.Format = TexDesc.Format; TexDesc.ClearValue.Color[0] = -flt16max; TexDesc.ClearValue.Color[1] = -flt16max; TexDesc.ClearValue.Color[2] = -flt16max; TexDesc.ClearValue.Color[3] = -flt16max; RefCntAutoPtr<ITexture> tex2DEpipolarInscattering; pDevice->CreateTexture(TexDesc, nullptr, &tex2DEpipolarInscattering); auto* tex2DEpipolarInscatteringSRV = tex2DEpipolarInscattering->GetDefaultView(TEXTURE_VIEW_SHADER_RESOURCE); m_ptex2DEpipolarInscatteringRTV = tex2DEpipolarInscattering->GetDefaultView(TEXTURE_VIEW_RENDER_TARGET); tex2DEpipolarInscatteringSRV->SetSampler(m_pLinearClampSampler); m_pResMapping->AddResource("g_tex2DScatteredColor", tex2DEpipolarInscatteringSRV, false); } { // MaxSamplesInSlice x NumSlices RGBA16F texture to store initial inscattered light, // for every epipolar sample TexDesc.Name = "Initial Scattered Light"; TexDesc.ClearValue.Format = TexDesc.Format; TexDesc.ClearValue.Color[0] = 0; TexDesc.ClearValue.Color[1] = 0; TexDesc.ClearValue.Color[2] = 0; TexDesc.ClearValue.Color[3] = 0; RefCntAutoPtr<ITexture> tex2DInitialScatteredLight; pDevice->CreateTexture(TexDesc, nullptr, &tex2DInitialScatteredLight); auto* tex2DInitialScatteredLightSRV = tex2DInitialScatteredLight->GetDefaultView(TEXTURE_VIEW_SHADER_RESOURCE); m_ptex2DInitialScatteredLightRTV = tex2DInitialScatteredLight->GetDefaultView(TEXTURE_VIEW_RENDER_TARGET); tex2DInitialScatteredLightSRV->SetSampler(m_pLinearClampSampler); m_pResMapping->AddResource("g_tex2DInitialInsctrIrradiance", tex2DInitialScatteredLightSRV, false); } TexDesc.ClearValue.Format = TEX_FORMAT_UNKNOWN; { // MaxSamplesInSlice x NumSlices depth stencil texture to mark samples for processing, // for every epipolar sample TexDesc.Name = "Epipolar Image Depth"; TexDesc.Format = EpipolarImageDepthFmt; TexDesc.BindFlags = BIND_DEPTH_STENCIL; TexDesc.ClearValue.Format = TexDesc.Format; TexDesc.ClearValue.DepthStencil.Depth = 1; TexDesc.ClearValue.DepthStencil.Stencil = 0; RefCntAutoPtr<ITexture> tex2DEpipolarImageDepth; pDevice->CreateTexture(TexDesc, nullptr, &tex2DEpipolarImageDepth); m_ptex2DEpipolarImageDSV = tex2DEpipolarImageDepth->GetDefaultView(TEXTURE_VIEW_DEPTH_STENCIL); } m_uiUpToDateResourceFlags |= UpToDateResourceFlags::AuxTextures; ResetShaderResourceBindings(); } void LightSctrPostProcess :: CreatePrecomputedScatteringLUT(IRenderDevice *pDevice, IDeviceContext *pContext) { const int ThreadGroupSize = pDevice->GetDeviceCaps().DevType == DeviceType::OpenGLES ? 8 : 16; if( !m_pPrecomputeSingleSctrCS ) { ShaderMacroHelper Macros; DefineMacros(Macros); Macros.AddShaderMacro( "THREAD_GROUP_SIZE", ThreadGroupSize ); Macros.Finalize(); m_pPrecomputeSingleSctrCS = CreateShader( pDevice, "PrecomputeSingleScattering.fx", "PrecomputeSingleScatteringCS", SHADER_TYPE_COMPUTE, Macros, SHADER_VARIABLE_TYPE_DYNAMIC ); PipelineStateDesc PSODesc; PSODesc.IsComputePipeline = true; PSODesc.ComputePipeline.pCS = m_pPrecomputeSingleSctrCS; pDevice->CreatePipelineState(PSODesc, &m_pPrecomputeSingleSctrPSO); m_pPrecomputeSingleSctrPSO->CreateShaderResourceBinding(&m_pPrecomputeSingleSctrSRB, true); } if( !m_pComputeSctrRadianceCS ) { ShaderMacroHelper Macros; DefineMacros(Macros); Macros.AddShaderMacro( "THREAD_GROUP_SIZE", ThreadGroupSize ); Macros.AddShaderMacro( "NUM_RANDOM_SPHERE_SAMPLES", m_uiNumRandomSamplesOnSphere ); Macros.Finalize(); m_pComputeSctrRadianceCS = CreateShader( pDevice, "ComputeSctrRadiance.fx", "ComputeSctrRadianceCS", SHADER_TYPE_COMPUTE, Macros, SHADER_VARIABLE_TYPE_DYNAMIC ); PipelineStateDesc PSODesc; PSODesc.IsComputePipeline = true; PSODesc.ComputePipeline.pCS = m_pComputeSctrRadianceCS; pDevice->CreatePipelineState(PSODesc, &m_pComputeSctrRadiancePSO); m_pComputeSctrRadianceSRB.Release(); m_pComputeSctrRadiancePSO->CreateShaderResourceBinding(&m_pComputeSctrRadianceSRB, true); } if( !m_pComputeScatteringOrderCS ) { ShaderMacroHelper Macros; DefineMacros(Macros); Macros.AddShaderMacro( "THREAD_GROUP_SIZE", ThreadGroupSize ); Macros.Finalize(); m_pComputeScatteringOrderCS = CreateShader( pDevice, "ComputeScatteringOrder.fx", "ComputeScatteringOrderCS", SHADER_TYPE_COMPUTE, Macros, SHADER_VARIABLE_TYPE_DYNAMIC ); PipelineStateDesc PSODesc; PSODesc.IsComputePipeline = true; PSODesc.ComputePipeline.pCS = m_pComputeScatteringOrderCS; pDevice->CreatePipelineState(PSODesc, &m_pComputeScatteringOrderPSO); m_pComputeScatteringOrderPSO->CreateShaderResourceBinding(&m_pComputeScatteringOrderSRB, true); } if( !m_pInitHighOrderScatteringCS ) { ShaderMacroHelper Macros; DefineMacros(Macros); Macros.AddShaderMacro( "THREAD_GROUP_SIZE", ThreadGroupSize ); Macros.Finalize(); m_pInitHighOrderScatteringCS = CreateShader( pDevice, "InitHighOrderScattering.fx", "InitHighOrderScatteringCS", SHADER_TYPE_COMPUTE, Macros, SHADER_VARIABLE_TYPE_DYNAMIC ); PipelineStateDesc PSODesc; PSODesc.IsComputePipeline = true; PSODesc.ComputePipeline.pCS = m_pInitHighOrderScatteringCS; pDevice->CreatePipelineState(PSODesc, &m_pInitHighOrderScatteringPSO); m_pInitHighOrderScatteringPSO->CreateShaderResourceBinding( &m_pInitHighOrderScatteringSRB, true ); } if( !m_pUpdateHighOrderScatteringCS ) { ShaderMacroHelper Macros; DefineMacros(Macros); Macros.AddShaderMacro( "THREAD_GROUP_SIZE", ThreadGroupSize ); Macros.Finalize(); m_pUpdateHighOrderScatteringCS = CreateShader( pDevice, "UpdateHighOrderScattering.fx", "UpdateHighOrderScatteringCS", SHADER_TYPE_COMPUTE, Macros, SHADER_VARIABLE_TYPE_DYNAMIC); PipelineStateDesc PSODesc; PSODesc.IsComputePipeline = true; PSODesc.ComputePipeline.pCS = m_pUpdateHighOrderScatteringCS; pDevice->CreatePipelineState(PSODesc, &m_pUpdateHighOrderScatteringPSO); m_pUpdateHighOrderScatteringPSO->CreateShaderResourceBinding(&m_pUpdateHighOrderScatteringSRB, true); } if( !m_pCombineScatteringOrdersCS ) { ShaderMacroHelper Macros; DefineMacros(Macros); Macros.AddShaderMacro( "THREAD_GROUP_SIZE", ThreadGroupSize ); Macros.Finalize(); m_pCombineScatteringOrdersCS = CreateShader( pDevice, "CombineScatteringOrders.fx", "CombineScatteringOrdersCS", SHADER_TYPE_COMPUTE, Macros, SHADER_VARIABLE_TYPE_DYNAMIC ); PipelineStateDesc PSODesc; PSODesc.IsComputePipeline = true; PSODesc.ComputePipeline.pCS = m_pCombineScatteringOrdersCS; pDevice->CreatePipelineState(PSODesc, &m_pCombineScatteringOrdersPSO); m_pCombineScatteringOrdersPSO->CreateShaderResourceBinding(&m_pCombineScatteringOrdersSRB, true); } if( !m_ptex2DSphereRandomSamplingSRV ) CreateRandomSphereSamplingTexture(pDevice); TextureDesc PrecomputedSctrTexDesc; PrecomputedSctrTexDesc.Type = RESOURCE_DIM_TEX_3D; PrecomputedSctrTexDesc.Width = sm_iPrecomputedSctrUDim; PrecomputedSctrTexDesc.Height = sm_iPrecomputedSctrVDim; PrecomputedSctrTexDesc.Depth = sm_iPrecomputedSctrWDim * sm_iPrecomputedSctrQDim; PrecomputedSctrTexDesc.MipLevels = 1; PrecomputedSctrTexDesc.Format = TEX_FORMAT_RGBA16_FLOAT; PrecomputedSctrTexDesc.Usage = USAGE_DEFAULT; PrecomputedSctrTexDesc.BindFlags = BIND_UNORDERED_ACCESS | BIND_SHADER_RESOURCE; if( !m_ptex3DSingleScatteringSRV ) { m_ptex3DSingleScatteringSRV.Release(); m_ptex3DHighOrderScatteringSRV.Release(); m_ptex3DMultipleScatteringSRV.Release(); RefCntAutoPtr<ITexture> ptex3DSingleSctr, ptex3DMultipleSctr; pDevice->CreateTexture(PrecomputedSctrTexDesc, nullptr, &ptex3DSingleSctr); m_ptex3DSingleScatteringSRV = ptex3DSingleSctr->GetDefaultView( TEXTURE_VIEW_SHADER_RESOURCE ); m_ptex3DSingleScatteringSRV->SetSampler( m_pLinearClampSampler ); m_pResMapping->AddResource( "g_rwtex3DSingleScattering", ptex3DSingleSctr->GetDefaultView( TEXTURE_VIEW_UNORDERED_ACCESS ), true ); // We have to bother with two texture, because HLSL only allows read-write operations on single // component textures pDevice->CreateTexture(PrecomputedSctrTexDesc, nullptr, &m_ptex3DHighOrderSctr); pDevice->CreateTexture(PrecomputedSctrTexDesc, nullptr, &m_ptex3DHighOrderSctr2); m_ptex3DHighOrderSctr->GetDefaultView( TEXTURE_VIEW_SHADER_RESOURCE )->SetSampler( m_pLinearClampSampler ); m_ptex3DHighOrderSctr2->GetDefaultView( TEXTURE_VIEW_SHADER_RESOURCE )->SetSampler( m_pLinearClampSampler ); pDevice->CreateTexture(PrecomputedSctrTexDesc, nullptr, &ptex3DMultipleSctr); m_ptex3DMultipleScatteringSRV = ptex3DMultipleSctr->GetDefaultView( TEXTURE_VIEW_SHADER_RESOURCE ); m_ptex3DMultipleScatteringSRV->SetSampler( m_pLinearClampSampler ); m_pResMapping->AddResource( "g_rwtex3DMultipleSctr", ptex3DMultipleSctr->GetDefaultView( TEXTURE_VIEW_UNORDERED_ACCESS ), true ); m_pResMapping->AddResource("g_tex3DSingleSctrLUT", m_ptex3DSingleScatteringSRV, true); m_pResMapping->AddResource("g_tex3DMultipleSctrLUT", m_ptex3DMultipleScatteringSRV, true); } // Precompute single scattering m_pPrecomputeSingleSctrSRB->BindResources( SHADER_TYPE_COMPUTE, m_pResMapping, BIND_SHADER_RESOURCES_VERIFY_ALL_RESOLVED ); DispatchComputeAttribs DispatchAttrs( PrecomputedSctrTexDesc.Width/ThreadGroupSize, PrecomputedSctrTexDesc.Height/ThreadGroupSize, PrecomputedSctrTexDesc.Depth); pContext->SetPipelineState(m_pPrecomputeSingleSctrPSO); pContext->CommitShaderResources(m_pPrecomputeSingleSctrSRB, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); pContext->DispatchCompute(DispatchAttrs); // Precompute multiple scattering // We need higher precision to store intermediate data PrecomputedSctrTexDesc.Format = TEX_FORMAT_RGBA32_FLOAT; RefCntAutoPtr<ITexture> ptex3DSctrRadiance, ptex3DInsctrOrder; RefCntAutoPtr<ITextureView> ptex3DSctrRadianceSRV, ptex3DInsctrOrderSRV; pDevice->CreateTexture(PrecomputedSctrTexDesc, nullptr, &ptex3DSctrRadiance); pDevice->CreateTexture(PrecomputedSctrTexDesc, nullptr, &ptex3DInsctrOrder); ptex3DSctrRadianceSRV = ptex3DSctrRadiance->GetDefaultView(TEXTURE_VIEW_SHADER_RESOURCE); ptex3DInsctrOrderSRV = ptex3DInsctrOrder->GetDefaultView(TEXTURE_VIEW_SHADER_RESOURCE); ptex3DSctrRadianceSRV->SetSampler( m_pLinearClampSampler ); ptex3DInsctrOrderSRV->SetSampler( m_pLinearClampSampler ); m_pResMapping->AddResource( "g_rwtex3DSctrRadiance", ptex3DSctrRadiance->GetDefaultView( TEXTURE_VIEW_UNORDERED_ACCESS ), true ); m_pResMapping->AddResource( "g_rwtex3DInsctrOrder", ptex3DInsctrOrder->GetDefaultView( TEXTURE_VIEW_UNORDERED_ACCESS ), true ); m_pComputeSctrRadianceSRB->BindResources( SHADER_TYPE_COMPUTE, m_pResMapping, 0 ); m_pComputeScatteringOrderSRB->BindResources( SHADER_TYPE_COMPUTE, m_pResMapping, 0 ); m_pInitHighOrderScatteringSRB->BindResources( SHADER_TYPE_COMPUTE, m_pResMapping, 0 ); m_pUpdateHighOrderScatteringSRB->BindResources( SHADER_TYPE_COMPUTE, m_pResMapping, 0 ); const int iNumScatteringOrders = pDevice->GetDeviceCaps().DevType == DeviceType::OpenGLES ? 3 : 4; for(int iSctrOrder = 1; iSctrOrder < iNumScatteringOrders; ++iSctrOrder) { // Step 1: compute differential in-scattering m_pComputeSctrRadianceSRB->GetVariable( SHADER_TYPE_COMPUTE, "g_tex3DPreviousSctrOrder" )->Set( (iSctrOrder == 1) ? m_ptex3DSingleScatteringSRV : ptex3DInsctrOrderSRV ); pContext->SetPipelineState(m_pComputeSctrRadiancePSO); pContext->CommitShaderResources(m_pComputeSctrRadianceSRB, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); pContext->DispatchCompute(DispatchAttrs); // It seemse like on Intel GPU, the driver accumulates work into big batch. // The resulting batch turns out to be too big for GPU to process it in allowed time // limit, and the system kills the driver. So we have to flush the command buffer to // force execution of compute shaders. pContext->Flush(); // Step 2: integrate differential in-scattering m_pComputeScatteringOrderSRB->GetVariable( SHADER_TYPE_COMPUTE, "g_tex3DPointwiseSctrRadiance" )->Set( ptex3DSctrRadianceSRV ); pContext->SetPipelineState(m_pComputeScatteringOrderPSO); pContext->CommitShaderResources(m_pComputeScatteringOrderSRB, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); pContext->DispatchCompute(DispatchAttrs); IPipelineState *pPSO = nullptr; IShader *pCS = nullptr; IShaderResourceBinding *pSRB = nullptr; // Step 3: accumulate high-order scattering scattering if( iSctrOrder == 1 ) { pCS = m_pInitHighOrderScatteringCS; pPSO = m_pInitHighOrderScatteringPSO; pSRB = m_pInitHighOrderScatteringSRB; } else { std::swap( m_ptex3DHighOrderSctr, m_ptex3DHighOrderSctr2 ); m_pUpdateHighOrderScatteringSRB->GetVariable( SHADER_TYPE_COMPUTE, "g_tex3DHighOrderOrderScattering" )->Set( m_ptex3DHighOrderSctr2->GetDefaultView(TEXTURE_VIEW_SHADER_RESOURCE) ); pCS = m_pUpdateHighOrderScatteringCS; pPSO = m_pUpdateHighOrderScatteringPSO; pSRB = m_pUpdateHighOrderScatteringSRB; } pSRB->GetVariable( SHADER_TYPE_COMPUTE, "g_rwtex3DHighOrderSctr" )->Set( m_ptex3DHighOrderSctr->GetDefaultView( TEXTURE_VIEW_UNORDERED_ACCESS ) ); pSRB->GetVariable( SHADER_TYPE_COMPUTE, "g_tex3DCurrentOrderScattering" )->Set( ptex3DInsctrOrderSRV ); pContext->SetPipelineState(pPSO); pContext->CommitShaderResources(pSRB, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); pContext->DispatchCompute(DispatchAttrs); // Flush the command buffer to force execution of compute shaders and avoid device // reset on low-end Intel GPUs. pContext->Flush(); } // Note that m_ptex3DHighOrderSctr and m_ptex3DHighOrderSctr2 are ping-ponged during pre-processing m_ptex3DHighOrderScatteringSRV = m_ptex3DHighOrderSctr->GetDefaultView( TEXTURE_VIEW_SHADER_RESOURCE ); m_ptex3DHighOrderScatteringSRV->SetSampler( m_pLinearClampSampler ); m_pResMapping->AddResource("g_tex3DHighOrderSctrLUT", m_ptex3DHighOrderScatteringSRV, false); m_pCombineScatteringOrdersSRB->BindResources( SHADER_TYPE_COMPUTE, m_pResMapping, BIND_SHADER_RESOURCES_VERIFY_ALL_RESOLVED ); // Combine single scattering and higher order scattering into single texture pContext->SetPipelineState(m_pCombineScatteringOrdersPSO); pContext->CommitShaderResources(m_pCombineScatteringOrdersSRB, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); pContext->DispatchCompute(DispatchAttrs); m_pResMapping->RemoveResourceByName( "g_rwtex3DMultipleSctr" ); m_pResMapping->RemoveResourceByName( "g_rwtex3DSingleScattering" ); m_pResMapping->RemoveResourceByName( "g_rwtex3DSctrRadiance" ); m_pResMapping->RemoveResourceByName( "g_rwtex3DInsctrOrder" ); m_uiUpToDateResourceFlags |= UpToDateResourceFlags::PrecomputedIntegralsTex; } void LightSctrPostProcess :: CreateLowResLuminanceTexture(IRenderDevice* pDevice, IDeviceContext* pDeviceCtx) { // Create low-resolution texture to store image luminance TextureDesc TexDesc; TexDesc.Name = "Low Res Luminance"; TexDesc.Type = RESOURCE_DIM_TEX_2D; TexDesc.Width = 1 << (sm_iLowResLuminanceMips-1); TexDesc.Height = 1 << (sm_iLowResLuminanceMips-1); TexDesc.Format = LuminanceTexFmt, TexDesc.MipLevels = sm_iLowResLuminanceMips; TexDesc.Usage = USAGE_DEFAULT; TexDesc.BindFlags = BIND_RENDER_TARGET | BIND_SHADER_RESOURCE; TexDesc.MiscFlags = MISC_TEXTURE_FLAG_GENERATE_MIPS; RefCntAutoPtr<ITexture> tex2DLowResLuminance; pDevice->CreateTexture(TexDesc, nullptr, &tex2DLowResLuminance); m_ptex2DLowResLuminanceSRV = tex2DLowResLuminance->GetDefaultView(TEXTURE_VIEW_SHADER_RESOURCE); m_ptex2DLowResLuminanceRTV = tex2DLowResLuminance->GetDefaultView(TEXTURE_VIEW_RENDER_TARGET); m_ptex2DLowResLuminanceSRV->SetSampler(m_pLinearClampSampler); m_pResMapping->AddResource("g_tex2DLowResLuminance", m_ptex2DLowResLuminanceSRV, false); TexDesc.Name = "Average Luminance"; TexDesc.Width = 1; TexDesc.Height = 1; TexDesc.MipLevels = 1; TexDesc.MiscFlags = MISC_TEXTURE_FLAG_NONE; TexDesc.ClearValue.Color[0] = 0.1f; TexDesc.ClearValue.Color[1] = 0.1f; TexDesc.ClearValue.Color[2] = 0.1f; TexDesc.ClearValue.Color[3] = 0.1f; RefCntAutoPtr<ITexture> tex2DAverageLuminance; pDevice->CreateTexture(TexDesc, nullptr, &tex2DAverageLuminance); auto* tex2DAverageLuminanceSRV = tex2DAverageLuminance->GetDefaultView(TEXTURE_VIEW_SHADER_RESOURCE); m_ptex2DAverageLuminanceRTV = tex2DAverageLuminance->GetDefaultView(TEXTURE_VIEW_RENDER_TARGET); tex2DAverageLuminanceSRV->SetSampler(m_pLinearClampSampler); // Set intial luminance to 1 ITextureView* pRTVs[] = {m_ptex2DAverageLuminanceRTV}; pDeviceCtx->SetRenderTargets(1, pRTVs, nullptr, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); pDeviceCtx->ClearRenderTarget(m_ptex2DAverageLuminanceRTV, TexDesc.ClearValue.Color, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); tex2DAverageLuminanceSRV->SetSampler(m_pLinearClampSampler); m_pResMapping->AddResource("g_tex2DAverageLuminance", tex2DAverageLuminanceSRV, false); ResetShaderResourceBindings(); m_uiUpToDateResourceFlags |= UpToDateResourceFlags::LowResLuminamceTex; } void LightSctrPostProcess :: CreateSliceUVDirAndOriginTexture(IRenderDevice* pDevice) { TextureDesc TexDesc; TexDesc.Name = "Slice UV Dir and Origin"; TexDesc.Type = RESOURCE_DIM_TEX_2D; TexDesc.Width = m_PostProcessingAttribs.m_uiNumEpipolarSlices; TexDesc.Height = m_PostProcessingAttribs.m_iNumCascades; TexDesc.Format = SliceUVDirAndOriginTexFmt; TexDesc.MipLevels = 1; TexDesc.Usage = USAGE_DEFAULT; TexDesc.BindFlags = BIND_RENDER_TARGET | BIND_SHADER_RESOURCE; RefCntAutoPtr<ITexture> tex2DSliceUVDirAndOrigin; pDevice->CreateTexture(TexDesc, nullptr, &tex2DSliceUVDirAndOrigin); auto* tex2DSliceUVDirAndOriginSRV = tex2DSliceUVDirAndOrigin->GetDefaultView(TEXTURE_VIEW_SHADER_RESOURCE); m_ptex2DSliceUVDirAndOriginRTV = tex2DSliceUVDirAndOrigin->GetDefaultView(TEXTURE_VIEW_RENDER_TARGET); tex2DSliceUVDirAndOriginSRV->SetSampler(m_pLinearClampSampler); m_pResMapping->AddResource("g_tex2DSliceUVDirAndOrigin", tex2DSliceUVDirAndOriginSRV, false); m_uiUpToDateResourceFlags |= UpToDateResourceFlags::SliceUVDirAndOriginTex; ResetShaderResourceBindings(); } void LightSctrPostProcess :: CreateCamSpaceZTexture(IRenderDevice* pDevice) { TextureDesc TexDesc; TexDesc.Name = "Cam-space Z"; TexDesc.Type = RESOURCE_DIM_TEX_2D; TexDesc.Width = m_uiBackBufferWidth; TexDesc.Height = m_uiBackBufferHeight; TexDesc.Format = CamSpaceZFmt; TexDesc.MipLevels = 1; TexDesc.Usage = USAGE_DEFAULT; TexDesc.BindFlags = BIND_RENDER_TARGET | BIND_SHADER_RESOURCE; RefCntAutoPtr<ITexture> ptex2DCamSpaceZ; pDevice->CreateTexture(TexDesc, nullptr, &ptex2DCamSpaceZ); m_ptex2DCamSpaceZRTV = ptex2DCamSpaceZ->GetDefaultView(TEXTURE_VIEW_RENDER_TARGET); auto* tex2DCamSpaceZSRV = ptex2DCamSpaceZ->GetDefaultView(TEXTURE_VIEW_SHADER_RESOURCE); tex2DCamSpaceZSRV->SetSampler(m_pLinearClampSampler); // Add texture to resource mapping m_pResMapping->AddResource("g_tex2DCamSpaceZ", tex2DCamSpaceZSRV, false); } void LightSctrPostProcess :: ReconstructCameraSpaceZ(FrameAttribs& FrameAttribs) { // Depth buffer is non-linear and cannot be interpolated directly // We have to reconstruct camera space z to be able to use bilinear filtering if (!m_pReconstrCamSpaceZPSO) { ShaderMacroHelper Macros; DefineMacros(Macros); Macros.Finalize(); ShaderVariableDesc Vars[] = { {"cbCameraAttribs", SHADER_VARIABLE_TYPE_STATIC}, {"g_tex2DDepthBuffer", SHADER_VARIABLE_TYPE_DYNAMIC} }; auto pReconstrCamSpaceZPS = CreateShader( FrameAttribs.pDevice, "ReconstructCameraSpaceZ.fx", "ReconstructCameraSpaceZPS", SHADER_TYPE_PIXEL, Macros, SHADER_VARIABLE_TYPE_MUTABLE, Vars, _countof(Vars) ); // Bind input resources required by the shader pReconstrCamSpaceZPS->BindResources(m_pResMapping, BIND_SHADER_RESOURCES_VERIFY_ALL_RESOLVED); TEXTURE_FORMAT RTVFmts[] = {CamSpaceZFmt}; m_pReconstrCamSpaceZPSO = CreateScreenSizeQuadPSO(FrameAttribs.pDevice, "ReconstructCameraSpaceZPSO", pReconstrCamSpaceZPS, DSS_DisableDepth, BS_Default, 1, RTVFmts, TEX_FORMAT_UNKNOWN); m_pReconstrCamSpaceZPSO->CreateShaderResourceBinding(&m_pReconstrCamSpaceZSRB, true); m_pReconstrCamSpaceZSRB->BindResources(SHADER_TYPE_PIXEL, m_pResMapping, BIND_SHADER_RESOURCES_KEEP_EXISTING); } m_pReconstrCamSpaceZSRB->GetVariable(SHADER_TYPE_PIXEL, "g_tex2DDepthBuffer")->Set(FrameAttribs.ptex2DSrcDepthBufferSRV); ITextureView* ppRTVs[] = {m_ptex2DCamSpaceZRTV}; FrameAttribs.pDeviceContext->SetRenderTargets(1, ppRTVs, nullptr, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); RenderScreenSizeQuad(FrameAttribs.pDeviceContext, m_pReconstrCamSpaceZPSO, m_pReconstrCamSpaceZSRB); } void LightSctrPostProcess :: RenderSliceEndpoints(FrameAttribs& FrameAttribs) { if (!m_pRendedSliceEndpointsPSO) { ShaderMacroHelper Macros; DefineMacros(Macros); Macros.Finalize(); ShaderVariableDesc Vars[] = { {"cbLightParams", SHADER_VARIABLE_TYPE_STATIC} }; auto pRendedSliceEndpointsPS = CreateShader(FrameAttribs.pDevice, "RenderSliceEndPoints.fx", "GenerateSliceEndpointsPS", SHADER_TYPE_PIXEL, Macros, SHADER_VARIABLE_TYPE_MUTABLE, Vars, _countof(Vars)); // Bind input resources required by the shader pRendedSliceEndpointsPS->BindResources( m_pResMapping, BIND_SHADER_RESOURCES_VERIFY_ALL_RESOLVED ); TEXTURE_FORMAT RTVFmts[] = {SliceEndpointsFmt}; m_pRendedSliceEndpointsPSO = CreateScreenSizeQuadPSO(FrameAttribs.pDevice, "RenderSliceEndPoints", pRendedSliceEndpointsPS, DSS_DisableDepth, BS_Default, 1, RTVFmts); m_pRendedSliceEndpointsPSO->CreateShaderResourceBinding(&m_pRendedSliceEndpointsSRB, true); } ITextureView* ppRTVs[] = {m_ptex2DSliceEndpointsRTV}; FrameAttribs.pDeviceContext->SetRenderTargets(1, ppRTVs, nullptr, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); RenderScreenSizeQuad(FrameAttribs.pDeviceContext, m_pRendedSliceEndpointsPSO, m_pRendedSliceEndpointsSRB); } void LightSctrPostProcess :: RenderCoordinateTexture(FrameAttribs& FrameAttribs) { if (!m_pRendedCoordTexPSO) { ShaderMacroHelper Macros; DefineMacros(Macros); Macros.Finalize(); auto pRendedCoordTexPS = CreateShader(FrameAttribs.pDevice, "RenderCoordinateTexture.fx", "GenerateCoordinateTexturePS", SHADER_TYPE_PIXEL, Macros, SHADER_VARIABLE_TYPE_MUTABLE); pRendedCoordTexPS->BindResources(m_pResMapping, BIND_SHADER_RESOURCES_VERIFY_ALL_RESOLVED); TEXTURE_FORMAT RTVFmts[] = {CoordinateTexFmt, EpipolarCamSpaceZFmt}; m_pRendedCoordTexPSO = CreateScreenSizeQuadPSO(FrameAttribs.pDevice, "RenderCoordinateTexture", pRendedCoordTexPS, DSS_IncStencilAlways, BS_Default, 2, RTVFmts, EpipolarImageDepthFmt); m_pRendedCoordTexSRB.Release(); } if (!m_pRendedCoordTexSRB) { m_pRendedCoordTexPSO->CreateShaderResourceBinding(&m_pRendedCoordTexSRB, true); m_pRendedCoordTexSRB->BindResources(SHADER_TYPE_PIXEL, m_pResMapping, BIND_SHADER_RESOURCES_KEEP_EXISTING | BIND_SHADER_RESOURCES_VERIFY_ALL_RESOLVED); } ITextureView* ppRTVs[] = {m_ptex2DCoordinateTextureRTV, m_ptex2DEpipolarCamSpaceZRTV}; FrameAttribs.pDeviceContext->SetRenderTargets(2, ppRTVs, m_ptex2DEpipolarImageDSV, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); // Clear both render targets with values that can't be correct projection space coordinates and camera space Z: float InvalidCoords[] = {-1e+30f, -1e+30f, -1e+30f, -1e+30f}; FrameAttribs.pDeviceContext->ClearRenderTarget(m_ptex2DCoordinateTextureRTV, InvalidCoords, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); FrameAttribs.pDeviceContext->ClearRenderTarget(m_ptex2DEpipolarCamSpaceZRTV, InvalidCoords, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); FrameAttribs.pDeviceContext->ClearDepthStencil(m_ptex2DEpipolarImageDSV, CLEAR_DEPTH_FLAG | CLEAR_STENCIL_FLAG, 1.0, 0, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); // Depth stencil state is configured to always increment stencil value. If coordinates are outside the screen, // the pixel shader discards the pixel and stencil value is left untouched. All such pixels will be skipped from // further processing RenderScreenSizeQuad(FrameAttribs.pDeviceContext, m_pRendedCoordTexPSO, m_pRendedCoordTexSRB); } void LightSctrPostProcess :: RenderCoarseUnshadowedInctr(FrameAttribs &FrameAttribs) { if (!m_pRenderCoarseUnshadowedInsctrPSO) { ShaderMacroHelper Macros; DefineMacros(Macros); Macros.Finalize(); auto EntryPoint = m_PostProcessingAttribs.m_uiExtinctionEvalMode == EXTINCTION_EVAL_MODE_EPIPOLAR ? "RenderCoarseUnshadowedInsctrAndExtinctionPS" : "RenderCoarseUnshadowedInsctrPS"; ShaderVariableDesc Vars[] = { {"cbParticipatingMediaScatteringParams", SHADER_VARIABLE_TYPE_STATIC}, {"cbCameraAttribs", SHADER_VARIABLE_TYPE_STATIC}, {"cbLightParams", SHADER_VARIABLE_TYPE_STATIC} }; auto pRenderCoarseUnshadowedInsctrPS = CreateShader( FrameAttribs.pDevice, "CoarseInsctr.fx", EntryPoint, SHADER_TYPE_PIXEL, Macros, SHADER_VARIABLE_TYPE_MUTABLE, Vars, _countof(Vars)); pRenderCoarseUnshadowedInsctrPS->BindResources( m_pResMapping, BIND_SHADER_RESOURCES_VERIFY_ALL_RESOLVED ); const auto* PSOName = m_PostProcessingAttribs.m_uiExtinctionEvalMode == EXTINCTION_EVAL_MODE_EPIPOLAR ? "RenderCoarseUnshadowedInsctrAndExtinctionPSO" : "RenderCoarseUnshadowedInsctrPSO"; TEXTURE_FORMAT RTVFmts[] = {EpipolarInsctrTexFmt, EpipolarExtinctionFmt}; Uint8 NumRTVs = m_PostProcessingAttribs.m_uiExtinctionEvalMode == EXTINCTION_EVAL_MODE_EPIPOLAR ? 2 : 1; m_pRenderCoarseUnshadowedInsctrPSO = CreateScreenSizeQuadPSO(FrameAttribs.pDevice, PSOName, pRenderCoarseUnshadowedInsctrPS, DSS_StencilEqKeepStencil, BS_Default, NumRTVs, RTVFmts, EpipolarImageDepthFmt); m_pRenderCoarseUnshadowedInsctrSRB.Release(); } if( m_PostProcessingAttribs.m_uiExtinctionEvalMode == EXTINCTION_EVAL_MODE_EPIPOLAR && !(m_uiUpToDateResourceFlags & UpToDateResourceFlags::ExtinctionTexture) ) { // Extinction texture size is num_slices x max_samples_in_slice. So the texture must be re-created when either changes. CreateExtinctionTexture(FrameAttribs.pDevice); } ITextureView *pRTVs[] = {m_ptex2DEpipolarInscatteringRTV, m_ptex2DEpipolarExtinctionRTV}; FrameAttribs.pDeviceContext->SetRenderTargets(m_PostProcessingAttribs.m_uiExtinctionEvalMode == EXTINCTION_EVAL_MODE_EPIPOLAR ? 2 : 1, pRTVs, m_ptex2DEpipolarImageDSV, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); float flt16max = 65504.f; // Epipolar Inscattering is 16-bit float const float InvalidInsctr[] = {-flt16max, -flt16max, -flt16max, -flt16max}; if( m_ptex2DEpipolarInscatteringRTV ) FrameAttribs.pDeviceContext->ClearRenderTarget(m_ptex2DEpipolarInscatteringRTV, InvalidInsctr, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); const float One[] = {1, 1, 1, 1}; if( m_ptex2DEpipolarExtinctionRTV ) FrameAttribs.pDeviceContext->ClearRenderTarget(m_ptex2DEpipolarExtinctionRTV, One, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); if (!m_pRenderCoarseUnshadowedInsctrSRB) { m_pRenderCoarseUnshadowedInsctrPSO->CreateShaderResourceBinding(&m_pRenderCoarseUnshadowedInsctrSRB, true); m_pRenderCoarseUnshadowedInsctrSRB->BindResources(SHADER_TYPE_PIXEL, m_pResMapping, BIND_SHADER_RESOURCES_KEEP_EXISTING | BIND_SHADER_RESOURCES_VERIFY_ALL_RESOLVED); } RenderScreenSizeQuad(FrameAttribs.pDeviceContext, m_pRenderCoarseUnshadowedInsctrPSO, m_pRenderCoarseUnshadowedInsctrSRB, 1); } void LightSctrPostProcess :: RefineSampleLocations(FrameAttribs &FrameAttribs) { if( !m_pRefineSampleLocationsCS ) { // Thread group size must be at least as large as initial sample step m_uiSampleRefinementCSThreadGroupSize = std::max( m_uiSampleRefinementCSMinimumThreadGroupSize, m_PostProcessingAttribs.m_uiInitialSampleStepInSlice ); // Thread group size cannot be larger than the total number of samples in slice m_uiSampleRefinementCSThreadGroupSize = std::min( m_uiSampleRefinementCSThreadGroupSize, m_PostProcessingAttribs.m_uiMaxSamplesInSlice ); // Using small group size is inefficient since a lot of SIMD lanes become idle ShaderMacroHelper Macros; DefineMacros(Macros); Macros.AddShaderMacro("INITIAL_SAMPLE_STEP", m_PostProcessingAttribs.m_uiInitialSampleStepInSlice); Macros.AddShaderMacro("THREAD_GROUP_SIZE" , m_uiSampleRefinementCSThreadGroupSize ); Macros.AddShaderMacro("REFINEMENT_CRITERION", m_PostProcessingAttribs.m_uiRefinementCriterion ); Macros.AddShaderMacro("AUTO_EXPOSURE", m_PostProcessingAttribs.m_bAutoExposure); Macros.Finalize(); ShaderVariableDesc Vars[] = { {"cbLightParams", SHADER_VARIABLE_TYPE_STATIC}, {"cbPostProcessingAttribs", SHADER_VARIABLE_TYPE_STATIC} }; m_pRefineSampleLocationsCS = CreateShader( FrameAttribs.pDevice, "RefineSampleLocations.fx", "RefineSampleLocationsCS", SHADER_TYPE_COMPUTE, Macros, SHADER_VARIABLE_TYPE_MUTABLE, Vars, _countof(Vars)); PipelineStateDesc PSODesc; PSODesc.IsComputePipeline = true; PSODesc.ComputePipeline.pCS = m_pRefineSampleLocationsCS; m_pRefineSampleLocationsPSO.Release(); m_pRefineSampleLocationsSRB.Release(); FrameAttribs.pDevice->CreatePipelineState(PSODesc, &m_pRefineSampleLocationsPSO); } m_pRefineSampleLocationsCS->BindResources( m_pResMapping, BIND_SHADER_RESOURCES_VERIFY_ALL_RESOLVED ); if( !m_pRefineSampleLocationsSRB ) { m_pRefineSampleLocationsPSO->CreateShaderResourceBinding(&m_pRefineSampleLocationsSRB, true); m_pRefineSampleLocationsSRB->BindResources(SHADER_TYPE_COMPUTE, m_pResMapping, BIND_SHADER_RESOURCES_VERIFY_ALL_RESOLVED); } DispatchComputeAttribs DispatchAttrs( m_PostProcessingAttribs.m_uiMaxSamplesInSlice/m_uiSampleRefinementCSThreadGroupSize, m_PostProcessingAttribs.m_uiNumEpipolarSlices, 1); FrameAttribs.pDeviceContext->SetPipelineState(m_pRefineSampleLocationsPSO); FrameAttribs.pDeviceContext->CommitShaderResources(m_pRefineSampleLocationsSRB, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); FrameAttribs.pDeviceContext->DispatchCompute(DispatchAttrs); } void LightSctrPostProcess :: MarkRayMarchingSamples(FrameAttribs &FrameAttribs) { if (!m_pMarkRayMarchingSamplesInStencilPSO) { ShaderMacroHelper Macros; DefineMacros(Macros); Macros.Finalize(); auto pMarkRayMarchingSamplesInStencilPS = CreateShader( FrameAttribs.pDevice, "MarkRayMarchingSamples.fx", "MarkRayMarchingSamplesInStencilPS", SHADER_TYPE_PIXEL, Macros, SHADER_VARIABLE_TYPE_MUTABLE ); pMarkRayMarchingSamplesInStencilPS->BindResources(m_pResMapping, BIND_SHADER_RESOURCES_VERIFY_ALL_RESOLVED); m_pMarkRayMarchingSamplesInStencilPSO = CreateScreenSizeQuadPSO(FrameAttribs.pDevice, "MarkRayMarchingSamples", pMarkRayMarchingSamplesInStencilPS, DSS_StencilEqIncStencil, BS_Default, 0, nullptr, EpipolarImageDepthFmt); m_pMarkRayMarchingSamplesInStencilSRB.Release(); } // Mark ray marching samples in the stencil // The depth stencil state is configured to pass only pixels, whose stencil value equals 1. Thus all epipolar samples with // coordinates outsied the screen (generated on the previous pass) are automatically discarded. The pixel shader only // passes samples which are interpolated from themselves, the rest are discarded. Thus after this pass all ray // marching samples will be marked with 2 in stencil if (!m_pMarkRayMarchingSamplesInStencilSRB) { m_pMarkRayMarchingSamplesInStencilPSO->CreateShaderResourceBinding(&m_pMarkRayMarchingSamplesInStencilSRB, true); m_pMarkRayMarchingSamplesInStencilSRB->BindResources(SHADER_TYPE_PIXEL, m_pResMapping, BIND_SHADER_RESOURCES_KEEP_EXISTING | BIND_SHADER_RESOURCES_VERIFY_ALL_RESOLVED); } FrameAttribs.pDeviceContext->SetRenderTargets(0, nullptr, m_ptex2DEpipolarImageDSV, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); RenderScreenSizeQuad(FrameAttribs.pDeviceContext, m_pMarkRayMarchingSamplesInStencilPSO, m_pMarkRayMarchingSamplesInStencilSRB, 1); } void LightSctrPostProcess :: RenderSliceUVDirAndOrig(FrameAttribs &FrameAttribs) { if (!m_pRenderSliceUVDirInSM_PSO) { ShaderMacroHelper Macros; DefineMacros(Macros); Macros.Finalize(); ShaderVariableDesc Vars[] = { {"cbLightParams", SHADER_VARIABLE_TYPE_STATIC}, {"cbCameraAttribs", SHADER_VARIABLE_TYPE_STATIC}, {"cbPostProcessingAttribs", SHADER_VARIABLE_TYPE_STATIC} }; auto pRenderSliceUVDirInSMPS = CreateShader(FrameAttribs.pDevice, "SliceUVDirection.fx", "RenderSliceUVDirInShadowMapTexturePS", SHADER_TYPE_PIXEL, Macros, SHADER_VARIABLE_TYPE_MUTABLE, Vars, _countof(Vars)); pRenderSliceUVDirInSMPS->BindResources(m_pResMapping, BIND_SHADER_RESOURCES_VERIFY_ALL_RESOLVED); TEXTURE_FORMAT RTVFmts[] = {SliceUVDirAndOriginTexFmt}; m_pRenderSliceUVDirInSM_PSO = CreateScreenSizeQuadPSO(FrameAttribs.pDevice, "RenderSliceUVDirAndOrigin", pRenderSliceUVDirInSMPS, DSS_DisableDepth, BS_Default, 1, RTVFmts); m_pRenderSliceUVDirInSM_SRB.Release(); } if( !(m_uiUpToDateResourceFlags & UpToDateResourceFlags::SliceUVDirAndOriginTex) ) { CreateSliceUVDirAndOriginTexture(FrameAttribs.pDevice); } if (FrameAttribs.pDevice->GetDeviceCaps().DevType == DeviceType::Vulkan) { // NOTE: this is only needed as a workaround until GLSLang optimizes out unused shader resources. // If m_pcbMiscParams is not mapped, it causes an error on Vulkan backend because it finds // a dynamic buffer that has not been mapped before the first use. MapHelper<MiscDynamicParams> pMiscDynamicParams(FrameAttribs.pDeviceContext, m_pcbMiscParams, MAP_WRITE, MAP_FLAG_DISCARD); } if (!m_pRenderSliceUVDirInSM_SRB) { m_pRenderSliceUVDirInSM_PSO->CreateShaderResourceBinding(&m_pRenderSliceUVDirInSM_SRB, true); m_pRenderSliceUVDirInSM_SRB->BindResources(SHADER_TYPE_PIXEL, m_pResMapping, BIND_SHADER_RESOURCES_KEEP_EXISTING | BIND_SHADER_RESOURCES_VERIFY_ALL_RESOLVED); } ITextureView* ppRTVs[] = {m_ptex2DSliceUVDirAndOriginRTV}; FrameAttribs.pDeviceContext->SetRenderTargets(1, ppRTVs, nullptr, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); RenderScreenSizeQuad(FrameAttribs.pDeviceContext, m_pRenderSliceUVDirInSM_PSO, m_pRenderSliceUVDirInSM_SRB, 0); } void LightSctrPostProcess :: Build1DMinMaxMipMap(FrameAttribs &FrameAttribs, int iCascadeIndex) { if (!m_pInitializeMinMaxShadowMapPSO) { ShaderMacroHelper Macros; DefineMacros(Macros); Macros.AddShaderMacro("IS_32BIT_MIN_MAX_MAP", m_PostProcessingAttribs.m_bIs32BitMinMaxMipMap); Macros.Finalize(); ShaderVariableDesc Vars[] = { {"g_tex2DSliceUVDirAndOrigin", SHADER_VARIABLE_TYPE_MUTABLE}, {"g_tex2DLightSpaceDepthMap", SHADER_VARIABLE_TYPE_DYNAMIC} }; auto pInitializeMinMaxShadowMapPS = CreateShader( FrameAttribs.pDevice, "InitializeMinMaxShadowMap.fx", "InitializeMinMaxShadowMapPS", SHADER_TYPE_PIXEL, Macros, SHADER_VARIABLE_TYPE_STATIC, Vars, _countof(Vars) ); pInitializeMinMaxShadowMapPS->BindResources(m_pResMapping, BIND_SHADER_RESOURCES_VERIFY_ALL_RESOLVED); TEXTURE_FORMAT RTVFmts[] = {m_ptex2DMinMaxShadowMapSRV[0]->GetTexture()->GetDesc().Format}; m_pInitializeMinMaxShadowMapPSO = CreateScreenSizeQuadPSO(FrameAttribs.pDevice, "InitMinMaxShadowMap", pInitializeMinMaxShadowMapPS, DSS_DisableDepth, BS_Default, 1, RTVFmts); m_pInitializeMinMaxShadowMapSRB.Release(); } if (!m_pComputeMinMaxSMLevelPSO) { ShaderMacroHelper Macros; DefineMacros(Macros); Macros.Finalize(); ShaderVariableDesc VarDesc[] = { {"cbMiscDynamicParams", SHADER_VARIABLE_TYPE_STATIC} }; auto pComputeMinMaxSMLevelPS = CreateShader( FrameAttribs.pDevice, "ComputeMinMaxShadowMapLevel.fx", "ComputeMinMaxShadowMapLevelPS", SHADER_TYPE_PIXEL, Macros, SHADER_VARIABLE_TYPE_MUTABLE, VarDesc, _countof(VarDesc) ); pComputeMinMaxSMLevelPS->BindResources(m_pResMapping, BIND_SHADER_RESOURCES_VERIFY_ALL_RESOLVED); TEXTURE_FORMAT RTVFmts[] = {m_ptex2DMinMaxShadowMapSRV[0]->GetTexture()->GetDesc().Format}; m_pComputeMinMaxSMLevelPSO = CreateScreenSizeQuadPSO(FrameAttribs.pDevice, "ComputeMinMaxShadowMapLevel", pComputeMinMaxSMLevelPS, DSS_DisableDepth, BS_Default, 1, RTVFmts); m_pComputeMinMaxSMLevelSRB[0].Release(); m_pComputeMinMaxSMLevelSRB[1].Release(); } if (!m_pComputeMinMaxSMLevelSRB[0]) { for(int Parity = 0; Parity < 2; ++Parity) { m_pComputeMinMaxSMLevelPSO->CreateShaderResourceBinding(&m_pComputeMinMaxSMLevelSRB[Parity], true); auto *pVar = m_pComputeMinMaxSMLevelSRB[Parity]->GetVariable(SHADER_TYPE_PIXEL, "g_tex2DMinMaxLightSpaceDepth"); pVar->Set(m_ptex2DMinMaxShadowMapSRV[Parity]); m_pComputeMinMaxSMLevelSRB[Parity]->BindResources(SHADER_TYPE_PIXEL | SHADER_TYPE_VERTEX, m_pResMapping, BIND_SHADER_RESOURCES_KEEP_EXISTING | BIND_SHADER_RESOURCES_VERIFY_ALL_RESOLVED); } } auto pShadowSampler = FrameAttribs.ptex2DShadowMapSRV->GetSampler(); FrameAttribs.ptex2DShadowMapSRV->SetSampler( m_pLinearClampSampler ); auto iMinMaxTexHeight = m_PostProcessingAttribs.m_uiNumEpipolarSlices; if( m_bUseCombinedMinMaxTexture ) iMinMaxTexHeight *= (m_PostProcessingAttribs.m_iNumCascades - m_PostProcessingAttribs.m_iFirstCascade); auto tex2DMinMaxShadowMap0 = m_ptex2DMinMaxShadowMapRTV[0]->GetTexture(); auto tex2DMinMaxShadowMap1 = m_ptex2DMinMaxShadowMapRTV[1]->GetTexture(); // Computing min/max mip map using compute shader is much slower because a lot of threads are idle Uint32 uiXOffset = 0; Uint32 uiPrevXOffset = 0; Uint32 uiParity = 0; #ifdef _DEBUG { const auto &MinMaxShadowMapTexDesc = m_ptex2DMinMaxShadowMapRTV[0]->GetTexture()->GetDesc(); assert( MinMaxShadowMapTexDesc.Width == m_PostProcessingAttribs.m_uiMinMaxShadowMapResolution ); assert( MinMaxShadowMapTexDesc.Height == iMinMaxTexHeight ); } #endif // Note that we start rendering min/max shadow map from step == 2 for(Uint32 iStep = 2; iStep <= (Uint32)m_PostProcessingAttribs.m_fMaxShadowMapStep; iStep *=2, uiParity = (uiParity+1)%2 ) { // Use two buffers which are in turn used as the source and destination ITextureView *pRTVs[] = {m_ptex2DMinMaxShadowMapRTV[uiParity]}; FrameAttribs.pDeviceContext->SetRenderTargets( _countof( pRTVs ), pRTVs, nullptr, RESOURCE_STATE_TRANSITION_MODE_TRANSITION ); Viewport VP; VP.Width = static_cast<float>( m_PostProcessingAttribs.m_uiMinMaxShadowMapResolution / iStep ); VP.Height = static_cast<float>( iMinMaxTexHeight ); VP.TopLeftX = static_cast<float>( uiXOffset ); VP.TopLeftY = 0; FrameAttribs.pDeviceContext->SetViewports(1, &VP, 0, 0 ); // Set source and destination min/max data offsets: { MapHelper<MiscDynamicParams> pMiscDynamicParams( FrameAttribs.pDeviceContext, m_pcbMiscParams, MAP_WRITE, MAP_FLAG_DISCARD ); pMiscDynamicParams->ui4SrcMinMaxLevelXOffset = uiPrevXOffset; pMiscDynamicParams->ui4DstMinMaxLevelXOffset = uiXOffset; pMiscDynamicParams->fCascadeInd = static_cast<float>(iCascadeIndex); } if( iStep == 2 ) { // At the initial pass, the shader gathers 8 depths which will be used for // PCF filtering at the sample location and its next neighbor along the slice // and outputs min/max depths if (!m_pInitializeMinMaxShadowMapSRB) { m_pInitializeMinMaxShadowMapPSO->CreateShaderResourceBinding(&m_pInitializeMinMaxShadowMapSRB, true); m_pInitializeMinMaxShadowMapSRB->BindResources(SHADER_TYPE_PIXEL, m_pResMapping, BIND_SHADER_RESOURCES_KEEP_EXISTING | BIND_SHADER_RESOURCES_VERIFY_ALL_RESOLVED); } // Set dynamic variable g_tex2DLightSpaceDepthMap m_pInitializeMinMaxShadowMapSRB->GetVariable(SHADER_TYPE_PIXEL, "g_tex2DLightSpaceDepthMap")->Set(FrameAttribs.ptex2DShadowMapSRV); RenderScreenSizeQuad(FrameAttribs.pDeviceContext, m_pInitializeMinMaxShadowMapPSO, m_pInitializeMinMaxShadowMapSRB); } else { // At the subsequent passes, the shader loads two min/max values from the next finer level // to compute next level of the binary tree RenderScreenSizeQuad(FrameAttribs.pDeviceContext, m_pComputeMinMaxSMLevelPSO, m_pComputeMinMaxSMLevelSRB[(uiParity + 1) % 2]); } // All the data must reside in 0-th texture, so copy current level, if necessary, from 1-st texture if( uiParity == 1 ) { Box SrcBox; SrcBox.MinX = uiXOffset; SrcBox.MaxX = uiXOffset + m_PostProcessingAttribs.m_uiMinMaxShadowMapResolution / iStep; SrcBox.MinY = 0; SrcBox.MaxY = iMinMaxTexHeight; CopyTextureAttribs CopyAttribs(tex2DMinMaxShadowMap1, RESOURCE_STATE_TRANSITION_MODE_TRANSITION, tex2DMinMaxShadowMap0, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); CopyAttribs.pSrcBox = &SrcBox; CopyAttribs.DstX = uiXOffset; FrameAttribs.pDeviceContext->CopyTexture(CopyAttribs); } uiPrevXOffset = uiXOffset; uiXOffset += m_PostProcessingAttribs.m_uiMinMaxShadowMapResolution / iStep; } FrameAttribs.ptex2DShadowMapSRV->SetSampler( pShadowSampler ); } void LightSctrPostProcess :: DoRayMarching(FrameAttribs &FrameAttribs, Uint32 uiMaxStepsAlongRay, int iCascadeIndex) { auto& pDoRayMarchPSO = m_pDoRayMarchPSO[m_PostProcessingAttribs.m_bUse1DMinMaxTree ? 1 : 0]; auto& pDoRayMarchSRB = m_pDoRayMarchSRB[m_PostProcessingAttribs.m_bUse1DMinMaxTree ? 1 : 0]; if (!pDoRayMarchPSO) { ShaderMacroHelper Macros; DefineMacros(Macros); Macros.AddShaderMacro("CASCADE_PROCESSING_MODE", m_PostProcessingAttribs.m_uiCascadeProcessingMode); Macros.AddShaderMacro("USE_1D_MIN_MAX_TREE", m_PostProcessingAttribs.m_bUse1DMinMaxTree); Macros.Finalize(); ShaderVariableDesc Vars[] = { {"cbParticipatingMediaScatteringParams", SHADER_VARIABLE_TYPE_STATIC}, {"cbLightParams", SHADER_VARIABLE_TYPE_STATIC}, {"cbCameraAttribs", SHADER_VARIABLE_TYPE_STATIC}, {"cbPostProcessingAttribs", SHADER_VARIABLE_TYPE_STATIC}, {"cbMiscDynamicParams", SHADER_VARIABLE_TYPE_STATIC} }; auto pDoRayMarchPS = CreateShader( FrameAttribs.pDevice, "RayMarch.fx", "RayMarchPS", SHADER_TYPE_PIXEL, Macros, SHADER_VARIABLE_TYPE_MUTABLE, Vars, _countof(Vars) ); pDoRayMarchPS->BindResources(m_pResMapping, BIND_SHADER_RESOURCES_VERIFY_ALL_RESOLVED); TEXTURE_FORMAT RTVFmts[] = {EpipolarInsctrTexFmt}; pDoRayMarchPSO = CreateScreenSizeQuadPSO(FrameAttribs.pDevice, "RayMarch", pDoRayMarchPS, DSS_StencilEqKeepStencil, BS_AdditiveBlend, 1, RTVFmts, EpipolarImageDepthFmt); pDoRayMarchSRB.Release(); } { MapHelper<MiscDynamicParams> pMiscDynamicParams( FrameAttribs.pDeviceContext, m_pcbMiscParams, MAP_WRITE, MAP_FLAG_DISCARD ); pMiscDynamicParams->fMaxStepsAlongRay = static_cast<float>( uiMaxStepsAlongRay ); pMiscDynamicParams->fCascadeInd = static_cast<float>(iCascadeIndex); } int iNumInst = 0; if( m_PostProcessingAttribs.m_bEnableLightShafts ) { switch(m_PostProcessingAttribs.m_uiCascadeProcessingMode) { case CASCADE_PROCESSING_MODE_SINGLE_PASS: case CASCADE_PROCESSING_MODE_MULTI_PASS: iNumInst = 1; break; case CASCADE_PROCESSING_MODE_MULTI_PASS_INST: iNumInst = m_PostProcessingAttribs.m_iNumCascades - m_PostProcessingAttribs.m_iFirstCascade; break; } } else { iNumInst = 1; } // Depth stencil view now contains 2 for these pixels, for which ray marchings is to be performed // Depth stencil state is configured to pass only these pixels and discard the rest if (!pDoRayMarchSRB) { pDoRayMarchPSO->CreateShaderResourceBinding(&pDoRayMarchSRB, true); if (FrameAttribs.pDevice->GetDeviceCaps().IsVulkanDevice()) { m_pResMapping->AddResource("g_tex2DColorBuffer", FrameAttribs.ptex2DSrcColorBufferSRV, false); FrameAttribs.ptex2DSrcColorBufferSRV->SetSampler(m_pLinearClampSampler); } pDoRayMarchSRB->BindResources(SHADER_TYPE_PIXEL, m_pResMapping, BIND_SHADER_RESOURCES_KEEP_EXISTING | BIND_SHADER_RESOURCES_VERIFY_ALL_RESOLVED); } ITextureView* ppRTVs[] = {m_ptex2DInitialScatteredLightRTV}; FrameAttribs.pDeviceContext->SetRenderTargets(1, ppRTVs, m_ptex2DEpipolarImageDSV, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); RenderScreenSizeQuad(FrameAttribs.pDeviceContext, pDoRayMarchPSO, pDoRayMarchSRB, 2, iNumInst); } void LightSctrPostProcess :: InterpolateInsctrIrradiance(FrameAttribs &FrameAttribs) { if (!m_pInterpolateIrradiancePSO) { ShaderMacroHelper Macros; DefineMacros(Macros); Macros.Finalize(); auto pInterpolateIrradiancePS = CreateShader( FrameAttribs.pDevice, "InterpolateIrradiance.fx", "InterpolateIrradiancePS", SHADER_TYPE_PIXEL, Macros, SHADER_VARIABLE_TYPE_MUTABLE ); pInterpolateIrradiancePS->BindResources(m_pResMapping, BIND_SHADER_RESOURCES_VERIFY_ALL_RESOLVED); TEXTURE_FORMAT RTVFmts[] = {EpipolarInsctrTexFmt}; m_pInterpolateIrradiancePSO = CreateScreenSizeQuadPSO(FrameAttribs.pDevice, "InterpolateIrradiance", pInterpolateIrradiancePS, DSS_DisableDepth, BS_Default, 1, RTVFmts); m_pInterpolateIrradianceSRB.Release(); } if (!m_pInterpolateIrradianceSRB) { m_pInterpolateIrradiancePSO->CreateShaderResourceBinding(&m_pInterpolateIrradianceSRB, true); m_pInterpolateIrradianceSRB->BindResources(SHADER_TYPE_PIXEL, m_pResMapping, BIND_SHADER_RESOURCES_KEEP_EXISTING | BIND_SHADER_RESOURCES_VERIFY_ALL_RESOLVED); } ITextureView* ppRTVs[] = {m_ptex2DEpipolarInscatteringRTV}; FrameAttribs.pDeviceContext->SetRenderTargets(1, ppRTVs, nullptr, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); RenderScreenSizeQuad(FrameAttribs.pDeviceContext, m_pInterpolateIrradiancePSO, m_pInterpolateIrradianceSRB); } void LightSctrPostProcess :: UnwarpEpipolarScattering(FrameAttribs &FrameAttribs, bool bRenderLuminance) { if (!m_pUnwarpEpipolarSctrImgPSO) { ShaderMacroHelper Macros; DefineMacros(Macros); Macros.AddShaderMacro("PERFORM_TONE_MAPPING", true); Macros.AddShaderMacro("AUTO_EXPOSURE", m_PostProcessingAttribs.m_bAutoExposure); Macros.AddShaderMacro("TONE_MAPPING_MODE", m_PostProcessingAttribs.m_uiToneMappingMode); Macros.AddShaderMacro("CORRECT_INSCATTERING_AT_DEPTH_BREAKS", m_PostProcessingAttribs.m_bCorrectScatteringAtDepthBreaks); Macros.Finalize(); ShaderVariableDesc Vars[] = { {"cbParticipatingMediaScatteringParams", SHADER_VARIABLE_TYPE_STATIC}, {"cbLightParams", SHADER_VARIABLE_TYPE_STATIC}, {"cbCameraAttribs", SHADER_VARIABLE_TYPE_STATIC}, {"cbPostProcessingAttribs", SHADER_VARIABLE_TYPE_STATIC}, {"cbMiscDynamicParams", SHADER_VARIABLE_TYPE_STATIC}, {"g_tex2DColorBuffer", SHADER_VARIABLE_TYPE_DYNAMIC}, }; auto pUnwarpEpipolarSctrImgPS = CreateShader( FrameAttribs.pDevice, "UnwarpEpipolarScattering.fx", "ApplyInscatteredRadiancePS", SHADER_TYPE_PIXEL, Macros, SHADER_VARIABLE_TYPE_MUTABLE, Vars, _countof(Vars) ); pUnwarpEpipolarSctrImgPS->BindResources(m_pResMapping, 0); TEXTURE_FORMAT RTVFmts[] = {m_BackBufferFmt}; m_pUnwarpEpipolarSctrImgPSO = CreateScreenSizeQuadPSO(FrameAttribs.pDevice, "UnwarpEpipolarScattering", pUnwarpEpipolarSctrImgPS, DSS_Default, BS_Default, 1, RTVFmts, m_DepthBufferFmt); m_pUnwarpEpipolarSctrImgSRB.Release(); } if (!m_pUnwarpAndRenderLuminancePSO) { ShaderMacroHelper Macros; DefineMacros(Macros); Macros.AddShaderMacro("PERFORM_TONE_MAPPING", false); // No inscattering correction - we need to render the entire image in low resolution Macros.AddShaderMacro("CORRECT_INSCATTERING_AT_DEPTH_BREAKS", false); Macros.Finalize(); ShaderVariableDesc Vars[] = { {"cbParticipatingMediaScatteringParams", SHADER_VARIABLE_TYPE_STATIC}, {"cbLightParams", SHADER_VARIABLE_TYPE_STATIC}, {"cbCameraAttribs", SHADER_VARIABLE_TYPE_STATIC}, {"cbPostProcessingAttribs", SHADER_VARIABLE_TYPE_STATIC}, {"cbMiscDynamicParams", SHADER_VARIABLE_TYPE_STATIC}, {"g_tex2DColorBuffer", SHADER_VARIABLE_TYPE_DYNAMIC}, }; auto pUnwarpAndRenderLuminancePS = CreateShader( FrameAttribs.pDevice, "UnwarpEpipolarScattering.fx", "ApplyInscatteredRadiancePS", SHADER_TYPE_PIXEL, Macros, SHADER_VARIABLE_TYPE_MUTABLE, Vars, _countof(Vars) ); pUnwarpAndRenderLuminancePS->BindResources(m_pResMapping, 0); TEXTURE_FORMAT RTVFmts[] = {LuminanceTexFmt}; m_pUnwarpAndRenderLuminancePSO = CreateScreenSizeQuadPSO(FrameAttribs.pDevice, "UnwarpAndRenderLuminance", pUnwarpAndRenderLuminancePS, DSS_DisableDepth, BS_Default, 1, RTVFmts); m_pUnwarpAndRenderLuminanceSRB.Release(); } FrameAttribs.ptex2DSrcColorBufferSRV->SetSampler(m_pPointClampSampler); // Unwarp inscattering image and apply it to attenuated backgorund if(bRenderLuminance) { if (!m_pUnwarpAndRenderLuminanceSRB) { m_pUnwarpAndRenderLuminancePSO->CreateShaderResourceBinding(&m_pUnwarpAndRenderLuminanceSRB, true); m_pUnwarpAndRenderLuminanceSRB->BindResources(SHADER_TYPE_PIXEL, m_pResMapping, BIND_SHADER_RESOURCES_KEEP_EXISTING); } // Set dynamic variable g_tex2DColorBuffer m_pUnwarpAndRenderLuminanceSRB->GetVariable(SHADER_TYPE_PIXEL, "g_tex2DColorBuffer")->Set(FrameAttribs.ptex2DSrcColorBufferSRV); // Disable depth testing - we need to render the entire image in low resolution RenderScreenSizeQuad(FrameAttribs.pDeviceContext, m_pUnwarpAndRenderLuminancePSO, m_pUnwarpAndRenderLuminanceSRB); } else { if (!m_pUnwarpEpipolarSctrImgSRB) { m_pUnwarpEpipolarSctrImgPSO->CreateShaderResourceBinding(&m_pUnwarpEpipolarSctrImgSRB, true); m_pUnwarpEpipolarSctrImgSRB->BindResources(SHADER_TYPE_PIXEL, m_pResMapping, BIND_SHADER_RESOURCES_KEEP_EXISTING); } // Set dynamic variable g_tex2DColorBuffer m_pUnwarpEpipolarSctrImgSRB->GetVariable(SHADER_TYPE_PIXEL, "g_tex2DColorBuffer")->Set(FrameAttribs.ptex2DSrcColorBufferSRV); // Enable depth testing to write 0.0 to the depth buffer. All pixel that require // inscattering correction (if enabled) will be discarded, so that 1.0 will be retained // This 1.0 will then be used to perform inscattering correction RenderScreenSizeQuad(FrameAttribs.pDeviceContext, m_pUnwarpEpipolarSctrImgPSO, m_pUnwarpEpipolarSctrImgSRB); } } void LightSctrPostProcess :: UpdateAverageLuminance(FrameAttribs &FrameAttribs) { if (!m_pUpdateAverageLuminancePSO) { ShaderMacroHelper Macros; DefineMacros(Macros); Macros.AddShaderMacro( "LIGHT_ADAPTATION", m_PostProcessingAttribs.m_bLightAdaptation ); // static_cast<int>() is required because Run() gets its arguments by reference // and gcc will try to find reference to sm_iLowResLuminanceMips, which does not exist Macros.AddShaderMacro("LOW_RES_LUMINANCE_MIPS", static_cast<int>(sm_iLowResLuminanceMips) ); Macros.Finalize(); ShaderVariableDesc Vars[] = { {"cbMiscDynamicParams", SHADER_VARIABLE_TYPE_STATIC} }; auto pUpdateAverageLuminancePS = CreateShader( FrameAttribs.pDevice, "UpdateAverageLuminance.fx", "UpdateAverageLuminancePS", SHADER_TYPE_PIXEL, Macros, SHADER_VARIABLE_TYPE_MUTABLE, Vars, _countof(Vars) ); pUpdateAverageLuminancePS->BindResources(m_pResMapping, BIND_SHADER_RESOURCES_VERIFY_ALL_RESOLVED); TEXTURE_FORMAT RTVFmts[] = {LuminanceTexFmt}; m_pUpdateAverageLuminancePSO = CreateScreenSizeQuadPSO(FrameAttribs.pDevice, "UpdateAverageLuminance", pUpdateAverageLuminancePS, DSS_DisableDepth, BS_AlphaBlend, 1, RTVFmts); m_pUpdateAverageLuminanceSRB.Release(); } { MapHelper<MiscDynamicParams> pMiscDynamicParams( FrameAttribs.pDeviceContext, m_pcbMiscParams, MAP_WRITE, MAP_FLAG_DISCARD ); pMiscDynamicParams->fElapsedTime = (float)FrameAttribs.dElapsedTime; } if (!m_pUpdateAverageLuminanceSRB) { m_pUpdateAverageLuminancePSO->CreateShaderResourceBinding(&m_pUpdateAverageLuminanceSRB, true); m_pUpdateAverageLuminanceSRB->BindResources(SHADER_TYPE_PIXEL, m_pResMapping, BIND_SHADER_RESOURCES_KEEP_EXISTING | BIND_SHADER_RESOURCES_VERIFY_ALL_RESOLVED); } ITextureView* ppRTVs[] = {m_ptex2DAverageLuminanceRTV}; FrameAttribs.pDeviceContext->SetRenderTargets(1, ppRTVs, nullptr, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); RenderScreenSizeQuad(FrameAttribs.pDeviceContext, m_pUpdateAverageLuminancePSO, m_pUpdateAverageLuminanceSRB); } void LightSctrPostProcess :: FixInscatteringAtDepthBreaks(FrameAttribs &FrameAttribs, Uint32 uiMaxStepsAlongRay, EFixInscatteringMode Mode) { //bool bRenderLuminance = Mode == EFixInscatteringMode::LuminanceOnly; if (!m_pFixInsctrAtDepthBreaksPSO[0]) { RefCntAutoPtr<IShader> pFixInsctrAtDepthBreaksPS[2]; // 0 - perform tone mapping, 1 - render luminance only for( int RenderLum = 0; RenderLum < 2; ++RenderLum ) { ShaderMacroHelper Macros; DefineMacros(Macros); Macros.AddShaderMacro("CASCADE_PROCESSING_MODE", CASCADE_PROCESSING_MODE_SINGLE_PASS); Macros.AddShaderMacro("PERFORM_TONE_MAPPING", RenderLum == 0); Macros.AddShaderMacro("AUTO_EXPOSURE", m_PostProcessingAttribs.m_bAutoExposure); Macros.AddShaderMacro("TONE_MAPPING_MODE", m_PostProcessingAttribs.m_uiToneMappingMode); Macros.AddShaderMacro("USE_1D_MIN_MAX_TREE", false); Macros.Finalize(); ShaderVariableDesc Vars[] = { {"cbParticipatingMediaScatteringParams", SHADER_VARIABLE_TYPE_STATIC}, {"cbLightParams", SHADER_VARIABLE_TYPE_STATIC}, {"cbCameraAttribs", SHADER_VARIABLE_TYPE_STATIC}, {"cbPostProcessingAttribs", SHADER_VARIABLE_TYPE_STATIC}, {"cbMiscDynamicParams", SHADER_VARIABLE_TYPE_STATIC}, {"g_tex2DColorBuffer", SHADER_VARIABLE_TYPE_DYNAMIC} }; pFixInsctrAtDepthBreaksPS[RenderLum] = CreateShader( FrameAttribs.pDevice, "RayMarch.fx", "FixAndApplyInscatteredRadiancePS", SHADER_TYPE_PIXEL, Macros, SHADER_VARIABLE_TYPE_MUTABLE, Vars, _countof(Vars) ); pFixInsctrAtDepthBreaksPS[RenderLum]->BindResources(m_pResMapping, BIND_SHADER_RESOURCES_VERIFY_ALL_RESOLVED); } TEXTURE_FORMAT RTVFmts[] = {LuminanceTexFmt}; // Luminance Only // Disable depth and stencil tests to render all pixels // Use default blend state to overwrite old luminance values m_pFixInsctrAtDepthBreaksPSO[0] = CreateScreenSizeQuadPSO(FrameAttribs.pDevice, "FixInsctrAtDepthBreaksLumOnly", pFixInsctrAtDepthBreaksPS[1], DSS_DisableDepth, BS_Default, 1, RTVFmts); m_pFixInsctrAtDepthBreaksSRB[0].Release(); RTVFmts[0] = m_BackBufferFmt; // Fix Inscattering // Depth breaks are marked with 1.0 in depth, so we enable depth test // to render only pixels that require correction // Use default blend state - the rendering is always done in single pass m_pFixInsctrAtDepthBreaksPSO[1] = CreateScreenSizeQuadPSO(FrameAttribs.pDevice, "FixInsctrAtDepthBreaks", pFixInsctrAtDepthBreaksPS[0], DSS_Default, BS_Default, 1, RTVFmts, m_DepthBufferFmt); m_pFixInsctrAtDepthBreaksSRB[1].Release(); // Full Screen Ray Marching // Disable depth and stencil tests since we are performing // full screen ray marching // Use default blend state - the rendering is always done in single pass m_pFixInsctrAtDepthBreaksPSO[2] = CreateScreenSizeQuadPSO(FrameAttribs.pDevice, "FixInsctrAtDepthBreaks", pFixInsctrAtDepthBreaksPS[0], DSS_DisableDepth, BS_Default, 1, RTVFmts, m_DepthBufferFmt); m_pFixInsctrAtDepthBreaksSRB[2].Release(); } { MapHelper<MiscDynamicParams> pMiscDynamicParams( FrameAttribs.pDeviceContext, m_pcbMiscParams, MAP_WRITE, MAP_FLAG_DISCARD ); pMiscDynamicParams->fMaxStepsAlongRay = static_cast<float>(uiMaxStepsAlongRay); pMiscDynamicParams->fCascadeInd = static_cast<float>(m_PostProcessingAttribs.m_iFirstCascade); } auto& FixInscatteringAtDepthBreaksPSO = m_pFixInsctrAtDepthBreaksPSO[static_cast<int>(Mode)]; auto& FixInscatteringAtDepthBreaksSRB = m_pFixInsctrAtDepthBreaksSRB[static_cast<int>(Mode)]; if (!FixInscatteringAtDepthBreaksSRB) { FixInscatteringAtDepthBreaksPSO->CreateShaderResourceBinding(&FixInscatteringAtDepthBreaksSRB, true); FixInscatteringAtDepthBreaksSRB->BindResources(SHADER_TYPE_PIXEL, m_pResMapping, BIND_SHADER_RESOURCES_KEEP_EXISTING); } // Set dynamic variable g_tex2DColorBuffer FixInscatteringAtDepthBreaksSRB->GetVariable(SHADER_TYPE_PIXEL, "g_tex2DColorBuffer")->Set(FrameAttribs.ptex2DSrcColorBufferSRV); RenderScreenSizeQuad(FrameAttribs.pDeviceContext, FixInscatteringAtDepthBreaksPSO, FixInscatteringAtDepthBreaksSRB); } void LightSctrPostProcess :: RenderSampleLocations(FrameAttribs& FrameAttribs) { if (!m_pRenderSampleLocationsPSO) { ShaderMacroHelper Macros; DefineMacros(Macros); Macros.Finalize(); // Shaders use SCREEN_RESLOUTION macro auto pRenderSampleLocationsVS = CreateShader( FrameAttribs.pDevice, "RenderSampling.fx", "RenderSampleLocationsVS", SHADER_TYPE_VERTEX, Macros, SHADER_VARIABLE_TYPE_MUTABLE); auto pRenderSampleLocationsPS = CreateShader( FrameAttribs.pDevice, "RenderSampling.fx", "RenderSampleLocationsPS", SHADER_TYPE_PIXEL, Macros, SHADER_VARIABLE_TYPE_MUTABLE); pRenderSampleLocationsVS->BindResources(m_pResMapping, BIND_SHADER_RESOURCES_VERIFY_ALL_RESOLVED); pRenderSampleLocationsPS->BindResources(m_pResMapping, BIND_SHADER_RESOURCES_VERIFY_ALL_RESOLVED); PipelineStateDesc PSODesc; PSODesc.Name = "Render sample locations PSO"; auto& GraphicsPipeline = PSODesc.GraphicsPipeline; GraphicsPipeline.RasterizerDesc.FillMode = FILL_MODE_SOLID; GraphicsPipeline.RasterizerDesc.CullMode = CULL_MODE_NONE; GraphicsPipeline.RasterizerDesc.FrontCounterClockwise = true; GraphicsPipeline.DepthStencilDesc = DSS_DisableDepth; GraphicsPipeline.BlendDesc = BS_AlphaBlend; GraphicsPipeline.pVS = pRenderSampleLocationsVS; GraphicsPipeline.pPS = pRenderSampleLocationsPS; GraphicsPipeline.NumRenderTargets = 1; GraphicsPipeline.RTVFormats[0] = m_BackBufferFmt; GraphicsPipeline.DSVFormat = m_DepthBufferFmt; GraphicsPipeline.PrimitiveTopology = PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP; FrameAttribs.pDevice->CreatePipelineState(PSODesc, &m_pRenderSampleLocationsPSO); m_pRenderSampleLocationsSRB.Release(); } if (!m_pRenderSampleLocationsSRB) { m_pRenderSampleLocationsPSO->CreateShaderResourceBinding(&m_pRenderSampleLocationsSRB, true); m_pRenderSampleLocationsSRB->BindResources(SHADER_TYPE_VERTEX | SHADER_TYPE_PIXEL, m_pResMapping, BIND_SHADER_RESOURCES_VERIFY_ALL_RESOLVED); } DrawAttribs Attribs; Attribs.NumVertices = 4; Attribs.NumInstances = m_PostProcessingAttribs.m_uiMaxSamplesInSlice * m_PostProcessingAttribs.m_uiNumEpipolarSlices; FrameAttribs.pDeviceContext->SetPipelineState(m_pRenderSampleLocationsPSO); FrameAttribs.pDeviceContext->CommitShaderResources(m_pRenderSampleLocationsSRB, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); FrameAttribs.pDeviceContext->Draw(Attribs); } void LightSctrPostProcess :: ResetShaderResourceBindings() { m_pRenderSampleLocationsSRB.Release(); m_pRefineSampleLocationsSRB.Release(); m_pComputeMinMaxSMLevelSRB[0].Release(); m_pComputeMinMaxSMLevelSRB[1].Release(); m_pRenderCoarseUnshadowedInsctrSRB.Release(); m_pRenderSliceUVDirInSM_SRB.Release(); m_pInterpolateIrradianceSRB.Release(); m_pMarkRayMarchingSamplesInStencilSRB.Release(); m_pInitializeMinMaxShadowMapSRB.Release(); for (size_t i=0; i < _countof(m_pDoRayMarchSRB); ++i) m_pDoRayMarchSRB[i].Release(); m_pRendedCoordTexSRB.Release(); for (size_t i=0; i < _countof(m_pFixInsctrAtDepthBreaksSRB); ++i) m_pFixInsctrAtDepthBreaksSRB[i].Release(); m_pUnwarpAndRenderLuminanceSRB.Release(); m_pUnwarpEpipolarSctrImgSRB.Release(); m_pUpdateAverageLuminanceSRB.Release(); } void LightSctrPostProcess :: CreateExtinctionTexture(IRenderDevice* pDevice) { TextureDesc TexDesc; TexDesc.Name = "Epipolar Extinction", TexDesc.Type = RESOURCE_DIM_TEX_2D; TexDesc.Width = m_PostProcessingAttribs.m_uiMaxSamplesInSlice; TexDesc.Height = m_PostProcessingAttribs.m_uiNumEpipolarSlices; TexDesc.Format = EpipolarExtinctionFmt; TexDesc.MipLevels = 1; TexDesc.Usage = USAGE_DEFAULT; TexDesc.BindFlags = BIND_RENDER_TARGET | BIND_SHADER_RESOURCE; TexDesc.ClearValue = {TEX_FORMAT_UNKNOWN, {1, 1, 1, 1}}; // MaxSamplesInSlice x NumSlices RGBA8_UNORM texture to store extinction // for every epipolar sample RefCntAutoPtr<ITexture> tex2DEpipolarExtinction; pDevice->CreateTexture(TexDesc, nullptr, &tex2DEpipolarExtinction); auto* tex2DEpipolarExtinctionSRV = tex2DEpipolarExtinction->GetDefaultView(TEXTURE_VIEW_SHADER_RESOURCE); tex2DEpipolarExtinctionSRV->SetSampler(m_pLinearClampSampler); m_pResMapping->AddResource("g_tex2DEpipolarExtinction", tex2DEpipolarExtinctionSRV, false); m_ptex2DEpipolarExtinctionRTV = tex2DEpipolarExtinction->GetDefaultView(TEXTURE_VIEW_RENDER_TARGET); m_uiUpToDateResourceFlags |= UpToDateResourceFlags::ExtinctionTexture; ResetShaderResourceBindings(); } void LightSctrPostProcess :: CreateAmbientSkyLightTexture(IRenderDevice* pDevice) { TextureDesc TexDesc; TexDesc.Name = "Ambient Sky Light"; TexDesc.Type = RESOURCE_DIM_TEX_2D; TexDesc.Width = sm_iAmbientSkyLightTexDim; TexDesc.Height = 1; TexDesc.Format = AmbientSkyLightTexFmt; TexDesc.MipLevels = 1; TexDesc.Usage = USAGE_DEFAULT; TexDesc.BindFlags = BIND_RENDER_TARGET | BIND_SHADER_RESOURCE; RefCntAutoPtr<ITexture> tex2DAmbientSkyLight; pDevice->CreateTexture(TexDesc, nullptr, &tex2DAmbientSkyLight); m_ptex2DAmbientSkyLightSRV = tex2DAmbientSkyLight->GetDefaultView(TEXTURE_VIEW_SHADER_RESOURCE); m_ptex2DAmbientSkyLightRTV = tex2DAmbientSkyLight->GetDefaultView(TEXTURE_VIEW_RENDER_TARGET); m_ptex2DAmbientSkyLightSRV->SetSampler(m_pLinearClampSampler); } void LightSctrPostProcess :: PerformPostProcessing(FrameAttribs &FrameAttribs, PostProcessingAttribs &PPAttribs) { bool bUseCombinedMinMaxTexture = PPAttribs.m_uiCascadeProcessingMode == CASCADE_PROCESSING_MODE_SINGLE_PASS || PPAttribs.m_uiCascadeProcessingMode == CASCADE_PROCESSING_MODE_MULTI_PASS_INST || PPAttribs.m_bCorrectScatteringAtDepthBreaks || PPAttribs.m_uiLightSctrTechnique == LIGHT_SCTR_TECHNIQUE_BRUTE_FORCE; bool ResetSRBs = m_ptex2DShadowMapSRV != FrameAttribs.ptex2DShadowMapSRV; m_ptex2DShadowMapSRV = FrameAttribs.ptex2DShadowMapSRV; if (PPAttribs.m_uiNumEpipolarSlices != m_PostProcessingAttribs.m_uiNumEpipolarSlices || PPAttribs.m_uiMaxSamplesInSlice != m_PostProcessingAttribs.m_uiMaxSamplesInSlice || PPAttribs.m_bOptimizeSampleLocations != m_PostProcessingAttribs.m_bOptimizeSampleLocations) { m_pRendedSliceEndpointsPSO.Release(); } if (PPAttribs.m_uiMaxSamplesInSlice != m_PostProcessingAttribs.m_uiMaxSamplesInSlice) m_pRendedCoordTexPSO.Release(); if (PPAttribs.m_uiMaxSamplesInSlice != m_PostProcessingAttribs.m_uiMaxSamplesInSlice || PPAttribs.m_uiInitialSampleStepInSlice != m_PostProcessingAttribs.m_uiInitialSampleStepInSlice || PPAttribs.m_uiRefinementCriterion != m_PostProcessingAttribs.m_uiRefinementCriterion || PPAttribs.m_bAutoExposure != m_PostProcessingAttribs.m_bAutoExposure) m_pRefineSampleLocationsCS.Release(); if (PPAttribs.m_bUse1DMinMaxTree != m_PostProcessingAttribs.m_bUse1DMinMaxTree || bUseCombinedMinMaxTexture != m_bUseCombinedMinMaxTexture || PPAttribs.m_uiNumEpipolarSlices != m_PostProcessingAttribs.m_uiNumEpipolarSlices || PPAttribs.m_bIs32BitMinMaxMipMap != m_PostProcessingAttribs.m_bIs32BitMinMaxMipMap ) { m_pInitializeMinMaxShadowMapPSO.Release(); m_pComputeMinMaxSMLevelPSO.Release(); } if (PPAttribs.m_bUse1DMinMaxTree != m_PostProcessingAttribs.m_bUse1DMinMaxTree || PPAttribs.m_uiCascadeProcessingMode != m_PostProcessingAttribs.m_uiCascadeProcessingMode || bUseCombinedMinMaxTexture != m_bUseCombinedMinMaxTexture || PPAttribs.m_bEnableLightShafts != m_PostProcessingAttribs.m_bEnableLightShafts || PPAttribs.m_uiMultipleScatteringMode != m_PostProcessingAttribs.m_uiMultipleScatteringMode || PPAttribs.m_uiSingleScatteringMode != m_PostProcessingAttribs.m_uiSingleScatteringMode) { for(int i=0; i<_countof(m_pDoRayMarchPSO); ++i) m_pDoRayMarchPSO[i].Release(); } if (PPAttribs.m_uiNumEpipolarSlices != m_PostProcessingAttribs.m_uiNumEpipolarSlices || PPAttribs.m_uiMaxSamplesInSlice != m_PostProcessingAttribs.m_uiMaxSamplesInSlice) { m_pUnwarpEpipolarSctrImgPSO.Release(); m_pUnwarpAndRenderLuminancePSO.Release(); } if (PPAttribs.m_bAutoExposure != m_PostProcessingAttribs.m_bAutoExposure || PPAttribs.m_uiToneMappingMode != m_PostProcessingAttribs.m_uiToneMappingMode || PPAttribs.m_bCorrectScatteringAtDepthBreaks != m_PostProcessingAttribs.m_bCorrectScatteringAtDepthBreaks) { m_pUnwarpEpipolarSctrImgPSO.Release(); } if (PPAttribs.m_bLightAdaptation != m_PostProcessingAttribs.m_bLightAdaptation) { m_pUpdateAverageLuminancePSO.Release(); } if( PPAttribs.m_uiCascadeProcessingMode != m_PostProcessingAttribs.m_uiCascadeProcessingMode || bUseCombinedMinMaxTexture != m_bUseCombinedMinMaxTexture || PPAttribs.m_bEnableLightShafts != m_PostProcessingAttribs.m_bEnableLightShafts || PPAttribs.m_uiMultipleScatteringMode != m_PostProcessingAttribs.m_uiMultipleScatteringMode || PPAttribs.m_uiSingleScatteringMode != m_PostProcessingAttribs.m_uiSingleScatteringMode || PPAttribs.m_bAutoExposure != m_PostProcessingAttribs.m_bAutoExposure || PPAttribs.m_uiToneMappingMode != m_PostProcessingAttribs.m_uiToneMappingMode) { for (size_t i=0; i<_countof(m_pFixInsctrAtDepthBreaksPSO); ++i) m_pFixInsctrAtDepthBreaksPSO[i].Release(); } if (PPAttribs.m_uiMaxSamplesInSlice != m_PostProcessingAttribs.m_uiMaxSamplesInSlice || PPAttribs.m_uiNumEpipolarSlices != m_PostProcessingAttribs.m_uiNumEpipolarSlices) { m_uiUpToDateResourceFlags &= ~UpToDateResourceFlags::AuxTextures; m_uiUpToDateResourceFlags &= ~UpToDateResourceFlags::ExtinctionTexture; m_uiUpToDateResourceFlags &= ~UpToDateResourceFlags::SliceUVDirAndOriginTex; m_pRenderSampleLocationsSRB.Release(); } if (PPAttribs.m_uiMinMaxShadowMapResolution != m_PostProcessingAttribs.m_uiMinMaxShadowMapResolution || PPAttribs.m_uiNumEpipolarSlices != m_PostProcessingAttribs.m_uiNumEpipolarSlices || PPAttribs.m_bUse1DMinMaxTree != m_PostProcessingAttribs.m_bUse1DMinMaxTree || PPAttribs.m_bIs32BitMinMaxMipMap != m_PostProcessingAttribs.m_bIs32BitMinMaxMipMap || bUseCombinedMinMaxTexture != m_bUseCombinedMinMaxTexture || (bUseCombinedMinMaxTexture && (PPAttribs.m_iFirstCascade != m_PostProcessingAttribs.m_iFirstCascade || PPAttribs.m_iNumCascades != m_PostProcessingAttribs.m_iNumCascades))) { for(int i=0; i < _countof(m_ptex2DMinMaxShadowMapSRV); ++i) m_ptex2DMinMaxShadowMapSRV[i].Release(); for(int i=0; i < _countof(m_ptex2DMinMaxShadowMapRTV); ++i) m_ptex2DMinMaxShadowMapRTV[i].Release(); m_pComputeMinMaxSMLevelSRB[0].Release(); m_pComputeMinMaxSMLevelSRB[1].Release(); ResetSRBs = true; } if (PPAttribs.m_iNumCascades != m_PostProcessingAttribs.m_iNumCascades) { m_uiUpToDateResourceFlags &= ~UpToDateResourceFlags::SliceUVDirAndOriginTex; } if (PPAttribs.m_uiCascadeProcessingMode != m_PostProcessingAttribs.m_uiCascadeProcessingMode) { m_pComputeMinMaxSMLevelPSO.Release(); } if (PPAttribs.m_uiExtinctionEvalMode != m_PostProcessingAttribs.m_uiExtinctionEvalMode) { m_ptex2DEpipolarExtinctionRTV.Release(); m_uiUpToDateResourceFlags &= ~UpToDateResourceFlags::ExtinctionTexture; m_pUnwarpEpipolarSctrImgPSO.Release(); m_pUnwarpAndRenderLuminancePSO.Release(); m_pRenderCoarseUnshadowedInsctrPSO.Release(); } if (PPAttribs.m_uiSingleScatteringMode != m_PostProcessingAttribs.m_uiSingleScatteringMode || PPAttribs.m_uiMultipleScatteringMode != m_PostProcessingAttribs.m_uiMultipleScatteringMode) m_pRenderCoarseUnshadowedInsctrPSO.Release(); bool bRecomputeSctrCoeffs = m_PostProcessingAttribs.m_bUseCustomSctrCoeffs != PPAttribs.m_bUseCustomSctrCoeffs || m_PostProcessingAttribs.m_fAerosolDensityScale != PPAttribs.m_fAerosolDensityScale || m_PostProcessingAttribs.m_fAerosolAbsorbtionScale != PPAttribs.m_fAerosolAbsorbtionScale || (PPAttribs.m_bUseCustomSctrCoeffs && (m_PostProcessingAttribs.m_f4CustomRlghBeta != PPAttribs.m_f4CustomRlghBeta || m_PostProcessingAttribs.m_f4CustomMieBeta != PPAttribs.m_f4CustomMieBeta) ); m_PostProcessingAttribs = PPAttribs; m_bUseCombinedMinMaxTexture = bUseCombinedMinMaxTexture; if (bRecomputeSctrCoeffs) { m_uiUpToDateResourceFlags &= ~UpToDateResourceFlags::PrecomputedOpticalDepthTex; m_uiUpToDateResourceFlags &= ~UpToDateResourceFlags::AmbientSkyLightTex; m_uiUpToDateResourceFlags &= ~UpToDateResourceFlags::PrecomputedIntegralsTex; ResetSRBs = true; ComputeScatteringCoefficients(FrameAttribs.pDeviceContext); } if (!(m_uiUpToDateResourceFlags & UpToDateResourceFlags::AuxTextures)) { CreateAuxTextures(FrameAttribs.pDevice); // Make sure extinction texture is re-created when first needed m_uiUpToDateResourceFlags &= ~UpToDateResourceFlags::ExtinctionTexture; m_ptex2DEpipolarExtinctionRTV.Release(); // Make sure slice UV and origin texture is re-created when first needed m_uiUpToDateResourceFlags &= ~UpToDateResourceFlags::SliceUVDirAndOriginTex; } if (!m_ptex2DMinMaxShadowMapSRV[0] && m_PostProcessingAttribs.m_bUse1DMinMaxTree) { CreateMinMaxShadowMap(FrameAttribs.pDevice); } #if 0 LightAttribs &LightAttribs = *FrameAttribs.pLightAttribs; const CameraAttribs &CamAttribs = FrameAttribs.CameraAttribs; // Note that in fact the outermost visible screen pixels do not lie exactly on the boundary (+1 or -1), but are biased by // 0.5 screen pixel size inwards. Using these adjusted boundaries improves precision and results in // smaller number of pixels which require inscattering correction assert( LightAttribs.bIsLightOnScreen == (fabs(FrameAttribs.pLightAttribs->f4LightScreenPos.x) <= 1.f - 1.f/(float)m_uiBackBufferWidth && fabs(FrameAttribs.pLightAttribs->f4LightScreenPos.y) <= 1.f - 1.f/(float)m_uiBackBufferHeight) ); const auto &SMAttribs = FrameAttribs.pLightAttribs->ShadowAttribs; UpdateConstantBuffer(FrameAttribs.pDeviceContext, m_pcbCameraAttribs, &CamAttribs, sizeof(CamAttribs)); //UpdateConstantBuffer(FrameAttribs.pDeviceContext, m_pcbLightAttribs, &LightAttribs, sizeof(LightAttribs)); #endif { MapHelper<PostProcessingAttribs> pPPAttribsBuffData( FrameAttribs.pDeviceContext, m_pcbPostProcessingAttribs, MAP_WRITE, MAP_FLAG_DISCARD ); memcpy(pPPAttribsBuffData, &m_PostProcessingAttribs, sizeof(m_PostProcessingAttribs)); } if (!(m_uiUpToDateResourceFlags & UpToDateResourceFlags::PrecomputedOpticalDepthTex)) { CreatePrecomputedOpticalDepthTexture(FrameAttribs.pDevice, FrameAttribs.pDeviceContext); } if ((m_PostProcessingAttribs.m_uiMultipleScatteringMode > MULTIPLE_SCTR_MODE_NONE || PPAttribs.m_uiSingleScatteringMode == SINGLE_SCTR_MODE_LUT) && !(m_uiUpToDateResourceFlags & UpToDateResourceFlags::PrecomputedIntegralsTex) ) { CreatePrecomputedScatteringLUT(FrameAttribs.pDevice, FrameAttribs.pDeviceContext); // We need to reset shader resource bindings, as some resources may have been recreated ResetSRBs = true; } if (ResetSRBs) { ResetShaderResourceBindings(); } if (/*m_PostProcessingAttribs.m_bAutoExposure &&*/ !(m_uiUpToDateResourceFlags & UpToDateResourceFlags::LowResLuminamceTex)) { CreateLowResLuminanceTexture(FrameAttribs.pDevice, FrameAttribs.pDeviceContext); } //m_pResMapping->AddResource("g_tex2DDepthBuffer", FrameAttribs.ptex2DSrcDepthBufferSRV, false); //m_pResMapping->AddResource("g_tex2DColorBuffer", FrameAttribs.ptex2DSrcColorBufferSRV, false); m_pResMapping->AddResource("g_tex2DLightSpaceDepthMap", FrameAttribs.ptex2DShadowMapSRV, false); m_pResMapping->AddResource("cbCameraAttribs", FrameAttribs.pcbCameraAttribs, false); m_pResMapping->AddResource("cbLightParams", FrameAttribs.pcbLightAttribs, false); { ITextureView *pRTVs[] = { FrameAttribs.ptex2DSrcColorBufferRTV }; FrameAttribs.pDeviceContext->SetRenderTargets(_countof(pRTVs), pRTVs, FrameAttribs.ptex2DSrcDepthBufferDSV, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); RenderSun(FrameAttribs); } ReconstructCameraSpaceZ(FrameAttribs); if (m_PostProcessingAttribs.m_uiLightSctrTechnique == LIGHT_SCTR_TECHNIQUE_EPIPOLAR_SAMPLING) { RenderSliceEndpoints(FrameAttribs); // Render coordinate texture and camera space z for epipolar location RenderCoordinateTexture(FrameAttribs); if (m_PostProcessingAttribs.m_uiRefinementCriterion == REFINEMENT_CRITERION_INSCTR_DIFF || m_PostProcessingAttribs.m_uiExtinctionEvalMode == EXTINCTION_EVAL_MODE_EPIPOLAR) { RenderCoarseUnshadowedInctr(FrameAttribs); } // Refine initial ray marching samples RefineSampleLocations(FrameAttribs); // Mark all ray marching samples in stencil MarkRayMarchingSamples( FrameAttribs ); if( m_PostProcessingAttribs.m_bEnableLightShafts && m_PostProcessingAttribs.m_bUse1DMinMaxTree ) { RenderSliceUVDirAndOrig(FrameAttribs); } ITextureView* ppRTVs[] = {m_ptex2DInitialScatteredLightRTV}; FrameAttribs.pDeviceContext->SetRenderTargets(1, ppRTVs, nullptr, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); const float Zero[] = {0,0,0,0}; FrameAttribs.pDeviceContext->ClearRenderTarget(m_ptex2DInitialScatteredLightRTV, Zero, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); int iLastCascade = (m_PostProcessingAttribs.m_bEnableLightShafts && m_PostProcessingAttribs.m_uiCascadeProcessingMode == CASCADE_PROCESSING_MODE_MULTI_PASS) ? m_PostProcessingAttribs.m_iNumCascades - 1 : m_PostProcessingAttribs.m_iFirstCascade; for(int iCascadeInd = m_PostProcessingAttribs.m_iFirstCascade; iCascadeInd <= iLastCascade; ++iCascadeInd) { // Build min/max mip map if( m_PostProcessingAttribs.m_bEnableLightShafts && m_PostProcessingAttribs.m_bUse1DMinMaxTree ) { Build1DMinMaxMipMap(FrameAttribs, iCascadeInd); } // Perform ray marching for selected samples DoRayMarching(FrameAttribs, m_PostProcessingAttribs.m_uiShadowMapResolution, iCascadeInd); } // Interpolate ray marching samples onto the rest of samples InterpolateInsctrIrradiance(FrameAttribs); const Uint32 uiMaxStepsAlongRayAtDepthBreak0 = std::min(m_PostProcessingAttribs.m_uiShadowMapResolution/4, 256u); //const Uint32 uiMaxStepsAlongRayAtDepthBreak1 = std::min(m_PostProcessingAttribs.m_uiShadowMapResolution/8, 128u); if (m_PostProcessingAttribs.m_bAutoExposure) { // Render scene luminance to low-resolution texture ITextureView *pRTVs[] = { m_ptex2DLowResLuminanceRTV }; FrameAttribs.pDeviceContext->SetRenderTargets(_countof(pRTVs), pRTVs, nullptr, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); UnwarpEpipolarScattering(FrameAttribs, true); FrameAttribs.pDeviceContext->GenerateMips(m_ptex2DLowResLuminanceSRV); UpdateAverageLuminance(FrameAttribs); } // Set the main back & depth buffers FrameAttribs.pDeviceContext->SetRenderTargets( 0, nullptr, nullptr, RESOURCE_STATE_TRANSITION_MODE_TRANSITION ); // Clear depth to 1.0. FrameAttribs.pDeviceContext->ClearDepthStencil( nullptr, CLEAR_DEPTH_FLAG, 1.f, 0, RESOURCE_STATE_TRANSITION_MODE_TRANSITION ); // Transform inscattering irradiance from epipolar coordinates back to rectangular // The shader will write 0.0 to the depth buffer, but all pixel that require inscattering // correction will be discarded and will keep 1.0 UnwarpEpipolarScattering(FrameAttribs, false); // Correct inscattering for pixels, for which no suitable interpolation sources were found if (m_PostProcessingAttribs.m_bCorrectScatteringAtDepthBreaks) { FixInscatteringAtDepthBreaks(FrameAttribs, uiMaxStepsAlongRayAtDepthBreak0, EFixInscatteringMode::FixInscattering); } if (m_PostProcessingAttribs.m_bShowSampling) { RenderSampleLocations(FrameAttribs); } } else if (m_PostProcessingAttribs.m_uiLightSctrTechnique == LIGHT_SCTR_TECHNIQUE_BRUTE_FORCE) { if (m_PostProcessingAttribs.m_bAutoExposure) { // Render scene luminance to low-resolution texture ITextureView *pRTVs[] = { m_ptex2DLowResLuminanceRTV }; FrameAttribs.pDeviceContext->SetRenderTargets(_countof(pRTVs), pRTVs, nullptr, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); FixInscatteringAtDepthBreaks(FrameAttribs, m_PostProcessingAttribs.m_uiShadowMapResolution, EFixInscatteringMode::LuminanceOnly); FrameAttribs.pDeviceContext->GenerateMips(m_ptex2DLowResLuminanceSRV); UpdateAverageLuminance(FrameAttribs); } // Set the main back & depth buffers FrameAttribs.pDeviceContext->SetRenderTargets(0, nullptr, nullptr, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); FixInscatteringAtDepthBreaks(FrameAttribs, m_PostProcessingAttribs.m_uiShadowMapResolution, EFixInscatteringMode::FullScreenRayMarching); } FrameAttribs.pDeviceContext->SetRenderTargets(0, nullptr, nullptr, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); } void LightSctrPostProcess :: CreateMinMaxShadowMap(IRenderDevice* pDevice) { TextureDesc MinMaxShadowMapTexDesc; MinMaxShadowMapTexDesc.Type = RESOURCE_DIM_TEX_2D; MinMaxShadowMapTexDesc.Width = m_PostProcessingAttribs.m_uiMinMaxShadowMapResolution; MinMaxShadowMapTexDesc.Height = m_PostProcessingAttribs.m_uiNumEpipolarSlices; MinMaxShadowMapTexDesc.MipLevels = 1; MinMaxShadowMapTexDesc.Format = m_PostProcessingAttribs.m_bIs32BitMinMaxMipMap ? TEX_FORMAT_RG32_FLOAT : TEX_FORMAT_RG16_UNORM; MinMaxShadowMapTexDesc.BindFlags = BIND_SHADER_RESOURCE | BIND_RENDER_TARGET; if (m_bUseCombinedMinMaxTexture) { MinMaxShadowMapTexDesc.Height *= (m_PostProcessingAttribs.m_iNumCascades - m_PostProcessingAttribs.m_iFirstCascade); } for(int i=0; i < 2; ++i) { std::string name = "MinMaxShadowMap"; name.push_back('0'+char(i)); MinMaxShadowMapTexDesc.Name = name.c_str(); m_ptex2DMinMaxShadowMapSRV[i].Release(); m_ptex2DMinMaxShadowMapRTV[i].Release(); RefCntAutoPtr<ITexture> ptex2DMinMaxShadowMap; // Create 2-D texture, shader resource and target view buffers on the device pDevice->CreateTexture( MinMaxShadowMapTexDesc, nullptr, &ptex2DMinMaxShadowMap); m_ptex2DMinMaxShadowMapSRV[i] = ptex2DMinMaxShadowMap->GetDefaultView( TEXTURE_VIEW_SHADER_RESOURCE ); m_ptex2DMinMaxShadowMapSRV[i]->SetSampler(m_pLinearClampSampler); m_ptex2DMinMaxShadowMapRTV[i] = ptex2DMinMaxShadowMap->GetDefaultView( TEXTURE_VIEW_RENDER_TARGET ); m_pResMapping->AddResource( "g_tex2DMinMaxLightSpaceDepth", m_ptex2DMinMaxShadowMapSRV[0], false ); } } float2 exp(const float2 &fX){ return float2(exp(fX.x), exp(fX.y)); } float3 exp(const float3 &fX){ return float3(exp(fX.x), exp(fX.y), exp(fX.z)); } // fCosChi = Pi/2 float2 ChapmanOrtho(const float2 &f2x) { static const float fConst = static_cast<float>( sqrt(M_PI / 2) ); float2 f2SqrtX = float2( sqrt(f2x.x), sqrt(f2x.y) ); return fConst * ( float2(1.f,1.f) / (2.f * f2SqrtX) + f2SqrtX ); } // |fCosChi| < Pi/2 float2 f2ChapmanRising(const float2 &f2X, float fCosChi) { float2 f2ChOrtho = ChapmanOrtho(f2X); return f2ChOrtho / ((f2ChOrtho-float2(1,1))*fCosChi + float2(1,1)); } float2 GetDensityIntegralFromChapmanFunc(float fHeightAboveSurface, const float3 &f3EarthCentreToPointDir, const float3 &f3RayDir, const AirScatteringAttribs &SctrMediaAttribs) { // Note: there is no intersection test with the Earth. However, // optical depth through the Earth is large, which effectively // occludes the light float fCosChi = dot(f3EarthCentreToPointDir, f3RayDir); float2 f2x = (fHeightAboveSurface + SctrMediaAttribs.fEarthRadius) * float2(1.f / SctrMediaAttribs.f2ParticleScaleHeight.x, 1.f / SctrMediaAttribs.f2ParticleScaleHeight.y); float2 f2VerticalAirMass = SctrMediaAttribs.f2ParticleScaleHeight * exp(-float2(fHeightAboveSurface,fHeightAboveSurface)/SctrMediaAttribs.f2ParticleScaleHeight); if( fCosChi >= 0.f ) { return f2VerticalAirMass * f2ChapmanRising(f2x, fCosChi); } else { float fSinChi = sqrt(1.f - fCosChi*fCosChi); float fh0 = (fHeightAboveSurface + SctrMediaAttribs.fEarthRadius) * fSinChi - SctrMediaAttribs.fEarthRadius; float2 f2VerticalAirMass0 = SctrMediaAttribs.f2ParticleScaleHeight * exp(-float2(fh0,fh0)/SctrMediaAttribs.f2ParticleScaleHeight); float2 f2x0 = float2(fh0 + SctrMediaAttribs.fEarthRadius,fh0 + SctrMediaAttribs.fEarthRadius)/SctrMediaAttribs.f2ParticleScaleHeight; float2 f2ChOrtho_x0 = ChapmanOrtho(f2x0); float2 f2Ch = f2ChapmanRising(f2x, -fCosChi); return f2VerticalAirMass0 * (2.f * f2ChOrtho_x0) - f2VerticalAirMass*f2Ch; } } void LightSctrPostProcess :: ComputeSunColor( const float3 &vDirectionOnSun, const float4 &f4ExtraterrestrialSunColor, float4 &f4SunColorAtGround, float4 &f4AmbientLight) { // Compute the ambient light values float zenithFactor = std::min( std::max(vDirectionOnSun.y, 0.0f), 1.0f); f4AmbientLight.x = zenithFactor*0.15f; f4AmbientLight.y = zenithFactor*0.1f; f4AmbientLight.z = std::max(0.005f, zenithFactor*0.25f); f4AmbientLight.w = 0.0f; float2 f2NetParticleDensityToAtmTop = GetDensityIntegralFromChapmanFunc(0, float3(0,1,0), vDirectionOnSun, m_MediaParams); float3 f3RlghExtCoeff = std::max( (float3&)m_MediaParams.f4RayleighExtinctionCoeff, float3(1e-8f,1e-8f,1e-8f) ); float3 f3RlghOpticalDepth = f3RlghExtCoeff * f2NetParticleDensityToAtmTop.x; float3 f3MieExtCoeff = std::max( (float3&)m_MediaParams.f4MieExtinctionCoeff, float3(1e-8f,1e-8f,1e-8f) ); float3 f3MieOpticalDepth = f3MieExtCoeff * f2NetParticleDensityToAtmTop.y; float3 f3TotalExtinction = exp( -(f3RlghOpticalDepth + f3MieOpticalDepth ) ); const float fEarthReflectance = 0.1f;// See [BN08] (float3&)f4SunColorAtGround = ((float3&)f4ExtraterrestrialSunColor) * f3TotalExtinction * fEarthReflectance; } void LightSctrPostProcess :: ComputeScatteringCoefficients(IDeviceContext* pDeviceCtx) { // For details, see "A practical Analytic Model for Daylight" by Preetham & Hoffman, p.23 // Wave lengths // [BN08] follows [REK04] and gives the following values for Rayleigh scattering coefficients: // RayleighBetha(lambda = (680nm, 550nm, 440nm) ) = (5.8, 13.5, 33.1)e-6 static const double dWaveLengths[] = { 680e-9, // red 550e-9, // green 440e-9 // blue }; // Calculate angular and total scattering coefficients for Rayleigh scattering: { float4& f4AngularRayleighSctrCoeff = m_MediaParams.f4AngularRayleighSctrCoeff; float4& f4TotalRayleighSctrCoeff = m_MediaParams.f4TotalRayleighSctrCoeff; float4& f4RayleighExtinctionCoeff = m_MediaParams.f4RayleighExtinctionCoeff; constexpr double n = 1.0003; // - Refractive index of air in the visible spectrum constexpr double N = 2.545e+25; // - Number of molecules per unit volume constexpr double Pn = 0.035; // - Depolarization factor for air which exoresses corrections // due to anisotropy of air molecules constexpr double dRayleighConst = 8.0*M_PI*M_PI*M_PI * (n*n - 1.0) * (n*n - 1.0) / (3.0 * N) * (6.0 + 3.0*Pn) / (6.0 - 7.0*Pn); for (int WaveNum = 0; WaveNum < 3; WaveNum++) { double dSctrCoeff; if (m_PostProcessingAttribs.m_bUseCustomSctrCoeffs) dSctrCoeff = f4TotalRayleighSctrCoeff[WaveNum] = m_PostProcessingAttribs.m_f4CustomRlghBeta[WaveNum]; else { double Lambda2 = dWaveLengths[WaveNum] * dWaveLengths[WaveNum]; double Lambda4 = Lambda2 * Lambda2; dSctrCoeff = dRayleighConst / Lambda4; // Total Rayleigh scattering coefficient is the integral of angular scattering coefficient in all directions f4TotalRayleighSctrCoeff[WaveNum] = static_cast<float>( dSctrCoeff ); } // Angular scattering coefficient is essentially volumetric scattering coefficient multiplied by the // normalized phase function // p(Theta) = 3/(16*Pi) * (1 + cos^2(Theta)) // f4AngularRayleighSctrCoeff contains all the terms exepting 1 + cos^2(Theta): f4AngularRayleighSctrCoeff[WaveNum] = static_cast<float>( 3.0 / (16.0*M_PI) * dSctrCoeff ); // f4AngularRayleighSctrCoeff[WaveNum] = f4TotalRayleighSctrCoeff[WaveNum] * p(Theta) } // Air molecules do not absorb light, so extinction coefficient is only caused by out-scattering f4RayleighExtinctionCoeff = f4TotalRayleighSctrCoeff; } // Calculate angular and total scattering coefficients for Mie scattering: { float4& f4AngularMieSctrCoeff = m_MediaParams.f4AngularMieSctrCoeff; float4& f4TotalMieSctrCoeff = m_MediaParams.f4TotalMieSctrCoeff; float4& f4MieExtinctionCoeff = m_MediaParams.f4MieExtinctionCoeff; if (m_PostProcessingAttribs.m_bUseCustomSctrCoeffs) { f4TotalMieSctrCoeff = m_PostProcessingAttribs.m_f4CustomMieBeta * m_PostProcessingAttribs.m_fAerosolDensityScale; } else { const bool bUsePreethamMethod = false; if (bUsePreethamMethod) { // Values for K came from the table 2 in the "A practical Analytic Model // for Daylight" by Preetham & Hoffman, p.28 constexpr double K[] = { 0.68455, // K[650nm] 0.678781, // K[570nm] (0.668532+0.669765)/2.0 // (K[470nm]+K[480nm])/2 }; assert( m_MediaParams.fTurbidity >= 1.f ); // Beta is an Angstrom's turbidity coefficient and is approximated by: //float beta = 0.04608365822050f * m_fTurbidity - 0.04586025928522f; ??????? const double c = (0.6544*m_MediaParams.fTurbidity - 0.6510)*1E-16; // concentration factor constexpr double v = 4; // Junge's exponent const double dTotalMieBetaTerm = 0.434 * c * M_PI * pow(2.0*M_PI, v-2); for (int WaveNum = 0; WaveNum < 3; WaveNum++) { double Lambdav_minus_2 = pow( dWaveLengths[WaveNum], v-2); double dTotalMieSctrCoeff = dTotalMieBetaTerm * K[WaveNum] / Lambdav_minus_2; f4TotalMieSctrCoeff[WaveNum] = static_cast<float>( dTotalMieSctrCoeff ); } //AtmScatteringAttribs.f4AngularMieSctrCoeff *= 0.02f; //AtmScatteringAttribs.f4TotalMieSctrCoeff *= 0.02f; } else { // [BN08] uses the following value (independent of wavelength) for Mie scattering coefficient: 2e-5 // For g=0.76 and MieBetha=2e-5 [BN08] was able to reproduce the same luminance as given by the // reference CIE sky light model const float fMieBethaBN08 = 2e-5f * m_PostProcessingAttribs.m_fAerosolDensityScale; m_MediaParams.f4TotalMieSctrCoeff = float4(fMieBethaBN08, fMieBethaBN08, fMieBethaBN08, 0); } } for (int WaveNum = 0; WaveNum < 3; WaveNum++) { // Normalized to unity Cornette-Shanks phase function has the following form: // F(theta) = 1/(4*PI) * 3*(1-g^2) / (2*(2+g^2)) * (1+cos^2(theta)) / (1 + g^2 - 2g*cos(theta))^(3/2) // The angular scattering coefficient is the volumetric scattering coefficient multiplied by the phase // function. 1/(4*PI) is baked into the f4AngularMieSctrCoeff, the other terms are baked into f4CS_g f4AngularMieSctrCoeff[WaveNum] = f4TotalMieSctrCoeff[WaveNum] / static_cast<float>(4.0 * M_PI); // [BN08] also uses slight absorption factor which is 10% of scattering f4MieExtinctionCoeff[WaveNum] = f4TotalMieSctrCoeff[WaveNum] * (1.f + m_PostProcessingAttribs.m_fAerosolAbsorbtionScale); } } { // For g=0.76 and MieBetha=2e-5 [BN08] was able to reproduce the same luminance as is given by the // reference CIE sky light model // Cornette phase function (see Nishita et al. 93): // F(theta) = 1/(4*PI) * 3*(1-g^2) / (2*(2+g^2)) * (1+cos^2(theta)) / (1 + g^2 - 2g*cos(theta))^(3/2) // 1/(4*PI) is baked into the f4AngularMieSctrCoeff float4 &f4CS_g = m_MediaParams.f4CS_g; float f_g = m_MediaParams.m_fAerosolPhaseFuncG; f4CS_g.x = 3*(1.f - f_g*f_g) / ( 2*(2.f + f_g*f_g) ); f4CS_g.y = 1.f + f_g*f_g; f4CS_g.z = -2.f*f_g; f4CS_g.w = 1.f; } m_MediaParams.f4TotalExtinctionCoeff = m_MediaParams.f4RayleighExtinctionCoeff + m_MediaParams.f4MieExtinctionCoeff; if (pDeviceCtx && m_pcbMediaAttribs) { pDeviceCtx->UpdateBuffer(m_pcbMediaAttribs, 0, sizeof( m_MediaParams ), &m_MediaParams, RESOURCE_STATE_TRANSITION_MODE_TRANSITION ); } } void LightSctrPostProcess :: RenderSun(FrameAttribs& FrameAttribs) { if( FrameAttribs.pLightAttribs->f4LightScreenPos.w <= 0 ) return; if (!m_pRenderSunSRB) { m_pRenderSunPSO->CreateShaderResourceBinding(&m_pRenderSunSRB, true); m_pRenderSunSRB->BindResources(SHADER_TYPE_PIXEL | SHADER_TYPE_VERTEX, m_pResMapping, BIND_SHADER_RESOURCES_VERIFY_ALL_RESOLVED); } RenderScreenSizeQuad(FrameAttribs.pDeviceContext, m_pRenderSunPSO, m_pRenderSunSRB); } void LightSctrPostProcess :: ComputeAmbientSkyLightTexture(IRenderDevice* pDevice, IDeviceContext* pContext) { if( !(m_uiUpToDateResourceFlags & UpToDateResourceFlags::PrecomputedOpticalDepthTex) ) { CreatePrecomputedOpticalDepthTexture(pDevice, pContext); } if( !(m_uiUpToDateResourceFlags & UpToDateResourceFlags::PrecomputedIntegralsTex) ) { CreatePrecomputedScatteringLUT(pDevice, pContext); } if( !m_pPrecomputeAmbientSkyLightPSO ) { ShaderMacroHelper Macros; Macros.AddShaderMacro( "NUM_RANDOM_SPHERE_SAMPLES", m_uiNumRandomSamplesOnSphere ); Macros.Finalize(); auto pPrecomputeAmbientSkyLightPS = CreateShader( pDevice, "PrecomputeAmbientSkyLight.fx", "PrecomputeAmbientSkyLightPS", SHADER_TYPE_PIXEL, Macros, SHADER_VARIABLE_TYPE_STATIC ); pPrecomputeAmbientSkyLightPS->BindResources( m_pResMapping, BIND_SHADER_RESOURCES_VERIFY_ALL_RESOLVED ); TEXTURE_FORMAT RTVFormats[] = {AmbientSkyLightTexFmt}; m_pPrecomputeAmbientSkyLightPSO = CreateScreenSizeQuadPSO(pDevice, "PrecomputeAmbientSkyLight", pPrecomputeAmbientSkyLightPS, DSS_DisableDepth, BS_Default, 1, RTVFormats, TEX_FORMAT_UNKNOWN); m_pPrecomputeAmbientSkyLightPSO->CreateShaderResourceBinding(&m_pPrecomputeAmbientSkyLightSRB, true); } // Create 2-D texture, shader resource and target view buffers on the device ITextureView *pRTVs[] = {m_ptex2DAmbientSkyLightRTV}; pContext->SetRenderTargets(1, pRTVs, nullptr, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); RenderScreenSizeQuad(pContext, m_pPrecomputeAmbientSkyLightPSO, m_pPrecomputeAmbientSkyLightSRB); m_uiUpToDateResourceFlags |= UpToDateResourceFlags::AmbientSkyLightTex; } ITextureView* LightSctrPostProcess :: GetAmbientSkyLightSRV(IRenderDevice *pDevice, IDeviceContext *pContext) { if( !(m_uiUpToDateResourceFlags & UpToDateResourceFlags::AmbientSkyLightTex) ) { ComputeAmbientSkyLightTexture(pDevice, pContext); } return m_ptex2DAmbientSkyLightSRV; } Fixed Apple clang build error /* Copyright 2015-2019 Egor Yusov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PROPRIETARY RIGHTS. * * In no event and under no legal theory, whether in tort (including negligence), * contract, or otherwise, unless required by applicable law (such as deliberate * and grossly negligent acts) or agreed to in writing, shall any Contributor be * liable for any damages, including any direct, indirect, special, incidental, * or consequential damages of any character arising as a result of this License or * out of the use or inability to use the software (including but not limited to damages * for loss of goodwill, work stoppage, computer failure or malfunction, or any and * all other commercial damages or losses), even if such Contributor has been advised * of the possibility of such damages. */ // This file is derived from the open source project provided by Intel Corportaion that // requires the following notice to be kept: //-------------------------------------------------------------------------------------- // Copyright 2013 Intel Corporation // All Rights Reserved // // Permission is granted to use, copy, distribute and prepare derivative works of this // software for any purpose and without fee, provided, that the above copyright notice // and this statement appear in all copies. Intel makes no representations about the // suitability of this software for any purpose. THIS SOFTWARE IS PROVIDED "AS IS." // INTEL SPECIFICALLY DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, AND ALL LIABILITY, // INCLUDING CONSEQUENTIAL AND OTHER INDIRECT DAMAGES, FOR THE USE OF THIS SOFTWARE, // INCLUDING LIABILITY FOR INFRINGEMENT OF ANY PROPRIETARY RIGHTS, AND INCLUDING THE // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. Intel does not // assume any responsibility for any errors which may appear in this software nor any // responsibility to update it. //-------------------------------------------------------------------------------------- #include "pch.h" #include "LightSctrPostProcess.h" #include "ConvenienceFunctions.h" #include "GraphicsUtilities.h" #include "GraphicsAccessories.h" #include "BasicShaderSourceStreamFactory.h" #include "MapHelper.h" #include "CommonlyUsedStates.h" using namespace Diligent; #define _USE_MATH_DEFINES #include <math.h> static const DepthStencilStateDesc DSS_CmpEqNoWrites { True, // DepthEnable False, // DepthWriteEnable COMPARISON_FUNC_EQUAL // DepthFunc }; // Disable depth testing and always increment stencil value // This depth stencil state is used to mark samples which will undergo further processing // Pixel shader discards pixels that should not be further processed, thus keeping the // stencil value untouched // For instance, pixel shader performing epipolar coordinates generation discards all // sampes, whoose coordinates are outside the screen [-1,1]x[-1,1] area static const DepthStencilStateDesc DSS_IncStencilAlways { False, // DepthEnable False, // DepthWriteEnable COMPARISON_FUNC_LESS, // DepthFunc True, // StencilEnable 0xFF, // StencilReadMask 0xFF, // StencilWriteMask StencilOpDesc { STENCIL_OP_KEEP, // StencilFailOp STENCIL_OP_KEEP, // StencilDepthFailOp STENCIL_OP_INCR_SAT, // StencilPassOp COMPARISON_FUNC_ALWAYS // StencilFunc }, StencilOpDesc { STENCIL_OP_KEEP, // StencilFailOp STENCIL_OP_KEEP, // StencilDepthFailOp STENCIL_OP_INCR_SAT, // StencilPassOp COMPARISON_FUNC_ALWAYS // StencilFunc } }; // Disable depth testing, stencil testing function equal, increment stencil // This state is used to process only those pixels that were marked at the previous pass // All pixels whith different stencil value are discarded from further processing as well // as some pixels can also be discarded during the draw call // For instance, pixel shader marking ray marching samples processes only those pixels which are inside // the screen. It also discards all but those samples that are interpolated from themselves static const DepthStencilStateDesc DSS_StencilEqIncStencil { False, // DepthEnable False, // DepthWriteEnable COMPARISON_FUNC_LESS, // DepthFunc True, // StencilEnable 0xFF, // StencilReadMask 0xFF, // StencilWriteMask StencilOpDesc { STENCIL_OP_KEEP, // StencilFailOp STENCIL_OP_KEEP, // StencilDepthFailOp STENCIL_OP_INCR_SAT, // StencilPassOp COMPARISON_FUNC_EQUAL // StencilFunc }, StencilOpDesc { STENCIL_OP_KEEP, // StencilFailOp STENCIL_OP_KEEP, // StencilDepthFailOp STENCIL_OP_INCR_SAT, // StencilPassOp COMPARISON_FUNC_EQUAL // StencilFunc } }; // Disable depth testing, stencil testing function equal, keep stencil static const DepthStencilStateDesc DSS_StencilEqKeepStencil = { False, // DepthEnable False, // DepthWriteEnable COMPARISON_FUNC_LESS, // DepthFunc True, // StencilEnable 0xFF, // StencilReadMask 0xFF, // StencilWriteMask StencilOpDesc { STENCIL_OP_KEEP, // StencilFailOp STENCIL_OP_KEEP, // StencilDepthFailOp STENCIL_OP_KEEP, // StencilPassOp COMPARISON_FUNC_EQUAL // StencilFunc }, StencilOpDesc { STENCIL_OP_KEEP, // StencilFailOp STENCIL_OP_KEEP, // StencilDepthFailOp STENCIL_OP_KEEP, // StencilPassOp COMPARISON_FUNC_EQUAL // StencilFunc } }; static const BlendStateDesc BS_AdditiveBlend = { False, // AlphaToCoverageEnable False, // IndependentBlendEnable RenderTargetBlendDesc { True, // BlendEnable False, // LogicOperationEnable BLEND_FACTOR_ONE, // SrcBlend BLEND_FACTOR_ONE, // DestBlend BLEND_OPERATION_ADD, // BlendOp BLEND_FACTOR_ONE, // SrcBlendAlpha BLEND_FACTOR_ONE, // DestBlendAlpha BLEND_OPERATION_ADD // BlendOpAlpha } }; static RefCntAutoPtr<IShader> CreateShader(IRenderDevice* pDevice, const Char* FileName, const Char* EntryPoint, SHADER_TYPE Type, const ShaderMacro* Macros, SHADER_VARIABLE_TYPE DefaultVarType, const ShaderVariableDesc* pVarDesc = nullptr, Uint32 NumVars = 0) { ShaderCreationAttribs Attribs; Attribs.EntryPoint = EntryPoint; Attribs.FilePath = FileName; Attribs.Macros = Macros; Attribs.SourceLanguage = SHADER_SOURCE_LANGUAGE_HLSL; Attribs.Desc.ShaderType = Type; Attribs.Desc.Name = EntryPoint; Attribs.Desc.VariableDesc = pVarDesc; Attribs.Desc.NumVariables = NumVars; Attribs.Desc.DefaultVariableType = DefaultVarType; BasicShaderSourceStreamFactory BasicSSSFactory("shaders;shaders\\atmosphere;shaders\\atmosphere\\precompute"); Attribs.pShaderSourceStreamFactory = &BasicSSSFactory; Attribs.UseCombinedTextureSamplers = true; RefCntAutoPtr<IShader> pShader; pDevice->CreateShader( Attribs, &pShader ); return pShader; } LightSctrPostProcess :: LightSctrPostProcess(IRenderDevice* pDevice, IDeviceContext* pContext, TEXTURE_FORMAT BackBufferFmt, TEXTURE_FORMAT DepthBufferFmt, TEXTURE_FORMAT OffscreenBackBufferFmt) : m_BackBufferFmt (BackBufferFmt), m_DepthBufferFmt (DepthBufferFmt), m_OffscreenBackBufferFmt (OffscreenBackBufferFmt), m_bUseCombinedMinMaxTexture(false), m_uiSampleRefinementCSThreadGroupSize(0), // Using small group size is inefficient because a lot of SIMD lanes become idle m_uiSampleRefinementCSMinimumThreadGroupSize(128),// Must be greater than 32 m_uiNumRandomSamplesOnSphere(pDevice->GetDeviceCaps().DevType == DeviceType::OpenGLES ? 64 : 128), m_uiUpToDateResourceFlags(0) { pDevice->CreateResourceMapping(ResourceMappingDesc(), &m_pResMapping); CreateUniformBuffer(pDevice, sizeof( PostProcessingAttribs ), "Postprocessing Attribs CB", &m_pcbPostProcessingAttribs); CreateUniformBuffer(pDevice, sizeof( MiscDynamicParams ), "Misc Dynamic Params CB", &m_pcbMiscParams); { BufferDesc CBDesc; CBDesc.Usage = USAGE_DEFAULT; CBDesc.BindFlags = BIND_UNIFORM_BUFFER; CBDesc.uiSizeInBytes = sizeof(AirScatteringAttribs); BufferData InitData{&m_MediaParams, CBDesc.uiSizeInBytes}; pDevice->CreateBuffer(CBDesc, &InitData, &m_pcbMediaAttribs); } // Add uniform buffers to the shader resource mapping. These buffers will never change. // Note that only buffer objects will stay unchanged, while the buffer contents can be updated. m_pResMapping->AddResource("cbPostProcessingAttribs", m_pcbPostProcessingAttribs, true); m_pResMapping->AddResource("cbParticipatingMediaScatteringParams", m_pcbMediaAttribs, true); m_pResMapping->AddResource("cbMiscDynamicParams", m_pcbMiscParams, true); pDevice->CreateSampler(Sam_LinearClamp, &m_pLinearClampSampler); pDevice->CreateSampler(Sam_PointClamp, &m_pPointClampSampler); { RefCntAutoPtr<IShader> pPrecomputeNetDensityToAtmTopPS; pPrecomputeNetDensityToAtmTopPS = CreateShader(pDevice, "PrecomputeNetDensityToAtmTop.fx", "PrecomputeNetDensityToAtmTopPS", SHADER_TYPE_PIXEL, nullptr, SHADER_VARIABLE_TYPE_STATIC); pPrecomputeNetDensityToAtmTopPS->BindResources(m_pResMapping, BIND_SHADER_RESOURCES_VERIFY_ALL_RESOLVED); TEXTURE_FORMAT RtvFmts[] = {TEX_FORMAT_RG32_FLOAT}; m_pPrecomputeNetDensityToAtmTopPSO = CreateScreenSizeQuadPSO(pDevice, "PrecomputeNetDensityToAtmTopPSO", pPrecomputeNetDensityToAtmTopPS, DSS_DisableDepth, BS_Default, 1, RtvFmts, TEX_FORMAT_UNKNOWN); m_pPrecomputeNetDensityToAtmTopPSO->CreateShaderResourceBinding(&m_pPrecomputeNetDensityToAtmTopSRB, true); } ComputeScatteringCoefficients(pContext); CreatePrecomputedOpticalDepthTexture(pDevice, pContext); CreateAmbientSkyLightTexture(pDevice); // Create sun rendering shaders and PSO { RefCntAutoPtr<IShader> pSunVS = CreateShader(pDevice, "Sun.fx", "SunVS", SHADER_TYPE_VERTEX, nullptr, SHADER_VARIABLE_TYPE_MUTABLE); RefCntAutoPtr<IShader> pSunPS = CreateShader(pDevice, "Sun.fx", "SunPS", SHADER_TYPE_PIXEL, nullptr, SHADER_VARIABLE_TYPE_MUTABLE); PipelineStateDesc PSODesc; PSODesc.Name = "Render Sun"; auto& GraphicsPipeline = PSODesc.GraphicsPipeline; GraphicsPipeline.RasterizerDesc.FillMode = FILL_MODE_SOLID; GraphicsPipeline.RasterizerDesc.CullMode = CULL_MODE_NONE; GraphicsPipeline.RasterizerDesc.FrontCounterClockwise = true; GraphicsPipeline.DepthStencilDesc = DSS_CmpEqNoWrites; GraphicsPipeline.pVS = pSunVS; GraphicsPipeline.pPS = pSunPS; GraphicsPipeline.NumRenderTargets = 1; GraphicsPipeline.RTVFormats[0] = OffscreenBackBufferFmt; GraphicsPipeline.DSVFormat = DepthBufferFmt; GraphicsPipeline.PrimitiveTopology = PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP; pDevice->CreatePipelineState(PSODesc, &m_pRenderSunPSO); } } LightSctrPostProcess :: ~LightSctrPostProcess() { } void LightSctrPostProcess :: OnWindowResize(IRenderDevice* pDevice, Uint32 uiBackBufferWidth, Uint32 uiBackBufferHeight) { m_uiBackBufferWidth = uiBackBufferWidth; m_uiBackBufferHeight = uiBackBufferHeight; // Release all shaders that depend on SCREEN_RESLOUTION shader macro // The shaders will be recreated first time they needed m_pRendedCoordTexPSO.Release(); m_pRendedSliceEndpointsPSO.Release(); m_pRenderSliceUVDirInSM_PSO.Release(); m_pRenderSampleLocationsPSO.Release(); m_pUnwarpEpipolarSctrImgPSO.Release(); m_pUnwarpAndRenderLuminancePSO.Release(); CreateCamSpaceZTexture(pDevice); } void LightSctrPostProcess :: DefineMacros(ShaderMacroHelper &Macros) { // Define common shader macros Macros.AddShaderMacro("NUM_EPIPOLAR_SLICES", m_PostProcessingAttribs.m_uiNumEpipolarSlices); Macros.AddShaderMacro("MAX_SAMPLES_IN_SLICE", m_PostProcessingAttribs.m_uiMaxSamplesInSlice); Macros.AddShaderMacro("OPTIMIZE_SAMPLE_LOCATIONS", m_PostProcessingAttribs.m_bOptimizeSampleLocations); Macros.AddShaderMacro("USE_COMBINED_MIN_MAX_TEXTURE", m_bUseCombinedMinMaxTexture ); Macros.AddShaderMacro("EXTINCTION_EVAL_MODE", m_PostProcessingAttribs.m_uiExtinctionEvalMode ); Macros.AddShaderMacro("ENABLE_LIGHT_SHAFTS", m_PostProcessingAttribs.m_bEnableLightShafts); Macros.AddShaderMacro("MULTIPLE_SCATTERING_MODE", m_PostProcessingAttribs.m_uiMultipleScatteringMode); Macros.AddShaderMacro("SINGLE_SCATTERING_MODE", m_PostProcessingAttribs.m_uiSingleScatteringMode); { std::stringstream ss; ss<<"float2("<<m_uiBackBufferWidth<<".0,"<<m_uiBackBufferHeight<<".0)"; Macros.AddShaderMacro("SCREEN_RESLOUTION", ss.str()); } { std::stringstream ss; ss<<"float4("<<sm_iPrecomputedSctrUDim<<".0," <<sm_iPrecomputedSctrVDim<<".0," <<sm_iPrecomputedSctrWDim<<".0," <<sm_iPrecomputedSctrQDim<<".0)"; Macros.AddShaderMacro("PRECOMPUTED_SCTR_LUT_DIM", ss.str()); } Macros.AddShaderMacro("EARTH_RADIUS", m_MediaParams.fEarthRadius); Macros.AddShaderMacro("ATM_TOP_HEIGHT", m_MediaParams.fAtmTopHeight); Macros.AddShaderMacro("ATM_TOP_RADIUS", m_MediaParams.fAtmTopRadius); { std::stringstream ss; ss<<"float2("<<m_MediaParams.f2ParticleScaleHeight.x<<".0,"<<m_MediaParams.f2ParticleScaleHeight.y<<".0)"; Macros.AddShaderMacro("PARTICLE_SCALE_HEIGHT", ss.str()); } } RefCntAutoPtr<IPipelineState> LightSctrPostProcess :: CreateScreenSizeQuadPSO(IRenderDevice* pDevice, const char* PSOName, IShader* PixelShader, const DepthStencilStateDesc& DSSDesc, const BlendStateDesc& BSDesc, Uint8 NumRTVs, TEXTURE_FORMAT RTVFmts[], TEXTURE_FORMAT DSVFmt) { if (!m_pQuadVS) { m_pQuadVS = CreateShader( pDevice, "ScreenSizeQuadVS.fx", "ScreenSizeQuadVS", SHADER_TYPE_VERTEX, nullptr, SHADER_VARIABLE_TYPE_STATIC ); } PipelineStateDesc PSODesc; PSODesc.Name = PSOName; auto& GraphicsPipeline = PSODesc.GraphicsPipeline; GraphicsPipeline.RasterizerDesc.FillMode = FILL_MODE_SOLID; GraphicsPipeline.RasterizerDesc.CullMode = CULL_MODE_NONE; GraphicsPipeline.RasterizerDesc.FrontCounterClockwise = true; GraphicsPipeline.DepthStencilDesc = DSSDesc; GraphicsPipeline.BlendDesc = BSDesc; GraphicsPipeline.pVS = m_pQuadVS; GraphicsPipeline.pPS = PixelShader; GraphicsPipeline.PrimitiveTopology = PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP; GraphicsPipeline.NumRenderTargets = NumRTVs; GraphicsPipeline.DSVFormat = DSVFmt; for (Uint32 rt=0; rt < NumRTVs; ++rt) GraphicsPipeline.RTVFormats[rt] = RTVFmts[rt]; RefCntAutoPtr<IPipelineState> PSO; pDevice->CreatePipelineState(PSODesc, &PSO); return PSO; } void LightSctrPostProcess::RenderScreenSizeQuad(IDeviceContext* pDeviceContext, IPipelineState* PSO, IShaderResourceBinding* SRB, Uint8 StencilRef, Uint32 NumQuads) { pDeviceContext->SetPipelineState(PSO); pDeviceContext->CommitShaderResources(SRB, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); pDeviceContext->SetStencilRef(StencilRef); DrawAttribs ScreenSizeQuadDrawAttrs; ScreenSizeQuadDrawAttrs.NumVertices = 4; ScreenSizeQuadDrawAttrs.NumInstances = NumQuads; pDeviceContext->Draw(ScreenSizeQuadDrawAttrs); } void LightSctrPostProcess::CreatePrecomputedOpticalDepthTexture(IRenderDevice* pDevice, IDeviceContext* pDeviceContext) { if (!m_ptex2DOccludedNetDensityToAtmTopSRV) { // Create texture if it has not been created yet. // Do not recreate texture if it already exists as this may // break static resource bindings. TextureDesc TexDesc; TexDesc.Name = "Occluded Net Density to Atm Top"; TexDesc.Type = RESOURCE_DIM_TEX_2D; TexDesc.Width = sm_iNumPrecomputedHeights; TexDesc.Height = sm_iNumPrecomputedAngles; TexDesc.Format = TEX_FORMAT_RG32_FLOAT; TexDesc.MipLevels = 1; TexDesc.Usage = USAGE_DEFAULT; TexDesc.BindFlags = BIND_SHADER_RESOURCE | BIND_RENDER_TARGET; RefCntAutoPtr<ITexture> tex2DOccludedNetDensityToAtmTop; pDevice->CreateTexture(TexDesc, nullptr, &tex2DOccludedNetDensityToAtmTop); m_ptex2DOccludedNetDensityToAtmTopSRV = tex2DOccludedNetDensityToAtmTop->GetDefaultView(TEXTURE_VIEW_SHADER_RESOURCE); m_ptex2DOccludedNetDensityToAtmTopSRV->SetSampler(m_pLinearClampSampler); m_ptex2DOccludedNetDensityToAtmTopRTV = tex2DOccludedNetDensityToAtmTop->GetDefaultView(TEXTURE_VIEW_RENDER_TARGET); m_pResMapping->AddResource("g_tex2DOccludedNetDensityToAtmTop", m_ptex2DOccludedNetDensityToAtmTopSRV, false); } ITextureView* pRTVs[] = {m_ptex2DOccludedNetDensityToAtmTopRTV}; pDeviceContext->SetRenderTargets(1, pRTVs, nullptr, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); RenderScreenSizeQuad(pDeviceContext, m_pPrecomputeNetDensityToAtmTopPSO, m_pPrecomputeNetDensityToAtmTopSRB, 0); m_uiUpToDateResourceFlags |= UpToDateResourceFlags::PrecomputedOpticalDepthTex; } void LightSctrPostProcess :: CreateRandomSphereSamplingTexture(IRenderDevice *pDevice) { TextureDesc RandomSphereSamplingTexDesc; RandomSphereSamplingTexDesc.Type = RESOURCE_DIM_TEX_2D; RandomSphereSamplingTexDesc.Width = m_uiNumRandomSamplesOnSphere; RandomSphereSamplingTexDesc.Height = 1; RandomSphereSamplingTexDesc.MipLevels = 1; RandomSphereSamplingTexDesc.Format = TEX_FORMAT_RGBA32_FLOAT; RandomSphereSamplingTexDesc.Usage = USAGE_STATIC; RandomSphereSamplingTexDesc.BindFlags = BIND_SHADER_RESOURCE; std::vector<float4> SphereSampling(m_uiNumRandomSamplesOnSphere); for(Uint32 iSample = 0; iSample < m_uiNumRandomSamplesOnSphere; ++iSample) { float4 &f4Sample = SphereSampling[iSample]; f4Sample.z = ((float)rand()/(float)RAND_MAX) * 2.f - 1.f; float t = ((float)rand()/(float)RAND_MAX) * 2.f * PI; float r = sqrt( std::max(1.f - f4Sample.z*f4Sample.z, 0.f) ); f4Sample.x = r * cos(t); f4Sample.y = r * sin(t); f4Sample.w = 0; } TextureSubResData Mip0Data; Mip0Data.pData = SphereSampling.data(); Mip0Data.Stride = m_uiNumRandomSamplesOnSphere*sizeof( float4 ); TextureData TexData; TexData.NumSubresources = 1; TexData.pSubResources = &Mip0Data; RefCntAutoPtr<ITexture> ptex2DSphereRandomSampling; pDevice->CreateTexture( RandomSphereSamplingTexDesc, &TexData, &ptex2DSphereRandomSampling ); m_ptex2DSphereRandomSamplingSRV = ptex2DSphereRandomSampling->GetDefaultView( TEXTURE_VIEW_SHADER_RESOURCE ); m_ptex2DSphereRandomSamplingSRV->SetSampler(m_pLinearClampSampler); m_pResMapping->AddResource( "g_tex2DSphereRandomSampling", m_ptex2DSphereRandomSamplingSRV, true ); } void LightSctrPostProcess :: CreateAuxTextures(IRenderDevice *pDevice) { TextureDesc TexDesc; TexDesc.Type = RESOURCE_DIM_TEX_2D; TexDesc.MipLevels = 1; TexDesc.Usage = USAGE_DEFAULT; TexDesc.BindFlags = BIND_RENDER_TARGET | BIND_SHADER_RESOURCE; { // MaxSamplesInSlice x NumSlices RG32F texture to store screen-space coordinates // for every epipolar sample TexDesc.Name = "Coordinate Texture"; TexDesc.Width = m_PostProcessingAttribs.m_uiMaxSamplesInSlice; TexDesc.Height = m_PostProcessingAttribs.m_uiNumEpipolarSlices; TexDesc.Format = CoordinateTexFmt; TexDesc.ClearValue.Format = TexDesc.Format; TexDesc.ClearValue.Color[0] = -1e+30f; TexDesc.ClearValue.Color[1] = -1e+30f; TexDesc.ClearValue.Color[2] = -1e+30f; TexDesc.ClearValue.Color[3] = -1e+30f; RefCntAutoPtr<ITexture> tex2DCoordinateTexture; pDevice->CreateTexture(TexDesc, nullptr, &tex2DCoordinateTexture); auto* tex2DCoordinateTextureSRV = tex2DCoordinateTexture->GetDefaultView(TEXTURE_VIEW_SHADER_RESOURCE); m_ptex2DCoordinateTextureRTV = tex2DCoordinateTexture->GetDefaultView(TEXTURE_VIEW_RENDER_TARGET); tex2DCoordinateTextureSRV->SetSampler(m_pLinearClampSampler); m_pResMapping->AddResource("g_tex2DCoordinates", tex2DCoordinateTextureSRV, false); } { // NumSlices x 1 RGBA32F texture to store end point coordinates for every epipolar slice TexDesc.Name = "Slice Endpoints"; TexDesc.Width = m_PostProcessingAttribs.m_uiNumEpipolarSlices; TexDesc.Height = 1; TexDesc.Format = SliceEndpointsFmt; TexDesc.ClearValue.Format = TexDesc.Format; TexDesc.ClearValue.Color[0] = -1e+30f; TexDesc.ClearValue.Color[1] = -1e+30f; TexDesc.ClearValue.Color[2] = -1e+30f; TexDesc.ClearValue.Color[3] = -1e+30f; RefCntAutoPtr<ITexture> tex2DSliceEndpoints; pDevice->CreateTexture(TexDesc, nullptr, &tex2DSliceEndpoints); auto* tex2DSliceEndpointsSRV = tex2DSliceEndpoints->GetDefaultView(TEXTURE_VIEW_SHADER_RESOURCE); m_ptex2DSliceEndpointsRTV = tex2DSliceEndpoints->GetDefaultView(TEXTURE_VIEW_RENDER_TARGET); tex2DSliceEndpointsSRV->SetSampler(m_pLinearClampSampler); m_pResMapping->AddResource("g_tex2DSliceEndPoints", tex2DSliceEndpointsSRV, false); } TexDesc.ClearValue.Format = TEX_FORMAT_UNKNOWN; { TexDesc.Name = "Interpolation Source"; // MaxSamplesInSlice x NumSlices RG16U texture to store two indices from which // the sample should be interpolated, for every epipolar sample TexDesc.Width = m_PostProcessingAttribs.m_uiMaxSamplesInSlice; TexDesc.Height = m_PostProcessingAttribs.m_uiNumEpipolarSlices; // In fact we only need RG16U texture to store interpolation source indices. // However, NVidia GLES does not supported imge load/store operations on this format, // so we have to resort to RGBA32U. TexDesc.Format = InterpolationSourceTexFmt; TexDesc.BindFlags = BIND_UNORDERED_ACCESS | BIND_SHADER_RESOURCE; RefCntAutoPtr<ITexture> tex2DInterpolationSource; pDevice->CreateTexture(TexDesc, nullptr, &tex2DInterpolationSource); auto* tex2DInterpolationSourceSRV = tex2DInterpolationSource->GetDefaultView(TEXTURE_VIEW_SHADER_RESOURCE); auto* tex2DInterpolationSourceUAV = tex2DInterpolationSource->GetDefaultView(TEXTURE_VIEW_UNORDERED_ACCESS); tex2DInterpolationSourceSRV->SetSampler(m_pPointClampSampler); m_pResMapping->AddResource("g_tex2DInterpolationSource", tex2DInterpolationSourceSRV, false); m_pResMapping->AddResource("g_rwtex2DInterpolationSource", tex2DInterpolationSourceUAV, false); } { // MaxSamplesInSlice x NumSlices R32F texture to store camera-space Z coordinate, // for every epipolar sample TexDesc.Name = "Epipolar Cam Space Z"; TexDesc.Format = EpipolarCamSpaceZFmt; TexDesc.BindFlags = BIND_RENDER_TARGET | BIND_SHADER_RESOURCE; RefCntAutoPtr<ITexture> tex2DEpipolarCamSpaceZ; pDevice->CreateTexture(TexDesc, nullptr, &tex2DEpipolarCamSpaceZ); auto* tex2DEpipolarCamSpaceZSRV = tex2DEpipolarCamSpaceZ->GetDefaultView(TEXTURE_VIEW_SHADER_RESOURCE); m_ptex2DEpipolarCamSpaceZRTV = tex2DEpipolarCamSpaceZ->GetDefaultView(TEXTURE_VIEW_RENDER_TARGET); tex2DEpipolarCamSpaceZSRV->SetSampler(m_pLinearClampSampler); m_pResMapping->AddResource("g_tex2DEpipolarCamSpaceZ", tex2DEpipolarCamSpaceZSRV, false); } { // MaxSamplesInSlice x NumSlices RGBA16F texture to store interpolated inscattered light, // for every epipolar sample TexDesc.Name = "Epipolar Inscattering"; TexDesc.Format = EpipolarInsctrTexFmt; constexpr float flt16max = 65504.f; TexDesc.ClearValue.Format = TexDesc.Format; TexDesc.ClearValue.Color[0] = -flt16max; TexDesc.ClearValue.Color[1] = -flt16max; TexDesc.ClearValue.Color[2] = -flt16max; TexDesc.ClearValue.Color[3] = -flt16max; RefCntAutoPtr<ITexture> tex2DEpipolarInscattering; pDevice->CreateTexture(TexDesc, nullptr, &tex2DEpipolarInscattering); auto* tex2DEpipolarInscatteringSRV = tex2DEpipolarInscattering->GetDefaultView(TEXTURE_VIEW_SHADER_RESOURCE); m_ptex2DEpipolarInscatteringRTV = tex2DEpipolarInscattering->GetDefaultView(TEXTURE_VIEW_RENDER_TARGET); tex2DEpipolarInscatteringSRV->SetSampler(m_pLinearClampSampler); m_pResMapping->AddResource("g_tex2DScatteredColor", tex2DEpipolarInscatteringSRV, false); } { // MaxSamplesInSlice x NumSlices RGBA16F texture to store initial inscattered light, // for every epipolar sample TexDesc.Name = "Initial Scattered Light"; TexDesc.ClearValue.Format = TexDesc.Format; TexDesc.ClearValue.Color[0] = 0; TexDesc.ClearValue.Color[1] = 0; TexDesc.ClearValue.Color[2] = 0; TexDesc.ClearValue.Color[3] = 0; RefCntAutoPtr<ITexture> tex2DInitialScatteredLight; pDevice->CreateTexture(TexDesc, nullptr, &tex2DInitialScatteredLight); auto* tex2DInitialScatteredLightSRV = tex2DInitialScatteredLight->GetDefaultView(TEXTURE_VIEW_SHADER_RESOURCE); m_ptex2DInitialScatteredLightRTV = tex2DInitialScatteredLight->GetDefaultView(TEXTURE_VIEW_RENDER_TARGET); tex2DInitialScatteredLightSRV->SetSampler(m_pLinearClampSampler); m_pResMapping->AddResource("g_tex2DInitialInsctrIrradiance", tex2DInitialScatteredLightSRV, false); } TexDesc.ClearValue.Format = TEX_FORMAT_UNKNOWN; { // MaxSamplesInSlice x NumSlices depth stencil texture to mark samples for processing, // for every epipolar sample TexDesc.Name = "Epipolar Image Depth"; TexDesc.Format = EpipolarImageDepthFmt; TexDesc.BindFlags = BIND_DEPTH_STENCIL; TexDesc.ClearValue.Format = TexDesc.Format; TexDesc.ClearValue.DepthStencil.Depth = 1; TexDesc.ClearValue.DepthStencil.Stencil = 0; RefCntAutoPtr<ITexture> tex2DEpipolarImageDepth; pDevice->CreateTexture(TexDesc, nullptr, &tex2DEpipolarImageDepth); m_ptex2DEpipolarImageDSV = tex2DEpipolarImageDepth->GetDefaultView(TEXTURE_VIEW_DEPTH_STENCIL); } m_uiUpToDateResourceFlags |= UpToDateResourceFlags::AuxTextures; ResetShaderResourceBindings(); } void LightSctrPostProcess :: CreatePrecomputedScatteringLUT(IRenderDevice *pDevice, IDeviceContext *pContext) { const int ThreadGroupSize = pDevice->GetDeviceCaps().DevType == DeviceType::OpenGLES ? 8 : 16; if( !m_pPrecomputeSingleSctrCS ) { ShaderMacroHelper Macros; DefineMacros(Macros); Macros.AddShaderMacro( "THREAD_GROUP_SIZE", ThreadGroupSize ); Macros.Finalize(); m_pPrecomputeSingleSctrCS = CreateShader( pDevice, "PrecomputeSingleScattering.fx", "PrecomputeSingleScatteringCS", SHADER_TYPE_COMPUTE, Macros, SHADER_VARIABLE_TYPE_DYNAMIC ); PipelineStateDesc PSODesc; PSODesc.IsComputePipeline = true; PSODesc.ComputePipeline.pCS = m_pPrecomputeSingleSctrCS; pDevice->CreatePipelineState(PSODesc, &m_pPrecomputeSingleSctrPSO); m_pPrecomputeSingleSctrPSO->CreateShaderResourceBinding(&m_pPrecomputeSingleSctrSRB, true); } if( !m_pComputeSctrRadianceCS ) { ShaderMacroHelper Macros; DefineMacros(Macros); Macros.AddShaderMacro( "THREAD_GROUP_SIZE", ThreadGroupSize ); Macros.AddShaderMacro( "NUM_RANDOM_SPHERE_SAMPLES", m_uiNumRandomSamplesOnSphere ); Macros.Finalize(); m_pComputeSctrRadianceCS = CreateShader( pDevice, "ComputeSctrRadiance.fx", "ComputeSctrRadianceCS", SHADER_TYPE_COMPUTE, Macros, SHADER_VARIABLE_TYPE_DYNAMIC ); PipelineStateDesc PSODesc; PSODesc.IsComputePipeline = true; PSODesc.ComputePipeline.pCS = m_pComputeSctrRadianceCS; pDevice->CreatePipelineState(PSODesc, &m_pComputeSctrRadiancePSO); m_pComputeSctrRadianceSRB.Release(); m_pComputeSctrRadiancePSO->CreateShaderResourceBinding(&m_pComputeSctrRadianceSRB, true); } if( !m_pComputeScatteringOrderCS ) { ShaderMacroHelper Macros; DefineMacros(Macros); Macros.AddShaderMacro( "THREAD_GROUP_SIZE", ThreadGroupSize ); Macros.Finalize(); m_pComputeScatteringOrderCS = CreateShader( pDevice, "ComputeScatteringOrder.fx", "ComputeScatteringOrderCS", SHADER_TYPE_COMPUTE, Macros, SHADER_VARIABLE_TYPE_DYNAMIC ); PipelineStateDesc PSODesc; PSODesc.IsComputePipeline = true; PSODesc.ComputePipeline.pCS = m_pComputeScatteringOrderCS; pDevice->CreatePipelineState(PSODesc, &m_pComputeScatteringOrderPSO); m_pComputeScatteringOrderPSO->CreateShaderResourceBinding(&m_pComputeScatteringOrderSRB, true); } if( !m_pInitHighOrderScatteringCS ) { ShaderMacroHelper Macros; DefineMacros(Macros); Macros.AddShaderMacro( "THREAD_GROUP_SIZE", ThreadGroupSize ); Macros.Finalize(); m_pInitHighOrderScatteringCS = CreateShader( pDevice, "InitHighOrderScattering.fx", "InitHighOrderScatteringCS", SHADER_TYPE_COMPUTE, Macros, SHADER_VARIABLE_TYPE_DYNAMIC ); PipelineStateDesc PSODesc; PSODesc.IsComputePipeline = true; PSODesc.ComputePipeline.pCS = m_pInitHighOrderScatteringCS; pDevice->CreatePipelineState(PSODesc, &m_pInitHighOrderScatteringPSO); m_pInitHighOrderScatteringPSO->CreateShaderResourceBinding( &m_pInitHighOrderScatteringSRB, true ); } if( !m_pUpdateHighOrderScatteringCS ) { ShaderMacroHelper Macros; DefineMacros(Macros); Macros.AddShaderMacro( "THREAD_GROUP_SIZE", ThreadGroupSize ); Macros.Finalize(); m_pUpdateHighOrderScatteringCS = CreateShader( pDevice, "UpdateHighOrderScattering.fx", "UpdateHighOrderScatteringCS", SHADER_TYPE_COMPUTE, Macros, SHADER_VARIABLE_TYPE_DYNAMIC); PipelineStateDesc PSODesc; PSODesc.IsComputePipeline = true; PSODesc.ComputePipeline.pCS = m_pUpdateHighOrderScatteringCS; pDevice->CreatePipelineState(PSODesc, &m_pUpdateHighOrderScatteringPSO); m_pUpdateHighOrderScatteringPSO->CreateShaderResourceBinding(&m_pUpdateHighOrderScatteringSRB, true); } if( !m_pCombineScatteringOrdersCS ) { ShaderMacroHelper Macros; DefineMacros(Macros); Macros.AddShaderMacro( "THREAD_GROUP_SIZE", ThreadGroupSize ); Macros.Finalize(); m_pCombineScatteringOrdersCS = CreateShader( pDevice, "CombineScatteringOrders.fx", "CombineScatteringOrdersCS", SHADER_TYPE_COMPUTE, Macros, SHADER_VARIABLE_TYPE_DYNAMIC ); PipelineStateDesc PSODesc; PSODesc.IsComputePipeline = true; PSODesc.ComputePipeline.pCS = m_pCombineScatteringOrdersCS; pDevice->CreatePipelineState(PSODesc, &m_pCombineScatteringOrdersPSO); m_pCombineScatteringOrdersPSO->CreateShaderResourceBinding(&m_pCombineScatteringOrdersSRB, true); } if( !m_ptex2DSphereRandomSamplingSRV ) CreateRandomSphereSamplingTexture(pDevice); TextureDesc PrecomputedSctrTexDesc; PrecomputedSctrTexDesc.Type = RESOURCE_DIM_TEX_3D; PrecomputedSctrTexDesc.Width = sm_iPrecomputedSctrUDim; PrecomputedSctrTexDesc.Height = sm_iPrecomputedSctrVDim; PrecomputedSctrTexDesc.Depth = sm_iPrecomputedSctrWDim * sm_iPrecomputedSctrQDim; PrecomputedSctrTexDesc.MipLevels = 1; PrecomputedSctrTexDesc.Format = TEX_FORMAT_RGBA16_FLOAT; PrecomputedSctrTexDesc.Usage = USAGE_DEFAULT; PrecomputedSctrTexDesc.BindFlags = BIND_UNORDERED_ACCESS | BIND_SHADER_RESOURCE; if( !m_ptex3DSingleScatteringSRV ) { m_ptex3DSingleScatteringSRV.Release(); m_ptex3DHighOrderScatteringSRV.Release(); m_ptex3DMultipleScatteringSRV.Release(); RefCntAutoPtr<ITexture> ptex3DSingleSctr, ptex3DMultipleSctr; pDevice->CreateTexture(PrecomputedSctrTexDesc, nullptr, &ptex3DSingleSctr); m_ptex3DSingleScatteringSRV = ptex3DSingleSctr->GetDefaultView( TEXTURE_VIEW_SHADER_RESOURCE ); m_ptex3DSingleScatteringSRV->SetSampler( m_pLinearClampSampler ); m_pResMapping->AddResource( "g_rwtex3DSingleScattering", ptex3DSingleSctr->GetDefaultView( TEXTURE_VIEW_UNORDERED_ACCESS ), true ); // We have to bother with two texture, because HLSL only allows read-write operations on single // component textures pDevice->CreateTexture(PrecomputedSctrTexDesc, nullptr, &m_ptex3DHighOrderSctr); pDevice->CreateTexture(PrecomputedSctrTexDesc, nullptr, &m_ptex3DHighOrderSctr2); m_ptex3DHighOrderSctr->GetDefaultView( TEXTURE_VIEW_SHADER_RESOURCE )->SetSampler( m_pLinearClampSampler ); m_ptex3DHighOrderSctr2->GetDefaultView( TEXTURE_VIEW_SHADER_RESOURCE )->SetSampler( m_pLinearClampSampler ); pDevice->CreateTexture(PrecomputedSctrTexDesc, nullptr, &ptex3DMultipleSctr); m_ptex3DMultipleScatteringSRV = ptex3DMultipleSctr->GetDefaultView( TEXTURE_VIEW_SHADER_RESOURCE ); m_ptex3DMultipleScatteringSRV->SetSampler( m_pLinearClampSampler ); m_pResMapping->AddResource( "g_rwtex3DMultipleSctr", ptex3DMultipleSctr->GetDefaultView( TEXTURE_VIEW_UNORDERED_ACCESS ), true ); m_pResMapping->AddResource("g_tex3DSingleSctrLUT", m_ptex3DSingleScatteringSRV, true); m_pResMapping->AddResource("g_tex3DMultipleSctrLUT", m_ptex3DMultipleScatteringSRV, true); } // Precompute single scattering m_pPrecomputeSingleSctrSRB->BindResources( SHADER_TYPE_COMPUTE, m_pResMapping, BIND_SHADER_RESOURCES_VERIFY_ALL_RESOLVED ); DispatchComputeAttribs DispatchAttrs( PrecomputedSctrTexDesc.Width/ThreadGroupSize, PrecomputedSctrTexDesc.Height/ThreadGroupSize, PrecomputedSctrTexDesc.Depth); pContext->SetPipelineState(m_pPrecomputeSingleSctrPSO); pContext->CommitShaderResources(m_pPrecomputeSingleSctrSRB, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); pContext->DispatchCompute(DispatchAttrs); // Precompute multiple scattering // We need higher precision to store intermediate data PrecomputedSctrTexDesc.Format = TEX_FORMAT_RGBA32_FLOAT; RefCntAutoPtr<ITexture> ptex3DSctrRadiance, ptex3DInsctrOrder; RefCntAutoPtr<ITextureView> ptex3DSctrRadianceSRV, ptex3DInsctrOrderSRV; pDevice->CreateTexture(PrecomputedSctrTexDesc, nullptr, &ptex3DSctrRadiance); pDevice->CreateTexture(PrecomputedSctrTexDesc, nullptr, &ptex3DInsctrOrder); ptex3DSctrRadianceSRV = ptex3DSctrRadiance->GetDefaultView(TEXTURE_VIEW_SHADER_RESOURCE); ptex3DInsctrOrderSRV = ptex3DInsctrOrder->GetDefaultView(TEXTURE_VIEW_SHADER_RESOURCE); ptex3DSctrRadianceSRV->SetSampler( m_pLinearClampSampler ); ptex3DInsctrOrderSRV->SetSampler( m_pLinearClampSampler ); m_pResMapping->AddResource( "g_rwtex3DSctrRadiance", ptex3DSctrRadiance->GetDefaultView( TEXTURE_VIEW_UNORDERED_ACCESS ), true ); m_pResMapping->AddResource( "g_rwtex3DInsctrOrder", ptex3DInsctrOrder->GetDefaultView( TEXTURE_VIEW_UNORDERED_ACCESS ), true ); m_pComputeSctrRadianceSRB->BindResources( SHADER_TYPE_COMPUTE, m_pResMapping, 0 ); m_pComputeScatteringOrderSRB->BindResources( SHADER_TYPE_COMPUTE, m_pResMapping, 0 ); m_pInitHighOrderScatteringSRB->BindResources( SHADER_TYPE_COMPUTE, m_pResMapping, 0 ); m_pUpdateHighOrderScatteringSRB->BindResources( SHADER_TYPE_COMPUTE, m_pResMapping, 0 ); const int iNumScatteringOrders = pDevice->GetDeviceCaps().DevType == DeviceType::OpenGLES ? 3 : 4; for(int iSctrOrder = 1; iSctrOrder < iNumScatteringOrders; ++iSctrOrder) { // Step 1: compute differential in-scattering m_pComputeSctrRadianceSRB->GetVariable( SHADER_TYPE_COMPUTE, "g_tex3DPreviousSctrOrder" )->Set( (iSctrOrder == 1) ? m_ptex3DSingleScatteringSRV : ptex3DInsctrOrderSRV ); pContext->SetPipelineState(m_pComputeSctrRadiancePSO); pContext->CommitShaderResources(m_pComputeSctrRadianceSRB, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); pContext->DispatchCompute(DispatchAttrs); // It seemse like on Intel GPU, the driver accumulates work into big batch. // The resulting batch turns out to be too big for GPU to process it in allowed time // limit, and the system kills the driver. So we have to flush the command buffer to // force execution of compute shaders. pContext->Flush(); // Step 2: integrate differential in-scattering m_pComputeScatteringOrderSRB->GetVariable( SHADER_TYPE_COMPUTE, "g_tex3DPointwiseSctrRadiance" )->Set( ptex3DSctrRadianceSRV ); pContext->SetPipelineState(m_pComputeScatteringOrderPSO); pContext->CommitShaderResources(m_pComputeScatteringOrderSRB, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); pContext->DispatchCompute(DispatchAttrs); IPipelineState *pPSO = nullptr; IShader *pCS = nullptr; IShaderResourceBinding *pSRB = nullptr; // Step 3: accumulate high-order scattering scattering if( iSctrOrder == 1 ) { pCS = m_pInitHighOrderScatteringCS; pPSO = m_pInitHighOrderScatteringPSO; pSRB = m_pInitHighOrderScatteringSRB; } else { std::swap( m_ptex3DHighOrderSctr, m_ptex3DHighOrderSctr2 ); m_pUpdateHighOrderScatteringSRB->GetVariable( SHADER_TYPE_COMPUTE, "g_tex3DHighOrderOrderScattering" )->Set( m_ptex3DHighOrderSctr2->GetDefaultView(TEXTURE_VIEW_SHADER_RESOURCE) ); pCS = m_pUpdateHighOrderScatteringCS; pPSO = m_pUpdateHighOrderScatteringPSO; pSRB = m_pUpdateHighOrderScatteringSRB; } pSRB->GetVariable( SHADER_TYPE_COMPUTE, "g_rwtex3DHighOrderSctr" )->Set( m_ptex3DHighOrderSctr->GetDefaultView( TEXTURE_VIEW_UNORDERED_ACCESS ) ); pSRB->GetVariable( SHADER_TYPE_COMPUTE, "g_tex3DCurrentOrderScattering" )->Set( ptex3DInsctrOrderSRV ); pContext->SetPipelineState(pPSO); pContext->CommitShaderResources(pSRB, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); pContext->DispatchCompute(DispatchAttrs); // Flush the command buffer to force execution of compute shaders and avoid device // reset on low-end Intel GPUs. pContext->Flush(); } // Note that m_ptex3DHighOrderSctr and m_ptex3DHighOrderSctr2 are ping-ponged during pre-processing m_ptex3DHighOrderScatteringSRV = m_ptex3DHighOrderSctr->GetDefaultView( TEXTURE_VIEW_SHADER_RESOURCE ); m_ptex3DHighOrderScatteringSRV->SetSampler( m_pLinearClampSampler ); m_pResMapping->AddResource("g_tex3DHighOrderSctrLUT", m_ptex3DHighOrderScatteringSRV, false); m_pCombineScatteringOrdersSRB->BindResources( SHADER_TYPE_COMPUTE, m_pResMapping, BIND_SHADER_RESOURCES_VERIFY_ALL_RESOLVED ); // Combine single scattering and higher order scattering into single texture pContext->SetPipelineState(m_pCombineScatteringOrdersPSO); pContext->CommitShaderResources(m_pCombineScatteringOrdersSRB, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); pContext->DispatchCompute(DispatchAttrs); m_pResMapping->RemoveResourceByName( "g_rwtex3DMultipleSctr" ); m_pResMapping->RemoveResourceByName( "g_rwtex3DSingleScattering" ); m_pResMapping->RemoveResourceByName( "g_rwtex3DSctrRadiance" ); m_pResMapping->RemoveResourceByName( "g_rwtex3DInsctrOrder" ); m_uiUpToDateResourceFlags |= UpToDateResourceFlags::PrecomputedIntegralsTex; } void LightSctrPostProcess :: CreateLowResLuminanceTexture(IRenderDevice* pDevice, IDeviceContext* pDeviceCtx) { // Create low-resolution texture to store image luminance TextureDesc TexDesc; TexDesc.Name = "Low Res Luminance"; TexDesc.Type = RESOURCE_DIM_TEX_2D; TexDesc.Width = 1 << (sm_iLowResLuminanceMips-1); TexDesc.Height = 1 << (sm_iLowResLuminanceMips-1); TexDesc.Format = LuminanceTexFmt, TexDesc.MipLevels = sm_iLowResLuminanceMips; TexDesc.Usage = USAGE_DEFAULT; TexDesc.BindFlags = BIND_RENDER_TARGET | BIND_SHADER_RESOURCE; TexDesc.MiscFlags = MISC_TEXTURE_FLAG_GENERATE_MIPS; RefCntAutoPtr<ITexture> tex2DLowResLuminance; pDevice->CreateTexture(TexDesc, nullptr, &tex2DLowResLuminance); m_ptex2DLowResLuminanceSRV = tex2DLowResLuminance->GetDefaultView(TEXTURE_VIEW_SHADER_RESOURCE); m_ptex2DLowResLuminanceRTV = tex2DLowResLuminance->GetDefaultView(TEXTURE_VIEW_RENDER_TARGET); m_ptex2DLowResLuminanceSRV->SetSampler(m_pLinearClampSampler); m_pResMapping->AddResource("g_tex2DLowResLuminance", m_ptex2DLowResLuminanceSRV, false); TexDesc.Name = "Average Luminance"; TexDesc.Width = 1; TexDesc.Height = 1; TexDesc.MipLevels = 1; TexDesc.MiscFlags = MISC_TEXTURE_FLAG_NONE; TexDesc.ClearValue.Color[0] = 0.1f; TexDesc.ClearValue.Color[1] = 0.1f; TexDesc.ClearValue.Color[2] = 0.1f; TexDesc.ClearValue.Color[3] = 0.1f; RefCntAutoPtr<ITexture> tex2DAverageLuminance; pDevice->CreateTexture(TexDesc, nullptr, &tex2DAverageLuminance); auto* tex2DAverageLuminanceSRV = tex2DAverageLuminance->GetDefaultView(TEXTURE_VIEW_SHADER_RESOURCE); m_ptex2DAverageLuminanceRTV = tex2DAverageLuminance->GetDefaultView(TEXTURE_VIEW_RENDER_TARGET); tex2DAverageLuminanceSRV->SetSampler(m_pLinearClampSampler); // Set intial luminance to 1 ITextureView* pRTVs[] = {m_ptex2DAverageLuminanceRTV}; pDeviceCtx->SetRenderTargets(1, pRTVs, nullptr, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); pDeviceCtx->ClearRenderTarget(m_ptex2DAverageLuminanceRTV, TexDesc.ClearValue.Color, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); tex2DAverageLuminanceSRV->SetSampler(m_pLinearClampSampler); m_pResMapping->AddResource("g_tex2DAverageLuminance", tex2DAverageLuminanceSRV, false); ResetShaderResourceBindings(); m_uiUpToDateResourceFlags |= UpToDateResourceFlags::LowResLuminamceTex; } void LightSctrPostProcess :: CreateSliceUVDirAndOriginTexture(IRenderDevice* pDevice) { TextureDesc TexDesc; TexDesc.Name = "Slice UV Dir and Origin"; TexDesc.Type = RESOURCE_DIM_TEX_2D; TexDesc.Width = m_PostProcessingAttribs.m_uiNumEpipolarSlices; TexDesc.Height = m_PostProcessingAttribs.m_iNumCascades; TexDesc.Format = SliceUVDirAndOriginTexFmt; TexDesc.MipLevels = 1; TexDesc.Usage = USAGE_DEFAULT; TexDesc.BindFlags = BIND_RENDER_TARGET | BIND_SHADER_RESOURCE; RefCntAutoPtr<ITexture> tex2DSliceUVDirAndOrigin; pDevice->CreateTexture(TexDesc, nullptr, &tex2DSliceUVDirAndOrigin); auto* tex2DSliceUVDirAndOriginSRV = tex2DSliceUVDirAndOrigin->GetDefaultView(TEXTURE_VIEW_SHADER_RESOURCE); m_ptex2DSliceUVDirAndOriginRTV = tex2DSliceUVDirAndOrigin->GetDefaultView(TEXTURE_VIEW_RENDER_TARGET); tex2DSliceUVDirAndOriginSRV->SetSampler(m_pLinearClampSampler); m_pResMapping->AddResource("g_tex2DSliceUVDirAndOrigin", tex2DSliceUVDirAndOriginSRV, false); m_uiUpToDateResourceFlags |= UpToDateResourceFlags::SliceUVDirAndOriginTex; ResetShaderResourceBindings(); } void LightSctrPostProcess :: CreateCamSpaceZTexture(IRenderDevice* pDevice) { TextureDesc TexDesc; TexDesc.Name = "Cam-space Z"; TexDesc.Type = RESOURCE_DIM_TEX_2D; TexDesc.Width = m_uiBackBufferWidth; TexDesc.Height = m_uiBackBufferHeight; TexDesc.Format = CamSpaceZFmt; TexDesc.MipLevels = 1; TexDesc.Usage = USAGE_DEFAULT; TexDesc.BindFlags = BIND_RENDER_TARGET | BIND_SHADER_RESOURCE; RefCntAutoPtr<ITexture> ptex2DCamSpaceZ; pDevice->CreateTexture(TexDesc, nullptr, &ptex2DCamSpaceZ); m_ptex2DCamSpaceZRTV = ptex2DCamSpaceZ->GetDefaultView(TEXTURE_VIEW_RENDER_TARGET); auto* tex2DCamSpaceZSRV = ptex2DCamSpaceZ->GetDefaultView(TEXTURE_VIEW_SHADER_RESOURCE); tex2DCamSpaceZSRV->SetSampler(m_pLinearClampSampler); // Add texture to resource mapping m_pResMapping->AddResource("g_tex2DCamSpaceZ", tex2DCamSpaceZSRV, false); } void LightSctrPostProcess :: ReconstructCameraSpaceZ(FrameAttribs& FrameAttribs) { // Depth buffer is non-linear and cannot be interpolated directly // We have to reconstruct camera space z to be able to use bilinear filtering if (!m_pReconstrCamSpaceZPSO) { ShaderMacroHelper Macros; DefineMacros(Macros); Macros.Finalize(); ShaderVariableDesc Vars[] = { {"cbCameraAttribs", SHADER_VARIABLE_TYPE_STATIC}, {"g_tex2DDepthBuffer", SHADER_VARIABLE_TYPE_DYNAMIC} }; auto pReconstrCamSpaceZPS = CreateShader( FrameAttribs.pDevice, "ReconstructCameraSpaceZ.fx", "ReconstructCameraSpaceZPS", SHADER_TYPE_PIXEL, Macros, SHADER_VARIABLE_TYPE_MUTABLE, Vars, _countof(Vars) ); // Bind input resources required by the shader pReconstrCamSpaceZPS->BindResources(m_pResMapping, BIND_SHADER_RESOURCES_VERIFY_ALL_RESOLVED); TEXTURE_FORMAT RTVFmts[] = {CamSpaceZFmt}; m_pReconstrCamSpaceZPSO = CreateScreenSizeQuadPSO(FrameAttribs.pDevice, "ReconstructCameraSpaceZPSO", pReconstrCamSpaceZPS, DSS_DisableDepth, BS_Default, 1, RTVFmts, TEX_FORMAT_UNKNOWN); m_pReconstrCamSpaceZPSO->CreateShaderResourceBinding(&m_pReconstrCamSpaceZSRB, true); m_pReconstrCamSpaceZSRB->BindResources(SHADER_TYPE_PIXEL, m_pResMapping, BIND_SHADER_RESOURCES_KEEP_EXISTING); } m_pReconstrCamSpaceZSRB->GetVariable(SHADER_TYPE_PIXEL, "g_tex2DDepthBuffer")->Set(FrameAttribs.ptex2DSrcDepthBufferSRV); ITextureView* ppRTVs[] = {m_ptex2DCamSpaceZRTV}; FrameAttribs.pDeviceContext->SetRenderTargets(1, ppRTVs, nullptr, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); RenderScreenSizeQuad(FrameAttribs.pDeviceContext, m_pReconstrCamSpaceZPSO, m_pReconstrCamSpaceZSRB); } void LightSctrPostProcess :: RenderSliceEndpoints(FrameAttribs& FrameAttribs) { if (!m_pRendedSliceEndpointsPSO) { ShaderMacroHelper Macros; DefineMacros(Macros); Macros.Finalize(); ShaderVariableDesc Vars[] = { {"cbLightParams", SHADER_VARIABLE_TYPE_STATIC} }; auto pRendedSliceEndpointsPS = CreateShader(FrameAttribs.pDevice, "RenderSliceEndPoints.fx", "GenerateSliceEndpointsPS", SHADER_TYPE_PIXEL, Macros, SHADER_VARIABLE_TYPE_MUTABLE, Vars, _countof(Vars)); // Bind input resources required by the shader pRendedSliceEndpointsPS->BindResources( m_pResMapping, BIND_SHADER_RESOURCES_VERIFY_ALL_RESOLVED ); TEXTURE_FORMAT RTVFmts[] = {SliceEndpointsFmt}; m_pRendedSliceEndpointsPSO = CreateScreenSizeQuadPSO(FrameAttribs.pDevice, "RenderSliceEndPoints", pRendedSliceEndpointsPS, DSS_DisableDepth, BS_Default, 1, RTVFmts); m_pRendedSliceEndpointsPSO->CreateShaderResourceBinding(&m_pRendedSliceEndpointsSRB, true); } ITextureView* ppRTVs[] = {m_ptex2DSliceEndpointsRTV}; FrameAttribs.pDeviceContext->SetRenderTargets(1, ppRTVs, nullptr, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); RenderScreenSizeQuad(FrameAttribs.pDeviceContext, m_pRendedSliceEndpointsPSO, m_pRendedSliceEndpointsSRB); } void LightSctrPostProcess :: RenderCoordinateTexture(FrameAttribs& FrameAttribs) { if (!m_pRendedCoordTexPSO) { ShaderMacroHelper Macros; DefineMacros(Macros); Macros.Finalize(); auto pRendedCoordTexPS = CreateShader(FrameAttribs.pDevice, "RenderCoordinateTexture.fx", "GenerateCoordinateTexturePS", SHADER_TYPE_PIXEL, Macros, SHADER_VARIABLE_TYPE_MUTABLE); pRendedCoordTexPS->BindResources(m_pResMapping, BIND_SHADER_RESOURCES_VERIFY_ALL_RESOLVED); TEXTURE_FORMAT RTVFmts[] = {CoordinateTexFmt, EpipolarCamSpaceZFmt}; m_pRendedCoordTexPSO = CreateScreenSizeQuadPSO(FrameAttribs.pDevice, "RenderCoordinateTexture", pRendedCoordTexPS, DSS_IncStencilAlways, BS_Default, 2, RTVFmts, EpipolarImageDepthFmt); m_pRendedCoordTexSRB.Release(); } if (!m_pRendedCoordTexSRB) { m_pRendedCoordTexPSO->CreateShaderResourceBinding(&m_pRendedCoordTexSRB, true); m_pRendedCoordTexSRB->BindResources(SHADER_TYPE_PIXEL, m_pResMapping, BIND_SHADER_RESOURCES_KEEP_EXISTING | BIND_SHADER_RESOURCES_VERIFY_ALL_RESOLVED); } ITextureView* ppRTVs[] = {m_ptex2DCoordinateTextureRTV, m_ptex2DEpipolarCamSpaceZRTV}; FrameAttribs.pDeviceContext->SetRenderTargets(2, ppRTVs, m_ptex2DEpipolarImageDSV, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); // Clear both render targets with values that can't be correct projection space coordinates and camera space Z: float InvalidCoords[] = {-1e+30f, -1e+30f, -1e+30f, -1e+30f}; FrameAttribs.pDeviceContext->ClearRenderTarget(m_ptex2DCoordinateTextureRTV, InvalidCoords, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); FrameAttribs.pDeviceContext->ClearRenderTarget(m_ptex2DEpipolarCamSpaceZRTV, InvalidCoords, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); FrameAttribs.pDeviceContext->ClearDepthStencil(m_ptex2DEpipolarImageDSV, CLEAR_DEPTH_FLAG | CLEAR_STENCIL_FLAG, 1.0, 0, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); // Depth stencil state is configured to always increment stencil value. If coordinates are outside the screen, // the pixel shader discards the pixel and stencil value is left untouched. All such pixels will be skipped from // further processing RenderScreenSizeQuad(FrameAttribs.pDeviceContext, m_pRendedCoordTexPSO, m_pRendedCoordTexSRB); } void LightSctrPostProcess :: RenderCoarseUnshadowedInctr(FrameAttribs &FrameAttribs) { if (!m_pRenderCoarseUnshadowedInsctrPSO) { ShaderMacroHelper Macros; DefineMacros(Macros); Macros.Finalize(); auto EntryPoint = m_PostProcessingAttribs.m_uiExtinctionEvalMode == EXTINCTION_EVAL_MODE_EPIPOLAR ? "RenderCoarseUnshadowedInsctrAndExtinctionPS" : "RenderCoarseUnshadowedInsctrPS"; ShaderVariableDesc Vars[] = { {"cbParticipatingMediaScatteringParams", SHADER_VARIABLE_TYPE_STATIC}, {"cbCameraAttribs", SHADER_VARIABLE_TYPE_STATIC}, {"cbLightParams", SHADER_VARIABLE_TYPE_STATIC} }; auto pRenderCoarseUnshadowedInsctrPS = CreateShader( FrameAttribs.pDevice, "CoarseInsctr.fx", EntryPoint, SHADER_TYPE_PIXEL, Macros, SHADER_VARIABLE_TYPE_MUTABLE, Vars, _countof(Vars)); pRenderCoarseUnshadowedInsctrPS->BindResources( m_pResMapping, BIND_SHADER_RESOURCES_VERIFY_ALL_RESOLVED ); const auto* PSOName = m_PostProcessingAttribs.m_uiExtinctionEvalMode == EXTINCTION_EVAL_MODE_EPIPOLAR ? "RenderCoarseUnshadowedInsctrAndExtinctionPSO" : "RenderCoarseUnshadowedInsctrPSO"; TEXTURE_FORMAT RTVFmts[] = {EpipolarInsctrTexFmt, EpipolarExtinctionFmt}; Uint8 NumRTVs = m_PostProcessingAttribs.m_uiExtinctionEvalMode == EXTINCTION_EVAL_MODE_EPIPOLAR ? 2 : 1; m_pRenderCoarseUnshadowedInsctrPSO = CreateScreenSizeQuadPSO(FrameAttribs.pDevice, PSOName, pRenderCoarseUnshadowedInsctrPS, DSS_StencilEqKeepStencil, BS_Default, NumRTVs, RTVFmts, EpipolarImageDepthFmt); m_pRenderCoarseUnshadowedInsctrSRB.Release(); } if( m_PostProcessingAttribs.m_uiExtinctionEvalMode == EXTINCTION_EVAL_MODE_EPIPOLAR && !(m_uiUpToDateResourceFlags & UpToDateResourceFlags::ExtinctionTexture) ) { // Extinction texture size is num_slices x max_samples_in_slice. So the texture must be re-created when either changes. CreateExtinctionTexture(FrameAttribs.pDevice); } ITextureView *pRTVs[] = {m_ptex2DEpipolarInscatteringRTV, m_ptex2DEpipolarExtinctionRTV}; FrameAttribs.pDeviceContext->SetRenderTargets(m_PostProcessingAttribs.m_uiExtinctionEvalMode == EXTINCTION_EVAL_MODE_EPIPOLAR ? 2 : 1, pRTVs, m_ptex2DEpipolarImageDSV, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); float flt16max = 65504.f; // Epipolar Inscattering is 16-bit float const float InvalidInsctr[] = {-flt16max, -flt16max, -flt16max, -flt16max}; if( m_ptex2DEpipolarInscatteringRTV ) FrameAttribs.pDeviceContext->ClearRenderTarget(m_ptex2DEpipolarInscatteringRTV, InvalidInsctr, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); const float One[] = {1, 1, 1, 1}; if( m_ptex2DEpipolarExtinctionRTV ) FrameAttribs.pDeviceContext->ClearRenderTarget(m_ptex2DEpipolarExtinctionRTV, One, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); if (!m_pRenderCoarseUnshadowedInsctrSRB) { m_pRenderCoarseUnshadowedInsctrPSO->CreateShaderResourceBinding(&m_pRenderCoarseUnshadowedInsctrSRB, true); m_pRenderCoarseUnshadowedInsctrSRB->BindResources(SHADER_TYPE_PIXEL, m_pResMapping, BIND_SHADER_RESOURCES_KEEP_EXISTING | BIND_SHADER_RESOURCES_VERIFY_ALL_RESOLVED); } RenderScreenSizeQuad(FrameAttribs.pDeviceContext, m_pRenderCoarseUnshadowedInsctrPSO, m_pRenderCoarseUnshadowedInsctrSRB, 1); } void LightSctrPostProcess :: RefineSampleLocations(FrameAttribs &FrameAttribs) { if( !m_pRefineSampleLocationsCS ) { // Thread group size must be at least as large as initial sample step m_uiSampleRefinementCSThreadGroupSize = std::max( m_uiSampleRefinementCSMinimumThreadGroupSize, m_PostProcessingAttribs.m_uiInitialSampleStepInSlice ); // Thread group size cannot be larger than the total number of samples in slice m_uiSampleRefinementCSThreadGroupSize = std::min( m_uiSampleRefinementCSThreadGroupSize, m_PostProcessingAttribs.m_uiMaxSamplesInSlice ); // Using small group size is inefficient since a lot of SIMD lanes become idle ShaderMacroHelper Macros; DefineMacros(Macros); Macros.AddShaderMacro("INITIAL_SAMPLE_STEP", m_PostProcessingAttribs.m_uiInitialSampleStepInSlice); Macros.AddShaderMacro("THREAD_GROUP_SIZE" , m_uiSampleRefinementCSThreadGroupSize ); Macros.AddShaderMacro("REFINEMENT_CRITERION", m_PostProcessingAttribs.m_uiRefinementCriterion ); Macros.AddShaderMacro("AUTO_EXPOSURE", m_PostProcessingAttribs.m_bAutoExposure); Macros.Finalize(); ShaderVariableDesc Vars[] = { {"cbLightParams", SHADER_VARIABLE_TYPE_STATIC}, {"cbPostProcessingAttribs", SHADER_VARIABLE_TYPE_STATIC} }; m_pRefineSampleLocationsCS = CreateShader( FrameAttribs.pDevice, "RefineSampleLocations.fx", "RefineSampleLocationsCS", SHADER_TYPE_COMPUTE, Macros, SHADER_VARIABLE_TYPE_MUTABLE, Vars, _countof(Vars)); PipelineStateDesc PSODesc; PSODesc.IsComputePipeline = true; PSODesc.ComputePipeline.pCS = m_pRefineSampleLocationsCS; m_pRefineSampleLocationsPSO.Release(); m_pRefineSampleLocationsSRB.Release(); FrameAttribs.pDevice->CreatePipelineState(PSODesc, &m_pRefineSampleLocationsPSO); } m_pRefineSampleLocationsCS->BindResources( m_pResMapping, BIND_SHADER_RESOURCES_VERIFY_ALL_RESOLVED ); if( !m_pRefineSampleLocationsSRB ) { m_pRefineSampleLocationsPSO->CreateShaderResourceBinding(&m_pRefineSampleLocationsSRB, true); m_pRefineSampleLocationsSRB->BindResources(SHADER_TYPE_COMPUTE, m_pResMapping, BIND_SHADER_RESOURCES_VERIFY_ALL_RESOLVED); } DispatchComputeAttribs DispatchAttrs( m_PostProcessingAttribs.m_uiMaxSamplesInSlice/m_uiSampleRefinementCSThreadGroupSize, m_PostProcessingAttribs.m_uiNumEpipolarSlices, 1); FrameAttribs.pDeviceContext->SetPipelineState(m_pRefineSampleLocationsPSO); FrameAttribs.pDeviceContext->CommitShaderResources(m_pRefineSampleLocationsSRB, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); FrameAttribs.pDeviceContext->DispatchCompute(DispatchAttrs); } void LightSctrPostProcess :: MarkRayMarchingSamples(FrameAttribs &FrameAttribs) { if (!m_pMarkRayMarchingSamplesInStencilPSO) { ShaderMacroHelper Macros; DefineMacros(Macros); Macros.Finalize(); auto pMarkRayMarchingSamplesInStencilPS = CreateShader( FrameAttribs.pDevice, "MarkRayMarchingSamples.fx", "MarkRayMarchingSamplesInStencilPS", SHADER_TYPE_PIXEL, Macros, SHADER_VARIABLE_TYPE_MUTABLE ); pMarkRayMarchingSamplesInStencilPS->BindResources(m_pResMapping, BIND_SHADER_RESOURCES_VERIFY_ALL_RESOLVED); m_pMarkRayMarchingSamplesInStencilPSO = CreateScreenSizeQuadPSO(FrameAttribs.pDevice, "MarkRayMarchingSamples", pMarkRayMarchingSamplesInStencilPS, DSS_StencilEqIncStencil, BS_Default, 0, nullptr, EpipolarImageDepthFmt); m_pMarkRayMarchingSamplesInStencilSRB.Release(); } // Mark ray marching samples in the stencil // The depth stencil state is configured to pass only pixels, whose stencil value equals 1. Thus all epipolar samples with // coordinates outsied the screen (generated on the previous pass) are automatically discarded. The pixel shader only // passes samples which are interpolated from themselves, the rest are discarded. Thus after this pass all ray // marching samples will be marked with 2 in stencil if (!m_pMarkRayMarchingSamplesInStencilSRB) { m_pMarkRayMarchingSamplesInStencilPSO->CreateShaderResourceBinding(&m_pMarkRayMarchingSamplesInStencilSRB, true); m_pMarkRayMarchingSamplesInStencilSRB->BindResources(SHADER_TYPE_PIXEL, m_pResMapping, BIND_SHADER_RESOURCES_KEEP_EXISTING | BIND_SHADER_RESOURCES_VERIFY_ALL_RESOLVED); } FrameAttribs.pDeviceContext->SetRenderTargets(0, nullptr, m_ptex2DEpipolarImageDSV, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); RenderScreenSizeQuad(FrameAttribs.pDeviceContext, m_pMarkRayMarchingSamplesInStencilPSO, m_pMarkRayMarchingSamplesInStencilSRB, 1); } void LightSctrPostProcess :: RenderSliceUVDirAndOrig(FrameAttribs &FrameAttribs) { if (!m_pRenderSliceUVDirInSM_PSO) { ShaderMacroHelper Macros; DefineMacros(Macros); Macros.Finalize(); ShaderVariableDesc Vars[] = { {"cbLightParams", SHADER_VARIABLE_TYPE_STATIC}, {"cbCameraAttribs", SHADER_VARIABLE_TYPE_STATIC}, {"cbPostProcessingAttribs", SHADER_VARIABLE_TYPE_STATIC} }; auto pRenderSliceUVDirInSMPS = CreateShader(FrameAttribs.pDevice, "SliceUVDirection.fx", "RenderSliceUVDirInShadowMapTexturePS", SHADER_TYPE_PIXEL, Macros, SHADER_VARIABLE_TYPE_MUTABLE, Vars, _countof(Vars)); pRenderSliceUVDirInSMPS->BindResources(m_pResMapping, BIND_SHADER_RESOURCES_VERIFY_ALL_RESOLVED); TEXTURE_FORMAT RTVFmts[] = {SliceUVDirAndOriginTexFmt}; m_pRenderSliceUVDirInSM_PSO = CreateScreenSizeQuadPSO(FrameAttribs.pDevice, "RenderSliceUVDirAndOrigin", pRenderSliceUVDirInSMPS, DSS_DisableDepth, BS_Default, 1, RTVFmts); m_pRenderSliceUVDirInSM_SRB.Release(); } if( !(m_uiUpToDateResourceFlags & UpToDateResourceFlags::SliceUVDirAndOriginTex) ) { CreateSliceUVDirAndOriginTexture(FrameAttribs.pDevice); } if (FrameAttribs.pDevice->GetDeviceCaps().DevType == DeviceType::Vulkan) { // NOTE: this is only needed as a workaround until GLSLang optimizes out unused shader resources. // If m_pcbMiscParams is not mapped, it causes an error on Vulkan backend because it finds // a dynamic buffer that has not been mapped before the first use. MapHelper<MiscDynamicParams> pMiscDynamicParams(FrameAttribs.pDeviceContext, m_pcbMiscParams, MAP_WRITE, MAP_FLAG_DISCARD); } if (!m_pRenderSliceUVDirInSM_SRB) { m_pRenderSliceUVDirInSM_PSO->CreateShaderResourceBinding(&m_pRenderSliceUVDirInSM_SRB, true); m_pRenderSliceUVDirInSM_SRB->BindResources(SHADER_TYPE_PIXEL, m_pResMapping, BIND_SHADER_RESOURCES_KEEP_EXISTING | BIND_SHADER_RESOURCES_VERIFY_ALL_RESOLVED); } ITextureView* ppRTVs[] = {m_ptex2DSliceUVDirAndOriginRTV}; FrameAttribs.pDeviceContext->SetRenderTargets(1, ppRTVs, nullptr, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); RenderScreenSizeQuad(FrameAttribs.pDeviceContext, m_pRenderSliceUVDirInSM_PSO, m_pRenderSliceUVDirInSM_SRB, 0); } void LightSctrPostProcess :: Build1DMinMaxMipMap(FrameAttribs &FrameAttribs, int iCascadeIndex) { if (!m_pInitializeMinMaxShadowMapPSO) { ShaderMacroHelper Macros; DefineMacros(Macros); Macros.AddShaderMacro("IS_32BIT_MIN_MAX_MAP", m_PostProcessingAttribs.m_bIs32BitMinMaxMipMap); Macros.Finalize(); ShaderVariableDesc Vars[] = { {"g_tex2DSliceUVDirAndOrigin", SHADER_VARIABLE_TYPE_MUTABLE}, {"g_tex2DLightSpaceDepthMap", SHADER_VARIABLE_TYPE_DYNAMIC} }; auto pInitializeMinMaxShadowMapPS = CreateShader( FrameAttribs.pDevice, "InitializeMinMaxShadowMap.fx", "InitializeMinMaxShadowMapPS", SHADER_TYPE_PIXEL, Macros, SHADER_VARIABLE_TYPE_STATIC, Vars, _countof(Vars) ); pInitializeMinMaxShadowMapPS->BindResources(m_pResMapping, BIND_SHADER_RESOURCES_VERIFY_ALL_RESOLVED); TEXTURE_FORMAT RTVFmts[] = {m_ptex2DMinMaxShadowMapSRV[0]->GetTexture()->GetDesc().Format}; m_pInitializeMinMaxShadowMapPSO = CreateScreenSizeQuadPSO(FrameAttribs.pDevice, "InitMinMaxShadowMap", pInitializeMinMaxShadowMapPS, DSS_DisableDepth, BS_Default, 1, RTVFmts); m_pInitializeMinMaxShadowMapSRB.Release(); } if (!m_pComputeMinMaxSMLevelPSO) { ShaderMacroHelper Macros; DefineMacros(Macros); Macros.Finalize(); ShaderVariableDesc VarDesc[] = { {"cbMiscDynamicParams", SHADER_VARIABLE_TYPE_STATIC} }; auto pComputeMinMaxSMLevelPS = CreateShader( FrameAttribs.pDevice, "ComputeMinMaxShadowMapLevel.fx", "ComputeMinMaxShadowMapLevelPS", SHADER_TYPE_PIXEL, Macros, SHADER_VARIABLE_TYPE_MUTABLE, VarDesc, _countof(VarDesc) ); pComputeMinMaxSMLevelPS->BindResources(m_pResMapping, BIND_SHADER_RESOURCES_VERIFY_ALL_RESOLVED); TEXTURE_FORMAT RTVFmts[] = {m_ptex2DMinMaxShadowMapSRV[0]->GetTexture()->GetDesc().Format}; m_pComputeMinMaxSMLevelPSO = CreateScreenSizeQuadPSO(FrameAttribs.pDevice, "ComputeMinMaxShadowMapLevel", pComputeMinMaxSMLevelPS, DSS_DisableDepth, BS_Default, 1, RTVFmts); m_pComputeMinMaxSMLevelSRB[0].Release(); m_pComputeMinMaxSMLevelSRB[1].Release(); } if (!m_pComputeMinMaxSMLevelSRB[0]) { for(int Parity = 0; Parity < 2; ++Parity) { m_pComputeMinMaxSMLevelPSO->CreateShaderResourceBinding(&m_pComputeMinMaxSMLevelSRB[Parity], true); auto *pVar = m_pComputeMinMaxSMLevelSRB[Parity]->GetVariable(SHADER_TYPE_PIXEL, "g_tex2DMinMaxLightSpaceDepth"); pVar->Set(m_ptex2DMinMaxShadowMapSRV[Parity]); m_pComputeMinMaxSMLevelSRB[Parity]->BindResources(SHADER_TYPE_PIXEL | SHADER_TYPE_VERTEX, m_pResMapping, BIND_SHADER_RESOURCES_KEEP_EXISTING | BIND_SHADER_RESOURCES_VERIFY_ALL_RESOLVED); } } auto pShadowSampler = FrameAttribs.ptex2DShadowMapSRV->GetSampler(); FrameAttribs.ptex2DShadowMapSRV->SetSampler( m_pLinearClampSampler ); auto iMinMaxTexHeight = m_PostProcessingAttribs.m_uiNumEpipolarSlices; if( m_bUseCombinedMinMaxTexture ) iMinMaxTexHeight *= (m_PostProcessingAttribs.m_iNumCascades - m_PostProcessingAttribs.m_iFirstCascade); auto tex2DMinMaxShadowMap0 = m_ptex2DMinMaxShadowMapRTV[0]->GetTexture(); auto tex2DMinMaxShadowMap1 = m_ptex2DMinMaxShadowMapRTV[1]->GetTexture(); // Computing min/max mip map using compute shader is much slower because a lot of threads are idle Uint32 uiXOffset = 0; Uint32 uiPrevXOffset = 0; Uint32 uiParity = 0; #ifdef _DEBUG { const auto &MinMaxShadowMapTexDesc = m_ptex2DMinMaxShadowMapRTV[0]->GetTexture()->GetDesc(); assert( MinMaxShadowMapTexDesc.Width == m_PostProcessingAttribs.m_uiMinMaxShadowMapResolution ); assert( MinMaxShadowMapTexDesc.Height == iMinMaxTexHeight ); } #endif // Note that we start rendering min/max shadow map from step == 2 for(Uint32 iStep = 2; iStep <= (Uint32)m_PostProcessingAttribs.m_fMaxShadowMapStep; iStep *=2, uiParity = (uiParity+1)%2 ) { // Use two buffers which are in turn used as the source and destination ITextureView *pRTVs[] = {m_ptex2DMinMaxShadowMapRTV[uiParity]}; FrameAttribs.pDeviceContext->SetRenderTargets( _countof( pRTVs ), pRTVs, nullptr, RESOURCE_STATE_TRANSITION_MODE_TRANSITION ); Viewport VP; VP.Width = static_cast<float>( m_PostProcessingAttribs.m_uiMinMaxShadowMapResolution / iStep ); VP.Height = static_cast<float>( iMinMaxTexHeight ); VP.TopLeftX = static_cast<float>( uiXOffset ); VP.TopLeftY = 0; FrameAttribs.pDeviceContext->SetViewports(1, &VP, 0, 0 ); // Set source and destination min/max data offsets: { MapHelper<MiscDynamicParams> pMiscDynamicParams( FrameAttribs.pDeviceContext, m_pcbMiscParams, MAP_WRITE, MAP_FLAG_DISCARD ); pMiscDynamicParams->ui4SrcMinMaxLevelXOffset = uiPrevXOffset; pMiscDynamicParams->ui4DstMinMaxLevelXOffset = uiXOffset; pMiscDynamicParams->fCascadeInd = static_cast<float>(iCascadeIndex); } if( iStep == 2 ) { // At the initial pass, the shader gathers 8 depths which will be used for // PCF filtering at the sample location and its next neighbor along the slice // and outputs min/max depths if (!m_pInitializeMinMaxShadowMapSRB) { m_pInitializeMinMaxShadowMapPSO->CreateShaderResourceBinding(&m_pInitializeMinMaxShadowMapSRB, true); m_pInitializeMinMaxShadowMapSRB->BindResources(SHADER_TYPE_PIXEL, m_pResMapping, BIND_SHADER_RESOURCES_KEEP_EXISTING | BIND_SHADER_RESOURCES_VERIFY_ALL_RESOLVED); } // Set dynamic variable g_tex2DLightSpaceDepthMap m_pInitializeMinMaxShadowMapSRB->GetVariable(SHADER_TYPE_PIXEL, "g_tex2DLightSpaceDepthMap")->Set(FrameAttribs.ptex2DShadowMapSRV); RenderScreenSizeQuad(FrameAttribs.pDeviceContext, m_pInitializeMinMaxShadowMapPSO, m_pInitializeMinMaxShadowMapSRB); } else { // At the subsequent passes, the shader loads two min/max values from the next finer level // to compute next level of the binary tree RenderScreenSizeQuad(FrameAttribs.pDeviceContext, m_pComputeMinMaxSMLevelPSO, m_pComputeMinMaxSMLevelSRB[(uiParity + 1) % 2]); } // All the data must reside in 0-th texture, so copy current level, if necessary, from 1-st texture if( uiParity == 1 ) { Box SrcBox; SrcBox.MinX = uiXOffset; SrcBox.MaxX = uiXOffset + m_PostProcessingAttribs.m_uiMinMaxShadowMapResolution / iStep; SrcBox.MinY = 0; SrcBox.MaxY = iMinMaxTexHeight; CopyTextureAttribs CopyAttribs(tex2DMinMaxShadowMap1, RESOURCE_STATE_TRANSITION_MODE_TRANSITION, tex2DMinMaxShadowMap0, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); CopyAttribs.pSrcBox = &SrcBox; CopyAttribs.DstX = uiXOffset; FrameAttribs.pDeviceContext->CopyTexture(CopyAttribs); } uiPrevXOffset = uiXOffset; uiXOffset += m_PostProcessingAttribs.m_uiMinMaxShadowMapResolution / iStep; } FrameAttribs.ptex2DShadowMapSRV->SetSampler( pShadowSampler ); } void LightSctrPostProcess :: DoRayMarching(FrameAttribs &FrameAttribs, Uint32 uiMaxStepsAlongRay, int iCascadeIndex) { auto& pDoRayMarchPSO = m_pDoRayMarchPSO[m_PostProcessingAttribs.m_bUse1DMinMaxTree ? 1 : 0]; auto& pDoRayMarchSRB = m_pDoRayMarchSRB[m_PostProcessingAttribs.m_bUse1DMinMaxTree ? 1 : 0]; if (!pDoRayMarchPSO) { ShaderMacroHelper Macros; DefineMacros(Macros); Macros.AddShaderMacro("CASCADE_PROCESSING_MODE", m_PostProcessingAttribs.m_uiCascadeProcessingMode); Macros.AddShaderMacro("USE_1D_MIN_MAX_TREE", m_PostProcessingAttribs.m_bUse1DMinMaxTree); Macros.Finalize(); ShaderVariableDesc Vars[] = { {"cbParticipatingMediaScatteringParams", SHADER_VARIABLE_TYPE_STATIC}, {"cbLightParams", SHADER_VARIABLE_TYPE_STATIC}, {"cbCameraAttribs", SHADER_VARIABLE_TYPE_STATIC}, {"cbPostProcessingAttribs", SHADER_VARIABLE_TYPE_STATIC}, {"cbMiscDynamicParams", SHADER_VARIABLE_TYPE_STATIC} }; auto pDoRayMarchPS = CreateShader( FrameAttribs.pDevice, "RayMarch.fx", "RayMarchPS", SHADER_TYPE_PIXEL, Macros, SHADER_VARIABLE_TYPE_MUTABLE, Vars, _countof(Vars) ); pDoRayMarchPS->BindResources(m_pResMapping, BIND_SHADER_RESOURCES_VERIFY_ALL_RESOLVED); TEXTURE_FORMAT RTVFmts[] = {EpipolarInsctrTexFmt}; pDoRayMarchPSO = CreateScreenSizeQuadPSO(FrameAttribs.pDevice, "RayMarch", pDoRayMarchPS, DSS_StencilEqKeepStencil, BS_AdditiveBlend, 1, RTVFmts, EpipolarImageDepthFmt); pDoRayMarchSRB.Release(); } { MapHelper<MiscDynamicParams> pMiscDynamicParams( FrameAttribs.pDeviceContext, m_pcbMiscParams, MAP_WRITE, MAP_FLAG_DISCARD ); pMiscDynamicParams->fMaxStepsAlongRay = static_cast<float>( uiMaxStepsAlongRay ); pMiscDynamicParams->fCascadeInd = static_cast<float>(iCascadeIndex); } int iNumInst = 0; if( m_PostProcessingAttribs.m_bEnableLightShafts ) { switch(m_PostProcessingAttribs.m_uiCascadeProcessingMode) { case CASCADE_PROCESSING_MODE_SINGLE_PASS: case CASCADE_PROCESSING_MODE_MULTI_PASS: iNumInst = 1; break; case CASCADE_PROCESSING_MODE_MULTI_PASS_INST: iNumInst = m_PostProcessingAttribs.m_iNumCascades - m_PostProcessingAttribs.m_iFirstCascade; break; } } else { iNumInst = 1; } // Depth stencil view now contains 2 for these pixels, for which ray marchings is to be performed // Depth stencil state is configured to pass only these pixels and discard the rest if (!pDoRayMarchSRB) { pDoRayMarchPSO->CreateShaderResourceBinding(&pDoRayMarchSRB, true); if (FrameAttribs.pDevice->GetDeviceCaps().IsVulkanDevice()) { m_pResMapping->AddResource("g_tex2DColorBuffer", FrameAttribs.ptex2DSrcColorBufferSRV, false); FrameAttribs.ptex2DSrcColorBufferSRV->SetSampler(m_pLinearClampSampler); } pDoRayMarchSRB->BindResources(SHADER_TYPE_PIXEL, m_pResMapping, BIND_SHADER_RESOURCES_KEEP_EXISTING | BIND_SHADER_RESOURCES_VERIFY_ALL_RESOLVED); } ITextureView* ppRTVs[] = {m_ptex2DInitialScatteredLightRTV}; FrameAttribs.pDeviceContext->SetRenderTargets(1, ppRTVs, m_ptex2DEpipolarImageDSV, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); RenderScreenSizeQuad(FrameAttribs.pDeviceContext, pDoRayMarchPSO, pDoRayMarchSRB, 2, iNumInst); } void LightSctrPostProcess :: InterpolateInsctrIrradiance(FrameAttribs &FrameAttribs) { if (!m_pInterpolateIrradiancePSO) { ShaderMacroHelper Macros; DefineMacros(Macros); Macros.Finalize(); auto pInterpolateIrradiancePS = CreateShader( FrameAttribs.pDevice, "InterpolateIrradiance.fx", "InterpolateIrradiancePS", SHADER_TYPE_PIXEL, Macros, SHADER_VARIABLE_TYPE_MUTABLE ); pInterpolateIrradiancePS->BindResources(m_pResMapping, BIND_SHADER_RESOURCES_VERIFY_ALL_RESOLVED); TEXTURE_FORMAT RTVFmts[] = {EpipolarInsctrTexFmt}; m_pInterpolateIrradiancePSO = CreateScreenSizeQuadPSO(FrameAttribs.pDevice, "InterpolateIrradiance", pInterpolateIrradiancePS, DSS_DisableDepth, BS_Default, 1, RTVFmts); m_pInterpolateIrradianceSRB.Release(); } if (!m_pInterpolateIrradianceSRB) { m_pInterpolateIrradiancePSO->CreateShaderResourceBinding(&m_pInterpolateIrradianceSRB, true); m_pInterpolateIrradianceSRB->BindResources(SHADER_TYPE_PIXEL, m_pResMapping, BIND_SHADER_RESOURCES_KEEP_EXISTING | BIND_SHADER_RESOURCES_VERIFY_ALL_RESOLVED); } ITextureView* ppRTVs[] = {m_ptex2DEpipolarInscatteringRTV}; FrameAttribs.pDeviceContext->SetRenderTargets(1, ppRTVs, nullptr, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); RenderScreenSizeQuad(FrameAttribs.pDeviceContext, m_pInterpolateIrradiancePSO, m_pInterpolateIrradianceSRB); } void LightSctrPostProcess :: UnwarpEpipolarScattering(FrameAttribs &FrameAttribs, bool bRenderLuminance) { if (!m_pUnwarpEpipolarSctrImgPSO) { ShaderMacroHelper Macros; DefineMacros(Macros); Macros.AddShaderMacro("PERFORM_TONE_MAPPING", true); Macros.AddShaderMacro("AUTO_EXPOSURE", m_PostProcessingAttribs.m_bAutoExposure); Macros.AddShaderMacro("TONE_MAPPING_MODE", m_PostProcessingAttribs.m_uiToneMappingMode); Macros.AddShaderMacro("CORRECT_INSCATTERING_AT_DEPTH_BREAKS", m_PostProcessingAttribs.m_bCorrectScatteringAtDepthBreaks); Macros.Finalize(); ShaderVariableDesc Vars[] = { {"cbParticipatingMediaScatteringParams", SHADER_VARIABLE_TYPE_STATIC}, {"cbLightParams", SHADER_VARIABLE_TYPE_STATIC}, {"cbCameraAttribs", SHADER_VARIABLE_TYPE_STATIC}, {"cbPostProcessingAttribs", SHADER_VARIABLE_TYPE_STATIC}, {"cbMiscDynamicParams", SHADER_VARIABLE_TYPE_STATIC}, {"g_tex2DColorBuffer", SHADER_VARIABLE_TYPE_DYNAMIC}, }; auto pUnwarpEpipolarSctrImgPS = CreateShader( FrameAttribs.pDevice, "UnwarpEpipolarScattering.fx", "ApplyInscatteredRadiancePS", SHADER_TYPE_PIXEL, Macros, SHADER_VARIABLE_TYPE_MUTABLE, Vars, _countof(Vars) ); pUnwarpEpipolarSctrImgPS->BindResources(m_pResMapping, 0); TEXTURE_FORMAT RTVFmts[] = {m_BackBufferFmt}; m_pUnwarpEpipolarSctrImgPSO = CreateScreenSizeQuadPSO(FrameAttribs.pDevice, "UnwarpEpipolarScattering", pUnwarpEpipolarSctrImgPS, DSS_Default, BS_Default, 1, RTVFmts, m_DepthBufferFmt); m_pUnwarpEpipolarSctrImgSRB.Release(); } if (!m_pUnwarpAndRenderLuminancePSO) { ShaderMacroHelper Macros; DefineMacros(Macros); Macros.AddShaderMacro("PERFORM_TONE_MAPPING", false); // No inscattering correction - we need to render the entire image in low resolution Macros.AddShaderMacro("CORRECT_INSCATTERING_AT_DEPTH_BREAKS", false); Macros.Finalize(); ShaderVariableDesc Vars[] = { {"cbParticipatingMediaScatteringParams", SHADER_VARIABLE_TYPE_STATIC}, {"cbLightParams", SHADER_VARIABLE_TYPE_STATIC}, {"cbCameraAttribs", SHADER_VARIABLE_TYPE_STATIC}, {"cbPostProcessingAttribs", SHADER_VARIABLE_TYPE_STATIC}, {"cbMiscDynamicParams", SHADER_VARIABLE_TYPE_STATIC}, {"g_tex2DColorBuffer", SHADER_VARIABLE_TYPE_DYNAMIC}, }; auto pUnwarpAndRenderLuminancePS = CreateShader( FrameAttribs.pDevice, "UnwarpEpipolarScattering.fx", "ApplyInscatteredRadiancePS", SHADER_TYPE_PIXEL, Macros, SHADER_VARIABLE_TYPE_MUTABLE, Vars, _countof(Vars) ); pUnwarpAndRenderLuminancePS->BindResources(m_pResMapping, 0); TEXTURE_FORMAT RTVFmts[] = {LuminanceTexFmt}; m_pUnwarpAndRenderLuminancePSO = CreateScreenSizeQuadPSO(FrameAttribs.pDevice, "UnwarpAndRenderLuminance", pUnwarpAndRenderLuminancePS, DSS_DisableDepth, BS_Default, 1, RTVFmts); m_pUnwarpAndRenderLuminanceSRB.Release(); } FrameAttribs.ptex2DSrcColorBufferSRV->SetSampler(m_pPointClampSampler); // Unwarp inscattering image and apply it to attenuated backgorund if(bRenderLuminance) { if (!m_pUnwarpAndRenderLuminanceSRB) { m_pUnwarpAndRenderLuminancePSO->CreateShaderResourceBinding(&m_pUnwarpAndRenderLuminanceSRB, true); m_pUnwarpAndRenderLuminanceSRB->BindResources(SHADER_TYPE_PIXEL, m_pResMapping, BIND_SHADER_RESOURCES_KEEP_EXISTING); } // Set dynamic variable g_tex2DColorBuffer m_pUnwarpAndRenderLuminanceSRB->GetVariable(SHADER_TYPE_PIXEL, "g_tex2DColorBuffer")->Set(FrameAttribs.ptex2DSrcColorBufferSRV); // Disable depth testing - we need to render the entire image in low resolution RenderScreenSizeQuad(FrameAttribs.pDeviceContext, m_pUnwarpAndRenderLuminancePSO, m_pUnwarpAndRenderLuminanceSRB); } else { if (!m_pUnwarpEpipolarSctrImgSRB) { m_pUnwarpEpipolarSctrImgPSO->CreateShaderResourceBinding(&m_pUnwarpEpipolarSctrImgSRB, true); m_pUnwarpEpipolarSctrImgSRB->BindResources(SHADER_TYPE_PIXEL, m_pResMapping, BIND_SHADER_RESOURCES_KEEP_EXISTING); } // Set dynamic variable g_tex2DColorBuffer m_pUnwarpEpipolarSctrImgSRB->GetVariable(SHADER_TYPE_PIXEL, "g_tex2DColorBuffer")->Set(FrameAttribs.ptex2DSrcColorBufferSRV); // Enable depth testing to write 0.0 to the depth buffer. All pixel that require // inscattering correction (if enabled) will be discarded, so that 1.0 will be retained // This 1.0 will then be used to perform inscattering correction RenderScreenSizeQuad(FrameAttribs.pDeviceContext, m_pUnwarpEpipolarSctrImgPSO, m_pUnwarpEpipolarSctrImgSRB); } } void LightSctrPostProcess :: UpdateAverageLuminance(FrameAttribs &FrameAttribs) { if (!m_pUpdateAverageLuminancePSO) { ShaderMacroHelper Macros; DefineMacros(Macros); Macros.AddShaderMacro( "LIGHT_ADAPTATION", m_PostProcessingAttribs.m_bLightAdaptation ); // static_cast<int>() is required because Run() gets its arguments by reference // and gcc will try to find reference to sm_iLowResLuminanceMips, which does not exist Macros.AddShaderMacro("LOW_RES_LUMINANCE_MIPS", static_cast<int>(sm_iLowResLuminanceMips) ); Macros.Finalize(); ShaderVariableDesc Vars[] = { {"cbMiscDynamicParams", SHADER_VARIABLE_TYPE_STATIC} }; auto pUpdateAverageLuminancePS = CreateShader( FrameAttribs.pDevice, "UpdateAverageLuminance.fx", "UpdateAverageLuminancePS", SHADER_TYPE_PIXEL, Macros, SHADER_VARIABLE_TYPE_MUTABLE, Vars, _countof(Vars) ); pUpdateAverageLuminancePS->BindResources(m_pResMapping, BIND_SHADER_RESOURCES_VERIFY_ALL_RESOLVED); TEXTURE_FORMAT RTVFmts[] = {LuminanceTexFmt}; m_pUpdateAverageLuminancePSO = CreateScreenSizeQuadPSO(FrameAttribs.pDevice, "UpdateAverageLuminance", pUpdateAverageLuminancePS, DSS_DisableDepth, BS_AlphaBlend, 1, RTVFmts); m_pUpdateAverageLuminanceSRB.Release(); } { MapHelper<MiscDynamicParams> pMiscDynamicParams( FrameAttribs.pDeviceContext, m_pcbMiscParams, MAP_WRITE, MAP_FLAG_DISCARD ); pMiscDynamicParams->fElapsedTime = (float)FrameAttribs.dElapsedTime; } if (!m_pUpdateAverageLuminanceSRB) { m_pUpdateAverageLuminancePSO->CreateShaderResourceBinding(&m_pUpdateAverageLuminanceSRB, true); m_pUpdateAverageLuminanceSRB->BindResources(SHADER_TYPE_PIXEL, m_pResMapping, BIND_SHADER_RESOURCES_KEEP_EXISTING | BIND_SHADER_RESOURCES_VERIFY_ALL_RESOLVED); } ITextureView* ppRTVs[] = {m_ptex2DAverageLuminanceRTV}; FrameAttribs.pDeviceContext->SetRenderTargets(1, ppRTVs, nullptr, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); RenderScreenSizeQuad(FrameAttribs.pDeviceContext, m_pUpdateAverageLuminancePSO, m_pUpdateAverageLuminanceSRB); } void LightSctrPostProcess :: FixInscatteringAtDepthBreaks(FrameAttribs &FrameAttribs, Uint32 uiMaxStepsAlongRay, EFixInscatteringMode Mode) { //bool bRenderLuminance = Mode == EFixInscatteringMode::LuminanceOnly; if (!m_pFixInsctrAtDepthBreaksPSO[0]) { RefCntAutoPtr<IShader> pFixInsctrAtDepthBreaksPS[2]; // 0 - perform tone mapping, 1 - render luminance only for( int RenderLum = 0; RenderLum < 2; ++RenderLum ) { ShaderMacroHelper Macros; DefineMacros(Macros); Macros.AddShaderMacro("CASCADE_PROCESSING_MODE", CASCADE_PROCESSING_MODE_SINGLE_PASS); Macros.AddShaderMacro("PERFORM_TONE_MAPPING", RenderLum == 0); Macros.AddShaderMacro("AUTO_EXPOSURE", m_PostProcessingAttribs.m_bAutoExposure); Macros.AddShaderMacro("TONE_MAPPING_MODE", m_PostProcessingAttribs.m_uiToneMappingMode); Macros.AddShaderMacro("USE_1D_MIN_MAX_TREE", false); Macros.Finalize(); ShaderVariableDesc Vars[] = { {"cbParticipatingMediaScatteringParams", SHADER_VARIABLE_TYPE_STATIC}, {"cbLightParams", SHADER_VARIABLE_TYPE_STATIC}, {"cbCameraAttribs", SHADER_VARIABLE_TYPE_STATIC}, {"cbPostProcessingAttribs", SHADER_VARIABLE_TYPE_STATIC}, {"cbMiscDynamicParams", SHADER_VARIABLE_TYPE_STATIC}, {"g_tex2DColorBuffer", SHADER_VARIABLE_TYPE_DYNAMIC} }; pFixInsctrAtDepthBreaksPS[RenderLum] = CreateShader( FrameAttribs.pDevice, "RayMarch.fx", "FixAndApplyInscatteredRadiancePS", SHADER_TYPE_PIXEL, Macros, SHADER_VARIABLE_TYPE_MUTABLE, Vars, _countof(Vars) ); pFixInsctrAtDepthBreaksPS[RenderLum]->BindResources(m_pResMapping, BIND_SHADER_RESOURCES_VERIFY_ALL_RESOLVED); } TEXTURE_FORMAT RTVFmts[] = {LuminanceTexFmt}; // Luminance Only // Disable depth and stencil tests to render all pixels // Use default blend state to overwrite old luminance values m_pFixInsctrAtDepthBreaksPSO[0] = CreateScreenSizeQuadPSO(FrameAttribs.pDevice, "FixInsctrAtDepthBreaksLumOnly", pFixInsctrAtDepthBreaksPS[1], DSS_DisableDepth, BS_Default, 1, RTVFmts); m_pFixInsctrAtDepthBreaksSRB[0].Release(); RTVFmts[0] = m_BackBufferFmt; // Fix Inscattering // Depth breaks are marked with 1.0 in depth, so we enable depth test // to render only pixels that require correction // Use default blend state - the rendering is always done in single pass m_pFixInsctrAtDepthBreaksPSO[1] = CreateScreenSizeQuadPSO(FrameAttribs.pDevice, "FixInsctrAtDepthBreaks", pFixInsctrAtDepthBreaksPS[0], DSS_Default, BS_Default, 1, RTVFmts, m_DepthBufferFmt); m_pFixInsctrAtDepthBreaksSRB[1].Release(); // Full Screen Ray Marching // Disable depth and stencil tests since we are performing // full screen ray marching // Use default blend state - the rendering is always done in single pass m_pFixInsctrAtDepthBreaksPSO[2] = CreateScreenSizeQuadPSO(FrameAttribs.pDevice, "FixInsctrAtDepthBreaks", pFixInsctrAtDepthBreaksPS[0], DSS_DisableDepth, BS_Default, 1, RTVFmts, m_DepthBufferFmt); m_pFixInsctrAtDepthBreaksSRB[2].Release(); } { MapHelper<MiscDynamicParams> pMiscDynamicParams( FrameAttribs.pDeviceContext, m_pcbMiscParams, MAP_WRITE, MAP_FLAG_DISCARD ); pMiscDynamicParams->fMaxStepsAlongRay = static_cast<float>(uiMaxStepsAlongRay); pMiscDynamicParams->fCascadeInd = static_cast<float>(m_PostProcessingAttribs.m_iFirstCascade); } auto& FixInscatteringAtDepthBreaksPSO = m_pFixInsctrAtDepthBreaksPSO[static_cast<int>(Mode)]; auto& FixInscatteringAtDepthBreaksSRB = m_pFixInsctrAtDepthBreaksSRB[static_cast<int>(Mode)]; if (!FixInscatteringAtDepthBreaksSRB) { FixInscatteringAtDepthBreaksPSO->CreateShaderResourceBinding(&FixInscatteringAtDepthBreaksSRB, true); FixInscatteringAtDepthBreaksSRB->BindResources(SHADER_TYPE_PIXEL, m_pResMapping, BIND_SHADER_RESOURCES_KEEP_EXISTING); } // Set dynamic variable g_tex2DColorBuffer FixInscatteringAtDepthBreaksSRB->GetVariable(SHADER_TYPE_PIXEL, "g_tex2DColorBuffer")->Set(FrameAttribs.ptex2DSrcColorBufferSRV); RenderScreenSizeQuad(FrameAttribs.pDeviceContext, FixInscatteringAtDepthBreaksPSO, FixInscatteringAtDepthBreaksSRB); } void LightSctrPostProcess :: RenderSampleLocations(FrameAttribs& FrameAttribs) { if (!m_pRenderSampleLocationsPSO) { ShaderMacroHelper Macros; DefineMacros(Macros); Macros.Finalize(); // Shaders use SCREEN_RESLOUTION macro auto pRenderSampleLocationsVS = CreateShader( FrameAttribs.pDevice, "RenderSampling.fx", "RenderSampleLocationsVS", SHADER_TYPE_VERTEX, Macros, SHADER_VARIABLE_TYPE_MUTABLE); auto pRenderSampleLocationsPS = CreateShader( FrameAttribs.pDevice, "RenderSampling.fx", "RenderSampleLocationsPS", SHADER_TYPE_PIXEL, Macros, SHADER_VARIABLE_TYPE_MUTABLE); pRenderSampleLocationsVS->BindResources(m_pResMapping, BIND_SHADER_RESOURCES_VERIFY_ALL_RESOLVED); pRenderSampleLocationsPS->BindResources(m_pResMapping, BIND_SHADER_RESOURCES_VERIFY_ALL_RESOLVED); PipelineStateDesc PSODesc; PSODesc.Name = "Render sample locations PSO"; auto& GraphicsPipeline = PSODesc.GraphicsPipeline; GraphicsPipeline.RasterizerDesc.FillMode = FILL_MODE_SOLID; GraphicsPipeline.RasterizerDesc.CullMode = CULL_MODE_NONE; GraphicsPipeline.RasterizerDesc.FrontCounterClockwise = true; GraphicsPipeline.DepthStencilDesc = DSS_DisableDepth; GraphicsPipeline.BlendDesc = BS_AlphaBlend; GraphicsPipeline.pVS = pRenderSampleLocationsVS; GraphicsPipeline.pPS = pRenderSampleLocationsPS; GraphicsPipeline.NumRenderTargets = 1; GraphicsPipeline.RTVFormats[0] = m_BackBufferFmt; GraphicsPipeline.DSVFormat = m_DepthBufferFmt; GraphicsPipeline.PrimitiveTopology = PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP; FrameAttribs.pDevice->CreatePipelineState(PSODesc, &m_pRenderSampleLocationsPSO); m_pRenderSampleLocationsSRB.Release(); } if (!m_pRenderSampleLocationsSRB) { m_pRenderSampleLocationsPSO->CreateShaderResourceBinding(&m_pRenderSampleLocationsSRB, true); m_pRenderSampleLocationsSRB->BindResources(SHADER_TYPE_VERTEX | SHADER_TYPE_PIXEL, m_pResMapping, BIND_SHADER_RESOURCES_VERIFY_ALL_RESOLVED); } DrawAttribs Attribs; Attribs.NumVertices = 4; Attribs.NumInstances = m_PostProcessingAttribs.m_uiMaxSamplesInSlice * m_PostProcessingAttribs.m_uiNumEpipolarSlices; FrameAttribs.pDeviceContext->SetPipelineState(m_pRenderSampleLocationsPSO); FrameAttribs.pDeviceContext->CommitShaderResources(m_pRenderSampleLocationsSRB, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); FrameAttribs.pDeviceContext->Draw(Attribs); } void LightSctrPostProcess :: ResetShaderResourceBindings() { m_pRenderSampleLocationsSRB.Release(); m_pRefineSampleLocationsSRB.Release(); m_pComputeMinMaxSMLevelSRB[0].Release(); m_pComputeMinMaxSMLevelSRB[1].Release(); m_pRenderCoarseUnshadowedInsctrSRB.Release(); m_pRenderSliceUVDirInSM_SRB.Release(); m_pInterpolateIrradianceSRB.Release(); m_pMarkRayMarchingSamplesInStencilSRB.Release(); m_pInitializeMinMaxShadowMapSRB.Release(); for (size_t i=0; i < _countof(m_pDoRayMarchSRB); ++i) m_pDoRayMarchSRB[i].Release(); m_pRendedCoordTexSRB.Release(); for (size_t i=0; i < _countof(m_pFixInsctrAtDepthBreaksSRB); ++i) m_pFixInsctrAtDepthBreaksSRB[i].Release(); m_pUnwarpAndRenderLuminanceSRB.Release(); m_pUnwarpEpipolarSctrImgSRB.Release(); m_pUpdateAverageLuminanceSRB.Release(); } void LightSctrPostProcess :: CreateExtinctionTexture(IRenderDevice* pDevice) { TextureDesc TexDesc; TexDesc.Name = "Epipolar Extinction", TexDesc.Type = RESOURCE_DIM_TEX_2D; TexDesc.Width = m_PostProcessingAttribs.m_uiMaxSamplesInSlice; TexDesc.Height = m_PostProcessingAttribs.m_uiNumEpipolarSlices; TexDesc.Format = EpipolarExtinctionFmt; TexDesc.MipLevels = 1; TexDesc.Usage = USAGE_DEFAULT; TexDesc.BindFlags = BIND_RENDER_TARGET | BIND_SHADER_RESOURCE; TexDesc.ClearValue.Format = TEX_FORMAT_UNKNOWN; TexDesc.ClearValue.Color[0] = 1; TexDesc.ClearValue.Color[1] = 1; TexDesc.ClearValue.Color[2] = 1; TexDesc.ClearValue.Color[3] = 1; // MaxSamplesInSlice x NumSlices RGBA8_UNORM texture to store extinction // for every epipolar sample RefCntAutoPtr<ITexture> tex2DEpipolarExtinction; pDevice->CreateTexture(TexDesc, nullptr, &tex2DEpipolarExtinction); auto* tex2DEpipolarExtinctionSRV = tex2DEpipolarExtinction->GetDefaultView(TEXTURE_VIEW_SHADER_RESOURCE); tex2DEpipolarExtinctionSRV->SetSampler(m_pLinearClampSampler); m_pResMapping->AddResource("g_tex2DEpipolarExtinction", tex2DEpipolarExtinctionSRV, false); m_ptex2DEpipolarExtinctionRTV = tex2DEpipolarExtinction->GetDefaultView(TEXTURE_VIEW_RENDER_TARGET); m_uiUpToDateResourceFlags |= UpToDateResourceFlags::ExtinctionTexture; ResetShaderResourceBindings(); } void LightSctrPostProcess :: CreateAmbientSkyLightTexture(IRenderDevice* pDevice) { TextureDesc TexDesc; TexDesc.Name = "Ambient Sky Light"; TexDesc.Type = RESOURCE_DIM_TEX_2D; TexDesc.Width = sm_iAmbientSkyLightTexDim; TexDesc.Height = 1; TexDesc.Format = AmbientSkyLightTexFmt; TexDesc.MipLevels = 1; TexDesc.Usage = USAGE_DEFAULT; TexDesc.BindFlags = BIND_RENDER_TARGET | BIND_SHADER_RESOURCE; RefCntAutoPtr<ITexture> tex2DAmbientSkyLight; pDevice->CreateTexture(TexDesc, nullptr, &tex2DAmbientSkyLight); m_ptex2DAmbientSkyLightSRV = tex2DAmbientSkyLight->GetDefaultView(TEXTURE_VIEW_SHADER_RESOURCE); m_ptex2DAmbientSkyLightRTV = tex2DAmbientSkyLight->GetDefaultView(TEXTURE_VIEW_RENDER_TARGET); m_ptex2DAmbientSkyLightSRV->SetSampler(m_pLinearClampSampler); } void LightSctrPostProcess :: PerformPostProcessing(FrameAttribs &FrameAttribs, PostProcessingAttribs &PPAttribs) { bool bUseCombinedMinMaxTexture = PPAttribs.m_uiCascadeProcessingMode == CASCADE_PROCESSING_MODE_SINGLE_PASS || PPAttribs.m_uiCascadeProcessingMode == CASCADE_PROCESSING_MODE_MULTI_PASS_INST || PPAttribs.m_bCorrectScatteringAtDepthBreaks || PPAttribs.m_uiLightSctrTechnique == LIGHT_SCTR_TECHNIQUE_BRUTE_FORCE; bool ResetSRBs = m_ptex2DShadowMapSRV != FrameAttribs.ptex2DShadowMapSRV; m_ptex2DShadowMapSRV = FrameAttribs.ptex2DShadowMapSRV; if (PPAttribs.m_uiNumEpipolarSlices != m_PostProcessingAttribs.m_uiNumEpipolarSlices || PPAttribs.m_uiMaxSamplesInSlice != m_PostProcessingAttribs.m_uiMaxSamplesInSlice || PPAttribs.m_bOptimizeSampleLocations != m_PostProcessingAttribs.m_bOptimizeSampleLocations) { m_pRendedSliceEndpointsPSO.Release(); } if (PPAttribs.m_uiMaxSamplesInSlice != m_PostProcessingAttribs.m_uiMaxSamplesInSlice) m_pRendedCoordTexPSO.Release(); if (PPAttribs.m_uiMaxSamplesInSlice != m_PostProcessingAttribs.m_uiMaxSamplesInSlice || PPAttribs.m_uiInitialSampleStepInSlice != m_PostProcessingAttribs.m_uiInitialSampleStepInSlice || PPAttribs.m_uiRefinementCriterion != m_PostProcessingAttribs.m_uiRefinementCriterion || PPAttribs.m_bAutoExposure != m_PostProcessingAttribs.m_bAutoExposure) m_pRefineSampleLocationsCS.Release(); if (PPAttribs.m_bUse1DMinMaxTree != m_PostProcessingAttribs.m_bUse1DMinMaxTree || bUseCombinedMinMaxTexture != m_bUseCombinedMinMaxTexture || PPAttribs.m_uiNumEpipolarSlices != m_PostProcessingAttribs.m_uiNumEpipolarSlices || PPAttribs.m_bIs32BitMinMaxMipMap != m_PostProcessingAttribs.m_bIs32BitMinMaxMipMap ) { m_pInitializeMinMaxShadowMapPSO.Release(); m_pComputeMinMaxSMLevelPSO.Release(); } if (PPAttribs.m_bUse1DMinMaxTree != m_PostProcessingAttribs.m_bUse1DMinMaxTree || PPAttribs.m_uiCascadeProcessingMode != m_PostProcessingAttribs.m_uiCascadeProcessingMode || bUseCombinedMinMaxTexture != m_bUseCombinedMinMaxTexture || PPAttribs.m_bEnableLightShafts != m_PostProcessingAttribs.m_bEnableLightShafts || PPAttribs.m_uiMultipleScatteringMode != m_PostProcessingAttribs.m_uiMultipleScatteringMode || PPAttribs.m_uiSingleScatteringMode != m_PostProcessingAttribs.m_uiSingleScatteringMode) { for(int i=0; i<_countof(m_pDoRayMarchPSO); ++i) m_pDoRayMarchPSO[i].Release(); } if (PPAttribs.m_uiNumEpipolarSlices != m_PostProcessingAttribs.m_uiNumEpipolarSlices || PPAttribs.m_uiMaxSamplesInSlice != m_PostProcessingAttribs.m_uiMaxSamplesInSlice) { m_pUnwarpEpipolarSctrImgPSO.Release(); m_pUnwarpAndRenderLuminancePSO.Release(); } if (PPAttribs.m_bAutoExposure != m_PostProcessingAttribs.m_bAutoExposure || PPAttribs.m_uiToneMappingMode != m_PostProcessingAttribs.m_uiToneMappingMode || PPAttribs.m_bCorrectScatteringAtDepthBreaks != m_PostProcessingAttribs.m_bCorrectScatteringAtDepthBreaks) { m_pUnwarpEpipolarSctrImgPSO.Release(); } if (PPAttribs.m_bLightAdaptation != m_PostProcessingAttribs.m_bLightAdaptation) { m_pUpdateAverageLuminancePSO.Release(); } if( PPAttribs.m_uiCascadeProcessingMode != m_PostProcessingAttribs.m_uiCascadeProcessingMode || bUseCombinedMinMaxTexture != m_bUseCombinedMinMaxTexture || PPAttribs.m_bEnableLightShafts != m_PostProcessingAttribs.m_bEnableLightShafts || PPAttribs.m_uiMultipleScatteringMode != m_PostProcessingAttribs.m_uiMultipleScatteringMode || PPAttribs.m_uiSingleScatteringMode != m_PostProcessingAttribs.m_uiSingleScatteringMode || PPAttribs.m_bAutoExposure != m_PostProcessingAttribs.m_bAutoExposure || PPAttribs.m_uiToneMappingMode != m_PostProcessingAttribs.m_uiToneMappingMode) { for (size_t i=0; i<_countof(m_pFixInsctrAtDepthBreaksPSO); ++i) m_pFixInsctrAtDepthBreaksPSO[i].Release(); } if (PPAttribs.m_uiMaxSamplesInSlice != m_PostProcessingAttribs.m_uiMaxSamplesInSlice || PPAttribs.m_uiNumEpipolarSlices != m_PostProcessingAttribs.m_uiNumEpipolarSlices) { m_uiUpToDateResourceFlags &= ~UpToDateResourceFlags::AuxTextures; m_uiUpToDateResourceFlags &= ~UpToDateResourceFlags::ExtinctionTexture; m_uiUpToDateResourceFlags &= ~UpToDateResourceFlags::SliceUVDirAndOriginTex; m_pRenderSampleLocationsSRB.Release(); } if (PPAttribs.m_uiMinMaxShadowMapResolution != m_PostProcessingAttribs.m_uiMinMaxShadowMapResolution || PPAttribs.m_uiNumEpipolarSlices != m_PostProcessingAttribs.m_uiNumEpipolarSlices || PPAttribs.m_bUse1DMinMaxTree != m_PostProcessingAttribs.m_bUse1DMinMaxTree || PPAttribs.m_bIs32BitMinMaxMipMap != m_PostProcessingAttribs.m_bIs32BitMinMaxMipMap || bUseCombinedMinMaxTexture != m_bUseCombinedMinMaxTexture || (bUseCombinedMinMaxTexture && (PPAttribs.m_iFirstCascade != m_PostProcessingAttribs.m_iFirstCascade || PPAttribs.m_iNumCascades != m_PostProcessingAttribs.m_iNumCascades))) { for(int i=0; i < _countof(m_ptex2DMinMaxShadowMapSRV); ++i) m_ptex2DMinMaxShadowMapSRV[i].Release(); for(int i=0; i < _countof(m_ptex2DMinMaxShadowMapRTV); ++i) m_ptex2DMinMaxShadowMapRTV[i].Release(); m_pComputeMinMaxSMLevelSRB[0].Release(); m_pComputeMinMaxSMLevelSRB[1].Release(); ResetSRBs = true; } if (PPAttribs.m_iNumCascades != m_PostProcessingAttribs.m_iNumCascades) { m_uiUpToDateResourceFlags &= ~UpToDateResourceFlags::SliceUVDirAndOriginTex; } if (PPAttribs.m_uiCascadeProcessingMode != m_PostProcessingAttribs.m_uiCascadeProcessingMode) { m_pComputeMinMaxSMLevelPSO.Release(); } if (PPAttribs.m_uiExtinctionEvalMode != m_PostProcessingAttribs.m_uiExtinctionEvalMode) { m_ptex2DEpipolarExtinctionRTV.Release(); m_uiUpToDateResourceFlags &= ~UpToDateResourceFlags::ExtinctionTexture; m_pUnwarpEpipolarSctrImgPSO.Release(); m_pUnwarpAndRenderLuminancePSO.Release(); m_pRenderCoarseUnshadowedInsctrPSO.Release(); } if (PPAttribs.m_uiSingleScatteringMode != m_PostProcessingAttribs.m_uiSingleScatteringMode || PPAttribs.m_uiMultipleScatteringMode != m_PostProcessingAttribs.m_uiMultipleScatteringMode) m_pRenderCoarseUnshadowedInsctrPSO.Release(); bool bRecomputeSctrCoeffs = m_PostProcessingAttribs.m_bUseCustomSctrCoeffs != PPAttribs.m_bUseCustomSctrCoeffs || m_PostProcessingAttribs.m_fAerosolDensityScale != PPAttribs.m_fAerosolDensityScale || m_PostProcessingAttribs.m_fAerosolAbsorbtionScale != PPAttribs.m_fAerosolAbsorbtionScale || (PPAttribs.m_bUseCustomSctrCoeffs && (m_PostProcessingAttribs.m_f4CustomRlghBeta != PPAttribs.m_f4CustomRlghBeta || m_PostProcessingAttribs.m_f4CustomMieBeta != PPAttribs.m_f4CustomMieBeta) ); m_PostProcessingAttribs = PPAttribs; m_bUseCombinedMinMaxTexture = bUseCombinedMinMaxTexture; if (bRecomputeSctrCoeffs) { m_uiUpToDateResourceFlags &= ~UpToDateResourceFlags::PrecomputedOpticalDepthTex; m_uiUpToDateResourceFlags &= ~UpToDateResourceFlags::AmbientSkyLightTex; m_uiUpToDateResourceFlags &= ~UpToDateResourceFlags::PrecomputedIntegralsTex; ResetSRBs = true; ComputeScatteringCoefficients(FrameAttribs.pDeviceContext); } if (!(m_uiUpToDateResourceFlags & UpToDateResourceFlags::AuxTextures)) { CreateAuxTextures(FrameAttribs.pDevice); // Make sure extinction texture is re-created when first needed m_uiUpToDateResourceFlags &= ~UpToDateResourceFlags::ExtinctionTexture; m_ptex2DEpipolarExtinctionRTV.Release(); // Make sure slice UV and origin texture is re-created when first needed m_uiUpToDateResourceFlags &= ~UpToDateResourceFlags::SliceUVDirAndOriginTex; } if (!m_ptex2DMinMaxShadowMapSRV[0] && m_PostProcessingAttribs.m_bUse1DMinMaxTree) { CreateMinMaxShadowMap(FrameAttribs.pDevice); } #if 0 LightAttribs &LightAttribs = *FrameAttribs.pLightAttribs; const CameraAttribs &CamAttribs = FrameAttribs.CameraAttribs; // Note that in fact the outermost visible screen pixels do not lie exactly on the boundary (+1 or -1), but are biased by // 0.5 screen pixel size inwards. Using these adjusted boundaries improves precision and results in // smaller number of pixels which require inscattering correction assert( LightAttribs.bIsLightOnScreen == (fabs(FrameAttribs.pLightAttribs->f4LightScreenPos.x) <= 1.f - 1.f/(float)m_uiBackBufferWidth && fabs(FrameAttribs.pLightAttribs->f4LightScreenPos.y) <= 1.f - 1.f/(float)m_uiBackBufferHeight) ); const auto &SMAttribs = FrameAttribs.pLightAttribs->ShadowAttribs; UpdateConstantBuffer(FrameAttribs.pDeviceContext, m_pcbCameraAttribs, &CamAttribs, sizeof(CamAttribs)); //UpdateConstantBuffer(FrameAttribs.pDeviceContext, m_pcbLightAttribs, &LightAttribs, sizeof(LightAttribs)); #endif { MapHelper<PostProcessingAttribs> pPPAttribsBuffData( FrameAttribs.pDeviceContext, m_pcbPostProcessingAttribs, MAP_WRITE, MAP_FLAG_DISCARD ); memcpy(pPPAttribsBuffData, &m_PostProcessingAttribs, sizeof(m_PostProcessingAttribs)); } if (!(m_uiUpToDateResourceFlags & UpToDateResourceFlags::PrecomputedOpticalDepthTex)) { CreatePrecomputedOpticalDepthTexture(FrameAttribs.pDevice, FrameAttribs.pDeviceContext); } if ((m_PostProcessingAttribs.m_uiMultipleScatteringMode > MULTIPLE_SCTR_MODE_NONE || PPAttribs.m_uiSingleScatteringMode == SINGLE_SCTR_MODE_LUT) && !(m_uiUpToDateResourceFlags & UpToDateResourceFlags::PrecomputedIntegralsTex) ) { CreatePrecomputedScatteringLUT(FrameAttribs.pDevice, FrameAttribs.pDeviceContext); // We need to reset shader resource bindings, as some resources may have been recreated ResetSRBs = true; } if (ResetSRBs) { ResetShaderResourceBindings(); } if (/*m_PostProcessingAttribs.m_bAutoExposure &&*/ !(m_uiUpToDateResourceFlags & UpToDateResourceFlags::LowResLuminamceTex)) { CreateLowResLuminanceTexture(FrameAttribs.pDevice, FrameAttribs.pDeviceContext); } //m_pResMapping->AddResource("g_tex2DDepthBuffer", FrameAttribs.ptex2DSrcDepthBufferSRV, false); //m_pResMapping->AddResource("g_tex2DColorBuffer", FrameAttribs.ptex2DSrcColorBufferSRV, false); m_pResMapping->AddResource("g_tex2DLightSpaceDepthMap", FrameAttribs.ptex2DShadowMapSRV, false); m_pResMapping->AddResource("cbCameraAttribs", FrameAttribs.pcbCameraAttribs, false); m_pResMapping->AddResource("cbLightParams", FrameAttribs.pcbLightAttribs, false); { ITextureView *pRTVs[] = { FrameAttribs.ptex2DSrcColorBufferRTV }; FrameAttribs.pDeviceContext->SetRenderTargets(_countof(pRTVs), pRTVs, FrameAttribs.ptex2DSrcDepthBufferDSV, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); RenderSun(FrameAttribs); } ReconstructCameraSpaceZ(FrameAttribs); if (m_PostProcessingAttribs.m_uiLightSctrTechnique == LIGHT_SCTR_TECHNIQUE_EPIPOLAR_SAMPLING) { RenderSliceEndpoints(FrameAttribs); // Render coordinate texture and camera space z for epipolar location RenderCoordinateTexture(FrameAttribs); if (m_PostProcessingAttribs.m_uiRefinementCriterion == REFINEMENT_CRITERION_INSCTR_DIFF || m_PostProcessingAttribs.m_uiExtinctionEvalMode == EXTINCTION_EVAL_MODE_EPIPOLAR) { RenderCoarseUnshadowedInctr(FrameAttribs); } // Refine initial ray marching samples RefineSampleLocations(FrameAttribs); // Mark all ray marching samples in stencil MarkRayMarchingSamples( FrameAttribs ); if( m_PostProcessingAttribs.m_bEnableLightShafts && m_PostProcessingAttribs.m_bUse1DMinMaxTree ) { RenderSliceUVDirAndOrig(FrameAttribs); } ITextureView* ppRTVs[] = {m_ptex2DInitialScatteredLightRTV}; FrameAttribs.pDeviceContext->SetRenderTargets(1, ppRTVs, nullptr, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); const float Zero[] = {0,0,0,0}; FrameAttribs.pDeviceContext->ClearRenderTarget(m_ptex2DInitialScatteredLightRTV, Zero, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); int iLastCascade = (m_PostProcessingAttribs.m_bEnableLightShafts && m_PostProcessingAttribs.m_uiCascadeProcessingMode == CASCADE_PROCESSING_MODE_MULTI_PASS) ? m_PostProcessingAttribs.m_iNumCascades - 1 : m_PostProcessingAttribs.m_iFirstCascade; for(int iCascadeInd = m_PostProcessingAttribs.m_iFirstCascade; iCascadeInd <= iLastCascade; ++iCascadeInd) { // Build min/max mip map if( m_PostProcessingAttribs.m_bEnableLightShafts && m_PostProcessingAttribs.m_bUse1DMinMaxTree ) { Build1DMinMaxMipMap(FrameAttribs, iCascadeInd); } // Perform ray marching for selected samples DoRayMarching(FrameAttribs, m_PostProcessingAttribs.m_uiShadowMapResolution, iCascadeInd); } // Interpolate ray marching samples onto the rest of samples InterpolateInsctrIrradiance(FrameAttribs); const Uint32 uiMaxStepsAlongRayAtDepthBreak0 = std::min(m_PostProcessingAttribs.m_uiShadowMapResolution/4, 256u); //const Uint32 uiMaxStepsAlongRayAtDepthBreak1 = std::min(m_PostProcessingAttribs.m_uiShadowMapResolution/8, 128u); if (m_PostProcessingAttribs.m_bAutoExposure) { // Render scene luminance to low-resolution texture ITextureView *pRTVs[] = { m_ptex2DLowResLuminanceRTV }; FrameAttribs.pDeviceContext->SetRenderTargets(_countof(pRTVs), pRTVs, nullptr, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); UnwarpEpipolarScattering(FrameAttribs, true); FrameAttribs.pDeviceContext->GenerateMips(m_ptex2DLowResLuminanceSRV); UpdateAverageLuminance(FrameAttribs); } // Set the main back & depth buffers FrameAttribs.pDeviceContext->SetRenderTargets( 0, nullptr, nullptr, RESOURCE_STATE_TRANSITION_MODE_TRANSITION ); // Clear depth to 1.0. FrameAttribs.pDeviceContext->ClearDepthStencil( nullptr, CLEAR_DEPTH_FLAG, 1.f, 0, RESOURCE_STATE_TRANSITION_MODE_TRANSITION ); // Transform inscattering irradiance from epipolar coordinates back to rectangular // The shader will write 0.0 to the depth buffer, but all pixel that require inscattering // correction will be discarded and will keep 1.0 UnwarpEpipolarScattering(FrameAttribs, false); // Correct inscattering for pixels, for which no suitable interpolation sources were found if (m_PostProcessingAttribs.m_bCorrectScatteringAtDepthBreaks) { FixInscatteringAtDepthBreaks(FrameAttribs, uiMaxStepsAlongRayAtDepthBreak0, EFixInscatteringMode::FixInscattering); } if (m_PostProcessingAttribs.m_bShowSampling) { RenderSampleLocations(FrameAttribs); } } else if (m_PostProcessingAttribs.m_uiLightSctrTechnique == LIGHT_SCTR_TECHNIQUE_BRUTE_FORCE) { if (m_PostProcessingAttribs.m_bAutoExposure) { // Render scene luminance to low-resolution texture ITextureView *pRTVs[] = { m_ptex2DLowResLuminanceRTV }; FrameAttribs.pDeviceContext->SetRenderTargets(_countof(pRTVs), pRTVs, nullptr, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); FixInscatteringAtDepthBreaks(FrameAttribs, m_PostProcessingAttribs.m_uiShadowMapResolution, EFixInscatteringMode::LuminanceOnly); FrameAttribs.pDeviceContext->GenerateMips(m_ptex2DLowResLuminanceSRV); UpdateAverageLuminance(FrameAttribs); } // Set the main back & depth buffers FrameAttribs.pDeviceContext->SetRenderTargets(0, nullptr, nullptr, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); FixInscatteringAtDepthBreaks(FrameAttribs, m_PostProcessingAttribs.m_uiShadowMapResolution, EFixInscatteringMode::FullScreenRayMarching); } FrameAttribs.pDeviceContext->SetRenderTargets(0, nullptr, nullptr, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); } void LightSctrPostProcess :: CreateMinMaxShadowMap(IRenderDevice* pDevice) { TextureDesc MinMaxShadowMapTexDesc; MinMaxShadowMapTexDesc.Type = RESOURCE_DIM_TEX_2D; MinMaxShadowMapTexDesc.Width = m_PostProcessingAttribs.m_uiMinMaxShadowMapResolution; MinMaxShadowMapTexDesc.Height = m_PostProcessingAttribs.m_uiNumEpipolarSlices; MinMaxShadowMapTexDesc.MipLevels = 1; MinMaxShadowMapTexDesc.Format = m_PostProcessingAttribs.m_bIs32BitMinMaxMipMap ? TEX_FORMAT_RG32_FLOAT : TEX_FORMAT_RG16_UNORM; MinMaxShadowMapTexDesc.BindFlags = BIND_SHADER_RESOURCE | BIND_RENDER_TARGET; if (m_bUseCombinedMinMaxTexture) { MinMaxShadowMapTexDesc.Height *= (m_PostProcessingAttribs.m_iNumCascades - m_PostProcessingAttribs.m_iFirstCascade); } for(int i=0; i < 2; ++i) { std::string name = "MinMaxShadowMap"; name.push_back('0'+char(i)); MinMaxShadowMapTexDesc.Name = name.c_str(); m_ptex2DMinMaxShadowMapSRV[i].Release(); m_ptex2DMinMaxShadowMapRTV[i].Release(); RefCntAutoPtr<ITexture> ptex2DMinMaxShadowMap; // Create 2-D texture, shader resource and target view buffers on the device pDevice->CreateTexture( MinMaxShadowMapTexDesc, nullptr, &ptex2DMinMaxShadowMap); m_ptex2DMinMaxShadowMapSRV[i] = ptex2DMinMaxShadowMap->GetDefaultView( TEXTURE_VIEW_SHADER_RESOURCE ); m_ptex2DMinMaxShadowMapSRV[i]->SetSampler(m_pLinearClampSampler); m_ptex2DMinMaxShadowMapRTV[i] = ptex2DMinMaxShadowMap->GetDefaultView( TEXTURE_VIEW_RENDER_TARGET ); m_pResMapping->AddResource( "g_tex2DMinMaxLightSpaceDepth", m_ptex2DMinMaxShadowMapSRV[0], false ); } } float2 exp(const float2 &fX){ return float2(exp(fX.x), exp(fX.y)); } float3 exp(const float3 &fX){ return float3(exp(fX.x), exp(fX.y), exp(fX.z)); } // fCosChi = Pi/2 float2 ChapmanOrtho(const float2 &f2x) { static const float fConst = static_cast<float>( sqrt(M_PI / 2) ); float2 f2SqrtX = float2( sqrt(f2x.x), sqrt(f2x.y) ); return fConst * ( float2(1.f,1.f) / (2.f * f2SqrtX) + f2SqrtX ); } // |fCosChi| < Pi/2 float2 f2ChapmanRising(const float2 &f2X, float fCosChi) { float2 f2ChOrtho = ChapmanOrtho(f2X); return f2ChOrtho / ((f2ChOrtho-float2(1,1))*fCosChi + float2(1,1)); } float2 GetDensityIntegralFromChapmanFunc(float fHeightAboveSurface, const float3 &f3EarthCentreToPointDir, const float3 &f3RayDir, const AirScatteringAttribs &SctrMediaAttribs) { // Note: there is no intersection test with the Earth. However, // optical depth through the Earth is large, which effectively // occludes the light float fCosChi = dot(f3EarthCentreToPointDir, f3RayDir); float2 f2x = (fHeightAboveSurface + SctrMediaAttribs.fEarthRadius) * float2(1.f / SctrMediaAttribs.f2ParticleScaleHeight.x, 1.f / SctrMediaAttribs.f2ParticleScaleHeight.y); float2 f2VerticalAirMass = SctrMediaAttribs.f2ParticleScaleHeight * exp(-float2(fHeightAboveSurface,fHeightAboveSurface)/SctrMediaAttribs.f2ParticleScaleHeight); if( fCosChi >= 0.f ) { return f2VerticalAirMass * f2ChapmanRising(f2x, fCosChi); } else { float fSinChi = sqrt(1.f - fCosChi*fCosChi); float fh0 = (fHeightAboveSurface + SctrMediaAttribs.fEarthRadius) * fSinChi - SctrMediaAttribs.fEarthRadius; float2 f2VerticalAirMass0 = SctrMediaAttribs.f2ParticleScaleHeight * exp(-float2(fh0,fh0)/SctrMediaAttribs.f2ParticleScaleHeight); float2 f2x0 = float2(fh0 + SctrMediaAttribs.fEarthRadius,fh0 + SctrMediaAttribs.fEarthRadius)/SctrMediaAttribs.f2ParticleScaleHeight; float2 f2ChOrtho_x0 = ChapmanOrtho(f2x0); float2 f2Ch = f2ChapmanRising(f2x, -fCosChi); return f2VerticalAirMass0 * (2.f * f2ChOrtho_x0) - f2VerticalAirMass*f2Ch; } } void LightSctrPostProcess :: ComputeSunColor( const float3 &vDirectionOnSun, const float4 &f4ExtraterrestrialSunColor, float4 &f4SunColorAtGround, float4 &f4AmbientLight) { // Compute the ambient light values float zenithFactor = std::min( std::max(vDirectionOnSun.y, 0.0f), 1.0f); f4AmbientLight.x = zenithFactor*0.15f; f4AmbientLight.y = zenithFactor*0.1f; f4AmbientLight.z = std::max(0.005f, zenithFactor*0.25f); f4AmbientLight.w = 0.0f; float2 f2NetParticleDensityToAtmTop = GetDensityIntegralFromChapmanFunc(0, float3(0,1,0), vDirectionOnSun, m_MediaParams); float3 f3RlghExtCoeff = std::max( (float3&)m_MediaParams.f4RayleighExtinctionCoeff, float3(1e-8f,1e-8f,1e-8f) ); float3 f3RlghOpticalDepth = f3RlghExtCoeff * f2NetParticleDensityToAtmTop.x; float3 f3MieExtCoeff = std::max( (float3&)m_MediaParams.f4MieExtinctionCoeff, float3(1e-8f,1e-8f,1e-8f) ); float3 f3MieOpticalDepth = f3MieExtCoeff * f2NetParticleDensityToAtmTop.y; float3 f3TotalExtinction = exp( -(f3RlghOpticalDepth + f3MieOpticalDepth ) ); const float fEarthReflectance = 0.1f;// See [BN08] (float3&)f4SunColorAtGround = ((float3&)f4ExtraterrestrialSunColor) * f3TotalExtinction * fEarthReflectance; } void LightSctrPostProcess :: ComputeScatteringCoefficients(IDeviceContext* pDeviceCtx) { // For details, see "A practical Analytic Model for Daylight" by Preetham & Hoffman, p.23 // Wave lengths // [BN08] follows [REK04] and gives the following values for Rayleigh scattering coefficients: // RayleighBetha(lambda = (680nm, 550nm, 440nm) ) = (5.8, 13.5, 33.1)e-6 static const double dWaveLengths[] = { 680e-9, // red 550e-9, // green 440e-9 // blue }; // Calculate angular and total scattering coefficients for Rayleigh scattering: { float4& f4AngularRayleighSctrCoeff = m_MediaParams.f4AngularRayleighSctrCoeff; float4& f4TotalRayleighSctrCoeff = m_MediaParams.f4TotalRayleighSctrCoeff; float4& f4RayleighExtinctionCoeff = m_MediaParams.f4RayleighExtinctionCoeff; constexpr double n = 1.0003; // - Refractive index of air in the visible spectrum constexpr double N = 2.545e+25; // - Number of molecules per unit volume constexpr double Pn = 0.035; // - Depolarization factor for air which exoresses corrections // due to anisotropy of air molecules constexpr double dRayleighConst = 8.0*M_PI*M_PI*M_PI * (n*n - 1.0) * (n*n - 1.0) / (3.0 * N) * (6.0 + 3.0*Pn) / (6.0 - 7.0*Pn); for (int WaveNum = 0; WaveNum < 3; WaveNum++) { double dSctrCoeff; if (m_PostProcessingAttribs.m_bUseCustomSctrCoeffs) dSctrCoeff = f4TotalRayleighSctrCoeff[WaveNum] = m_PostProcessingAttribs.m_f4CustomRlghBeta[WaveNum]; else { double Lambda2 = dWaveLengths[WaveNum] * dWaveLengths[WaveNum]; double Lambda4 = Lambda2 * Lambda2; dSctrCoeff = dRayleighConst / Lambda4; // Total Rayleigh scattering coefficient is the integral of angular scattering coefficient in all directions f4TotalRayleighSctrCoeff[WaveNum] = static_cast<float>( dSctrCoeff ); } // Angular scattering coefficient is essentially volumetric scattering coefficient multiplied by the // normalized phase function // p(Theta) = 3/(16*Pi) * (1 + cos^2(Theta)) // f4AngularRayleighSctrCoeff contains all the terms exepting 1 + cos^2(Theta): f4AngularRayleighSctrCoeff[WaveNum] = static_cast<float>( 3.0 / (16.0*M_PI) * dSctrCoeff ); // f4AngularRayleighSctrCoeff[WaveNum] = f4TotalRayleighSctrCoeff[WaveNum] * p(Theta) } // Air molecules do not absorb light, so extinction coefficient is only caused by out-scattering f4RayleighExtinctionCoeff = f4TotalRayleighSctrCoeff; } // Calculate angular and total scattering coefficients for Mie scattering: { float4& f4AngularMieSctrCoeff = m_MediaParams.f4AngularMieSctrCoeff; float4& f4TotalMieSctrCoeff = m_MediaParams.f4TotalMieSctrCoeff; float4& f4MieExtinctionCoeff = m_MediaParams.f4MieExtinctionCoeff; if (m_PostProcessingAttribs.m_bUseCustomSctrCoeffs) { f4TotalMieSctrCoeff = m_PostProcessingAttribs.m_f4CustomMieBeta * m_PostProcessingAttribs.m_fAerosolDensityScale; } else { const bool bUsePreethamMethod = false; if (bUsePreethamMethod) { // Values for K came from the table 2 in the "A practical Analytic Model // for Daylight" by Preetham & Hoffman, p.28 constexpr double K[] = { 0.68455, // K[650nm] 0.678781, // K[570nm] (0.668532+0.669765)/2.0 // (K[470nm]+K[480nm])/2 }; assert( m_MediaParams.fTurbidity >= 1.f ); // Beta is an Angstrom's turbidity coefficient and is approximated by: //float beta = 0.04608365822050f * m_fTurbidity - 0.04586025928522f; ??????? const double c = (0.6544*m_MediaParams.fTurbidity - 0.6510)*1E-16; // concentration factor constexpr double v = 4; // Junge's exponent const double dTotalMieBetaTerm = 0.434 * c * M_PI * pow(2.0*M_PI, v-2); for (int WaveNum = 0; WaveNum < 3; WaveNum++) { double Lambdav_minus_2 = pow( dWaveLengths[WaveNum], v-2); double dTotalMieSctrCoeff = dTotalMieBetaTerm * K[WaveNum] / Lambdav_minus_2; f4TotalMieSctrCoeff[WaveNum] = static_cast<float>( dTotalMieSctrCoeff ); } //AtmScatteringAttribs.f4AngularMieSctrCoeff *= 0.02f; //AtmScatteringAttribs.f4TotalMieSctrCoeff *= 0.02f; } else { // [BN08] uses the following value (independent of wavelength) for Mie scattering coefficient: 2e-5 // For g=0.76 and MieBetha=2e-5 [BN08] was able to reproduce the same luminance as given by the // reference CIE sky light model const float fMieBethaBN08 = 2e-5f * m_PostProcessingAttribs.m_fAerosolDensityScale; m_MediaParams.f4TotalMieSctrCoeff = float4(fMieBethaBN08, fMieBethaBN08, fMieBethaBN08, 0); } } for (int WaveNum = 0; WaveNum < 3; WaveNum++) { // Normalized to unity Cornette-Shanks phase function has the following form: // F(theta) = 1/(4*PI) * 3*(1-g^2) / (2*(2+g^2)) * (1+cos^2(theta)) / (1 + g^2 - 2g*cos(theta))^(3/2) // The angular scattering coefficient is the volumetric scattering coefficient multiplied by the phase // function. 1/(4*PI) is baked into the f4AngularMieSctrCoeff, the other terms are baked into f4CS_g f4AngularMieSctrCoeff[WaveNum] = f4TotalMieSctrCoeff[WaveNum] / static_cast<float>(4.0 * M_PI); // [BN08] also uses slight absorption factor which is 10% of scattering f4MieExtinctionCoeff[WaveNum] = f4TotalMieSctrCoeff[WaveNum] * (1.f + m_PostProcessingAttribs.m_fAerosolAbsorbtionScale); } } { // For g=0.76 and MieBetha=2e-5 [BN08] was able to reproduce the same luminance as is given by the // reference CIE sky light model // Cornette phase function (see Nishita et al. 93): // F(theta) = 1/(4*PI) * 3*(1-g^2) / (2*(2+g^2)) * (1+cos^2(theta)) / (1 + g^2 - 2g*cos(theta))^(3/2) // 1/(4*PI) is baked into the f4AngularMieSctrCoeff float4 &f4CS_g = m_MediaParams.f4CS_g; float f_g = m_MediaParams.m_fAerosolPhaseFuncG; f4CS_g.x = 3*(1.f - f_g*f_g) / ( 2*(2.f + f_g*f_g) ); f4CS_g.y = 1.f + f_g*f_g; f4CS_g.z = -2.f*f_g; f4CS_g.w = 1.f; } m_MediaParams.f4TotalExtinctionCoeff = m_MediaParams.f4RayleighExtinctionCoeff + m_MediaParams.f4MieExtinctionCoeff; if (pDeviceCtx && m_pcbMediaAttribs) { pDeviceCtx->UpdateBuffer(m_pcbMediaAttribs, 0, sizeof( m_MediaParams ), &m_MediaParams, RESOURCE_STATE_TRANSITION_MODE_TRANSITION ); } } void LightSctrPostProcess :: RenderSun(FrameAttribs& FrameAttribs) { if( FrameAttribs.pLightAttribs->f4LightScreenPos.w <= 0 ) return; if (!m_pRenderSunSRB) { m_pRenderSunPSO->CreateShaderResourceBinding(&m_pRenderSunSRB, true); m_pRenderSunSRB->BindResources(SHADER_TYPE_PIXEL | SHADER_TYPE_VERTEX, m_pResMapping, BIND_SHADER_RESOURCES_VERIFY_ALL_RESOLVED); } RenderScreenSizeQuad(FrameAttribs.pDeviceContext, m_pRenderSunPSO, m_pRenderSunSRB); } void LightSctrPostProcess :: ComputeAmbientSkyLightTexture(IRenderDevice* pDevice, IDeviceContext* pContext) { if( !(m_uiUpToDateResourceFlags & UpToDateResourceFlags::PrecomputedOpticalDepthTex) ) { CreatePrecomputedOpticalDepthTexture(pDevice, pContext); } if( !(m_uiUpToDateResourceFlags & UpToDateResourceFlags::PrecomputedIntegralsTex) ) { CreatePrecomputedScatteringLUT(pDevice, pContext); } if( !m_pPrecomputeAmbientSkyLightPSO ) { ShaderMacroHelper Macros; Macros.AddShaderMacro( "NUM_RANDOM_SPHERE_SAMPLES", m_uiNumRandomSamplesOnSphere ); Macros.Finalize(); auto pPrecomputeAmbientSkyLightPS = CreateShader( pDevice, "PrecomputeAmbientSkyLight.fx", "PrecomputeAmbientSkyLightPS", SHADER_TYPE_PIXEL, Macros, SHADER_VARIABLE_TYPE_STATIC ); pPrecomputeAmbientSkyLightPS->BindResources( m_pResMapping, BIND_SHADER_RESOURCES_VERIFY_ALL_RESOLVED ); TEXTURE_FORMAT RTVFormats[] = {AmbientSkyLightTexFmt}; m_pPrecomputeAmbientSkyLightPSO = CreateScreenSizeQuadPSO(pDevice, "PrecomputeAmbientSkyLight", pPrecomputeAmbientSkyLightPS, DSS_DisableDepth, BS_Default, 1, RTVFormats, TEX_FORMAT_UNKNOWN); m_pPrecomputeAmbientSkyLightPSO->CreateShaderResourceBinding(&m_pPrecomputeAmbientSkyLightSRB, true); } // Create 2-D texture, shader resource and target view buffers on the device ITextureView *pRTVs[] = {m_ptex2DAmbientSkyLightRTV}; pContext->SetRenderTargets(1, pRTVs, nullptr, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); RenderScreenSizeQuad(pContext, m_pPrecomputeAmbientSkyLightPSO, m_pPrecomputeAmbientSkyLightSRB); m_uiUpToDateResourceFlags |= UpToDateResourceFlags::AmbientSkyLightTex; } ITextureView* LightSctrPostProcess :: GetAmbientSkyLightSRV(IRenderDevice *pDevice, IDeviceContext *pContext) { if( !(m_uiUpToDateResourceFlags & UpToDateResourceFlags::AmbientSkyLightTex) ) { ComputeAmbientSkyLightTexture(pDevice, pContext); } return m_ptex2DAmbientSkyLightSRV; }
/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ //----------------------------------------------------------------- // Implementation of the alignment steering class // It provides an access to the track space points // written along the esd tracks. The class enables // the user to plug any track fitter (deriving from // AliTrackFitter class) and minimization fo the // track residual sums (deriving from the AliTrackResiduals). //----------------------------------------------------------------- #include <TChain.h> #include <TFile.h> #include <TVector3.h> #include <TSystem.h> #include "AliAlignmentTracks.h" #include "AliTrackPointArray.h" #include "AliAlignObjParams.h" #include "AliTrackFitterRieman.h" #include "AliTrackResidualsChi2.h" #include "AliESDEvent.h" #include "AliLog.h" ClassImp(AliAlignmentTracks) //______________________________________________________________________________ AliAlignmentTracks::AliAlignmentTracks(): fESDChain(0), fPointsFilename("AliTrackPoints.root"), fPointsFile(0), fPointsTree(0), fLastIndex(0), fArrayIndex(0), fIsIndexBuilt(kFALSE), fAlignObjs(0), fMisalignObjs(0), fTrackFitter(0), fMinimizer(0), fDoUpdate(kTRUE), fCovIsUsed(kFALSE) { // Default constructor InitIndex(); InitAlignObjs(); } //______________________________________________________________________________ AliAlignmentTracks::AliAlignmentTracks(TChain *esdchain): fESDChain(esdchain), fPointsFilename("AliTrackPoints.root"), fPointsFile(0), fPointsTree(0), fLastIndex(0), fArrayIndex(0), fIsIndexBuilt(kFALSE), fAlignObjs(0), fMisalignObjs(0), fTrackFitter(0), fMinimizer(0), fDoUpdate(kTRUE), fCovIsUsed(kFALSE) { // Constructor in the case // the user provides an already // built TChain with ESD trees InitIndex(); InitAlignObjs(); } //______________________________________________________________________________ AliAlignmentTracks::AliAlignmentTracks(const char *esdfilename, const char *esdtreename): fESDChain(new TChain(esdtreename)), fPointsFilename("AliTrackPoints.root"), fPointsFile(0), fPointsTree(0), fLastIndex(0), fArrayIndex(0), fIsIndexBuilt(kFALSE), fAlignObjs(0), fMisalignObjs(0), fTrackFitter(0), fMinimizer(0), fDoUpdate(kTRUE), fCovIsUsed(kFALSE) { // Constructor in the case // the user provides a single ESD file // or a directory containing ESD files fESDChain->Add(esdfilename); InitIndex(); InitAlignObjs(); } //______________________________________________________________________________ AliAlignmentTracks::~AliAlignmentTracks() { // Destructor if (fESDChain) delete fESDChain; DeleteIndex(); DeleteAlignObjs(); delete fTrackFitter; delete fMinimizer; if (fPointsFile) fPointsFile->Close(); } //______________________________________________________________________________ void AliAlignmentTracks::AddESD(TChain *esdchain) { // Add a chain with ESD files if (fESDChain) fESDChain->Add(esdchain); else fESDChain = esdchain; } //______________________________________________________________________________ void AliAlignmentTracks::AddESD(const char *esdfilename, const char *esdtreename) { // Add a single file or // a directory to the chain // with the ESD files if (fESDChain) fESDChain->AddFile(esdfilename,TChain::kBigNumber,esdtreename); else { fESDChain = new TChain(esdtreename); fESDChain->Add(esdfilename); } } //________________________________________________________________________ void AliAlignmentTracks::ProcessESD(Bool_t onlyITS, Int_t minITSpts, Bool_t cuts, Float_t minAngleWrtITSModulePlanes, Float_t minMom,Float_t maxMom, Float_t minAbsSinPhi,Float_t maxAbsSinPhi, Float_t minSinTheta,Float_t maxSinTheta) { // Analyzes and filters ESD tracks // Stores the selected track space points // into the output file if (!fESDChain) return; AliESDEvent *esd = new AliESDEvent(); esd->ReadFromTree(fESDChain); AliESDfriend *esdf = 0; fESDChain->SetBranchStatus("ESDfriend*",1); fESDChain->SetBranchAddress("ESDfriend.",&esdf); // Open the output file if (fPointsFilename.IsNull()) { AliWarning("Incorrect output filename!"); return; } TFile *pointsFile = TFile::Open(fPointsFilename,"RECREATE"); if (!pointsFile || !pointsFile->IsOpen()) { AliWarning(Form("Can't open %s !",fPointsFilename.Data())); return; } TTree *pointsTree = new TTree("spTree", "Tree with track space point arrays"); const AliTrackPointArray *array = 0; AliTrackPointArray *array2 = 0; if(onlyITS) { // only ITS AliTrackPoints pointsTree->Branch("SP","AliTrackPointArray", &array2); } else { pointsTree->Branch("SP","AliTrackPointArray", &array); } Int_t ievent = 0; while (fESDChain->GetEntry(ievent++)) { if (!esd) break; esd->SetESDfriend(esdf); //Attach the friend to the ESD Int_t ntracks = esd->GetNumberOfTracks(); for (Int_t itrack=0; itrack < ntracks; itrack++) { AliESDtrack * track = esd->GetTrack(itrack); if (!track) continue; if(track->GetNcls(0) < minITSpts) continue; if(cuts) { if(track->GetP()<minMom || track->GetP()>maxMom) continue; Float_t abssinphi = TMath::Abs(TMath::Sin(track->GetAlpha()+TMath::ASin(track->GetSnp()))); if(abssinphi<minAbsSinPhi || abssinphi>maxAbsSinPhi) continue; Float_t sintheta = TMath::Sin(0.5*TMath::Pi()-TMath::ATan(track->GetTgl())); if(sintheta<minSinTheta || sintheta>maxSinTheta) continue; } AliTrackPoint point; array = track->GetTrackPointArray(); if(onlyITS) { Bool_t layerOK[6]={kTRUE,kTRUE,kTRUE,kTRUE,kTRUE,kTRUE}; Int_t ipt,volId,modId,layerId; Int_t jpt=0; for(ipt=0; ipt<array->GetNPoints(); ipt++) { array->GetPoint(point,ipt); volId = point.GetVolumeID(); layerId = AliGeomManager::VolUIDToLayer(volId,modId); if(layerId>6) continue; // check minAngleWrtITSModulePlanes if(cuts) { Double_t p[3]; track->GetDirection(p); TVector3 pvec(p[0],p[1],p[2]); Double_t rot[9]; AliGeomManager::GetOrigRotation(volId,rot); TVector3 normvec(rot[1],rot[4],rot[7]); Double_t angle = pvec.Angle(normvec); if(angle>0.5*TMath::Pi()) angle = TMath::Pi()-angle; angle = 0.5*TMath::Pi()-angle; if(angle<minAngleWrtITSModulePlanes) { layerOK[layerId-1]=kFALSE; continue; } } jpt++; } if(jpt < minITSpts) continue; array2 = new AliTrackPointArray(jpt); jpt=0; for(ipt=0; ipt<array->GetNPoints(); ipt++) { array->GetPoint(point,ipt); volId = point.GetVolumeID(); layerId = AliGeomManager::VolUIDToLayer(volId,modId); if(layerId>6 || !layerOK[layerId-1]) continue; array2->AddPoint(jpt,&point); jpt++; } } // end if(onlyITS) pointsTree->Fill(); } } if (!pointsTree->Write()) { AliWarning("Can't write the tree with track point arrays!"); return; } pointsFile->Close(); return; } //_____________________________________________________________________________ void AliAlignmentTracks::ProcessESDCosmics(Bool_t onlyITS, Int_t minITSpts,Float_t maxMatchingAngle, Bool_t cuts, Float_t minAngleWrtITSModulePlanes, Float_t minMom,Float_t maxMom, Float_t minAbsSinPhi,Float_t maxAbsSinPhi, Float_t minSinTheta,Float_t maxSinTheta) { // Analyzes and filters ESD tracks // Merges inward and outward tracks in one single track // Stores the selected track space points // into the output file if (!fESDChain) return; AliESDEvent *esd = new AliESDEvent(); esd->ReadFromTree(fESDChain); AliESDfriend *esdf = 0; fESDChain->SetBranchStatus("ESDfriend*",1); fESDChain->SetBranchAddress("ESDfriend.",&esdf); // Open the output file if (fPointsFilename.IsNull()) { AliWarning("Incorrect output filename!"); return; } TFile *pointsFile = TFile::Open(fPointsFilename,"RECREATE"); if (!pointsFile || !pointsFile->IsOpen()) { AliWarning(Form("Can't open %s !",fPointsFilename.Data())); return; } TTree *pointsTree = new TTree("spTree", "Tree with track space point arrays"); const AliTrackPointArray *array = 0; AliTrackPointArray *array2 = 0; pointsTree->Branch("SP","AliTrackPointArray", &array2); Int_t ievent = 0; while (fESDChain->GetEntry(ievent++)) { if (!esd) break; esd->SetESDfriend(esdf); //Attach the friend to the ESD Int_t ntracks = esd->GetNumberOfTracks(); if(ntracks<2) continue; Int_t *goodtracksArray = new Int_t[ntracks]; Float_t *phiArray = new Float_t[ntracks]; Float_t *thetaArray = new Float_t[ntracks]; Int_t ngt=0; for (Int_t itrack=0; itrack < ntracks; itrack++) { AliESDtrack * track = esd->GetTrack(itrack); if (!track) continue; if(track->GetNcls(0) < minITSpts) continue; Float_t phi = track->GetAlpha()+TMath::ASin(track->GetSnp()); Float_t theta = 0.5*TMath::Pi()-TMath::ATan(track->GetTgl()); if(cuts) { if(track->GetP()<minMom || track->GetP()>maxMom) continue; Float_t abssinphi = TMath::Abs(TMath::Sin(phi)); if(abssinphi<minAbsSinPhi || abssinphi>maxAbsSinPhi) continue; Float_t sintheta = TMath::Sin(theta); if(sintheta<minSinTheta || sintheta>maxSinTheta) continue; } goodtracksArray[ngt]=itrack; phiArray[ngt]=phi; thetaArray[ngt]=theta; ngt++; } if(ngt<2) { delete [] goodtracksArray; goodtracksArray=0; delete [] phiArray; phiArray=0; delete [] thetaArray; thetaArray=0; continue; } // check matching of the two tracks from the muon Float_t min = 10000000.; Int_t good1 = -1, good2 = -1; for(Int_t itr1=0; itr1<ngt-1; itr1++) { for(Int_t itr2=itr1+1; itr2<ngt; itr2++) { Float_t deltatheta = TMath::Abs(TMath::Pi()-thetaArray[itr1]-thetaArray[itr2]); if(deltatheta>maxMatchingAngle) continue; Float_t deltaphi = TMath::Abs(TMath::Abs(phiArray[itr1]-phiArray[itr2])-TMath::Pi()); if(deltaphi>maxMatchingAngle) continue; //printf("%f %f %f %f\n",deltaphi,deltatheta,thetaArray[itr1],thetaArray[itr2]); if(deltatheta+deltaphi<min) { min=deltatheta+deltaphi; good1 = goodtracksArray[itr1]; good2 = goodtracksArray[itr2]; } } } delete [] goodtracksArray; goodtracksArray=0; delete [] phiArray; phiArray=0; delete [] thetaArray; thetaArray=0; if(good1<0) continue; AliESDtrack * track1 = esd->GetTrack(good1); AliESDtrack * track2 = esd->GetTrack(good2); AliTrackPoint point; Int_t ipt,volId,modId,layerId; Int_t jpt=0; Bool_t layerOK[6][2]; for(Int_t l1=0;l1<6;l1++) for(Int_t l2=0;l2<2;l2++) layerOK[l1][l2]=kTRUE; array = track1->GetTrackPointArray(); for(ipt=0; ipt<array->GetNPoints(); ipt++) { array->GetPoint(point,ipt); if(onlyITS) { volId = point.GetVolumeID(); layerId = AliGeomManager::VolUIDToLayer(volId,modId); if(layerId>6) continue; // check minAngleWrtITSModulePlanes if(cuts) { Double_t p[3]; track1->GetDirection(p); TVector3 pvec(p[0],p[1],p[2]); Double_t rot[9]; AliGeomManager::GetOrigRotation(volId,rot); TVector3 normvec(rot[1],rot[4],rot[7]); Double_t angle = pvec.Angle(normvec); if(angle>0.5*TMath::Pi()) angle = TMath::Pi()-angle; angle = 0.5*TMath::Pi()-angle; if(angle<minAngleWrtITSModulePlanes) { layerOK[layerId-1][0]=kFALSE; continue; } } } jpt++; } array = track2->GetTrackPointArray(); for(ipt=0; ipt<array->GetNPoints(); ipt++) { array->GetPoint(point,ipt); if(onlyITS) { volId = point.GetVolumeID(); layerId = AliGeomManager::VolUIDToLayer(volId,modId); if(layerId>6) continue; // check minAngleWrtITSModulePlanes if(cuts) { Double_t p[3]; track2->GetDirection(p); TVector3 pvec(p[0],p[1],p[2]); Double_t rot[9]; AliGeomManager::GetOrigRotation(volId,rot); TVector3 normvec(rot[1],rot[4],rot[7]); Double_t angle = pvec.Angle(normvec); if(angle>0.5*TMath::Pi()) angle = TMath::Pi()-angle; angle = 0.5*TMath::Pi()-angle; if(angle<minAngleWrtITSModulePlanes) { layerOK[layerId-1][0]=kFALSE; continue; } } } jpt++; } if(jpt < 2*minITSpts) continue; array2 = new AliTrackPointArray(jpt); jpt=0; array = track1->GetTrackPointArray(); for(ipt=0; ipt<array->GetNPoints(); ipt++) { array->GetPoint(point,ipt); if(onlyITS) { volId = point.GetVolumeID(); layerId = AliGeomManager::VolUIDToLayer(volId,modId); if(layerId>6 || !layerOK[layerId-1][0]) continue; } array2->AddPoint(jpt,&point); jpt++; } array = track2->GetTrackPointArray(); for(ipt=0; ipt<array->GetNPoints(); ipt++) { array->GetPoint(point,ipt); if(onlyITS) { volId = point.GetVolumeID(); layerId = AliGeomManager::VolUIDToLayer(volId,modId); if(layerId>6 || !layerOK[layerId-1][1]) continue; } array2->AddPoint(jpt,&point); jpt++; } pointsTree->Fill(); } if (!pointsTree->Write()) { AliWarning("Can't write the tree with track point arrays!"); return; } pointsFile->Close(); return; } //______________________________________________________________________________ void AliAlignmentTracks::ProcessESD(TSelector *selector) { AliWarning(Form("ESD processing based on selector is not yet implemented (%p) !",selector)); } //______________________________________________________________________________ void AliAlignmentTracks::BuildIndex() { // Build index of points tree entries // Used for access based on the volume IDs if (fIsIndexBuilt) return; fIsIndexBuilt = kTRUE; // Dummy object is created in order // to initialize the volume paths AliAlignObjParams alobj; fPointsFile = TFile::Open(fPointsFilename); if (!fPointsFile || !fPointsFile->IsOpen()) { AliWarning(Form("Can't open %s !",fPointsFilename.Data())); return; } // AliTrackPointArray* array = new AliTrackPointArray; AliTrackPointArray* array = 0; fPointsTree = (TTree*) fPointsFile->Get("spTree"); if (!fPointsTree) { AliWarning("No pointsTree found!"); return; } fPointsTree->SetBranchAddress("SP", &array); Int_t nArrays = (Int_t)fPointsTree->GetEntries(); for (Int_t iArray = 0; iArray < nArrays; iArray++) { fPointsTree->GetEvent(iArray); if (!array) continue; for (Int_t ipoint = 0; ipoint < array->GetNPoints(); ipoint++) { UShort_t volId = array->GetVolumeID()[ipoint]; // check if the volId is valid if (!AliGeomManager::SymName(volId)) { AliError(Form("The volume id %d has no default volume name !", volId)); continue; } Int_t modId; Int_t layerId = AliGeomManager::VolUIDToLayer(volId,modId) - AliGeomManager::kFirstLayer; if (!fArrayIndex[layerId][modId]) { //first entry for this volume fArrayIndex[layerId][modId] = new TArrayI(1000); } else { Int_t size = fArrayIndex[layerId][modId]->GetSize(); // If needed allocate new size if (fLastIndex[layerId][modId] >= size) fArrayIndex[layerId][modId]->Set(size + 1000); } // Check if the index is already filled Bool_t fillIndex = kTRUE; if (fLastIndex[layerId][modId] != 0) { if ((*fArrayIndex[layerId][modId])[fLastIndex[layerId][modId]-1] == iArray) fillIndex = kFALSE; } // Fill the index array and store last filled index if (fillIndex) { (*fArrayIndex[layerId][modId])[fLastIndex[layerId][modId]] = iArray; fLastIndex[layerId][modId]++; } } } } //______________________________________________________________________________ void AliAlignmentTracks::InitIndex() { // Initialize the index arrays Int_t nLayers = AliGeomManager::kLastLayer - AliGeomManager::kFirstLayer; fLastIndex = new Int_t*[nLayers]; fArrayIndex = new TArrayI**[nLayers]; for (Int_t iLayer = 0; iLayer < (AliGeomManager::kLastLayer - AliGeomManager::kFirstLayer); iLayer++) { fLastIndex[iLayer] = new Int_t[AliGeomManager::LayerSize(iLayer + AliGeomManager::kFirstLayer)]; fArrayIndex[iLayer] = new TArrayI*[AliGeomManager::LayerSize(iLayer + AliGeomManager::kFirstLayer)]; for (Int_t iModule = 0; iModule < AliGeomManager::LayerSize(iLayer + AliGeomManager::kFirstLayer); iModule++) { fLastIndex[iLayer][iModule] = 0; fArrayIndex[iLayer][iModule] = 0; } } } //______________________________________________________________________________ void AliAlignmentTracks::ResetIndex() { // Reset the value of the last filled index // Do not realocate memory fIsIndexBuilt = kFALSE; for (Int_t iLayer = 0; iLayer < AliGeomManager::kLastLayer - AliGeomManager::kFirstLayer; iLayer++) { for (Int_t iModule = 0; iModule < AliGeomManager::LayerSize(iLayer + AliGeomManager::kFirstLayer); iModule++) { fLastIndex[iLayer][iModule] = 0; } } } //______________________________________________________________________________ void AliAlignmentTracks::DeleteIndex() { // Delete the index arrays // Called by the destructor for (Int_t iLayer = 0; iLayer < (AliGeomManager::kLastLayer - AliGeomManager::kFirstLayer); iLayer++) { for (Int_t iModule = 0; iModule < AliGeomManager::LayerSize(iLayer + AliGeomManager::kFirstLayer); iModule++) { if (fArrayIndex[iLayer][iModule]) { delete fArrayIndex[iLayer][iModule]; fArrayIndex[iLayer][iModule] = 0; } } delete [] fLastIndex[iLayer]; delete [] fArrayIndex[iLayer]; } delete [] fLastIndex; delete [] fArrayIndex; } //______________________________________________________________________________ Bool_t AliAlignmentTracks::ReadAlignObjs(const char *alignObjFileName, const char* arrayName) { // Read alignment object from a file: update the alignobj already present with the one in the file // To be replaced by a call to CDB if(gSystem->AccessPathName(alignObjFileName,kFileExists)){ printf("Wrong AlignObjs File Name \n"); return kFALSE; } TFile *fRealign=TFile::Open(alignObjFileName); if (!fRealign || !fRealign->IsOpen()) { AliError(Form("Could not open Align Obj File file %s !",alignObjFileName)); return kFALSE; } printf("Getting TClonesArray \n"); TClonesArray *clnarray=(TClonesArray*)fRealign->Get(arrayName); Int_t size=clnarray->GetSize(); UShort_t volid; for(Int_t ivol=0;ivol<size;ivol++){ AliAlignObjParams *a=(AliAlignObjParams*)clnarray->At(ivol); volid=a->GetVolUID(); Int_t iModule; AliGeomManager::ELayerID iLayer = AliGeomManager::VolUIDToLayer(volid,iModule); if(iLayer<AliGeomManager::kFirstLayer||iLayer>AliGeomManager::kSSD2)continue; printf("Updating volume: %d ,layer: %d module: %d \n",volid,iLayer,iModule); *fAlignObjs[iLayer-AliGeomManager::kFirstLayer][iModule] *= *a; } delete clnarray; fRealign->Close(); return kTRUE; } //______________________________________________________________________________ void AliAlignmentTracks::InitAlignObjs() { // Initialize the alignment objects array Int_t nLayers = AliGeomManager::kLastLayer - AliGeomManager::kFirstLayer; fAlignObjs = new AliAlignObj**[nLayers]; for (Int_t iLayer = 0; iLayer < (AliGeomManager::kLastLayer - AliGeomManager::kFirstLayer); iLayer++) { fAlignObjs[iLayer] = new AliAlignObj*[AliGeomManager::LayerSize(iLayer + AliGeomManager::kFirstLayer)]; for (Int_t iModule = 0; iModule < AliGeomManager::LayerSize(iLayer + AliGeomManager::kFirstLayer); iModule++) { UShort_t volid = AliGeomManager::LayerToVolUID(iLayer+ AliGeomManager::kFirstLayer,iModule); fAlignObjs[iLayer][iModule] = new AliAlignObjParams(AliGeomManager::SymName(volid),volid,0,0,0,0,0,0,kTRUE); } } } //______________________________________________________________________________ void AliAlignmentTracks::ResetAlignObjs() { // Reset the alignment objects array for (Int_t iLayer = 0; iLayer < (AliGeomManager::kLastLayer - AliGeomManager::kFirstLayer); iLayer++) { for (Int_t iModule = 0; iModule < AliGeomManager::LayerSize(iLayer + AliGeomManager::kFirstLayer); iModule++) fAlignObjs[iLayer][iModule]->SetPars(0,0,0,0,0,0); } } //______________________________________________________________________________ void AliAlignmentTracks::DeleteAlignObjs() { // Delete the alignment objects array for (Int_t iLayer = 0; iLayer < (AliGeomManager::kLastLayer - AliGeomManager::kFirstLayer); iLayer++) { for (Int_t iModule = 0; iModule < AliGeomManager::LayerSize(iLayer + AliGeomManager::kFirstLayer); iModule++) if (fAlignObjs[iLayer][iModule]) delete fAlignObjs[iLayer][iModule]; delete [] fAlignObjs[iLayer]; } delete [] fAlignObjs; fAlignObjs = 0; } Bool_t AliAlignmentTracks::AlignDetector(AliGeomManager::ELayerID firstLayer, AliGeomManager::ELayerID lastLayer, AliGeomManager::ELayerID layerRangeMin, AliGeomManager::ELayerID layerRangeMax, Int_t iterations) { // Align detector volumes within // a given layer range // (could be whole detector). // Tracks are fitted only within // the range defined by the user. Int_t nModules = 0; for (Int_t iLayer = firstLayer; iLayer <= lastLayer; iLayer++) nModules += AliGeomManager::LayerSize(iLayer); TArrayI volIds(nModules); Int_t modnum = 0; for (Int_t iLayer = firstLayer; iLayer <= lastLayer; iLayer++) { for (Int_t iModule = 0; iModule < AliGeomManager::LayerSize(iLayer); iModule++) { UShort_t volId = AliGeomManager::LayerToVolUID(iLayer,iModule); volIds.AddAt(volId,modnum); modnum++; } } Bool_t result = kFALSE; while (iterations > 0) { if (!(result = AlignVolumes(&volIds,0x0,layerRangeMin,layerRangeMax))) break; iterations--; } return result; } //______________________________________________________________________________ Bool_t AliAlignmentTracks::AlignLayer(AliGeomManager::ELayerID layer, AliGeomManager::ELayerID layerRangeMin, AliGeomManager::ELayerID layerRangeMax, Int_t iterations) { // Align detector volumes within // a given layer. // Tracks are fitted only within // the range defined by the user. Int_t nModules = AliGeomManager::LayerSize(layer); TArrayI volIds(nModules); for (Int_t iModule = 0; iModule < nModules; iModule++) { UShort_t volId = AliGeomManager::LayerToVolUID(layer,iModule); volIds.AddAt(volId,iModule); } Bool_t result = kFALSE; while (iterations > 0) { if (!(result = AlignVolumes(&volIds,0x0,layerRangeMin,layerRangeMax))) break; iterations--; } return result; } //______________________________________________________________________________ Bool_t AliAlignmentTracks::AlignVolume(UShort_t volId, UShort_t volIdFit, Int_t iterations) { // Align single detector volume to // another volume. // Tracks are fitted only within // the second volume. TArrayI volIds(1); volIds.AddAt(volId,0); TArrayI volIdsFit(1); volIdsFit.AddAt(volIdFit,0); Bool_t result = kFALSE; while (iterations > 0) { if (!(result = AlignVolumes(&volIds,&volIdsFit))) break; iterations--; } return result; } //______________________________________________________________________________ Bool_t AliAlignmentTracks::AlignVolumes(const TArrayI *volids, const TArrayI *volidsfit, AliGeomManager::ELayerID layerRangeMin, AliGeomManager::ELayerID layerRangeMax, Int_t iterations) { // Align a set of detector volumes. // Tracks are fitted only within // the range defined by the user // (by layerRangeMin and layerRangeMax) // or within the set of volidsfit // Repeat the procedure 'iterations' times Int_t nVolIds = volids->GetSize(); if (nVolIds == 0) { AliError("Volume IDs array is empty!"); return kFALSE; } // Load only the tracks with at least one // space point in the set of volume (volids) BuildIndex(); AliTrackPointArray **points; Int_t pointsdim; // Start the iterations Bool_t result = kFALSE; while (iterations > 0) { Int_t nArrays = LoadPoints(volids, points,pointsdim); if (nArrays == 0) return kFALSE; AliTrackResiduals *minimizer = CreateMinimizer(); minimizer->SetNTracks(nArrays); minimizer->InitAlignObj(); AliTrackFitter *fitter = CreateFitter(); for (Int_t iArray = 0; iArray < nArrays; iArray++) { if (!points[iArray]) continue; fitter->SetTrackPointArray(points[iArray], kFALSE); if (fitter->Fit(volids,volidsfit,layerRangeMin,layerRangeMax) == kFALSE) continue; AliTrackPointArray *pVolId,*pTrack; fitter->GetTrackResiduals(pVolId,pTrack); minimizer->AddTrackPointArrays(pVolId,pTrack); } if (!(result = minimizer->Minimize())) break; // Update the alignment object(s) if (fDoUpdate) for (Int_t iVolId = 0; iVolId < nVolIds; iVolId++) { UShort_t volid = (*volids)[iVolId]; Int_t iModule; AliGeomManager::ELayerID iLayer = AliGeomManager::VolUIDToLayer(volid,iModule); AliAlignObj *alignObj = fAlignObjs[iLayer-AliGeomManager::kFirstLayer][iModule]; *alignObj *= *minimizer->GetAlignObj(); if(iterations==1)alignObj->Print(""); } UnloadPoints(pointsdim, points); iterations--; } return result; } //______________________________________________________________________________ Int_t AliAlignmentTracks::LoadPoints(const TArrayI *volids, AliTrackPointArray** &points,Int_t &pointsdim) { // Load track point arrays with at least // one space point in a given set of detector // volumes (array volids). // Use the already created tree index for // fast access. if (!fPointsTree) { AliError("Tree with the space point arrays not initialized!"); points = 0; return 0; } Int_t nVolIds = volids->GetSize(); if (nVolIds == 0) { AliError("Volume IDs array is empty!"); points = 0; return 0; } Int_t nArrays = 0; for (Int_t iVolId = 0; iVolId < nVolIds; iVolId++) { UShort_t volid = (*volids)[iVolId]; Int_t iModule; AliGeomManager::ELayerID iLayer = AliGeomManager::VolUIDToLayer(volid,iModule); // In case of empty index if (fLastIndex[iLayer-AliGeomManager::kFirstLayer][iModule] == 0) { AliWarning(Form("There are no space-points belonging to the volume which is to be aligned (Volume ID =%d)!",volid)); continue; } nArrays += fLastIndex[iLayer-AliGeomManager::kFirstLayer][iModule]; } if (nArrays == 0) { AliError("There are no space-points belonging to all of the volumes which are to be aligned!"); points = 0x0; return 0; } AliTrackPointArray* array = 0; fPointsTree->SetBranchAddress("SP", &array); // Allocate the pointer to the space-point arrays pointsdim=nArrays; points = new AliTrackPointArray*[nArrays]; for (Int_t i = 0; i < nArrays; i++) points[i] = 0x0; // Init the array used to flag already loaded tree entries Bool_t *indexUsed = new Bool_t[(UInt_t)fPointsTree->GetEntries()]; for (Int_t i = 0; i < fPointsTree->GetEntries(); i++) indexUsed[i] = kFALSE; // Start the loop over the volume ids Int_t iArray = 0; for (Int_t iVolId = 0; iVolId < nVolIds; iVolId++) { UShort_t volid = (*volids)[iVolId]; Int_t iModule; AliGeomManager::ELayerID iLayer = AliGeomManager::VolUIDToLayer(volid,iModule); Int_t nArraysId = fLastIndex[iLayer-AliGeomManager::kFirstLayer][iModule]; TArrayI *index = fArrayIndex[iLayer-AliGeomManager::kFirstLayer][iModule]; AliTrackPoint p; for (Int_t iArrayId = 0; iArrayId < nArraysId; iArrayId++) { // Get tree entry Int_t entry = (*index)[iArrayId]; if (indexUsed[entry] == kTRUE) { nArrays--; continue; } fPointsTree->GetEvent(entry); if (!array) { AliWarning("Wrong space point array index!"); continue; } indexUsed[entry] = kTRUE; // Get the space-point array Int_t nPoints = array->GetNPoints(); points[iArray] = new AliTrackPointArray(nPoints); for (Int_t iPoint = 0; iPoint < nPoints; iPoint++) { array->GetPoint(p,iPoint); Int_t modnum; AliGeomManager::ELayerID layer = AliGeomManager::VolUIDToLayer(p.GetVolumeID(),modnum); // check if the layer id is valid if ((layer < AliGeomManager::kFirstLayer) || (layer >= AliGeomManager::kLastLayer)) { AliError(Form("Layer index is invalid: %d (%d -> %d) !", layer,AliGeomManager::kFirstLayer,AliGeomManager::kLastLayer-1)); continue; } if ((modnum >= AliGeomManager::LayerSize(layer)) || (modnum < 0)) { AliError(Form("Module number inside layer %d is invalid: %d (0 -> %d)", layer,modnum,AliGeomManager::LayerSize(layer))); continue; } // Misalignment is introduced here // Switch it off in case of real // alignment job! if (fMisalignObjs) { AliAlignObj *misalignObj = fMisalignObjs[layer-AliGeomManager::kFirstLayer][modnum]; if (misalignObj) misalignObj->Transform(p); } // End of misalignment AliAlignObj *alignObj = fAlignObjs[layer-AliGeomManager::kFirstLayer][modnum]; UShort_t volp=p.GetVolumeID(); Bool_t found=kFALSE; if(fCovIsUsed){ for (Int_t iVol = 0; iVol < nVolIds; iVol++) { UShort_t vol = (*volids)[iVol]; if(volp==vol){ alignObj->Transform(p,kFALSE); found=kTRUE; break; } } } if(!found)alignObj->Transform(p,fCovIsUsed); points[iArray]->AddPoint(iPoint,&p); } iArray++; } } delete [] indexUsed; return nArrays; } //______________________________________________________________________________ void AliAlignmentTracks::UnloadPoints(Int_t n, AliTrackPointArray **points) { // Unload track point arrays for a given // detector volume for (Int_t iArray = 0; iArray < n; iArray++) delete points[iArray]; delete [] points; } //______________________________________________________________________________ AliTrackFitter *AliAlignmentTracks::CreateFitter() { // Check if the user has already supplied // a track fitter object. // If not, create a default one. if (!fTrackFitter) fTrackFitter = new AliTrackFitterRieman; return fTrackFitter; } //______________________________________________________________________________ AliTrackResiduals *AliAlignmentTracks::CreateMinimizer() { // Check if the user has already supplied // a track residuals minimizer object. // If not, create a default one. if (!fMinimizer) fMinimizer = new AliTrackResidualsChi2; return fMinimizer; } //______________________________________________________________________________ Bool_t AliAlignmentTracks::Misalign(const char *misalignObjFileName, const char* arrayName) { // The method reads from a file a set of AliAlignObj which are // then used to apply misalignments directly on the track // space-points. The method is supposed to be used only for // fast development and debugging of the alignment algorithms. // Be careful not to use it in the case of 'real' alignment // scenario since it will bias the results. // Initialize the misalignment objects array Int_t nLayers = AliGeomManager::kLastLayer - AliGeomManager::kFirstLayer; fMisalignObjs = new AliAlignObj**[nLayers]; for (Int_t iLayer = 0; iLayer < (AliGeomManager::kLastLayer - AliGeomManager::kFirstLayer); iLayer++) { fMisalignObjs[iLayer] = new AliAlignObj*[AliGeomManager::LayerSize(iLayer + AliGeomManager::kFirstLayer)]; for (Int_t iModule = 0; iModule < AliGeomManager::LayerSize(iLayer + AliGeomManager::kFirstLayer); iModule++) fMisalignObjs[iLayer][iModule] = 0x0; } // Open the misliagnment file and load the array with // misalignment objects TFile* inFile = TFile::Open(misalignObjFileName,"READ"); if (!inFile || !inFile->IsOpen()) { AliError(Form("Could not open misalignment file %s !",misalignObjFileName)); return kFALSE; } TClonesArray* array = ((TClonesArray*) inFile->Get(arrayName)); if (!array) { AliError(Form("Could not find misalignment array %s in the file %s !",arrayName,misalignObjFileName)); inFile->Close(); return kFALSE; } inFile->Close(); // Store the misalignment objects for further usage Int_t nObjs = array->GetEntriesFast(); AliGeomManager::ELayerID layerId; // volume layer Int_t modId; // volume ID inside the layer for(Int_t i=0; i<nObjs; i++) { AliAlignObj* alObj = (AliAlignObj*)array->UncheckedAt(i); alObj->GetVolUID(layerId,modId); if(layerId<AliGeomManager::kFirstLayer) { AliWarning(Form("Alignment object is ignored: %s",alObj->GetSymName())); continue; } fMisalignObjs[layerId-AliGeomManager::kFirstLayer][modId] = alObj; } return kTRUE; } //________________________________________________ void AliAlignmentTracks::WriteRealignObjArray(TString outfilename,AliGeomManager::ELayerID layerRangeMin,AliGeomManager::ELayerID layerRangeMax){ Int_t last=0; TClonesArray *clonesArray=new TClonesArray("AliAlignObjParams",2200); TClonesArray &alo=*clonesArray; for (Int_t iLayer = layerRangeMin-AliGeomManager::kFirstLayer; iLayer <= (layerRangeMax - AliGeomManager::kFirstLayer);iLayer++) { for (Int_t iModule = 0; iModule < AliGeomManager::LayerSize(iLayer + AliGeomManager::kFirstLayer); iModule++) { AliAlignObj *alignObj = fAlignObjs[iLayer][iModule]; new(alo[last])AliAlignObjParams(*alignObj); last++; } } TFile *file=new TFile(outfilename.Data(),"RECREATE"); file->cd(); alo.Write("ITSAlignObjs",TObject::kSingleKey); file->Close(); delete clonesArray; return; } Coverity 14106 /************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ //----------------------------------------------------------------- // Implementation of the alignment steering class // It provides an access to the track space points // written along the esd tracks. The class enables // the user to plug any track fitter (deriving from // AliTrackFitter class) and minimization fo the // track residual sums (deriving from the AliTrackResiduals). //----------------------------------------------------------------- #include <TChain.h> #include <TFile.h> #include <TVector3.h> #include <TSystem.h> #include "AliAlignmentTracks.h" #include "AliTrackPointArray.h" #include "AliAlignObjParams.h" #include "AliTrackFitterRieman.h" #include "AliTrackResidualsChi2.h" #include "AliESDEvent.h" #include "AliLog.h" ClassImp(AliAlignmentTracks) //______________________________________________________________________________ AliAlignmentTracks::AliAlignmentTracks(): fESDChain(0), fPointsFilename("AliTrackPoints.root"), fPointsFile(0), fPointsTree(0), fLastIndex(0), fArrayIndex(0), fIsIndexBuilt(kFALSE), fAlignObjs(0), fMisalignObjs(0), fTrackFitter(0), fMinimizer(0), fDoUpdate(kTRUE), fCovIsUsed(kFALSE) { // Default constructor InitIndex(); InitAlignObjs(); } //______________________________________________________________________________ AliAlignmentTracks::AliAlignmentTracks(TChain *esdchain): fESDChain(esdchain), fPointsFilename("AliTrackPoints.root"), fPointsFile(0), fPointsTree(0), fLastIndex(0), fArrayIndex(0), fIsIndexBuilt(kFALSE), fAlignObjs(0), fMisalignObjs(0), fTrackFitter(0), fMinimizer(0), fDoUpdate(kTRUE), fCovIsUsed(kFALSE) { // Constructor in the case // the user provides an already // built TChain with ESD trees InitIndex(); InitAlignObjs(); } //______________________________________________________________________________ AliAlignmentTracks::AliAlignmentTracks(const char *esdfilename, const char *esdtreename): fESDChain(new TChain(esdtreename)), fPointsFilename("AliTrackPoints.root"), fPointsFile(0), fPointsTree(0), fLastIndex(0), fArrayIndex(0), fIsIndexBuilt(kFALSE), fAlignObjs(0), fMisalignObjs(0), fTrackFitter(0), fMinimizer(0), fDoUpdate(kTRUE), fCovIsUsed(kFALSE) { // Constructor in the case // the user provides a single ESD file // or a directory containing ESD files fESDChain->Add(esdfilename); InitIndex(); InitAlignObjs(); } //______________________________________________________________________________ AliAlignmentTracks::~AliAlignmentTracks() { // Destructor if (fESDChain) delete fESDChain; DeleteIndex(); DeleteAlignObjs(); delete fTrackFitter; delete fMinimizer; if (fPointsFile) fPointsFile->Close(); } //______________________________________________________________________________ void AliAlignmentTracks::AddESD(TChain *esdchain) { // Add a chain with ESD files if (fESDChain) fESDChain->Add(esdchain); else fESDChain = esdchain; } //______________________________________________________________________________ void AliAlignmentTracks::AddESD(const char *esdfilename, const char *esdtreename) { // Add a single file or // a directory to the chain // with the ESD files if (fESDChain) fESDChain->AddFile(esdfilename,TChain::kBigNumber,esdtreename); else { fESDChain = new TChain(esdtreename); fESDChain->Add(esdfilename); } } //________________________________________________________________________ void AliAlignmentTracks::ProcessESD(Bool_t onlyITS, Int_t minITSpts, Bool_t cuts, Float_t minAngleWrtITSModulePlanes, Float_t minMom,Float_t maxMom, Float_t minAbsSinPhi,Float_t maxAbsSinPhi, Float_t minSinTheta,Float_t maxSinTheta) { // Analyzes and filters ESD tracks // Stores the selected track space points // into the output file if (!fESDChain) return; AliESDEvent *esd = new AliESDEvent(); esd->ReadFromTree(fESDChain); AliESDfriend *esdf = 0; fESDChain->SetBranchStatus("ESDfriend*",1); fESDChain->SetBranchAddress("ESDfriend.",&esdf); // Open the output file if (fPointsFilename.IsNull()) { AliWarning("Incorrect output filename!"); return; } TFile *pointsFile = TFile::Open(fPointsFilename,"RECREATE"); if (!pointsFile || !pointsFile->IsOpen()) { AliWarning(Form("Can't open %s !",fPointsFilename.Data())); return; } TTree *pointsTree = new TTree("spTree", "Tree with track space point arrays"); const AliTrackPointArray *array = 0; AliTrackPointArray *array2 = 0; if(onlyITS) { // only ITS AliTrackPoints pointsTree->Branch("SP","AliTrackPointArray", &array2); } else { pointsTree->Branch("SP","AliTrackPointArray", &array); } Int_t ievent = 0; while (fESDChain->GetEntry(ievent++)) { if (!esd) break; esd->SetESDfriend(esdf); //Attach the friend to the ESD Int_t ntracks = esd->GetNumberOfTracks(); for (Int_t itrack=0; itrack < ntracks; itrack++) { AliESDtrack * track = esd->GetTrack(itrack); if (!track) continue; if(track->GetNcls(0) < minITSpts) continue; if(cuts) { if(track->GetP()<minMom || track->GetP()>maxMom) continue; Float_t abssinphi = TMath::Abs(TMath::Sin(track->GetAlpha()+TMath::ASin(track->GetSnp()))); if(abssinphi<minAbsSinPhi || abssinphi>maxAbsSinPhi) continue; Float_t sintheta = TMath::Sin(0.5*TMath::Pi()-TMath::ATan(track->GetTgl())); if(sintheta<minSinTheta || sintheta>maxSinTheta) continue; } AliTrackPoint point; array = track->GetTrackPointArray(); if(onlyITS) { Bool_t layerOK[6]={kTRUE,kTRUE,kTRUE,kTRUE,kTRUE,kTRUE}; Int_t ipt,volId,modId,layerId; Int_t jpt=0; for(ipt=0; ipt<array->GetNPoints(); ipt++) { array->GetPoint(point,ipt); volId = point.GetVolumeID(); layerId = AliGeomManager::VolUIDToLayer(volId,modId); if(layerId>6) continue; // check minAngleWrtITSModulePlanes if(cuts) { Double_t p[3]; track->GetDirection(p); TVector3 pvec(p[0],p[1],p[2]); Double_t rot[9]; AliGeomManager::GetOrigRotation(volId,rot); TVector3 normvec(rot[1],rot[4],rot[7]); Double_t angle = pvec.Angle(normvec); if(angle>0.5*TMath::Pi()) angle = TMath::Pi()-angle; angle = 0.5*TMath::Pi()-angle; if(angle<minAngleWrtITSModulePlanes) { layerOK[layerId-1]=kFALSE; continue; } } jpt++; } if(jpt < minITSpts) continue; array2 = new AliTrackPointArray(jpt); jpt=0; for(ipt=0; ipt<array->GetNPoints(); ipt++) { array->GetPoint(point,ipt); volId = point.GetVolumeID(); layerId = AliGeomManager::VolUIDToLayer(volId,modId); if(layerId>6 || !layerOK[layerId-1]) continue; array2->AddPoint(jpt,&point); jpt++; } } // end if(onlyITS) pointsTree->Fill(); } } if (!pointsTree->Write()) { AliWarning("Can't write the tree with track point arrays!"); return; } pointsFile->Close(); return; } //_____________________________________________________________________________ void AliAlignmentTracks::ProcessESDCosmics(Bool_t onlyITS, Int_t minITSpts,Float_t maxMatchingAngle, Bool_t cuts, Float_t minAngleWrtITSModulePlanes, Float_t minMom,Float_t maxMom, Float_t minAbsSinPhi,Float_t maxAbsSinPhi, Float_t minSinTheta,Float_t maxSinTheta) { // Analyzes and filters ESD tracks // Merges inward and outward tracks in one single track // Stores the selected track space points // into the output file if (!fESDChain) return; AliESDEvent *esd = new AliESDEvent(); esd->ReadFromTree(fESDChain); AliESDfriend *esdf = 0; fESDChain->SetBranchStatus("ESDfriend*",1); fESDChain->SetBranchAddress("ESDfriend.",&esdf); // Open the output file if (fPointsFilename.IsNull()) { AliWarning("Incorrect output filename!"); return; } TFile *pointsFile = TFile::Open(fPointsFilename,"RECREATE"); if (!pointsFile || !pointsFile->IsOpen()) { AliWarning(Form("Can't open %s !",fPointsFilename.Data())); return; } TTree *pointsTree = new TTree("spTree", "Tree with track space point arrays"); const AliTrackPointArray *array = 0; AliTrackPointArray *array2 = 0; pointsTree->Branch("SP","AliTrackPointArray", &array2); Int_t ievent = 0; while (fESDChain->GetEntry(ievent++)) { if (!esd) break; esd->SetESDfriend(esdf); //Attach the friend to the ESD Int_t ntracks = esd->GetNumberOfTracks(); if(ntracks<2) continue; Int_t *goodtracksArray = new Int_t[ntracks]; Float_t *phiArray = new Float_t[ntracks]; Float_t *thetaArray = new Float_t[ntracks]; Int_t ngt=0; for (Int_t itrack=0; itrack < ntracks; itrack++) { AliESDtrack * track = esd->GetTrack(itrack); if (!track) continue; if(track->GetNcls(0) < minITSpts) continue; Float_t phi = track->GetAlpha()+TMath::ASin(track->GetSnp()); Float_t theta = 0.5*TMath::Pi()-TMath::ATan(track->GetTgl()); if(cuts) { if(track->GetP()<minMom || track->GetP()>maxMom) continue; Float_t abssinphi = TMath::Abs(TMath::Sin(phi)); if(abssinphi<minAbsSinPhi || abssinphi>maxAbsSinPhi) continue; Float_t sintheta = TMath::Sin(theta); if(sintheta<minSinTheta || sintheta>maxSinTheta) continue; } goodtracksArray[ngt]=itrack; phiArray[ngt]=phi; thetaArray[ngt]=theta; ngt++; } if(ngt<2) { delete [] goodtracksArray; goodtracksArray=0; delete [] phiArray; phiArray=0; delete [] thetaArray; thetaArray=0; continue; } // check matching of the two tracks from the muon Float_t min = 10000000.; Int_t good1 = -1, good2 = -1; for(Int_t itr1=0; itr1<ngt-1; itr1++) { for(Int_t itr2=itr1+1; itr2<ngt; itr2++) { Float_t deltatheta = TMath::Abs(TMath::Pi()-thetaArray[itr1]-thetaArray[itr2]); if(deltatheta>maxMatchingAngle) continue; Float_t deltaphi = TMath::Abs(TMath::Abs(phiArray[itr1]-phiArray[itr2])-TMath::Pi()); if(deltaphi>maxMatchingAngle) continue; //printf("%f %f %f %f\n",deltaphi,deltatheta,thetaArray[itr1],thetaArray[itr2]); if(deltatheta+deltaphi<min) { min=deltatheta+deltaphi; good1 = goodtracksArray[itr1]; good2 = goodtracksArray[itr2]; } } } delete [] goodtracksArray; goodtracksArray=0; delete [] phiArray; phiArray=0; delete [] thetaArray; thetaArray=0; if(good1<0) continue; AliESDtrack * track1 = esd->GetTrack(good1); AliESDtrack * track2 = esd->GetTrack(good2); AliTrackPoint point; Int_t ipt,volId,modId,layerId; Int_t jpt=0; Bool_t layerOK[6][2]; for(Int_t l1=0;l1<6;l1++) for(Int_t l2=0;l2<2;l2++) layerOK[l1][l2]=kTRUE; array = track1->GetTrackPointArray(); for(ipt=0; ipt<array->GetNPoints(); ipt++) { array->GetPoint(point,ipt); if(onlyITS) { volId = point.GetVolumeID(); layerId = AliGeomManager::VolUIDToLayer(volId,modId); if(layerId>6) continue; // check minAngleWrtITSModulePlanes if(cuts) { Double_t p[3]; track1->GetDirection(p); TVector3 pvec(p[0],p[1],p[2]); Double_t rot[9]; AliGeomManager::GetOrigRotation(volId,rot); TVector3 normvec(rot[1],rot[4],rot[7]); Double_t angle = pvec.Angle(normvec); if(angle>0.5*TMath::Pi()) angle = TMath::Pi()-angle; angle = 0.5*TMath::Pi()-angle; if(angle<minAngleWrtITSModulePlanes) { layerOK[layerId-1][0]=kFALSE; continue; } } } jpt++; } array = track2->GetTrackPointArray(); for(ipt=0; ipt<array->GetNPoints(); ipt++) { array->GetPoint(point,ipt); if(onlyITS) { volId = point.GetVolumeID(); layerId = AliGeomManager::VolUIDToLayer(volId,modId); if(layerId>6) continue; // check minAngleWrtITSModulePlanes if(cuts) { Double_t p[3]; track2->GetDirection(p); TVector3 pvec(p[0],p[1],p[2]); Double_t rot[9]; AliGeomManager::GetOrigRotation(volId,rot); TVector3 normvec(rot[1],rot[4],rot[7]); Double_t angle = pvec.Angle(normvec); if(angle>0.5*TMath::Pi()) angle = TMath::Pi()-angle; angle = 0.5*TMath::Pi()-angle; if(angle<minAngleWrtITSModulePlanes) { layerOK[layerId-1][0]=kFALSE; continue; } } } jpt++; } if(jpt < 2*minITSpts) continue; array2 = new AliTrackPointArray(jpt); jpt=0; array = track1->GetTrackPointArray(); for(ipt=0; ipt<array->GetNPoints(); ipt++) { array->GetPoint(point,ipt); if(onlyITS) { volId = point.GetVolumeID(); layerId = AliGeomManager::VolUIDToLayer(volId,modId); if(layerId>6 || !layerOK[layerId-1][0]) continue; } array2->AddPoint(jpt,&point); jpt++; } array = track2->GetTrackPointArray(); for(ipt=0; ipt<array->GetNPoints(); ipt++) { array->GetPoint(point,ipt); if(onlyITS) { volId = point.GetVolumeID(); layerId = AliGeomManager::VolUIDToLayer(volId,modId); if(layerId>6 || !layerOK[layerId-1][1]) continue; } array2->AddPoint(jpt,&point); jpt++; } pointsTree->Fill(); } if (!pointsTree->Write()) { AliWarning("Can't write the tree with track point arrays!"); return; } pointsFile->Close(); return; } //______________________________________________________________________________ void AliAlignmentTracks::ProcessESD(TSelector *selector) { AliWarning(Form("ESD processing based on selector is not yet implemented (%p) !",selector)); } //______________________________________________________________________________ void AliAlignmentTracks::BuildIndex() { // Build index of points tree entries // Used for access based on the volume IDs if (fIsIndexBuilt) return; fIsIndexBuilt = kTRUE; // Dummy object is created in order // to initialize the volume paths AliAlignObjParams alobj; fPointsFile = TFile::Open(fPointsFilename); if (!fPointsFile || !fPointsFile->IsOpen()) { AliWarning(Form("Can't open %s !",fPointsFilename.Data())); return; } // AliTrackPointArray* array = new AliTrackPointArray; AliTrackPointArray* array = 0; fPointsTree = (TTree*) fPointsFile->Get("spTree"); if (!fPointsTree) { AliWarning("No pointsTree found!"); return; } fPointsTree->SetBranchAddress("SP", &array); Int_t nArrays = (Int_t)fPointsTree->GetEntries(); for (Int_t iArray = 0; iArray < nArrays; iArray++) { fPointsTree->GetEvent(iArray); if (!array) continue; for (Int_t ipoint = 0; ipoint < array->GetNPoints(); ipoint++) { UShort_t volId = array->GetVolumeID()[ipoint]; // check if the volId is valid if (!AliGeomManager::SymName(volId)) { AliError(Form("The volume id %d has no default volume name !", volId)); continue; } Int_t modId; Int_t layerId = AliGeomManager::VolUIDToLayer(volId,modId) - AliGeomManager::kFirstLayer; if (!fArrayIndex[layerId][modId]) { //first entry for this volume fArrayIndex[layerId][modId] = new TArrayI(1000); } else { Int_t size = fArrayIndex[layerId][modId]->GetSize(); // If needed allocate new size if (fLastIndex[layerId][modId] >= size) fArrayIndex[layerId][modId]->Set(size + 1000); } // Check if the index is already filled Bool_t fillIndex = kTRUE; if (fLastIndex[layerId][modId] != 0) { if ((*fArrayIndex[layerId][modId])[fLastIndex[layerId][modId]-1] == iArray) fillIndex = kFALSE; } // Fill the index array and store last filled index if (fillIndex) { (*fArrayIndex[layerId][modId])[fLastIndex[layerId][modId]] = iArray; fLastIndex[layerId][modId]++; } } } } //______________________________________________________________________________ void AliAlignmentTracks::InitIndex() { // Initialize the index arrays Int_t nLayers = AliGeomManager::kLastLayer - AliGeomManager::kFirstLayer; fLastIndex = new Int_t*[nLayers]; fArrayIndex = new TArrayI**[nLayers]; for (Int_t iLayer = 0; iLayer < (AliGeomManager::kLastLayer - AliGeomManager::kFirstLayer); iLayer++) { fLastIndex[iLayer] = new Int_t[AliGeomManager::LayerSize(iLayer + AliGeomManager::kFirstLayer)]; fArrayIndex[iLayer] = new TArrayI*[AliGeomManager::LayerSize(iLayer + AliGeomManager::kFirstLayer)]; for (Int_t iModule = 0; iModule < AliGeomManager::LayerSize(iLayer + AliGeomManager::kFirstLayer); iModule++) { fLastIndex[iLayer][iModule] = 0; fArrayIndex[iLayer][iModule] = 0; } } } //______________________________________________________________________________ void AliAlignmentTracks::ResetIndex() { // Reset the value of the last filled index // Do not realocate memory fIsIndexBuilt = kFALSE; for (Int_t iLayer = 0; iLayer < AliGeomManager::kLastLayer - AliGeomManager::kFirstLayer; iLayer++) { for (Int_t iModule = 0; iModule < AliGeomManager::LayerSize(iLayer + AliGeomManager::kFirstLayer); iModule++) { fLastIndex[iLayer][iModule] = 0; } } } //______________________________________________________________________________ void AliAlignmentTracks::DeleteIndex() { // Delete the index arrays // Called by the destructor for (Int_t iLayer = 0; iLayer < (AliGeomManager::kLastLayer - AliGeomManager::kFirstLayer); iLayer++) { for (Int_t iModule = 0; iModule < AliGeomManager::LayerSize(iLayer + AliGeomManager::kFirstLayer); iModule++) { if (fArrayIndex[iLayer][iModule]) { delete fArrayIndex[iLayer][iModule]; fArrayIndex[iLayer][iModule] = 0; } } delete [] fLastIndex[iLayer]; delete [] fArrayIndex[iLayer]; } delete [] fLastIndex; delete [] fArrayIndex; } //______________________________________________________________________________ Bool_t AliAlignmentTracks::ReadAlignObjs(const char *alignObjFileName, const char* arrayName) { // Read alignment object from a file: update the alignobj already present with the one in the file // To be replaced by a call to CDB if(gSystem->AccessPathName(alignObjFileName,kFileExists)){ printf("Wrong AlignObjs File Name \n"); return kFALSE; } TFile *fRealign=TFile::Open(alignObjFileName); if (!fRealign || !fRealign->IsOpen()) { AliError(Form("Could not open Align Obj File file %s !",alignObjFileName)); return kFALSE; } printf("Getting TClonesArray \n"); TClonesArray *clnarray=(TClonesArray*)fRealign->Get(arrayName); Int_t size=clnarray->GetSize(); UShort_t volid; for(Int_t ivol=0;ivol<size;ivol++){ AliAlignObjParams *a=(AliAlignObjParams*)clnarray->At(ivol); volid=a->GetVolUID(); Int_t iModule; AliGeomManager::ELayerID iLayer = AliGeomManager::VolUIDToLayer(volid,iModule); if(iLayer<AliGeomManager::kFirstLayer||iLayer>AliGeomManager::kSSD2)continue; printf("Updating volume: %d ,layer: %d module: %d \n",volid,iLayer,iModule); *fAlignObjs[iLayer-AliGeomManager::kFirstLayer][iModule] *= *a; } delete clnarray; fRealign->Close(); return kTRUE; } //______________________________________________________________________________ void AliAlignmentTracks::InitAlignObjs() { // Initialize the alignment objects array Int_t nLayers = AliGeomManager::kLastLayer - AliGeomManager::kFirstLayer; fAlignObjs = new AliAlignObj**[nLayers]; for (Int_t iLayer = 0; iLayer < (AliGeomManager::kLastLayer - AliGeomManager::kFirstLayer); iLayer++) { fAlignObjs[iLayer] = new AliAlignObj*[AliGeomManager::LayerSize(iLayer + AliGeomManager::kFirstLayer)]; for (Int_t iModule = 0; iModule < AliGeomManager::LayerSize(iLayer + AliGeomManager::kFirstLayer); iModule++) { UShort_t volid = AliGeomManager::LayerToVolUID(iLayer+ AliGeomManager::kFirstLayer,iModule); fAlignObjs[iLayer][iModule] = new AliAlignObjParams(AliGeomManager::SymName(volid),volid,0,0,0,0,0,0,kTRUE); } } } //______________________________________________________________________________ void AliAlignmentTracks::ResetAlignObjs() { // Reset the alignment objects array for (Int_t iLayer = 0; iLayer < (AliGeomManager::kLastLayer - AliGeomManager::kFirstLayer); iLayer++) { for (Int_t iModule = 0; iModule < AliGeomManager::LayerSize(iLayer + AliGeomManager::kFirstLayer); iModule++) fAlignObjs[iLayer][iModule]->SetPars(0,0,0,0,0,0); } } //______________________________________________________________________________ void AliAlignmentTracks::DeleteAlignObjs() { // Delete the alignment objects array for (Int_t iLayer = 0; iLayer < (AliGeomManager::kLastLayer - AliGeomManager::kFirstLayer); iLayer++) { for (Int_t iModule = 0; iModule < AliGeomManager::LayerSize(iLayer + AliGeomManager::kFirstLayer); iModule++) if (fAlignObjs[iLayer][iModule]) delete fAlignObjs[iLayer][iModule]; delete [] fAlignObjs[iLayer]; } delete [] fAlignObjs; fAlignObjs = 0; } Bool_t AliAlignmentTracks::AlignDetector(AliGeomManager::ELayerID firstLayer, AliGeomManager::ELayerID lastLayer, AliGeomManager::ELayerID layerRangeMin, AliGeomManager::ELayerID layerRangeMax, Int_t iterations) { // Align detector volumes within // a given layer range // (could be whole detector). // Tracks are fitted only within // the range defined by the user. Int_t nModules = 0; for (Int_t iLayer = firstLayer; iLayer <= lastLayer; iLayer++) nModules += AliGeomManager::LayerSize(iLayer); TArrayI volIds(nModules); Int_t modnum = 0; for (Int_t iLayer = firstLayer; iLayer <= lastLayer; iLayer++) { for (Int_t iModule = 0; iModule < AliGeomManager::LayerSize(iLayer); iModule++) { UShort_t volId = AliGeomManager::LayerToVolUID(iLayer,iModule); volIds.AddAt(volId,modnum); modnum++; } } Bool_t result = kFALSE; while (iterations > 0) { if (!(result = AlignVolumes(&volIds,0x0,layerRangeMin,layerRangeMax))) break; iterations--; } return result; } //______________________________________________________________________________ Bool_t AliAlignmentTracks::AlignLayer(AliGeomManager::ELayerID layer, AliGeomManager::ELayerID layerRangeMin, AliGeomManager::ELayerID layerRangeMax, Int_t iterations) { // Align detector volumes within // a given layer. // Tracks are fitted only within // the range defined by the user. Int_t nModules = AliGeomManager::LayerSize(layer); TArrayI volIds(nModules); for (Int_t iModule = 0; iModule < nModules; iModule++) { UShort_t volId = AliGeomManager::LayerToVolUID(layer,iModule); volIds.AddAt(volId,iModule); } Bool_t result = kFALSE; while (iterations > 0) { if (!(result = AlignVolumes(&volIds,0x0,layerRangeMin,layerRangeMax))) break; iterations--; } return result; } //______________________________________________________________________________ Bool_t AliAlignmentTracks::AlignVolume(UShort_t volId, UShort_t volIdFit, Int_t iterations) { // Align single detector volume to // another volume. // Tracks are fitted only within // the second volume. TArrayI volIds(1); volIds.AddAt(volId,0); TArrayI volIdsFit(1); volIdsFit.AddAt(volIdFit,0); Bool_t result = kFALSE; while (iterations > 0) { if (!(result = AlignVolumes(&volIds,&volIdsFit))) break; iterations--; } return result; } //______________________________________________________________________________ Bool_t AliAlignmentTracks::AlignVolumes(const TArrayI *volids, const TArrayI *volidsfit, AliGeomManager::ELayerID layerRangeMin, AliGeomManager::ELayerID layerRangeMax, Int_t iterations) { // Align a set of detector volumes. // Tracks are fitted only within // the range defined by the user // (by layerRangeMin and layerRangeMax) // or within the set of volidsfit // Repeat the procedure 'iterations' times Int_t nVolIds = volids->GetSize(); if (nVolIds == 0) { AliError("Volume IDs array is empty!"); return kFALSE; } // Load only the tracks with at least one // space point in the set of volume (volids) BuildIndex(); AliTrackPointArray **points; Int_t pointsdim; // Start the iterations Bool_t result = kFALSE; while (iterations > 0) { Int_t nArrays = LoadPoints(volids, points,pointsdim); if (nArrays == 0) { UnloadPoints(pointsdim, points); return kFALSE; } AliTrackResiduals *minimizer = CreateMinimizer(); minimizer->SetNTracks(nArrays); minimizer->InitAlignObj(); AliTrackFitter *fitter = CreateFitter(); for (Int_t iArray = 0; iArray < nArrays; iArray++) { if (!points[iArray]) continue; fitter->SetTrackPointArray(points[iArray], kFALSE); if (fitter->Fit(volids,volidsfit,layerRangeMin,layerRangeMax) == kFALSE) continue; AliTrackPointArray *pVolId,*pTrack; fitter->GetTrackResiduals(pVolId,pTrack); minimizer->AddTrackPointArrays(pVolId,pTrack); } if (!(result = minimizer->Minimize())) break; // Update the alignment object(s) if (fDoUpdate) for (Int_t iVolId = 0; iVolId < nVolIds; iVolId++) { UShort_t volid = (*volids)[iVolId]; Int_t iModule; AliGeomManager::ELayerID iLayer = AliGeomManager::VolUIDToLayer(volid,iModule); AliAlignObj *alignObj = fAlignObjs[iLayer-AliGeomManager::kFirstLayer][iModule]; *alignObj *= *minimizer->GetAlignObj(); if(iterations==1)alignObj->Print(""); } UnloadPoints(pointsdim, points); iterations--; } return result; } //______________________________________________________________________________ Int_t AliAlignmentTracks::LoadPoints(const TArrayI *volids, AliTrackPointArray** &points,Int_t &pointsdim) { // Load track point arrays with at least // one space point in a given set of detector // volumes (array volids). // Use the already created tree index for // fast access. if (!fPointsTree) { AliError("Tree with the space point arrays not initialized!"); points = 0; return 0; } Int_t nVolIds = volids->GetSize(); if (nVolIds == 0) { AliError("Volume IDs array is empty!"); points = 0; return 0; } Int_t nArrays = 0; for (Int_t iVolId = 0; iVolId < nVolIds; iVolId++) { UShort_t volid = (*volids)[iVolId]; Int_t iModule; AliGeomManager::ELayerID iLayer = AliGeomManager::VolUIDToLayer(volid,iModule); // In case of empty index if (fLastIndex[iLayer-AliGeomManager::kFirstLayer][iModule] == 0) { AliWarning(Form("There are no space-points belonging to the volume which is to be aligned (Volume ID =%d)!",volid)); continue; } nArrays += fLastIndex[iLayer-AliGeomManager::kFirstLayer][iModule]; } if (nArrays == 0) { AliError("There are no space-points belonging to all of the volumes which are to be aligned!"); points = 0x0; return 0; } AliTrackPointArray* array = 0; fPointsTree->SetBranchAddress("SP", &array); // Allocate the pointer to the space-point arrays pointsdim=nArrays; points = new AliTrackPointArray*[nArrays]; for (Int_t i = 0; i < nArrays; i++) points[i] = 0x0; // Init the array used to flag already loaded tree entries Bool_t *indexUsed = new Bool_t[(UInt_t)fPointsTree->GetEntries()]; for (Int_t i = 0; i < fPointsTree->GetEntries(); i++) indexUsed[i] = kFALSE; // Start the loop over the volume ids Int_t iArray = 0; for (Int_t iVolId = 0; iVolId < nVolIds; iVolId++) { UShort_t volid = (*volids)[iVolId]; Int_t iModule; AliGeomManager::ELayerID iLayer = AliGeomManager::VolUIDToLayer(volid,iModule); Int_t nArraysId = fLastIndex[iLayer-AliGeomManager::kFirstLayer][iModule]; TArrayI *index = fArrayIndex[iLayer-AliGeomManager::kFirstLayer][iModule]; AliTrackPoint p; for (Int_t iArrayId = 0; iArrayId < nArraysId; iArrayId++) { // Get tree entry Int_t entry = (*index)[iArrayId]; if (indexUsed[entry] == kTRUE) { nArrays--; continue; } fPointsTree->GetEvent(entry); if (!array) { AliWarning("Wrong space point array index!"); continue; } indexUsed[entry] = kTRUE; // Get the space-point array Int_t nPoints = array->GetNPoints(); points[iArray] = new AliTrackPointArray(nPoints); for (Int_t iPoint = 0; iPoint < nPoints; iPoint++) { array->GetPoint(p,iPoint); Int_t modnum; AliGeomManager::ELayerID layer = AliGeomManager::VolUIDToLayer(p.GetVolumeID(),modnum); // check if the layer id is valid if ((layer < AliGeomManager::kFirstLayer) || (layer >= AliGeomManager::kLastLayer)) { AliError(Form("Layer index is invalid: %d (%d -> %d) !", layer,AliGeomManager::kFirstLayer,AliGeomManager::kLastLayer-1)); continue; } if ((modnum >= AliGeomManager::LayerSize(layer)) || (modnum < 0)) { AliError(Form("Module number inside layer %d is invalid: %d (0 -> %d)", layer,modnum,AliGeomManager::LayerSize(layer))); continue; } // Misalignment is introduced here // Switch it off in case of real // alignment job! if (fMisalignObjs) { AliAlignObj *misalignObj = fMisalignObjs[layer-AliGeomManager::kFirstLayer][modnum]; if (misalignObj) misalignObj->Transform(p); } // End of misalignment AliAlignObj *alignObj = fAlignObjs[layer-AliGeomManager::kFirstLayer][modnum]; UShort_t volp=p.GetVolumeID(); Bool_t found=kFALSE; if(fCovIsUsed){ for (Int_t iVol = 0; iVol < nVolIds; iVol++) { UShort_t vol = (*volids)[iVol]; if(volp==vol){ alignObj->Transform(p,kFALSE); found=kTRUE; break; } } } if(!found)alignObj->Transform(p,fCovIsUsed); points[iArray]->AddPoint(iPoint,&p); } iArray++; } } delete [] indexUsed; return nArrays; } //______________________________________________________________________________ void AliAlignmentTracks::UnloadPoints(Int_t n, AliTrackPointArray **points) { // Unload track point arrays for a given // detector volume for (Int_t iArray = 0; iArray < n; iArray++) delete points[iArray]; delete [] points; } //______________________________________________________________________________ AliTrackFitter *AliAlignmentTracks::CreateFitter() { // Check if the user has already supplied // a track fitter object. // If not, create a default one. if (!fTrackFitter) fTrackFitter = new AliTrackFitterRieman; return fTrackFitter; } //______________________________________________________________________________ AliTrackResiduals *AliAlignmentTracks::CreateMinimizer() { // Check if the user has already supplied // a track residuals minimizer object. // If not, create a default one. if (!fMinimizer) fMinimizer = new AliTrackResidualsChi2; return fMinimizer; } //______________________________________________________________________________ Bool_t AliAlignmentTracks::Misalign(const char *misalignObjFileName, const char* arrayName) { // The method reads from a file a set of AliAlignObj which are // then used to apply misalignments directly on the track // space-points. The method is supposed to be used only for // fast development and debugging of the alignment algorithms. // Be careful not to use it in the case of 'real' alignment // scenario since it will bias the results. // Initialize the misalignment objects array Int_t nLayers = AliGeomManager::kLastLayer - AliGeomManager::kFirstLayer; fMisalignObjs = new AliAlignObj**[nLayers]; for (Int_t iLayer = 0; iLayer < (AliGeomManager::kLastLayer - AliGeomManager::kFirstLayer); iLayer++) { fMisalignObjs[iLayer] = new AliAlignObj*[AliGeomManager::LayerSize(iLayer + AliGeomManager::kFirstLayer)]; for (Int_t iModule = 0; iModule < AliGeomManager::LayerSize(iLayer + AliGeomManager::kFirstLayer); iModule++) fMisalignObjs[iLayer][iModule] = 0x0; } // Open the misliagnment file and load the array with // misalignment objects TFile* inFile = TFile::Open(misalignObjFileName,"READ"); if (!inFile || !inFile->IsOpen()) { AliError(Form("Could not open misalignment file %s !",misalignObjFileName)); return kFALSE; } TClonesArray* array = ((TClonesArray*) inFile->Get(arrayName)); if (!array) { AliError(Form("Could not find misalignment array %s in the file %s !",arrayName,misalignObjFileName)); inFile->Close(); return kFALSE; } inFile->Close(); // Store the misalignment objects for further usage Int_t nObjs = array->GetEntriesFast(); AliGeomManager::ELayerID layerId; // volume layer Int_t modId; // volume ID inside the layer for(Int_t i=0; i<nObjs; i++) { AliAlignObj* alObj = (AliAlignObj*)array->UncheckedAt(i); alObj->GetVolUID(layerId,modId); if(layerId<AliGeomManager::kFirstLayer) { AliWarning(Form("Alignment object is ignored: %s",alObj->GetSymName())); continue; } fMisalignObjs[layerId-AliGeomManager::kFirstLayer][modId] = alObj; } return kTRUE; } //________________________________________________ void AliAlignmentTracks::WriteRealignObjArray(TString outfilename,AliGeomManager::ELayerID layerRangeMin,AliGeomManager::ELayerID layerRangeMax){ Int_t last=0; TClonesArray *clonesArray=new TClonesArray("AliAlignObjParams",2200); TClonesArray &alo=*clonesArray; for (Int_t iLayer = layerRangeMin-AliGeomManager::kFirstLayer; iLayer <= (layerRangeMax - AliGeomManager::kFirstLayer);iLayer++) { for (Int_t iModule = 0; iModule < AliGeomManager::LayerSize(iLayer + AliGeomManager::kFirstLayer); iModule++) { AliAlignObj *alignObj = fAlignObjs[iLayer][iModule]; new(alo[last])AliAlignObjParams(*alignObj); last++; } } TFile *file=new TFile(outfilename.Data(),"RECREATE"); file->cd(); alo.Write("ITSAlignObjs",TObject::kSingleKey); file->Close(); delete clonesArray; return; }
/* * Copyright (C) 2005-2019 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "itkMacro.h" #include <iostream> #include <complex> //only for the isnan() test line 148 #include "otbMath.h" #include "otbVectorImage.h" #include "otbBandMathXImageFilter.h" #include "otbImageFileWriter.h" #include "itkImageRegionIteratorWithIndex.h" int otbBandMathXImageFilter(int itkNotUsed(argc), char* itkNotUsed(argv)[]) { typedef otb::VectorImage<double, 2> ImageType; typedef ImageType::PixelType PixelType; typedef otb::BandMathXImageFilter<ImageType> FilterType; unsigned int i; const unsigned int N = 100, D1 = 3, D2 = 1, D3 = 1; ImageType::SizeType size; size.Fill(N); ImageType::IndexType index; index.Fill(0); ImageType::RegionType region; region.SetSize(size); region.SetIndex(index); ImageType::Pointer image1 = ImageType::New(); ImageType::Pointer image2 = ImageType::New(); ImageType::Pointer image3 = ImageType::New(); image1->SetLargestPossibleRegion(region); image1->SetBufferedRegion(region); image1->SetRequestedRegion(region); image1->SetNumberOfComponentsPerPixel(D1); image1->Allocate(); image2->SetLargestPossibleRegion(region); image2->SetBufferedRegion(region); image2->SetRequestedRegion(region); image2->SetNumberOfComponentsPerPixel(D2); image2->Allocate(); image3->SetLargestPossibleRegion(region); image3->SetBufferedRegion(region); image3->SetRequestedRegion(region); image3->SetNumberOfComponentsPerPixel(D3); image3->Allocate(); typedef itk::ImageRegionIteratorWithIndex<ImageType> IteratorType; IteratorType it1(image1, region); IteratorType it2(image2, region); IteratorType it3(image3, region); ImageType::PixelType val1, val2, val3; val1.SetSize(D1); val2.SetSize(D2); val3.SetSize(D3); for (it1.GoToBegin(), it2.GoToBegin(), it3.GoToBegin(); !it1.IsAtEnd(); ++it1, ++it2, ++it3) { ImageType::IndexType i1 = it1.GetIndex(); ImageType::IndexType i2 = it2.GetIndex(); ImageType::IndexType i3 = it3.GetIndex(); val1[0] = i1[0] + i1[1] - 50; val1[1] = i1[0] * i1[1] - 50; val1[2] = i1[0] / (i1[1] + 1) + 5; val2[0] = i2[0] * i2[1]; val3[0] = i3[0] + i3[1] * i3[1]; it1.Set(val1); it2.Set(val2); it3.Set(val3); } FilterType::Pointer filter = FilterType::New(); std::cout << "Number Of Threads : " << filter->GetNumberOfThreads() << std::endl; filter->SetNthInput(0, image1); filter->SetNthInput(1, image2); filter->SetNthInput(2, image3, "canal3"); filter->SetExpression("vcos(2 * pi * im1) div (2 * pi * bands(im2,{1,1,1}) + {3.38,3.38,3.38}) mult vsin(pi * bands(canal3,{1,1,1}))"); // Sub-test 1 filter->SetExpression("im1b1 / im2b1"); // Sub-test 2 (Edge Effect Handling) filter->Update(); // if (filter->GetNumberOfOutputs() != 2) ImageType::Pointer output1 = filter->GetOutput(0); ImageType::Pointer output2 = filter->GetOutput(1); std::cout << "\n--- Standard Use\n"; std::cout << "Parsed Expression : " << filter->GetExpression(0) << std::endl; // Sub-test 1 IteratorType itoutput1(output1, region); for (it1.GoToBegin(), it2.GoToBegin(), it3.GoToBegin(), itoutput1.GoToBegin(); !it1.IsAtEnd(); ++it1, ++it2, ++it3, ++itoutput1) { ImageType::IndexType i1 = it1.GetIndex(); ImageType::IndexType i2 = it2.GetIndex(); ImageType::IndexType i3 = it3.GetIndex(); PixelType px1(D1), px2(D2), px3(D3); px1[0] = (i1[0] + i1[1] - 50); px1[1] = (i1[0] * i1[1] - 50); px1[2] = (i1[0] / (i1[1] + 1) + 5); px2[0] = (i2[0] * i2[1]); px3[0] = (i3[0] + i3[1] * i3[1]); double result1 = itoutput1.Get()[0], result2 = itoutput1.Get()[1], result3 = itoutput1.Get()[2]; double error1, error2, error3; double expected1 = std::cos(2 * otb::CONST_PI * px1[0]) / (2 * otb::CONST_PI * px2[0] + 3.38) * std::sin(otb::CONST_PI * px3[0]); double expected2 = std::cos(2 * otb::CONST_PI * px1[1]) / (2 * otb::CONST_PI * px2[0] + 3.38) * std::sin(otb::CONST_PI * px3[0]); double expected3 = std::cos(2 * otb::CONST_PI * px1[2]) / (2 * otb::CONST_PI * px2[0] + 3.38) * std::sin(otb::CONST_PI * px3[0]); /*std::cout << "Pixel_1 = " << it1.Get()[0] << " Pixel_2 = " << it2.Get()[0] << " Pixel_3 = " << it3.Get()[0] << " Result = " << itoutput1.Get()[0] << " Expected = " << expected1 << std::endl; */ error1 = (result1 - expected1) * (result1 - expected1) / (result1 + expected1); error2 = (result2 - expected2) * (result2 - expected2) / (result2 + expected2); error3 = (result3 - expected3) * (result3 - expected3) / (result3 + expected3); if ((error1 > 1E-9) || (error2 > 1E-9) || (error3 > 1E-9)) { itkGenericExceptionMacro(<< std::endl << "Error = " << error1 << " > 1E-9 -> TEST FAILLED" << std::endl << "Pixel_1 = " << it1.Get()[0] << " Pixel_2 = " << it2.Get()[0] << " Pixel_3 = " << it3.Get()[0] << " Result = " << result1 << " Expected = " << expected1 << std::endl << "Error = " << error2 << " > 1E-9 -> TEST FAILLED" << std::endl << "Pixel_1 = " << it1.Get()[1] << " Pixel_2 = " << it2.Get()[0] << " Pixel_3 = " << it3.Get()[0] << " Result = " << result2 << " Expected = " << expected2 << std::endl << "Error = " << error3 << " > 1E-9 -> TEST FAILLED" << std::endl << "Pixel_1 = " << it1.Get()[2] << " Pixel_2 = " << it2.Get()[0] << " Pixel_3 = " << it3.Get()[0] << " Result = " << result3 << " Expected = " << expected3 << std::endl); } } // Sub-test 2 /** Edge Effect Handling */ IteratorType itoutput2(output2, region); std::cout << "\n--- Edge Effect Handling\n"; std::cout << "- +/-inf section\n"; std::cout << "- nan section\n"; it1.GoToBegin(); it2.GoToBegin(); itoutput2.GoToBegin(); for (i = 1; i <= 50; ++i, ++it1, ++it2, ++itoutput2) { } if (vnl_math_isnan(itoutput2.Get()[0])) std::cout << "Pixel_1 = " << it1.Get() << " Pixel_2 = " << it2.Get() << " Result = " << itoutput2.Get() << " Expected = nan\n"; else itkGenericExceptionMacro(<< "\nError > Bad Edge Effect Handling -> Test Failled\n" << "Pixel_1 = " << it1.Get() << " Pixel_2 = " << it2.Get() << " Result = " << itoutput2.Get() << " Expected = nan\n"); std::cout << std::endl; return EXIT_SUCCESS; } int otbBandMathXImageFilterConv(int itkNotUsed(argc), char* argv[]) { const char* inputFilename = argv[1]; typedef otb::VectorImage<double, 2> ImageType; typedef ImageType::PixelType PixelType; typedef otb::BandMathXImageFilter<ImageType> FilterType; const unsigned int N = 100, D1 = 3, D2 = 1, D3 = 1; ImageType::SizeType size; size.Fill(N); ImageType::IndexType index; index.Fill(0); ImageType::RegionType region; region.SetSize(size); region.SetIndex(index); ImageType::Pointer image1 = ImageType::New(); ImageType::Pointer image2 = ImageType::New(); ImageType::Pointer image3 = ImageType::New(); image1->SetLargestPossibleRegion(region); image1->SetBufferedRegion(region); image1->SetRequestedRegion(region); image1->SetNumberOfComponentsPerPixel(D1); image1->Allocate(); image2->SetLargestPossibleRegion(region); image2->SetBufferedRegion(region); image2->SetRequestedRegion(region); image2->SetNumberOfComponentsPerPixel(D2); image2->Allocate(); image3->SetLargestPossibleRegion(region); image3->SetBufferedRegion(region); image3->SetRequestedRegion(region); image3->SetNumberOfComponentsPerPixel(D3); image3->Allocate(); typedef itk::ConstNeighborhoodIterator<ImageType> IteratorType; IteratorType::RadiusType radius; radius[0] = 1; // Size x direction radius[1] = 2; // Size y direction IteratorType it1(radius, image1, region); it1.NeedToUseBoundaryConditionOn(); IteratorType it2(radius, image2, region); it2.NeedToUseBoundaryConditionOn(); IteratorType it3(radius, image3, region); it3.NeedToUseBoundaryConditionOn(); PixelType::ValueType imageAb2Mini = itk::NumericTraits<PixelType::ValueType>::max(); PixelType::ValueType imageAb3Mean = 0.0, n = 0.0; PixelType::ValueType imageAb3Var = 0.0; PixelType::ValueType imageAb1Sum = 0.0; PixelType::ValueType im2b1Maxi = itk::NumericTraits<PixelType::ValueType>::min(); for (it1.GoToBegin(), it2.GoToBegin(), it3.GoToBegin(); !it1.IsAtEnd(); ++it1, ++it2, ++it3) { ImageType::IndexType i1 = it1.GetIndex(); ImageType::IndexType i2 = it2.GetIndex(); ImageType::IndexType i3 = it3.GetIndex(); it1.GetCenterPixel()[0] = i1[0] + i1[1] - 50; it1.GetCenterPixel()[1] = i1[0] * i1[1] - 50; it1.GetCenterPixel()[2] = i1[0] / (i1[1] + 1) + 5; it2.GetCenterPixel()[0] = i2[0] * i2[1]; it3.GetCenterPixel()[0] = i3[0] + i3[1] * i3[1]; // Minimum of im1 band 2 if (imageAb2Mini > it1.GetCenterPixel()[1]) imageAb2Mini = it1.GetCenterPixel()[1]; // Mean of im1 band 3 imageAb3Mean += it1.GetCenterPixel()[2]; n++; // Var of im1 band 3 imageAb3Var += std::pow(it1.GetCenterPixel()[2], 2.0); // Maximum of im2 band 1 if (im2b1Maxi < it2.GetCenterPixel()[0]) im2b1Maxi = it2.GetCenterPixel()[0]; // Sum of im1 band1 imageAb1Sum += it1.GetCenterPixel()[0]; } imageAb3Mean = imageAb3Mean / n; imageAb3Var = (n / (n - 1)) * (imageAb3Var / n - imageAb3Mean * imageAb3Mean); // unbiased FilterType::Pointer filter = FilterType::New(); std::cout << "Number Of Threads : " << filter->GetNumberOfThreads() << std::endl; double expo = 1.1; filter->SetNthInput(0, image1, "imageA"); filter->SetNthInput(1, image2); filter->SetNthInput(2, image3, "canal3"); // filter->SetMatrix("kernel1","{ 0.1 , 0.2 , 0.3; 0.4 , 0.5 , 0.6; 0.7 , 0.8 , 0.9; 1.0 , 1.1 , 1.2; 1.3 , 1.4 , 1.5 }"); // filter->SetConstant("expo",expo); // filter->SetExpression("conv(kernel1,imageAb1N3x5,imageAb2N3x5); im2b1^1.1; vcos(canal3); mean(imageAb2N3x3); var(imageAb2N3x3); median(imageAb2N3x3)"); filter->ImportContext(inputFilename); // Equivalent to three commands above filter->SetExpression( "(vmax(canal3b1N3x5)+vmin(canal3b1N3x5)) div {2.0} + {imageAb3Var} dv 2.0 + {imageAb2Mini / im2b1Maxi} mlt 3.4 + {imageAb3Mean / imageAb1Sum * " "imageAb3Var} pw 1.2 ; vect2scal(vacos({0.5}) + vasin({0.5}) + vatan({0.5})) > 2.0 ?{1}:{0}"); filter->Update(); if (filter->GetNumberOfOutputs() != 2) itkGenericExceptionMacro(<< "Wrong number of outputs."); ImageType::Pointer output1 = filter->GetOutput(0); ImageType::Pointer output2 = filter->GetOutput(1); if (output1->GetNumberOfComponentsPerPixel() != 7) itkGenericExceptionMacro(<< "Wrong number of components per pixel (input 1)."); if (output2->GetNumberOfComponentsPerPixel() != 2) itkGenericExceptionMacro(<< "Wrong number of components per pixel (input 2)."); std::cout << "\n--- Standard Use\n"; std::cout << "Parsed Expression 1 : " << filter->GetExpression(0) << std::endl; std::cout << "Parsed Expression 2 : " << filter->GetExpression(1) << std::endl; // Sub-test 1 IteratorType itoutput1(radius, output1, region); IteratorType itoutput2(radius, output2, region); for (it1.GoToBegin(), it2.GoToBegin(), it3.GoToBegin(), itoutput1.GoToBegin(), itoutput2.GoToBegin(); !it1.IsAtEnd(); ++it1, ++it2, ++it3, ++itoutput1, ++itoutput2) { PixelType px1(output1->GetNumberOfComponentsPerPixel()); PixelType px2(output2->GetNumberOfComponentsPerPixel()); float coefs[15] = {0.1f, 0.2f, 0.3f, 0.4f, 0.5f, 0.6f, 0.7f, 0.8f, 0.9f, 1.0f, 1.1f, 1.2f, 1.3f, 1.4f, 1.5f}; // expression 1 px1[0] = 0; for (unsigned int i = 0; i < it1.Size(); ++i) px1[0] += coefs[i] * it1.GetPixel(i)[0]; px1[1] = 0; for (unsigned int i = 0; i < it1.Size(); ++i) px1[1] += coefs[i] * it1.GetPixel(i)[1]; px1[2] = std::pow(it2.GetCenterPixel()[0], expo); px1[3] = std::cos(it3.GetCenterPixel()[0]); // mean var median std::vector<double> vect; for (int i = 3; i <= 11; i++) vect.push_back(it1.GetPixel(i)[1]); px1[4] = 0.0; for (unsigned int i = 0; i < vect.size(); i++) px1[4] += vect[i]; px1[4] /= ((double)vect.size()); // mean px1[5] = 0.0; for (unsigned int i = 0; i < vect.size(); i++) px1[5] += (vect[i] - px1[4]) * (vect[i] - px1[4]); px1[5] /= ((double)vect.size()); // var std::sort(vect.begin(), vect.end()); px1[6] = vect[(int)(vect.size() / 2.)]; // median // expression 2 std::vector<double> vect2; for (unsigned int i = 0; i < it3.Size(); i++) vect2.push_back(it3.GetPixel(i)[0]); std::sort(vect2.begin(), vect2.end()); px2[0] = (vect2.back() + vect2.front()) / 2.0 + imageAb3Var / 2.0 + (imageAb2Mini / im2b1Maxi) * 3.4 + std::pow(imageAb3Mean / imageAb1Sum * imageAb3Var, 1.2); if (std::acos(0.5) + std::asin(0.5) + std::atan(0.5) > 2.0) px2[1] = 1.0; else px2[1] = 0.0; // expression 1 double result1 = itoutput1.GetCenterPixel()[0], result2 = itoutput1.GetCenterPixel()[1], result3 = itoutput1.GetCenterPixel()[2], result4 = itoutput1.GetCenterPixel()[3], result5 = itoutput1.GetCenterPixel()[4], result6 = itoutput1.GetCenterPixel()[5], result7 = itoutput1.GetCenterPixel()[6]; double error1, error2, error3, error4, error5, error6, error7; double expected1 = px1[0], expected2 = px1[1], expected3 = px1[2], expected4 = px1[3], expected5 = px1[4], expected6 = px1[5], expected7 = px1[6]; error1 = (result1 - expected1) * (result1 - expected1) / (result1 + expected1); error2 = (result2 - expected2) * (result2 - expected2) / (result2 + expected2); error3 = (result3 - expected3) * (result3 - expected3) / (result3 + expected3); error4 = (result4 - expected4) * (result4 - expected4) / (result4 + expected4); error5 = (result5 - expected5) * (result5 - expected5) / (result5 + expected5); error6 = (result6 - expected6) * (result6 - expected6) / (result6 + expected6); error7 = (result7 - expected7) * (result7 - expected7) / (result7 + expected7); // expression 2 double result8 = itoutput2.GetCenterPixel()[0]; double result9 = itoutput2.GetCenterPixel()[1]; double expected8 = px2[0]; double expected9 = px2[1]; double error8 = (result8 - expected8) * (result8 - expected8) / (result8 + expected8); double error9 = (result9 - expected9) * (result9 - expected9) / (result9 + expected9); if ((error1 > 1E-9) || (error2 > 1E-9) || (error3 > 1E-9) || (error4 > 1E-9) || (error5 > 1E-9) || (error6 > 1E-9) || (error7 > 1E-9) || (error8 > 1E-9) || (error9 > 1E-9)) { itkGenericExceptionMacro(<< "TEST FAILLED" << std::endl << "Error1 = " << error1 << std::endl << " Result1 = " << result1 << " Expected1 = " << expected1 << std::endl << "Error2 = " << error2 << std::endl << " Result2 = " << result2 << " Expected2 = " << expected2 << std::endl << "Error3 = " << error3 << std::endl << " Result3 = " << result3 << " Expected3 = " << expected3 << std::endl << "Error4 = " << error4 << std::endl << " Result4 = " << result4 << " Expected4 = " << expected4 << std::endl << "Error5 = " << error5 << std::endl << " Result5 = " << result5 << " Expected5 = " << expected5 << std::endl << "Error6 = " << error6 << std::endl << " Result6 = " << result6 << " Expected6 = " << expected6 << std::endl << "Error7 = " << error7 << std::endl << " Result7 = " << result7 << " Expected7 = " << expected7 << std::endl << "Error8 = " << error8 << std::endl << " Result8 = " << result8 << " Expected8 = " << expected8 << std::endl << "Error9 = " << error9 << std::endl << " Result9 = " << result9 << " Expected9 = " << expected9 << std::endl); } } return EXIT_SUCCESS; } int otbBandMathXImageFilterTxt(int itkNotUsed(argc), char* argv[]) { const char* inputFilename = argv[1]; const char* outputFilename = argv[2]; typedef otb::VectorImage<double, 2> ImageType; typedef otb::BandMathXImageFilter<ImageType> FilterType; FilterType::Pointer filter = FilterType::New(); filter->ImportContext(inputFilename); filter->ExportContext(outputFilename); return EXIT_SUCCESS; } int otbBandMathXImageFilterWithIdx(int itkNotUsed(argc), char* argv[]) { const char* outfname1 = argv[1]; const char* outfname2 = argv[2]; typedef otb::VectorImage<double, 2> ImageType; typedef otb::BandMathXImageFilter<ImageType> FilterType; typedef otb::ImageFileWriter<ImageType> WriterType; const unsigned int N = 100, D1 = 1, D2 = 1, D3 = 1; ImageType::SizeType size; size.Fill(N); ImageType::IndexType index; index.Fill(0); ImageType::RegionType region; region.SetSize(size); region.SetIndex(index); ImageType::PointType origin; origin[0] = -25; origin[1] = -25; ImageType::SpacingType spacing; spacing[0] = 0.5; spacing[1] = 0.5; ImageType::Pointer image1 = ImageType::New(); ImageType::Pointer image2 = ImageType::New(); ImageType::Pointer image3 = ImageType::New(); image1->SetLargestPossibleRegion(region); image1->SetBufferedRegion(region); image1->SetRequestedRegion(region); image1->SetNumberOfComponentsPerPixel(D1); image1->Allocate(); image2->SetLargestPossibleRegion(region); image2->SetBufferedRegion(region); image2->SetRequestedRegion(region); image2->SetNumberOfComponentsPerPixel(D2); image2->Allocate(); image3->SetLargestPossibleRegion(region); image3->SetBufferedRegion(region); image3->SetRequestedRegion(region); image3->SetNumberOfComponentsPerPixel(D3); image3->Allocate(); typedef itk::ImageRegionIteratorWithIndex<ImageType> IteratorType; IteratorType it1(image1, region); IteratorType it2(image2, region); IteratorType it3(image3, region); image1->SetOrigin(origin); image1->SetSignedSpacing(spacing); image2->SetOrigin(origin); image2->SetSignedSpacing(spacing); image3->SetOrigin(origin); image3->SetSignedSpacing(spacing); for (it1.GoToBegin(), it2.GoToBegin(), it3.GoToBegin(); !it1.IsAtEnd(); ++it1, ++it2, ++it3) { ImageType::IndexType i1 = it1.GetIndex(); ImageType::IndexType i2 = it2.GetIndex(); ImageType::IndexType i3 = it3.GetIndex(); it1.Get()[0] = i1[0] + i1[1] - 50; it2.Get()[0] = i2[0] * i2[1]; it3.Get()[0] = i3[0] + i3[1] * i3[1]; } FilterType::Pointer filter = FilterType::New(); std::cout << "Number Of Threads : " << filter->GetNumberOfThreads() << std::endl; filter->SetNthInput(0, image1); filter->SetNthInput(1, image2); filter->SetNthInput(2, image3); filter->SetExpression("(sqrt(idxX*idxX+idxY*idxY) < 50) ? im1b1 : im2b1"); filter->SetExpression("(sqrt(im2PhyX*im2PhyX+im2PhyY*im2PhyY) < 25) ? im2b1 : im3b1"); WriterType::Pointer writer = WriterType::New(); writer->SetInput(filter->GetOutput(0)); writer->SetFileName(outfname1); writer->Update(); WriterType::Pointer writer2 = WriterType::New(); writer2->SetInput(filter->GetOutput(1)); writer2->SetFileName(outfname2); writer2->Update(); return EXIT_SUCCESS; } int otbBandMathXImageFilterBandsFailures(int itkNotUsed(argc), char* itkNotUsed(argv)[]) { typedef otb::VectorImage<double, 2> ImageType; typedef otb::BandMathXImageFilter<ImageType> FilterType; const unsigned int N = 100, D1 = 3; ImageType::SizeType size; size.Fill(N); ImageType::IndexType index; index.Fill(0); ImageType::RegionType region; region.SetSize(size); region.SetIndex(index); ImageType::Pointer image = ImageType::New(); image->SetLargestPossibleRegion(region); image->SetBufferedRegion(region); image->SetRequestedRegion(region); image->SetNumberOfComponentsPerPixel(D1); image->Allocate(); FilterType::Pointer filter = FilterType::New(); filter->SetNthInput(0, image); std::vector<std::string> exps = { "bands(im1,{4,1})", "bands(im1,{1,-1})", "bands(im1,{1,2,3,1,2,3,0})" }; for ( std::string exp: exps ) { filter->SetExpression(exp); try { filter->Update(); throw ; } catch (::itk::RangeError& e) { std::cout << "INFO: Exception thrown as expected : " << e.what() << std::endl; filter->ClearExpression(); } catch (...) { itkGenericExceptionMacro(<< "TEST FAILLED: " << exp << "should have raise a RangeError exception" << std::endl); } } return EXIT_SUCCESS; } CI: Fixed error computation in otbBandMathXImageFilter /* * Copyright (C) 2005-2019 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "itkMacro.h" #include <iostream> #include <complex> //only for the isnan() test line 148 #include "otbMath.h" #include "otbVectorImage.h" #include "otbBandMathXImageFilter.h" #include "otbImageFileWriter.h" #include "itkImageRegionIteratorWithIndex.h" int otbBandMathXImageFilter(int itkNotUsed(argc), char* itkNotUsed(argv)[]) { typedef otb::VectorImage<double, 2> ImageType; typedef ImageType::PixelType PixelType; typedef otb::BandMathXImageFilter<ImageType> FilterType; unsigned int i; const unsigned int N = 100, D1 = 3, D2 = 1, D3 = 1; ImageType::SizeType size; size.Fill(N); ImageType::IndexType index; index.Fill(0); ImageType::RegionType region; region.SetSize(size); region.SetIndex(index); ImageType::Pointer image1 = ImageType::New(); ImageType::Pointer image2 = ImageType::New(); ImageType::Pointer image3 = ImageType::New(); image1->SetLargestPossibleRegion(region); image1->SetBufferedRegion(region); image1->SetRequestedRegion(region); image1->SetNumberOfComponentsPerPixel(D1); image1->Allocate(); image2->SetLargestPossibleRegion(region); image2->SetBufferedRegion(region); image2->SetRequestedRegion(region); image2->SetNumberOfComponentsPerPixel(D2); image2->Allocate(); image3->SetLargestPossibleRegion(region); image3->SetBufferedRegion(region); image3->SetRequestedRegion(region); image3->SetNumberOfComponentsPerPixel(D3); image3->Allocate(); typedef itk::ImageRegionIteratorWithIndex<ImageType> IteratorType; IteratorType it1(image1, region); IteratorType it2(image2, region); IteratorType it3(image3, region); ImageType::PixelType val1, val2, val3; val1.SetSize(D1); val2.SetSize(D2); val3.SetSize(D3); for (it1.GoToBegin(), it2.GoToBegin(), it3.GoToBegin(); !it1.IsAtEnd(); ++it1, ++it2, ++it3) { ImageType::IndexType i1 = it1.GetIndex(); ImageType::IndexType i2 = it2.GetIndex(); ImageType::IndexType i3 = it3.GetIndex(); val1[0] = i1[0] + i1[1] - 50; val1[1] = i1[0] * i1[1] - 50; val1[2] = i1[0] / (i1[1] + 1) + 5; val2[0] = i2[0] * i2[1]; val3[0] = i3[0] + i3[1] * i3[1]; it1.Set(val1); it2.Set(val2); it3.Set(val3); } FilterType::Pointer filter = FilterType::New(); std::cout << "Number Of Threads : " << filter->GetNumberOfThreads() << std::endl; filter->SetNthInput(0, image1); filter->SetNthInput(1, image2); filter->SetNthInput(2, image3, "canal3"); filter->SetExpression("vcos(2 * pi * im1) div (2 * pi * bands(im2,{1,1,1}) + {3.38,3.38,3.38}) mult vsin(pi * bands(canal3,{1,1,1}))"); // Sub-test 1 filter->SetExpression("im1b1 / im2b1"); // Sub-test 2 (Edge Effect Handling) filter->Update(); // if (filter->GetNumberOfOutputs() != 2) ImageType::Pointer output1 = filter->GetOutput(0); ImageType::Pointer output2 = filter->GetOutput(1); std::cout << "\n--- Standard Use\n"; std::cout << "Parsed Expression : " << filter->GetExpression(0) << std::endl; // Sub-test 1 IteratorType itoutput1(output1, region); for (it1.GoToBegin(), it2.GoToBegin(), it3.GoToBegin(), itoutput1.GoToBegin(); !it1.IsAtEnd(); ++it1, ++it2, ++it3, ++itoutput1) { ImageType::IndexType i1 = it1.GetIndex(); ImageType::IndexType i2 = it2.GetIndex(); ImageType::IndexType i3 = it3.GetIndex(); PixelType px1(D1), px2(D2), px3(D3); px1[0] = (i1[0] + i1[1] - 50); px1[1] = (i1[0] * i1[1] - 50); px1[2] = (i1[0] / (i1[1] + 1) + 5); px2[0] = (i2[0] * i2[1]); px3[0] = (i3[0] + i3[1] * i3[1]); double result1 = itoutput1.Get()[0], result2 = itoutput1.Get()[1], result3 = itoutput1.Get()[2]; double error1, error2, error3; double expected1 = std::cos(2 * otb::CONST_PI * px1[0]) / (2 * otb::CONST_PI * px2[0] + 3.38) * std::sin(otb::CONST_PI * px3[0]); double expected2 = std::cos(2 * otb::CONST_PI * px1[1]) / (2 * otb::CONST_PI * px2[0] + 3.38) * std::sin(otb::CONST_PI * px3[0]); double expected3 = std::cos(2 * otb::CONST_PI * px1[2]) / (2 * otb::CONST_PI * px2[0] + 3.38) * std::sin(otb::CONST_PI * px3[0]); /*std::cout << "Pixel_1 = " << it1.Get()[0] << " Pixel_2 = " << it2.Get()[0] << " Pixel_3 = " << it3.Get()[0] << " Result = " << itoutput1.Get()[0] << " Expected = " << expected1 << std::endl; */ error1 = (result1 - expected1) * (result1 - expected1) / abs(result1 + expected1); error2 = (result2 - expected2) * (result2 - expected2) / abs(result2 + expected2); error3 = (result3 - expected3) * (result3 - expected3) / abs(result3 + expected3); if ((error1 > 1E-9) || (error2 > 1E-9) || (error3 > 1E-9)) { itkGenericExceptionMacro(<< std::endl << "Error = " << error1 << " > 1E-9 -> TEST FAILLED" << std::endl << "Pixel_1 = " << it1.Get()[0] << " Pixel_2 = " << it2.Get()[0] << " Pixel_3 = " << it3.Get()[0] << " Result = " << result1 << " Expected = " << expected1 << std::endl << "Error = " << error2 << " > 1E-9 -> TEST FAILLED" << std::endl << "Pixel_1 = " << it1.Get()[1] << " Pixel_2 = " << it2.Get()[0] << " Pixel_3 = " << it3.Get()[0] << " Result = " << result2 << " Expected = " << expected2 << std::endl << "Error = " << error3 << " > 1E-9 -> TEST FAILLED" << std::endl << "Pixel_1 = " << it1.Get()[2] << " Pixel_2 = " << it2.Get()[0] << " Pixel_3 = " << it3.Get()[0] << " Result = " << result3 << " Expected = " << expected3 << std::endl); } } // Sub-test 2 /** Edge Effect Handling */ IteratorType itoutput2(output2, region); std::cout << "\n--- Edge Effect Handling\n"; std::cout << "- +/-inf section\n"; std::cout << "- nan section\n"; it1.GoToBegin(); it2.GoToBegin(); itoutput2.GoToBegin(); for (i = 1; i <= 50; ++i, ++it1, ++it2, ++itoutput2) { } if (vnl_math_isnan(itoutput2.Get()[0])) std::cout << "Pixel_1 = " << it1.Get() << " Pixel_2 = " << it2.Get() << " Result = " << itoutput2.Get() << " Expected = nan\n"; else itkGenericExceptionMacro(<< "\nError > Bad Edge Effect Handling -> Test Failled\n" << "Pixel_1 = " << it1.Get() << " Pixel_2 = " << it2.Get() << " Result = " << itoutput2.Get() << " Expected = nan\n"); std::cout << std::endl; return EXIT_SUCCESS; } int otbBandMathXImageFilterConv(int itkNotUsed(argc), char* argv[]) { const char* inputFilename = argv[1]; typedef otb::VectorImage<double, 2> ImageType; typedef ImageType::PixelType PixelType; typedef otb::BandMathXImageFilter<ImageType> FilterType; const unsigned int N = 100, D1 = 3, D2 = 1, D3 = 1; ImageType::SizeType size; size.Fill(N); ImageType::IndexType index; index.Fill(0); ImageType::RegionType region; region.SetSize(size); region.SetIndex(index); ImageType::Pointer image1 = ImageType::New(); ImageType::Pointer image2 = ImageType::New(); ImageType::Pointer image3 = ImageType::New(); image1->SetLargestPossibleRegion(region); image1->SetBufferedRegion(region); image1->SetRequestedRegion(region); image1->SetNumberOfComponentsPerPixel(D1); image1->Allocate(); image2->SetLargestPossibleRegion(region); image2->SetBufferedRegion(region); image2->SetRequestedRegion(region); image2->SetNumberOfComponentsPerPixel(D2); image2->Allocate(); image3->SetLargestPossibleRegion(region); image3->SetBufferedRegion(region); image3->SetRequestedRegion(region); image3->SetNumberOfComponentsPerPixel(D3); image3->Allocate(); typedef itk::ConstNeighborhoodIterator<ImageType> IteratorType; IteratorType::RadiusType radius; radius[0] = 1; // Size x direction radius[1] = 2; // Size y direction IteratorType it1(radius, image1, region); it1.NeedToUseBoundaryConditionOn(); IteratorType it2(radius, image2, region); it2.NeedToUseBoundaryConditionOn(); IteratorType it3(radius, image3, region); it3.NeedToUseBoundaryConditionOn(); PixelType::ValueType imageAb2Mini = itk::NumericTraits<PixelType::ValueType>::max(); PixelType::ValueType imageAb3Mean = 0.0, n = 0.0; PixelType::ValueType imageAb3Var = 0.0; PixelType::ValueType imageAb1Sum = 0.0; PixelType::ValueType im2b1Maxi = itk::NumericTraits<PixelType::ValueType>::min(); for (it1.GoToBegin(), it2.GoToBegin(), it3.GoToBegin(); !it1.IsAtEnd(); ++it1, ++it2, ++it3) { ImageType::IndexType i1 = it1.GetIndex(); ImageType::IndexType i2 = it2.GetIndex(); ImageType::IndexType i3 = it3.GetIndex(); it1.GetCenterPixel()[0] = i1[0] + i1[1] - 50; it1.GetCenterPixel()[1] = i1[0] * i1[1] - 50; it1.GetCenterPixel()[2] = i1[0] / (i1[1] + 1) + 5; it2.GetCenterPixel()[0] = i2[0] * i2[1]; it3.GetCenterPixel()[0] = i3[0] + i3[1] * i3[1]; // Minimum of im1 band 2 if (imageAb2Mini > it1.GetCenterPixel()[1]) imageAb2Mini = it1.GetCenterPixel()[1]; // Mean of im1 band 3 imageAb3Mean += it1.GetCenterPixel()[2]; n++; // Var of im1 band 3 imageAb3Var += std::pow(it1.GetCenterPixel()[2], 2.0); // Maximum of im2 band 1 if (im2b1Maxi < it2.GetCenterPixel()[0]) im2b1Maxi = it2.GetCenterPixel()[0]; // Sum of im1 band1 imageAb1Sum += it1.GetCenterPixel()[0]; } imageAb3Mean = imageAb3Mean / n; imageAb3Var = (n / (n - 1)) * (imageAb3Var / n - imageAb3Mean * imageAb3Mean); // unbiased FilterType::Pointer filter = FilterType::New(); std::cout << "Number Of Threads : " << filter->GetNumberOfThreads() << std::endl; double expo = 1.1; filter->SetNthInput(0, image1, "imageA"); filter->SetNthInput(1, image2); filter->SetNthInput(2, image3, "canal3"); // filter->SetMatrix("kernel1","{ 0.1 , 0.2 , 0.3; 0.4 , 0.5 , 0.6; 0.7 , 0.8 , 0.9; 1.0 , 1.1 , 1.2; 1.3 , 1.4 , 1.5 }"); // filter->SetConstant("expo",expo); // filter->SetExpression("conv(kernel1,imageAb1N3x5,imageAb2N3x5); im2b1^1.1; vcos(canal3); mean(imageAb2N3x3); var(imageAb2N3x3); median(imageAb2N3x3)"); filter->ImportContext(inputFilename); // Equivalent to three commands above filter->SetExpression( "(vmax(canal3b1N3x5)+vmin(canal3b1N3x5)) div {2.0} + {imageAb3Var} dv 2.0 + {imageAb2Mini / im2b1Maxi} mlt 3.4 + {imageAb3Mean / imageAb1Sum * " "imageAb3Var} pw 1.2 ; vect2scal(vacos({0.5}) + vasin({0.5}) + vatan({0.5})) > 2.0 ?{1}:{0}"); filter->Update(); if (filter->GetNumberOfOutputs() != 2) itkGenericExceptionMacro(<< "Wrong number of outputs."); ImageType::Pointer output1 = filter->GetOutput(0); ImageType::Pointer output2 = filter->GetOutput(1); if (output1->GetNumberOfComponentsPerPixel() != 7) itkGenericExceptionMacro(<< "Wrong number of components per pixel (input 1)."); if (output2->GetNumberOfComponentsPerPixel() != 2) itkGenericExceptionMacro(<< "Wrong number of components per pixel (input 2)."); std::cout << "\n--- Standard Use\n"; std::cout << "Parsed Expression 1 : " << filter->GetExpression(0) << std::endl; std::cout << "Parsed Expression 2 : " << filter->GetExpression(1) << std::endl; // Sub-test 1 IteratorType itoutput1(radius, output1, region); IteratorType itoutput2(radius, output2, region); for (it1.GoToBegin(), it2.GoToBegin(), it3.GoToBegin(), itoutput1.GoToBegin(), itoutput2.GoToBegin(); !it1.IsAtEnd(); ++it1, ++it2, ++it3, ++itoutput1, ++itoutput2) { PixelType px1(output1->GetNumberOfComponentsPerPixel()); PixelType px2(output2->GetNumberOfComponentsPerPixel()); float coefs[15] = {0.1f, 0.2f, 0.3f, 0.4f, 0.5f, 0.6f, 0.7f, 0.8f, 0.9f, 1.0f, 1.1f, 1.2f, 1.3f, 1.4f, 1.5f}; // expression 1 px1[0] = 0; for (unsigned int i = 0; i < it1.Size(); ++i) px1[0] += coefs[i] * it1.GetPixel(i)[0]; px1[1] = 0; for (unsigned int i = 0; i < it1.Size(); ++i) px1[1] += coefs[i] * it1.GetPixel(i)[1]; px1[2] = std::pow(it2.GetCenterPixel()[0], expo); px1[3] = std::cos(it3.GetCenterPixel()[0]); // mean var median std::vector<double> vect; for (int i = 3; i <= 11; i++) vect.push_back(it1.GetPixel(i)[1]); px1[4] = 0.0; for (unsigned int i = 0; i < vect.size(); i++) px1[4] += vect[i]; px1[4] /= ((double)vect.size()); // mean px1[5] = 0.0; for (unsigned int i = 0; i < vect.size(); i++) px1[5] += (vect[i] - px1[4]) * (vect[i] - px1[4]); px1[5] /= ((double)vect.size()); // var std::sort(vect.begin(), vect.end()); px1[6] = vect[(int)(vect.size() / 2.)]; // median // expression 2 std::vector<double> vect2; for (unsigned int i = 0; i < it3.Size(); i++) vect2.push_back(it3.GetPixel(i)[0]); std::sort(vect2.begin(), vect2.end()); px2[0] = (vect2.back() + vect2.front()) / 2.0 + imageAb3Var / 2.0 + (imageAb2Mini / im2b1Maxi) * 3.4 + std::pow(imageAb3Mean / imageAb1Sum * imageAb3Var, 1.2); if (std::acos(0.5) + std::asin(0.5) + std::atan(0.5) > 2.0) px2[1] = 1.0; else px2[1] = 0.0; // expression 1 double result1 = itoutput1.GetCenterPixel()[0], result2 = itoutput1.GetCenterPixel()[1], result3 = itoutput1.GetCenterPixel()[2], result4 = itoutput1.GetCenterPixel()[3], result5 = itoutput1.GetCenterPixel()[4], result6 = itoutput1.GetCenterPixel()[5], result7 = itoutput1.GetCenterPixel()[6]; double error1, error2, error3, error4, error5, error6, error7; double expected1 = px1[0], expected2 = px1[1], expected3 = px1[2], expected4 = px1[3], expected5 = px1[4], expected6 = px1[5], expected7 = px1[6]; error1 = (result1 - expected1) * (result1 - expected1) / (result1 + expected1); error2 = (result2 - expected2) * (result2 - expected2) / (result2 + expected2); error3 = (result3 - expected3) * (result3 - expected3) / (result3 + expected3); error4 = (result4 - expected4) * (result4 - expected4) / (result4 + expected4); error5 = (result5 - expected5) * (result5 - expected5) / (result5 + expected5); error6 = (result6 - expected6) * (result6 - expected6) / (result6 + expected6); error7 = (result7 - expected7) * (result7 - expected7) / (result7 + expected7); // expression 2 double result8 = itoutput2.GetCenterPixel()[0]; double result9 = itoutput2.GetCenterPixel()[1]; double expected8 = px2[0]; double expected9 = px2[1]; double error8 = (result8 - expected8) * (result8 - expected8) / (result8 + expected8); double error9 = (result9 - expected9) * (result9 - expected9) / (result9 + expected9); if ((error1 > 1E-9) || (error2 > 1E-9) || (error3 > 1E-9) || (error4 > 1E-9) || (error5 > 1E-9) || (error6 > 1E-9) || (error7 > 1E-9) || (error8 > 1E-9) || (error9 > 1E-9)) { itkGenericExceptionMacro(<< "TEST FAILLED" << std::endl << "Error1 = " << error1 << std::endl << " Result1 = " << result1 << " Expected1 = " << expected1 << std::endl << "Error2 = " << error2 << std::endl << " Result2 = " << result2 << " Expected2 = " << expected2 << std::endl << "Error3 = " << error3 << std::endl << " Result3 = " << result3 << " Expected3 = " << expected3 << std::endl << "Error4 = " << error4 << std::endl << " Result4 = " << result4 << " Expected4 = " << expected4 << std::endl << "Error5 = " << error5 << std::endl << " Result5 = " << result5 << " Expected5 = " << expected5 << std::endl << "Error6 = " << error6 << std::endl << " Result6 = " << result6 << " Expected6 = " << expected6 << std::endl << "Error7 = " << error7 << std::endl << " Result7 = " << result7 << " Expected7 = " << expected7 << std::endl << "Error8 = " << error8 << std::endl << " Result8 = " << result8 << " Expected8 = " << expected8 << std::endl << "Error9 = " << error9 << std::endl << " Result9 = " << result9 << " Expected9 = " << expected9 << std::endl); } } return EXIT_SUCCESS; } int otbBandMathXImageFilterTxt(int itkNotUsed(argc), char* argv[]) { const char* inputFilename = argv[1]; const char* outputFilename = argv[2]; typedef otb::VectorImage<double, 2> ImageType; typedef otb::BandMathXImageFilter<ImageType> FilterType; FilterType::Pointer filter = FilterType::New(); filter->ImportContext(inputFilename); filter->ExportContext(outputFilename); return EXIT_SUCCESS; } int otbBandMathXImageFilterWithIdx(int itkNotUsed(argc), char* argv[]) { const char* outfname1 = argv[1]; const char* outfname2 = argv[2]; typedef otb::VectorImage<double, 2> ImageType; typedef otb::BandMathXImageFilter<ImageType> FilterType; typedef otb::ImageFileWriter<ImageType> WriterType; const unsigned int N = 100, D1 = 1, D2 = 1, D3 = 1; ImageType::SizeType size; size.Fill(N); ImageType::IndexType index; index.Fill(0); ImageType::RegionType region; region.SetSize(size); region.SetIndex(index); ImageType::PointType origin; origin[0] = -25; origin[1] = -25; ImageType::SpacingType spacing; spacing[0] = 0.5; spacing[1] = 0.5; ImageType::Pointer image1 = ImageType::New(); ImageType::Pointer image2 = ImageType::New(); ImageType::Pointer image3 = ImageType::New(); image1->SetLargestPossibleRegion(region); image1->SetBufferedRegion(region); image1->SetRequestedRegion(region); image1->SetNumberOfComponentsPerPixel(D1); image1->Allocate(); image2->SetLargestPossibleRegion(region); image2->SetBufferedRegion(region); image2->SetRequestedRegion(region); image2->SetNumberOfComponentsPerPixel(D2); image2->Allocate(); image3->SetLargestPossibleRegion(region); image3->SetBufferedRegion(region); image3->SetRequestedRegion(region); image3->SetNumberOfComponentsPerPixel(D3); image3->Allocate(); typedef itk::ImageRegionIteratorWithIndex<ImageType> IteratorType; IteratorType it1(image1, region); IteratorType it2(image2, region); IteratorType it3(image3, region); image1->SetOrigin(origin); image1->SetSignedSpacing(spacing); image2->SetOrigin(origin); image2->SetSignedSpacing(spacing); image3->SetOrigin(origin); image3->SetSignedSpacing(spacing); for (it1.GoToBegin(), it2.GoToBegin(), it3.GoToBegin(); !it1.IsAtEnd(); ++it1, ++it2, ++it3) { ImageType::IndexType i1 = it1.GetIndex(); ImageType::IndexType i2 = it2.GetIndex(); ImageType::IndexType i3 = it3.GetIndex(); it1.Get()[0] = i1[0] + i1[1] - 50; it2.Get()[0] = i2[0] * i2[1]; it3.Get()[0] = i3[0] + i3[1] * i3[1]; } FilterType::Pointer filter = FilterType::New(); std::cout << "Number Of Threads : " << filter->GetNumberOfThreads() << std::endl; filter->SetNthInput(0, image1); filter->SetNthInput(1, image2); filter->SetNthInput(2, image3); filter->SetExpression("(sqrt(idxX*idxX+idxY*idxY) < 50) ? im1b1 : im2b1"); filter->SetExpression("(sqrt(im2PhyX*im2PhyX+im2PhyY*im2PhyY) < 25) ? im2b1 : im3b1"); WriterType::Pointer writer = WriterType::New(); writer->SetInput(filter->GetOutput(0)); writer->SetFileName(outfname1); writer->Update(); WriterType::Pointer writer2 = WriterType::New(); writer2->SetInput(filter->GetOutput(1)); writer2->SetFileName(outfname2); writer2->Update(); return EXIT_SUCCESS; } int otbBandMathXImageFilterBandsFailures(int itkNotUsed(argc), char* itkNotUsed(argv)[]) { typedef otb::VectorImage<double, 2> ImageType; typedef otb::BandMathXImageFilter<ImageType> FilterType; const unsigned int N = 100, D1 = 3; ImageType::SizeType size; size.Fill(N); ImageType::IndexType index; index.Fill(0); ImageType::RegionType region; region.SetSize(size); region.SetIndex(index); ImageType::Pointer image = ImageType::New(); image->SetLargestPossibleRegion(region); image->SetBufferedRegion(region); image->SetRequestedRegion(region); image->SetNumberOfComponentsPerPixel(D1); image->Allocate(); FilterType::Pointer filter = FilterType::New(); filter->SetNthInput(0, image); std::vector<std::string> exps = { "bands(im1,{4,1})", "bands(im1,{1,-1})", "bands(im1,{1,2,3,1,2,3,0})" }; for ( std::string exp: exps ) { filter->SetExpression(exp); try { filter->Update(); throw ; } catch (::itk::RangeError& e) { std::cout << "INFO: Exception thrown as expected : " << e.what() << std::endl; filter->ClearExpression(); } catch (...) { itkGenericExceptionMacro(<< "TEST FAILLED: " << exp << "should have raise a RangeError exception" << std::endl); } } return EXIT_SUCCESS; }
/* ** nw.grainbang~.c ** ** MSP object ** sends out a single grains when it receives a bang ** 2001/07/18 started by Nathan Wolek ** ** Copyright © 2002,2014 by Nathan Wolek ** License: http://opensource.org/licenses/BSD-3-Clause ** */ #include "c74_msp.h" using namespace c74::max; //#define DEBUG //enable debugging messages #define OBJECT_NAME "nw.grainbang~" // name of the object /* for the assist method */ #define ASSIST_INLET 1 #define ASSIST_OUTLET 2 /* for the grain stage */ #define NEW_GRAIN 2 #define FINISH_GRAIN 1 #define NO_GRAIN 0 /* for direction flag */ #define FORWARD_GRAINS 0 #define REVERSE_GRAINS 1 /* for interpolation flag */ #define INTERP_OFF 0 #define INTERP_ON 1 static t_class *grainbang_class; // required global pointing to this class typedef struct _grainbang { t_pxobject x_obj; // <-- // sound buffer info t_symbol *snd_sym; t_buffer_ref *snd_buf_ptr; t_buffer_ref *next_snd_buf_ptr; //double snd_last_out; //removed 2005.02.02 //long snd_buf_length; //removed 2002.07.11 short snd_interp; // window buffer info t_symbol *win_sym; t_buffer_ref *win_buf_ptr; t_buffer_ref *next_win_buf_ptr; //double win_last_out; //removed 2005.02.02 //long win_buf_length; //removed 2002.07.11 short win_interp; // current grain info double grain_pos_start; // in samples double grain_length; // in milliseconds double grain_pitch; // as multiplier double grain_gain; // linear gain mult double grain_sound_length; // in milliseconds double win_step_size; // in samples double snd_step_size; // in samples double curr_win_pos; // in samples double curr_snd_pos; // in samples short grain_direction; // forward or reverse // defered grain info at control rate double next_grain_pos_start; // in milliseconds double next_grain_length; // in milliseconds double next_grain_pitch; // as multiplier double next_grain_gain; // linear gain mult short next_grain_direction; // forward or reverse // signal or control grain info short grain_pos_start_connected; // <-- short grain_length_connected; // <-- short grain_pitch_connected; // <-- short grain_gain_connected; // grain tracking info short grain_stage; long curr_count_samp; //long curr_grain_samp; //removed 2003.08.04 double output_sr; // <-- double output_1oversr; // <-- //overflow outlet, added 2002.10.23 void *out_overflow; // <-- } t_grainbang; void *grainbang_new(t_symbol *snd, t_symbol *win); void grainbang_perform64zero(t_grainbang *x, t_object *dsp64, double **ins, long numins, double **outs,long numouts, long vectorsize, long flags, void *userparam); void grainbang_perform64(t_grainbang *x, t_object *dsp64, double **ins, long numins, double **outs,long numouts, long vectorsize, long flags, void *userparam); void grainbang_dsp64(t_grainbang *x, t_object *dsp64, short *count, double samplerate, long maxvectorsize, long flags); void grainbang_setsnd(t_grainbang *x, t_symbol *s); void grainbang_setwin(t_grainbang *x, t_symbol *s); void grainbang_float(t_grainbang *x, double f); void grainbang_int(t_grainbang *x, long l); void grainbang_bang(t_grainbang *x); void grainbang_overflow(t_grainbang *x, t_symbol *s, short argc, t_atom argv); void grainbang_initGrain(t_grainbang *x, float in_pos_start, float in_length, float in_pitch_mult, float in_gain_mult); void grainbang_sndInterp(t_grainbang *x, long l); void grainbang_winInterp(t_grainbang *x, long l); void grainbang_reverse(t_grainbang *x, long l); void grainbang_assist(t_grainbang *x, t_object *b, long msg, long arg, char *s); void grainbang_getinfo(t_grainbang *x); double mcLinearInterp(float *in_array, long index_i, double index_frac, long in_size, short in_chans); t_symbol *ps_buffer; /******************************************************************************** int main(void) inputs: nothing description: called the first time the object is used in MAX environment; defines inlets, outlets and accepted messages returns: int ********************************************************************************/ int C74_EXPORT main(void) { t_class *c; c = class_new(OBJECT_NAME, (method)grainbang_new, (method)dsp_free, (short)sizeof(t_grainbang), 0L, A_SYM, A_SYM, 0); class_dspinit(c); // add standard functions to class /* bind method "grainbang_setsnd" to the 'setSound' message */ class_addmethod(c, (method)grainbang_setsnd, "setSound", A_SYM, 0); /* bind method "grainbang_setwin" to the 'setWin' message */ class_addmethod(c, (method)grainbang_setwin, "setWin", A_SYM, 0); /* bind method "grainbang_float" to incoming floats */ class_addmethod(c, (method)grainbang_float, "float", A_FLOAT, 0); /* bind method "grainbang_int" to incoming ints */ class_addmethod(c, (method)grainbang_int, "int", A_LONG, 0); /* bind method "grainbang_bang" to incoming bangs */ class_addmethod(c, (method)grainbang_bang, "bang", 0); /* bind method "grainbang_reverse" to the direction message */ class_addmethod(c, (method)grainbang_reverse, "reverse", A_LONG, 0); /* bind method "grainbang_sndInterp" to the sndInterp message */ class_addmethod(c, (method)grainbang_sndInterp, "sndInterp", A_LONG, 0); /* bind method "grainbang_winInterp" to the winInterp message */ class_addmethod(c, (method)grainbang_winInterp, "winInterp", A_LONG, 0); /* bind method "grainbang_assist" to the assistance message */ class_addmethod(c, (method)grainbang_assist, "assist", A_CANT, 0); /* bind method "grainbang_getinfo" to the getinfo message */ class_addmethod(c, (method)grainbang_getinfo, "getinfo", A_NOTHING, 0); /* bind method "grainbang_dsp64" to the dsp64 message */ class_addmethod(c, (method)grainbang_dsp64, "dsp64", A_CANT, 0); class_register(CLASS_BOX, c); // register the class w max grainbang_class = c; /* needed for 'buffer~' work, checks for validity of buffer specified */ ps_buffer = gensym("buffer~"); #ifdef DEBUG //object_post((t_object*)x, "%s: main function was called", OBJECT_NAME); #endif /* DEBUG */ return 0; } /******************************************************************************** void *grainbang_new(double initial_pos) inputs: *snd -- name of buffer holding sound *win -- name of buffer holding window description: called for each new instance of object in the MAX environment; defines inlets and outlets; sets variables and buffers returns: nothing ********************************************************************************/ void *grainbang_new(t_symbol *snd, t_symbol *win) { t_grainbang *x = (t_grainbang *) object_alloc((t_class*) grainbang_class); dsp_setup((t_pxobject *)x, 5); // five inlets x->out_overflow = outlet_new((t_pxobject *)x, "bang"); // overflow outlet outlet_new((t_pxobject *)x, "signal"); // sample count outlet outlet_new((t_pxobject *)x, "signal"); // signal ch2 outlet outlet_new((t_pxobject *)x, "signal"); // signal ch1 outlet /* set buffer names */ x->snd_sym = snd; x->win_sym = win; /* zero pointers */ x->snd_buf_ptr = x->next_snd_buf_ptr = NULL; x->win_buf_ptr = x->next_win_buf_ptr = NULL; /* setup variables */ x->grain_pos_start = x->next_grain_pos_start = 0.0; x->grain_length = x->next_grain_length = 50.0; x->grain_pitch = x->next_grain_pitch = 1.0; x->grain_gain = x->next_grain_gain = 1.0; x->grain_stage = NO_GRAIN; x->win_step_size = x->snd_step_size = 0.0; x->curr_win_pos = x->curr_snd_pos = 0.0; x->curr_count_samp = -1; /* set flags to defaults */ x->snd_interp = INTERP_ON; x->win_interp = INTERP_ON; x->grain_direction = x->next_grain_direction = FORWARD_GRAINS; x->x_obj.z_misc = Z_NO_INPLACE; /* return a pointer to the new object */ return (x); } /******************************************************************************** void grainbang_dsp64() inputs: x -- pointer to this object dsp64 -- signal chain to which object belongs count -- array detailing number of signals attached to each inlet samplerate -- number of samples per second maxvectorsize -- sample frames per vector of audio flags -- description: called when 64 bit DSP call chain is built; adds object to signal flow returns: nothing ********************************************************************************/ void grainbang_dsp64(t_grainbang *x, t_object *dsp64, short *count, double samplerate, long maxvectorsize, long flags) { #ifdef DEBUG object_post((t_object*)x, "%s: adding 64 bit perform method", OBJECT_NAME); #endif /* DEBUG */ /* set buffers */ grainbang_setsnd(x, x->snd_sym); grainbang_setwin(x, x->win_sym); /* test inlets for signal data */ x->grain_pos_start_connected = count[1]; x->grain_length_connected = count[2]; x->grain_pitch_connected = count[3]; x->grain_gain_connected = count[4]; // grab sample rate x->output_sr = samplerate; x->output_1oversr = 1.0 / x->output_sr; // set stage to no grain //x->grain_stage = NO_GRAIN; if (count[5]) { // if output connected.. #ifdef DEBUG object_post((t_object*)x, "%s: output is being computed", OBJECT_NAME); #endif /* DEBUG */ dsp_add64(dsp64, (t_object*)x, (t_perfroutine64)grainbang_perform64, 0, NULL); } else { // if not... #ifdef DEBUG object_post((t_object*)x, "%s: no output computed", OBJECT_NAME); #endif /* DEBUG */ } } /******************************************************************************** void *grainbang_perform64zero() inputs: x -- dsp64 -- ins -- numins -- outs -- numouts -- vectorsize -- flags -- userparam -- description: called at interrupt level to compute object's output at 64-bit, writes zeros to every outlet returns: nothing ********************************************************************************/ void grainbang_perform64zero(t_grainbang *x, t_object *dsp64, double **ins, long numins, double **outs, long numouts, long vectorsize, long flags, void *userparam) { for (auto channel=0; channel<numouts; ++channel) { for (auto i=0; i<vectorsize; ++i) outs[channel][i] = 0.0; } } /******************************************************************************** void *grainbang_perform64() inputs: x -- dsp64 -- ins -- numins -- outs -- numouts -- vectorsize -- flags -- userparam -- description: called at interrupt level to compute object's output at 64-bit returns: nothing ********************************************************************************/ void grainbang_perform64(t_grainbang *x, t_object *dsp64, double **ins, long numins, double **outs, long numouts, long vectorsize, long flags, void *userparam) { // local vars outlets and inlets double *in_sound_start = ins[1]; double *in_dur = ins[2]; double *in_sample_increment = ins[3]; double *in_gain = ins[4]; double *out_signal = outs[0]; double *out_signal2 = outs[1]; double *out_sample_count = outs[2]; // local vars for snd and win buffer t_buffer_obj *snd_object, *win_object; float *tab_s, *tab_w; double snd_out, snd_out2, win_out; long size_s, size_w, chan_s; // local vars for object vars and while loop double index_s, index_w, temp_index_frac; long n, count_samp, temp_index_int, temp_index_int_times_chan; double s_step_size, w_step_size, g_gain; short interp_s, interp_w, g_direction; // check to make sure buffers are loaded with proper file types if (x->x_obj.z_disabled) // and object is enabled goto out; if (x->snd_buf_ptr == NULL || (x->win_buf_ptr == NULL)) goto zero; // get sound buffer info snd_object = buffer_ref_getobject(x->snd_buf_ptr); tab_s = buffer_locksamples(snd_object); if (!tab_s) // buffer samples were not accessible goto zero; size_s = buffer_getframecount(snd_object); chan_s = buffer_getchannelcount(snd_object); // get window buffer info win_object = buffer_ref_getobject(x->win_buf_ptr); tab_w = buffer_locksamples(win_object); if (!tab_w) // buffer samples were not accessible goto zero; size_w = buffer_getframecount(win_object); // get snd and win index info index_s = x->curr_snd_pos; index_w = x->curr_win_pos; s_step_size = x->snd_step_size; w_step_size = x->win_step_size; // get grain options interp_s = x->snd_interp; interp_w = x->win_interp; g_gain = x->grain_gain; g_direction = x->grain_direction; // get history from last vector count_samp = x->curr_count_samp; n = vectorsize; while(n--) { // advance window index index_w += w_step_size; if (index_w > size_w) { // if we exceed the window size if (x->grain_stage == FINISH_GRAIN) { // and if the grain is sounding x->grain_stage = NO_GRAIN; count_samp = -1; } } // should we start a grain ? if (count_samp == -1) { // if sample count is -1... if (x->grain_stage == NEW_GRAIN) { // if bang... buffer_unlocksamples(snd_object); buffer_unlocksamples(win_object); grainbang_initGrain(x, *in_sound_start, *in_dur, *in_sample_increment, *in_gain); // get snd buffer info snd_object = buffer_ref_getobject(x->snd_buf_ptr); tab_s = buffer_locksamples(snd_object); if (!tab_s) { // buffer samples were not accessible *out_signal = 0.0; *out_signal2 = 0.0; *out_sample_count = (double)count_samp; goto advance_pointers; } size_s = buffer_getframecount(snd_object); // get win buffer info win_object = buffer_ref_getobject(x->win_buf_ptr); tab_w = buffer_locksamples(win_object); if (!tab_w) { // buffer samples were not accessible *out_signal = 0.0; *out_signal2 = 0.0; *out_sample_count = (double)count_samp; goto advance_pointers; } size_w = buffer_getframecount(win_object); // get snd and win index info index_s = x->curr_snd_pos; index_w = x->curr_win_pos; s_step_size = x->snd_step_size; w_step_size = x->win_step_size; // get grain options interp_s = x->snd_interp; interp_w = x->win_interp; g_gain = x->grain_gain; g_direction = x->grain_direction; // get history from last vector count_samp = x->curr_count_samp; // move to next stage x->grain_stage = FINISH_GRAIN; } else { // if not... *out_signal = 0.0; *out_signal2 = 0.0; *out_sample_count = (double)count_samp; goto advance_pointers; } } // if we made it here, then we will actually start counting count_samp++; // advance sound index if (g_direction == FORWARD_GRAINS) { index_s += s_step_size; // addition } else { // if REVERSE_GRAINS index_s -= s_step_size; // subtract } // wrap sound index if not within bounds while (index_s < 0.0) index_s += size_s; while (index_s >= size_s) index_s -= size_s; // WINDOW OUT // compute temporary vars for interpolation temp_index_int = (long)(index_w); // integer portion of index temp_index_frac = index_w - (double)temp_index_int; // fractional portion of index // get value from the win buffer samples if (interp_w == INTERP_ON) { win_out = mcLinearInterp(tab_w, temp_index_int, temp_index_frac, size_w, 1); } else { // if INTERP_OFF win_out = tab_w[temp_index_int]; } // SOUND OUT // compute temporary vars for interpolation temp_index_int = (long)(index_s); // integer portion of index temp_index_frac = index_s - (double)temp_index_int; // fractional portion of index temp_index_int_times_chan = temp_index_int * chan_s; // get value from the snd buffer samples if (interp_s == INTERP_ON) { snd_out = mcLinearInterp(tab_s, temp_index_int_times_chan, temp_index_frac, size_s, chan_s); snd_out2 = 0.; } else { // if INTERP_OFF snd_out = tab_s[temp_index_int_times_chan]; snd_out2 = 0.; } // OUTLETS // multiply snd_out by win_out by gain value *out_signal = snd_out * win_out * g_gain; *out_signal2 = snd_out2 * win_out * g_gain;; *out_sample_count = (double)count_samp; advance_pointers: // advance all pointers ++in_sound_start, ++in_dur, ++in_sample_increment, ++in_gain; ++out_signal, ++out_signal2, ++out_sample_count; } // update object history for next vector x->curr_snd_pos = index_s; x->curr_win_pos = index_w; x->curr_count_samp = count_samp; buffer_unlocksamples(snd_object); buffer_unlocksamples(win_object); return; // alternate blank output zero: n = vectorsize; while(n--) { *out_signal++ = 0.; *out_signal2++ = 0.; *out_sample_count++ = -1.; } out: return; } /******************************************************************************** void grainbang_initGrain() inputs: x -- pointer to this object in_pos_start -- offset within sampled buffer in_length -- length of grain in_pitch_mult -- sample playback speed, 1 = normal in_gain_mult -- scales gain output, 1 = no change description: initializes grain vars; called from perform method when bang is received returns: nothing ********************************************************************************/ void grainbang_initGrain(t_grainbang *x, float in_pos_start, float in_length, float in_pitch_mult, float in_gain_mult) { #ifdef DEBUG object_post((t_object*)x, "%s: initializing grain", OBJECT_NAME); #endif /* DEBUG */ t_buffer_obj *snd_object; t_buffer_obj *win_object; if (x->next_snd_buf_ptr != NULL) { //added 2002.07.24 x->snd_buf_ptr = x->next_snd_buf_ptr; x->next_snd_buf_ptr = NULL; //x->snd_last_out = 0.0; //removed 2005.02.02 #ifdef DEBUG object_post((t_object*)x, "%s: sound buffer pointer updated", OBJECT_NAME); #endif /* DEBUG */ } if (x->next_win_buf_ptr != NULL) { //added 2002.07.24 x->win_buf_ptr = x->next_win_buf_ptr; x->next_win_buf_ptr = NULL; //x->win_last_out = 0.0; //removed 2005.02.02 #ifdef DEBUG object_post((t_object*)x, "%s: window buffer pointer updated", OBJECT_NAME); #endif /* DEBUG */ } snd_object = buffer_ref_getobject(x->snd_buf_ptr); win_object = buffer_ref_getobject(x->win_buf_ptr); /* should input variables be at audio or control rate ? */ // temporarily stash here as milliseconds x->grain_pos_start = x->grain_pos_start_connected ? in_pos_start : x->next_grain_pos_start; x->grain_length = x->grain_length_connected ? in_length : x->next_grain_length; x->grain_pitch = x->grain_pitch_connected ? in_pitch_mult : x->next_grain_pitch; x->grain_gain = x->grain_gain_connected ? in_gain_mult : x->next_grain_gain; /* compute dependent variables */ // compute amount of sound file for grain x->grain_sound_length = x->grain_length * x->grain_pitch; if (x->grain_sound_length < 0.) x->grain_sound_length *= -1.; // needs to be positive to prevent buffer overruns // compute window buffer step size per vector sample x->win_step_size = (double)(buffer_getframecount(win_object)) / (x->grain_length * x->output_sr * 0.001); if (x->win_step_size < 0.) x->win_step_size *= -1.; // needs to be positive to prevent buffer overruns // compute sound buffer step size per vector sample x->snd_step_size = x->grain_pitch * buffer_getsamplerate(snd_object) * x->output_1oversr; if (x->snd_step_size < 0.) x->snd_step_size *= -1.; // needs to be positive to prevent buffer overruns // update direction option x->grain_direction = x->next_grain_direction; if (x->grain_direction == FORWARD_GRAINS) { // if forward... x->grain_pos_start = x->grain_pos_start * buffer_getmillisamplerate(snd_object); x->curr_snd_pos = x->grain_pos_start - x->snd_step_size; } else { // if reverse... x->grain_pos_start = (x->grain_pos_start + x->grain_sound_length) * buffer_getmillisamplerate(snd_object); x->curr_snd_pos = x->grain_pos_start + x->snd_step_size; } x->curr_win_pos = 0.0; // reset history x->curr_count_samp = -1; // send report out at beginning of grain ? #ifdef DEBUG object_post((t_object*)x, "%s: beginning of grain", OBJECT_NAME); object_post((t_object*)x, "%s: win step size = %f samps", OBJECT_NAME, x->win_step_size); object_post((t_object*)x, "%s: snd step size = %f samps", OBJECT_NAME, x->snd_step_size); #endif /* DEBUG */ } /******************************************************************************** void grainbang_setsnd(t_index *x, t_symbol *s) inputs: x -- pointer to this object s -- name of buffer to link description: links buffer holding the grain sound source returns: nothing ********************************************************************************/ void grainbang_setsnd(t_grainbang *x, t_symbol *s) { t_buffer_ref *b = buffer_ref_new((t_object*)x, s); if (buffer_ref_exists(b)) { t_buffer_obj *b_object = buffer_ref_getobject(b); if (buffer_getchannelcount(b_object) > 2) { object_error((t_object*)x, "%s: buffer~ > %s < must be mono or stereo", OBJECT_NAME, s->s_name); x->next_snd_buf_ptr = NULL; //added 2002.07.15 } else { if (x->snd_buf_ptr == NULL) { // if first buffer make current buffer x->snd_sym = s; x->snd_buf_ptr = b; //x->snd_last_out = 0.0; //removed 2005.02.02 #ifdef DEBUG object_post((t_object*)x, "%s: current sound set to buffer~ > %s <", OBJECT_NAME, s->s_name); #endif /* DEBUG */ } else { // defer to next buffer x->snd_sym = s; x->next_snd_buf_ptr = b; //x->snd_buf_length = b->b_frames; //removed 2002.07.11 //x->snd_last_out = 0.0; //removed 2002.07.24 #ifdef DEBUG object_post((t_object*)x, "%s: next sound set to buffer~ > %s <", OBJECT_NAME, s->s_name); #endif /* DEBUG */ } } } else { object_error((t_object*)x, "%s: no buffer~ * %s * found", OBJECT_NAME, s->s_name); x->next_snd_buf_ptr = NULL; } } /******************************************************************************** void grainbang_setwin(t_grainbang *x, t_symbol *s) inputs: x -- pointer to this object s -- name of buffer to link description: links buffer holding the grain window returns: nothing ********************************************************************************/ void grainbang_setwin(t_grainbang *x, t_symbol *s) { t_buffer_ref *b = buffer_ref_new((t_object*)x, s); if (buffer_ref_exists(b)) { t_buffer_obj *b_object = buffer_ref_getobject(b); if (buffer_getchannelcount(b_object) != 1) { object_error((t_object*)x, "%s: buffer~ > %s < must be mono", OBJECT_NAME, s->s_name); x->next_win_buf_ptr = NULL; //added 2002.07.15 } else { if (x->win_buf_ptr == NULL) { // if first buffer make current buffer x->win_sym = s; x->win_buf_ptr = b; //x->win_last_out = 0.0; //removed 2005.02.02 /* set current win position to 1 more than length */ x->curr_win_pos = 0.0; #ifdef DEBUG object_post((t_object*)x, "%s: current window set to buffer~ > %s <", OBJECT_NAME, s->s_name); #endif /* DEBUG */ } else { // else defer to next buffer x->win_sym = s; x->next_win_buf_ptr = b; //x->win_buf_length = b->b_frames; //removed 2002.07.11 //x->win_last_out = 0.0; //removed 2002.07.24 #ifdef DEBUG object_post((t_object*)x, "%s: next window set to buffer~ > %s <", OBJECT_NAME, s->s_name); #endif /* DEBUG */ } } } else { object_error((t_object*)x, "%s: no buffer~ > %s < found", OBJECT_NAME, s->s_name); x->next_win_buf_ptr = NULL; } } /******************************************************************************** void grainbang_float(t_grainbang *x, double f) inputs: x -- pointer to our object f -- value of float input description: handles floats sent to inlets; inlet 2 sets "next_grain_pos_start" variable; inlet 3 sets "next_grain_length" variable; inlet 4 sets "next_grain_pitch" variable; left inlet generates error message in max window returns: nothing ********************************************************************************/ void grainbang_float(t_grainbang *x, double f) { switch (x->x_obj.z_in) { case 1: x->next_grain_pos_start = f; break; case 2: x->next_grain_length = f; break; case 3: x->next_grain_pitch = f; break; case 4: x->next_grain_gain = f; break; default: object_post((t_object*)x, "%s: inlet does not accept floats", OBJECT_NAME); break; } } /******************************************************************************** void grainbang_int(t_grainbang *x, long l) inputs: x -- pointer to our object l -- value of int input description: handles ints sent to inlets; inlet 2 sets "next_grain_pos_start" variable; inlet 3 sets "next_grain_length" variable; inlet 4 sets "next_grain_pitch" variable; left inlet generates error message in max window returns: nothing ********************************************************************************/ void grainbang_int(t_grainbang *x, long l) { switch (x->x_obj.z_in) { case 1: x->next_grain_pos_start = (double)l; break; case 2: x->next_grain_length = (double)l; break; case 3: x->next_grain_pitch = (double)l; break; case 4: x->next_grain_gain = (double)l; break; default: object_post((t_object*)x, "%s: inlet does not accept ints", OBJECT_NAME); break; } } /******************************************************************************** void grainbang_bang(t_grainbang *x) inputs: x -- pointer to our object description: handles bangs sent to inlets; inlet 1 creates a grain; all others post an error to the max window returns: nothing ********************************************************************************/ void grainbang_bang(t_grainbang *x) { if (x->x_obj.z_in == 0) // if inlet 1 { if (sys_getdspstate() && x->grain_stage == NO_GRAIN) { x->grain_stage = NEW_GRAIN; #ifdef DEBUG object_post((t_object*)x, "%s: grain stage set to new grain", OBJECT_NAME); #endif // DEBUG // } else { defer(x, (method)grainbang_overflow,0L,0,0L); //added 2002.11.19 } } else // all other inlets { object_post((t_object*)x, "%s: that inlet does not accept bangs", OBJECT_NAME); } } /******************************************************************************** void grainbang_overflow(t_grainbang *x, t_symbol *s, short argc, t_atom argv) inputs: x -- pointer to our object description: handles bangs sent to overflow outlet; allows the method to be deferred returns: nothing ********************************************************************************/ void grainbang_overflow(t_grainbang *x, t_symbol *s, short argc, t_atom argv) { if (sys_getdspstate()) { outlet_bang(x->out_overflow); } } /******************************************************************************** void grainbang_sndInterp(t_grainbang *x, long l) inputs: x -- pointer to our object l -- flag value description: method called when "sndInterp" message is received; allows user to define whether interpolation is used in pulling values from the sound buffer; default is on returns: nothing ********************************************************************************/ void grainbang_sndInterp(t_grainbang *x, long l) { if (l == INTERP_OFF) { x->snd_interp = INTERP_OFF; #ifdef DEBUG object_post((t_object*)x, "%s: sndInterp is set to off", OBJECT_NAME); #endif // DEBUG // } else if (l == INTERP_ON) { x->snd_interp = INTERP_ON; #ifdef DEBUG object_post((t_object*)x, "%s: sndInterp is set to on", OBJECT_NAME); #endif // DEBUG // } else { object_error((t_object*)x, "%s: sndInterp message was not understood", OBJECT_NAME); } } /******************************************************************************** void grainbang_winInterp(t_grainbang *x, long l) inputs: x -- pointer to our object l -- flag value description: method called when "winInterp" message is received; allows user to define whether interpolation is used in pulling values from the window buffer; default is on returns: nothing ********************************************************************************/ void grainbang_winInterp(t_grainbang *x, long l) { if (l == INTERP_OFF) { x->win_interp = INTERP_OFF; #ifdef DEBUG object_post((t_object*)x, "%s: winInterp is set to off", OBJECT_NAME); #endif // DEBUG // } else if (l == INTERP_ON) { x->win_interp = INTERP_ON; #ifdef DEBUG object_post((t_object*)x, "%s: winInterp is set to on", OBJECT_NAME); #endif // DEBUG // } else { object_error((t_object*)x, "%s: winInterp was not understood", OBJECT_NAME); } } /******************************************************************************** void grainbang_reverse(t_grainbang *x, long l) inputs: x -- pointer to our object l -- flag value description: method called when "reverse" message is received; allows user to define whether sound is played forward or reverse; default is forward returns: nothing ********************************************************************************/ void grainbang_reverse(t_grainbang *x, long l) { if (l == REVERSE_GRAINS) { x->next_grain_direction = REVERSE_GRAINS; #ifdef DEBUG object_post((t_object*)x, "%s: reverse is set to on", OBJECT_NAME); #endif // DEBUG // } else if (l == FORWARD_GRAINS) { x->next_grain_direction = FORWARD_GRAINS; #ifdef DEBUG object_post((t_object*)x, "%s: reverse is set to off", OBJECT_NAME); #endif // DEBUG // } else { object_error((t_object*)x, "%s: reverse was not understood", OBJECT_NAME); } } /******************************************************************************** void grainbang_assist(t_grainbang *x, t_object *b, long msg, long arg, char *s) inputs: x -- pointer to our object b -- msg -- arg -- s -- description: method called when "assist" message is received; allows inlets and outlets to display assist messages as the mouse passes over them returns: nothing ********************************************************************************/ void grainbang_assist(t_grainbang *x, t_object *b, long msg, long arg, char *s) { if (msg==ASSIST_INLET) { switch (arg) { case 0: strcpy(s, "(bang) starts grain production"); break; case 1: strcpy(s, "(signal/float) sound buffer offset in ms"); break; case 2: strcpy(s, "(signal/float) grain duration in ms"); break; case 3: strcpy(s, "(signal/float) sample increment, 1.0 = unchanged"); break; case 4: strcpy(s, "(signal/float) gain multiplier, 1.0 = unchanged"); break; } } else if (msg==ASSIST_OUTLET) { switch (arg) { case 0: strcpy(s, "(signal) audio channel 1"); break; case 1: strcpy(s, "(signal) audio channel 2 COMING SOON"); break; case 2: strcpy(s, "(signal) sample count"); break; case 3: strcpy(s, "(bang) overflow"); break; } } #ifdef DEBUG object_post((t_object*)x, "%s: assist message displayed", OBJECT_NAME); #endif /* DEBUG */ } /******************************************************************************** void grainbang_getinfo(t_grainbang *x) inputs: x -- pointer to our object description: method called when "getinfo" message is received; displays info about object and lst update returns: nothing ********************************************************************************/ void grainbang_getinfo(t_grainbang *x) { object_post((t_object*)x, "%s object by Nathan Wolek", OBJECT_NAME); object_post((t_object*)x, "Last updated on %s - www.nathanwolek.com", __DATE__); } /******************************************************************************** double mcLinearInterp(float *in_array, long index_i, double index_frac, long in_size, short in_chans) inputs: *in_array -- name of array of input values index_i -- index value of sample, specific channel within interleaved frame index_frac -- fractional portion of index value for interp in_size -- size of input buffer to perform wrapping in_chans -- number of channels in input buffer description: performs linear interpolation on an input array and to return value of a fractional sample location returns: interpolated output ********************************************************************************/ double mcLinearInterp(float *in_array, long index_i, double index_frac, long in_size, short in_chans) { double out, sample1, sample2; long index_iP1 = index_i + in_chans; // corresponding sample in next frame // make sure that index_iP1 is not out of range while (index_iP1 >= in_size * in_chans) index_iP1 -= in_size; // get samples sample1 = (double)in_array[index_i]; sample2 = (double)in_array[index_iP1]; //linear interp formula out = sample1 + index_frac * (sample2 - sample1); return out; } more changes to support stereo buffers with grainbang. working without mono copy to outlet 2. issue #18 /* ** nw.grainbang~.c ** ** MSP object ** sends out a single grains when it receives a bang ** 2001/07/18 started by Nathan Wolek ** ** Copyright © 2002,2014 by Nathan Wolek ** License: http://opensource.org/licenses/BSD-3-Clause ** */ #include "c74_msp.h" using namespace c74::max; //#define DEBUG //enable debugging messages #define OBJECT_NAME "nw.grainbang~" // name of the object /* for the assist method */ #define ASSIST_INLET 1 #define ASSIST_OUTLET 2 /* for the grain stage */ #define NEW_GRAIN 2 #define FINISH_GRAIN 1 #define NO_GRAIN 0 /* for direction flag */ #define FORWARD_GRAINS 0 #define REVERSE_GRAINS 1 /* for interpolation flag */ #define INTERP_OFF 0 #define INTERP_ON 1 static t_class *grainbang_class; // required global pointing to this class typedef struct _grainbang { t_pxobject x_obj; // <-- // sound buffer info t_symbol *snd_sym; t_buffer_ref *snd_buf_ptr; t_buffer_ref *next_snd_buf_ptr; //double snd_last_out; //removed 2005.02.02 //long snd_buf_length; //removed 2002.07.11 short snd_interp; // window buffer info t_symbol *win_sym; t_buffer_ref *win_buf_ptr; t_buffer_ref *next_win_buf_ptr; //double win_last_out; //removed 2005.02.02 //long win_buf_length; //removed 2002.07.11 short win_interp; // current grain info double grain_pos_start; // in samples double grain_length; // in milliseconds double grain_pitch; // as multiplier double grain_gain; // linear gain mult double grain_sound_length; // in milliseconds double win_step_size; // in samples double snd_step_size; // in samples double curr_win_pos; // in samples double curr_snd_pos; // in samples short grain_direction; // forward or reverse // defered grain info at control rate double next_grain_pos_start; // in milliseconds double next_grain_length; // in milliseconds double next_grain_pitch; // as multiplier double next_grain_gain; // linear gain mult short next_grain_direction; // forward or reverse // signal or control grain info short grain_pos_start_connected; // <-- short grain_length_connected; // <-- short grain_pitch_connected; // <-- short grain_gain_connected; // grain tracking info short grain_stage; long curr_count_samp; //long curr_grain_samp; //removed 2003.08.04 double output_sr; // <-- double output_1oversr; // <-- //overflow outlet, added 2002.10.23 void *out_overflow; // <-- } t_grainbang; void *grainbang_new(t_symbol *snd, t_symbol *win); void grainbang_perform64zero(t_grainbang *x, t_object *dsp64, double **ins, long numins, double **outs,long numouts, long vectorsize, long flags, void *userparam); void grainbang_perform64(t_grainbang *x, t_object *dsp64, double **ins, long numins, double **outs,long numouts, long vectorsize, long flags, void *userparam); void grainbang_dsp64(t_grainbang *x, t_object *dsp64, short *count, double samplerate, long maxvectorsize, long flags); void grainbang_setsnd(t_grainbang *x, t_symbol *s); void grainbang_setwin(t_grainbang *x, t_symbol *s); void grainbang_float(t_grainbang *x, double f); void grainbang_int(t_grainbang *x, long l); void grainbang_bang(t_grainbang *x); void grainbang_overflow(t_grainbang *x, t_symbol *s, short argc, t_atom argv); void grainbang_initGrain(t_grainbang *x, float in_pos_start, float in_length, float in_pitch_mult, float in_gain_mult); void grainbang_sndInterp(t_grainbang *x, long l); void grainbang_winInterp(t_grainbang *x, long l); void grainbang_reverse(t_grainbang *x, long l); void grainbang_assist(t_grainbang *x, t_object *b, long msg, long arg, char *s); void grainbang_getinfo(t_grainbang *x); double mcLinearInterp(float *in_array, long index_i, double index_frac, long in_size, short in_chans); t_symbol *ps_buffer; /******************************************************************************** int main(void) inputs: nothing description: called the first time the object is used in MAX environment; defines inlets, outlets and accepted messages returns: int ********************************************************************************/ int C74_EXPORT main(void) { t_class *c; c = class_new(OBJECT_NAME, (method)grainbang_new, (method)dsp_free, (short)sizeof(t_grainbang), 0L, A_SYM, A_SYM, 0); class_dspinit(c); // add standard functions to class /* bind method "grainbang_setsnd" to the 'setSound' message */ class_addmethod(c, (method)grainbang_setsnd, "setSound", A_SYM, 0); /* bind method "grainbang_setwin" to the 'setWin' message */ class_addmethod(c, (method)grainbang_setwin, "setWin", A_SYM, 0); /* bind method "grainbang_float" to incoming floats */ class_addmethod(c, (method)grainbang_float, "float", A_FLOAT, 0); /* bind method "grainbang_int" to incoming ints */ class_addmethod(c, (method)grainbang_int, "int", A_LONG, 0); /* bind method "grainbang_bang" to incoming bangs */ class_addmethod(c, (method)grainbang_bang, "bang", 0); /* bind method "grainbang_reverse" to the direction message */ class_addmethod(c, (method)grainbang_reverse, "reverse", A_LONG, 0); /* bind method "grainbang_sndInterp" to the sndInterp message */ class_addmethod(c, (method)grainbang_sndInterp, "sndInterp", A_LONG, 0); /* bind method "grainbang_winInterp" to the winInterp message */ class_addmethod(c, (method)grainbang_winInterp, "winInterp", A_LONG, 0); /* bind method "grainbang_assist" to the assistance message */ class_addmethod(c, (method)grainbang_assist, "assist", A_CANT, 0); /* bind method "grainbang_getinfo" to the getinfo message */ class_addmethod(c, (method)grainbang_getinfo, "getinfo", A_NOTHING, 0); /* bind method "grainbang_dsp64" to the dsp64 message */ class_addmethod(c, (method)grainbang_dsp64, "dsp64", A_CANT, 0); class_register(CLASS_BOX, c); // register the class w max grainbang_class = c; /* needed for 'buffer~' work, checks for validity of buffer specified */ ps_buffer = gensym("buffer~"); #ifdef DEBUG //object_post((t_object*)x, "%s: main function was called", OBJECT_NAME); #endif /* DEBUG */ return 0; } /******************************************************************************** void *grainbang_new(double initial_pos) inputs: *snd -- name of buffer holding sound *win -- name of buffer holding window description: called for each new instance of object in the MAX environment; defines inlets and outlets; sets variables and buffers returns: nothing ********************************************************************************/ void *grainbang_new(t_symbol *snd, t_symbol *win) { t_grainbang *x = (t_grainbang *) object_alloc((t_class*) grainbang_class); dsp_setup((t_pxobject *)x, 5); // five inlets x->out_overflow = outlet_new((t_pxobject *)x, "bang"); // overflow outlet outlet_new((t_pxobject *)x, "signal"); // sample count outlet outlet_new((t_pxobject *)x, "signal"); // signal ch2 outlet outlet_new((t_pxobject *)x, "signal"); // signal ch1 outlet /* set buffer names */ x->snd_sym = snd; x->win_sym = win; /* zero pointers */ x->snd_buf_ptr = x->next_snd_buf_ptr = NULL; x->win_buf_ptr = x->next_win_buf_ptr = NULL; /* setup variables */ x->grain_pos_start = x->next_grain_pos_start = 0.0; x->grain_length = x->next_grain_length = 50.0; x->grain_pitch = x->next_grain_pitch = 1.0; x->grain_gain = x->next_grain_gain = 1.0; x->grain_stage = NO_GRAIN; x->win_step_size = x->snd_step_size = 0.0; x->curr_win_pos = x->curr_snd_pos = 0.0; x->curr_count_samp = -1; /* set flags to defaults */ x->snd_interp = INTERP_ON; x->win_interp = INTERP_ON; x->grain_direction = x->next_grain_direction = FORWARD_GRAINS; x->x_obj.z_misc = Z_NO_INPLACE; /* return a pointer to the new object */ return (x); } /******************************************************************************** void grainbang_dsp64() inputs: x -- pointer to this object dsp64 -- signal chain to which object belongs count -- array detailing number of signals attached to each inlet samplerate -- number of samples per second maxvectorsize -- sample frames per vector of audio flags -- description: called when 64 bit DSP call chain is built; adds object to signal flow returns: nothing ********************************************************************************/ void grainbang_dsp64(t_grainbang *x, t_object *dsp64, short *count, double samplerate, long maxvectorsize, long flags) { #ifdef DEBUG object_post((t_object*)x, "%s: adding 64 bit perform method", OBJECT_NAME); #endif /* DEBUG */ /* set buffers */ grainbang_setsnd(x, x->snd_sym); grainbang_setwin(x, x->win_sym); /* test inlets for signal data */ x->grain_pos_start_connected = count[1]; x->grain_length_connected = count[2]; x->grain_pitch_connected = count[3]; x->grain_gain_connected = count[4]; // grab sample rate x->output_sr = samplerate; x->output_1oversr = 1.0 / x->output_sr; // set stage to no grain //x->grain_stage = NO_GRAIN; if (count[5]) { // if output connected.. #ifdef DEBUG object_post((t_object*)x, "%s: output is being computed", OBJECT_NAME); #endif /* DEBUG */ dsp_add64(dsp64, (t_object*)x, (t_perfroutine64)grainbang_perform64, 0, NULL); } else { // if not... #ifdef DEBUG object_post((t_object*)x, "%s: no output computed", OBJECT_NAME); #endif /* DEBUG */ } } /******************************************************************************** void *grainbang_perform64zero() inputs: x -- dsp64 -- ins -- numins -- outs -- numouts -- vectorsize -- flags -- userparam -- description: called at interrupt level to compute object's output at 64-bit, writes zeros to every outlet returns: nothing ********************************************************************************/ void grainbang_perform64zero(t_grainbang *x, t_object *dsp64, double **ins, long numins, double **outs, long numouts, long vectorsize, long flags, void *userparam) { for (auto channel=0; channel<numouts; ++channel) { for (auto i=0; i<vectorsize; ++i) outs[channel][i] = 0.0; } } /******************************************************************************** void *grainbang_perform64() inputs: x -- dsp64 -- ins -- numins -- outs -- numouts -- vectorsize -- flags -- userparam -- description: called at interrupt level to compute object's output at 64-bit returns: nothing ********************************************************************************/ void grainbang_perform64(t_grainbang *x, t_object *dsp64, double **ins, long numins, double **outs, long numouts, long vectorsize, long flags, void *userparam) { // local vars outlets and inlets double *in_sound_start = ins[1]; double *in_dur = ins[2]; double *in_sample_increment = ins[3]; double *in_gain = ins[4]; double *out_signal = outs[0]; double *out_signal2 = outs[1]; double *out_sample_count = outs[2]; // local vars for snd and win buffer t_buffer_obj *snd_object, *win_object; float *tab_s, *tab_w; double snd_out, snd_out2, win_out; long size_s, size_w, chan_s; // local vars for object vars and while loop double index_s, index_w, temp_index_frac; long n, count_samp, temp_index_int, temp_index_int_times_chan; double s_step_size, w_step_size, g_gain; short interp_s, interp_w, g_direction; // check to make sure buffers are loaded with proper file types if (x->x_obj.z_disabled) // and object is enabled goto out; if (x->snd_buf_ptr == NULL || (x->win_buf_ptr == NULL)) goto zero; // get sound buffer info snd_object = buffer_ref_getobject(x->snd_buf_ptr); tab_s = buffer_locksamples(snd_object); if (!tab_s) // buffer samples were not accessible goto zero; size_s = buffer_getframecount(snd_object); chan_s = buffer_getchannelcount(snd_object); // get window buffer info win_object = buffer_ref_getobject(x->win_buf_ptr); tab_w = buffer_locksamples(win_object); if (!tab_w) // buffer samples were not accessible goto zero; size_w = buffer_getframecount(win_object); // get snd and win index info index_s = x->curr_snd_pos; index_w = x->curr_win_pos; s_step_size = x->snd_step_size; w_step_size = x->win_step_size; // get grain options interp_s = x->snd_interp; interp_w = x->win_interp; g_gain = x->grain_gain; g_direction = x->grain_direction; // get history from last vector count_samp = x->curr_count_samp; n = vectorsize; while(n--) { // advance window index index_w += w_step_size; if (index_w > size_w) { // if we exceed the window size if (x->grain_stage == FINISH_GRAIN) { // and if the grain is sounding x->grain_stage = NO_GRAIN; count_samp = -1; } } // should we start a grain ? if (count_samp == -1) { // if sample count is -1... if (x->grain_stage == NEW_GRAIN) { // if bang... buffer_unlocksamples(snd_object); buffer_unlocksamples(win_object); grainbang_initGrain(x, *in_sound_start, *in_dur, *in_sample_increment, *in_gain); // get snd buffer info snd_object = buffer_ref_getobject(x->snd_buf_ptr); tab_s = buffer_locksamples(snd_object); if (!tab_s) { // buffer samples were not accessible *out_signal = 0.0; *out_signal2 = 0.0; *out_sample_count = (double)count_samp; goto advance_pointers; } size_s = buffer_getframecount(snd_object); // get win buffer info win_object = buffer_ref_getobject(x->win_buf_ptr); tab_w = buffer_locksamples(win_object); if (!tab_w) { // buffer samples were not accessible *out_signal = 0.0; *out_signal2 = 0.0; *out_sample_count = (double)count_samp; goto advance_pointers; } size_w = buffer_getframecount(win_object); // get snd and win index info index_s = x->curr_snd_pos; index_w = x->curr_win_pos; s_step_size = x->snd_step_size; w_step_size = x->win_step_size; // get grain options interp_s = x->snd_interp; interp_w = x->win_interp; g_gain = x->grain_gain; g_direction = x->grain_direction; // get history from last vector count_samp = x->curr_count_samp; // move to next stage x->grain_stage = FINISH_GRAIN; } else { // if not... *out_signal = 0.0; *out_signal2 = 0.0; *out_sample_count = (double)count_samp; goto advance_pointers; } } // if we made it here, then we will actually start counting count_samp++; // advance sound index if (g_direction == FORWARD_GRAINS) { index_s += s_step_size; // addition } else { // if REVERSE_GRAINS index_s -= s_step_size; // subtract } // wrap sound index if not within bounds while (index_s < 0.0) index_s += size_s; while (index_s >= size_s) index_s -= size_s; // WINDOW OUT // compute temporary vars for interpolation temp_index_int = (long)(index_w); // integer portion of index temp_index_frac = index_w - (double)temp_index_int; // fractional portion of index // get value from the win buffer samples if (interp_w == INTERP_ON) { win_out = mcLinearInterp(tab_w, temp_index_int, temp_index_frac, size_w, 1); } else { // if INTERP_OFF win_out = tab_w[temp_index_int]; } // SOUND OUT // compute temporary vars for interpolation temp_index_int = (long)(index_s); // integer portion of index temp_index_frac = index_s - (double)temp_index_int; // fractional portion of index temp_index_int_times_chan = temp_index_int * chan_s; // get value from the snd buffer samples if (interp_s == INTERP_ON) { snd_out = mcLinearInterp(tab_s, temp_index_int_times_chan, temp_index_frac, size_s, chan_s); snd_out2 = (chan_s == 2) ? mcLinearInterp(tab_s, temp_index_int_times_chan + 1, temp_index_frac, size_s, chan_s) : 0.; } else { // if INTERP_OFF snd_out = tab_s[temp_index_int_times_chan]; snd_out2 = (chan_s == 2) ? tab_s[temp_index_int_times_chan + 1] : 0.; } // OUTLETS // multiply snd_out by win_out by gain value *out_signal = snd_out * win_out * g_gain; *out_signal2 = snd_out2 * win_out * g_gain;; *out_sample_count = (double)count_samp; advance_pointers: // advance all pointers ++in_sound_start, ++in_dur, ++in_sample_increment, ++in_gain; ++out_signal, ++out_signal2, ++out_sample_count; } // update object history for next vector x->curr_snd_pos = index_s; x->curr_win_pos = index_w; x->curr_count_samp = count_samp; buffer_unlocksamples(snd_object); buffer_unlocksamples(win_object); return; // alternate blank output zero: n = vectorsize; while(n--) { *out_signal++ = 0.; *out_signal2++ = 0.; *out_sample_count++ = -1.; } out: return; } /******************************************************************************** void grainbang_initGrain() inputs: x -- pointer to this object in_pos_start -- offset within sampled buffer in_length -- length of grain in_pitch_mult -- sample playback speed, 1 = normal in_gain_mult -- scales gain output, 1 = no change description: initializes grain vars; called from perform method when bang is received returns: nothing ********************************************************************************/ void grainbang_initGrain(t_grainbang *x, float in_pos_start, float in_length, float in_pitch_mult, float in_gain_mult) { #ifdef DEBUG object_post((t_object*)x, "%s: initializing grain", OBJECT_NAME); #endif /* DEBUG */ t_buffer_obj *snd_object; t_buffer_obj *win_object; if (x->next_snd_buf_ptr != NULL) { //added 2002.07.24 x->snd_buf_ptr = x->next_snd_buf_ptr; x->next_snd_buf_ptr = NULL; //x->snd_last_out = 0.0; //removed 2005.02.02 #ifdef DEBUG object_post((t_object*)x, "%s: sound buffer pointer updated", OBJECT_NAME); #endif /* DEBUG */ } if (x->next_win_buf_ptr != NULL) { //added 2002.07.24 x->win_buf_ptr = x->next_win_buf_ptr; x->next_win_buf_ptr = NULL; //x->win_last_out = 0.0; //removed 2005.02.02 #ifdef DEBUG object_post((t_object*)x, "%s: window buffer pointer updated", OBJECT_NAME); #endif /* DEBUG */ } snd_object = buffer_ref_getobject(x->snd_buf_ptr); win_object = buffer_ref_getobject(x->win_buf_ptr); /* should input variables be at audio or control rate ? */ // temporarily stash here as milliseconds x->grain_pos_start = x->grain_pos_start_connected ? in_pos_start : x->next_grain_pos_start; x->grain_length = x->grain_length_connected ? in_length : x->next_grain_length; x->grain_pitch = x->grain_pitch_connected ? in_pitch_mult : x->next_grain_pitch; x->grain_gain = x->grain_gain_connected ? in_gain_mult : x->next_grain_gain; /* compute dependent variables */ // compute amount of sound file for grain x->grain_sound_length = x->grain_length * x->grain_pitch; if (x->grain_sound_length < 0.) x->grain_sound_length *= -1.; // needs to be positive to prevent buffer overruns // compute window buffer step size per vector sample x->win_step_size = (double)(buffer_getframecount(win_object)) / (x->grain_length * x->output_sr * 0.001); if (x->win_step_size < 0.) x->win_step_size *= -1.; // needs to be positive to prevent buffer overruns // compute sound buffer step size per vector sample x->snd_step_size = x->grain_pitch * buffer_getsamplerate(snd_object) * x->output_1oversr; if (x->snd_step_size < 0.) x->snd_step_size *= -1.; // needs to be positive to prevent buffer overruns // update direction option x->grain_direction = x->next_grain_direction; if (x->grain_direction == FORWARD_GRAINS) { // if forward... x->grain_pos_start = x->grain_pos_start * buffer_getmillisamplerate(snd_object); x->curr_snd_pos = x->grain_pos_start - x->snd_step_size; } else { // if reverse... x->grain_pos_start = (x->grain_pos_start + x->grain_sound_length) * buffer_getmillisamplerate(snd_object); x->curr_snd_pos = x->grain_pos_start + x->snd_step_size; } x->curr_win_pos = 0.0; // reset history x->curr_count_samp = -1; // send report out at beginning of grain ? #ifdef DEBUG object_post((t_object*)x, "%s: beginning of grain", OBJECT_NAME); object_post((t_object*)x, "%s: win step size = %f samps", OBJECT_NAME, x->win_step_size); object_post((t_object*)x, "%s: snd step size = %f samps", OBJECT_NAME, x->snd_step_size); #endif /* DEBUG */ } /******************************************************************************** void grainbang_setsnd(t_index *x, t_symbol *s) inputs: x -- pointer to this object s -- name of buffer to link description: links buffer holding the grain sound source returns: nothing ********************************************************************************/ void grainbang_setsnd(t_grainbang *x, t_symbol *s) { t_buffer_ref *b = buffer_ref_new((t_object*)x, s); if (buffer_ref_exists(b)) { t_buffer_obj *b_object = buffer_ref_getobject(b); if (buffer_getchannelcount(b_object) > 2) { object_error((t_object*)x, "%s: buffer~ > %s < must be mono or stereo", OBJECT_NAME, s->s_name); x->next_snd_buf_ptr = NULL; //added 2002.07.15 } else { if (x->snd_buf_ptr == NULL) { // if first buffer make current buffer x->snd_sym = s; x->snd_buf_ptr = b; //x->snd_last_out = 0.0; //removed 2005.02.02 #ifdef DEBUG object_post((t_object*)x, "%s: current sound set to buffer~ > %s <", OBJECT_NAME, s->s_name); #endif /* DEBUG */ } else { // defer to next buffer x->snd_sym = s; x->next_snd_buf_ptr = b; //x->snd_buf_length = b->b_frames; //removed 2002.07.11 //x->snd_last_out = 0.0; //removed 2002.07.24 #ifdef DEBUG object_post((t_object*)x, "%s: next sound set to buffer~ > %s <", OBJECT_NAME, s->s_name); #endif /* DEBUG */ } } } else { object_error((t_object*)x, "%s: no buffer~ * %s * found", OBJECT_NAME, s->s_name); x->next_snd_buf_ptr = NULL; } } /******************************************************************************** void grainbang_setwin(t_grainbang *x, t_symbol *s) inputs: x -- pointer to this object s -- name of buffer to link description: links buffer holding the grain window returns: nothing ********************************************************************************/ void grainbang_setwin(t_grainbang *x, t_symbol *s) { t_buffer_ref *b = buffer_ref_new((t_object*)x, s); if (buffer_ref_exists(b)) { t_buffer_obj *b_object = buffer_ref_getobject(b); if (buffer_getchannelcount(b_object) != 1) { object_error((t_object*)x, "%s: buffer~ > %s < must be mono", OBJECT_NAME, s->s_name); x->next_win_buf_ptr = NULL; //added 2002.07.15 } else { if (x->win_buf_ptr == NULL) { // if first buffer make current buffer x->win_sym = s; x->win_buf_ptr = b; //x->win_last_out = 0.0; //removed 2005.02.02 /* set current win position to 1 more than length */ x->curr_win_pos = 0.0; #ifdef DEBUG object_post((t_object*)x, "%s: current window set to buffer~ > %s <", OBJECT_NAME, s->s_name); #endif /* DEBUG */ } else { // else defer to next buffer x->win_sym = s; x->next_win_buf_ptr = b; //x->win_buf_length = b->b_frames; //removed 2002.07.11 //x->win_last_out = 0.0; //removed 2002.07.24 #ifdef DEBUG object_post((t_object*)x, "%s: next window set to buffer~ > %s <", OBJECT_NAME, s->s_name); #endif /* DEBUG */ } } } else { object_error((t_object*)x, "%s: no buffer~ > %s < found", OBJECT_NAME, s->s_name); x->next_win_buf_ptr = NULL; } } /******************************************************************************** void grainbang_float(t_grainbang *x, double f) inputs: x -- pointer to our object f -- value of float input description: handles floats sent to inlets; inlet 2 sets "next_grain_pos_start" variable; inlet 3 sets "next_grain_length" variable; inlet 4 sets "next_grain_pitch" variable; left inlet generates error message in max window returns: nothing ********************************************************************************/ void grainbang_float(t_grainbang *x, double f) { switch (x->x_obj.z_in) { case 1: x->next_grain_pos_start = f; break; case 2: x->next_grain_length = f; break; case 3: x->next_grain_pitch = f; break; case 4: x->next_grain_gain = f; break; default: object_post((t_object*)x, "%s: inlet does not accept floats", OBJECT_NAME); break; } } /******************************************************************************** void grainbang_int(t_grainbang *x, long l) inputs: x -- pointer to our object l -- value of int input description: handles ints sent to inlets; inlet 2 sets "next_grain_pos_start" variable; inlet 3 sets "next_grain_length" variable; inlet 4 sets "next_grain_pitch" variable; left inlet generates error message in max window returns: nothing ********************************************************************************/ void grainbang_int(t_grainbang *x, long l) { switch (x->x_obj.z_in) { case 1: x->next_grain_pos_start = (double)l; break; case 2: x->next_grain_length = (double)l; break; case 3: x->next_grain_pitch = (double)l; break; case 4: x->next_grain_gain = (double)l; break; default: object_post((t_object*)x, "%s: inlet does not accept ints", OBJECT_NAME); break; } } /******************************************************************************** void grainbang_bang(t_grainbang *x) inputs: x -- pointer to our object description: handles bangs sent to inlets; inlet 1 creates a grain; all others post an error to the max window returns: nothing ********************************************************************************/ void grainbang_bang(t_grainbang *x) { if (x->x_obj.z_in == 0) // if inlet 1 { if (sys_getdspstate() && x->grain_stage == NO_GRAIN) { x->grain_stage = NEW_GRAIN; #ifdef DEBUG object_post((t_object*)x, "%s: grain stage set to new grain", OBJECT_NAME); #endif // DEBUG // } else { defer(x, (method)grainbang_overflow,0L,0,0L); //added 2002.11.19 } } else // all other inlets { object_post((t_object*)x, "%s: that inlet does not accept bangs", OBJECT_NAME); } } /******************************************************************************** void grainbang_overflow(t_grainbang *x, t_symbol *s, short argc, t_atom argv) inputs: x -- pointer to our object description: handles bangs sent to overflow outlet; allows the method to be deferred returns: nothing ********************************************************************************/ void grainbang_overflow(t_grainbang *x, t_symbol *s, short argc, t_atom argv) { if (sys_getdspstate()) { outlet_bang(x->out_overflow); } } /******************************************************************************** void grainbang_sndInterp(t_grainbang *x, long l) inputs: x -- pointer to our object l -- flag value description: method called when "sndInterp" message is received; allows user to define whether interpolation is used in pulling values from the sound buffer; default is on returns: nothing ********************************************************************************/ void grainbang_sndInterp(t_grainbang *x, long l) { if (l == INTERP_OFF) { x->snd_interp = INTERP_OFF; #ifdef DEBUG object_post((t_object*)x, "%s: sndInterp is set to off", OBJECT_NAME); #endif // DEBUG // } else if (l == INTERP_ON) { x->snd_interp = INTERP_ON; #ifdef DEBUG object_post((t_object*)x, "%s: sndInterp is set to on", OBJECT_NAME); #endif // DEBUG // } else { object_error((t_object*)x, "%s: sndInterp message was not understood", OBJECT_NAME); } } /******************************************************************************** void grainbang_winInterp(t_grainbang *x, long l) inputs: x -- pointer to our object l -- flag value description: method called when "winInterp" message is received; allows user to define whether interpolation is used in pulling values from the window buffer; default is on returns: nothing ********************************************************************************/ void grainbang_winInterp(t_grainbang *x, long l) { if (l == INTERP_OFF) { x->win_interp = INTERP_OFF; #ifdef DEBUG object_post((t_object*)x, "%s: winInterp is set to off", OBJECT_NAME); #endif // DEBUG // } else if (l == INTERP_ON) { x->win_interp = INTERP_ON; #ifdef DEBUG object_post((t_object*)x, "%s: winInterp is set to on", OBJECT_NAME); #endif // DEBUG // } else { object_error((t_object*)x, "%s: winInterp was not understood", OBJECT_NAME); } } /******************************************************************************** void grainbang_reverse(t_grainbang *x, long l) inputs: x -- pointer to our object l -- flag value description: method called when "reverse" message is received; allows user to define whether sound is played forward or reverse; default is forward returns: nothing ********************************************************************************/ void grainbang_reverse(t_grainbang *x, long l) { if (l == REVERSE_GRAINS) { x->next_grain_direction = REVERSE_GRAINS; #ifdef DEBUG object_post((t_object*)x, "%s: reverse is set to on", OBJECT_NAME); #endif // DEBUG // } else if (l == FORWARD_GRAINS) { x->next_grain_direction = FORWARD_GRAINS; #ifdef DEBUG object_post((t_object*)x, "%s: reverse is set to off", OBJECT_NAME); #endif // DEBUG // } else { object_error((t_object*)x, "%s: reverse was not understood", OBJECT_NAME); } } /******************************************************************************** void grainbang_assist(t_grainbang *x, t_object *b, long msg, long arg, char *s) inputs: x -- pointer to our object b -- msg -- arg -- s -- description: method called when "assist" message is received; allows inlets and outlets to display assist messages as the mouse passes over them returns: nothing ********************************************************************************/ void grainbang_assist(t_grainbang *x, t_object *b, long msg, long arg, char *s) { if (msg==ASSIST_INLET) { switch (arg) { case 0: strcpy(s, "(bang) starts grain production"); break; case 1: strcpy(s, "(signal/float) sound buffer offset in ms"); break; case 2: strcpy(s, "(signal/float) grain duration in ms"); break; case 3: strcpy(s, "(signal/float) sample increment, 1.0 = unchanged"); break; case 4: strcpy(s, "(signal/float) gain multiplier, 1.0 = unchanged"); break; } } else if (msg==ASSIST_OUTLET) { switch (arg) { case 0: strcpy(s, "(signal) audio channel 1"); break; case 1: strcpy(s, "(signal) audio channel 2 COMING SOON"); break; case 2: strcpy(s, "(signal) sample count"); break; case 3: strcpy(s, "(bang) overflow"); break; } } #ifdef DEBUG object_post((t_object*)x, "%s: assist message displayed", OBJECT_NAME); #endif /* DEBUG */ } /******************************************************************************** void grainbang_getinfo(t_grainbang *x) inputs: x -- pointer to our object description: method called when "getinfo" message is received; displays info about object and lst update returns: nothing ********************************************************************************/ void grainbang_getinfo(t_grainbang *x) { object_post((t_object*)x, "%s object by Nathan Wolek", OBJECT_NAME); object_post((t_object*)x, "Last updated on %s - www.nathanwolek.com", __DATE__); } /******************************************************************************** double mcLinearInterp(float *in_array, long index_i, double index_frac, long in_size, short in_chans) inputs: *in_array -- name of array of input values index_i -- index value of sample, specific channel within interleaved frame index_frac -- fractional portion of index value for interp in_size -- size of input buffer to perform wrapping in_chans -- number of channels in input buffer description: performs linear interpolation on an input array and to return value of a fractional sample location returns: interpolated output ********************************************************************************/ double mcLinearInterp(float *in_array, long index_i, double index_frac, long in_size, short in_chans) { double out, sample1, sample2; long index_iP1 = index_i + in_chans; // corresponding sample in next frame // make sure that index_iP1 is not out of range while (index_iP1 >= in_size * in_chans) index_iP1 -= in_size; // get samples sample1 = (double)in_array[index_i]; sample2 = (double)in_array[index_iP1]; //linear interp formula out = sample1 + index_frac * (sample2 - sample1); return out; }
/************************************************************************************************** * Leading Charged Track+V0 Correlations.(Works for Real Data) * * Yuko Sekiguchi * Center for Nuclear Study(CNS) , University of Tokyo * * Email:y_sekiguchi@cns.s.u-tokyo.ac.jp * **************************************************************************************************/ #include "AliAnalysisManager.h" #include "TGrid.h" #include "AliLog.h" #include <TChain.h> #include <TDatabasePDG.h> #include <TFile.h> #include <TH1.h> #include <TH2.h> #include <TH3.h> #include <TList.h> #include <TLorentzVector.h> #include <TMap.h> #include <TMath.h> #include <TObjArray.h> #include <TPDGCode.h> #include <TParameter.h> #include <TROOT.h> #include <TRandom.h> #include <TTree.h> #include <TProfile.h> #include <TObjectTable.h> #include "AliAnalysisUtils.h" #include "AliAODTrack.h" #include "AliAODTracklets.h" #include "AliCFContainer.h" #include "AliGenEventHeader.h" #include "AliTHn.h" #include "AliAODEvent.h" #include "AliESDAD.h" #include "AliESDEvent.h" #include "AliVAD.h" #include "AliAODForwardMult.h" #include "AliAODVertex.h" #include "AliAODv0.h" #include "AliESDVertex.h" //#include "AliAODPid.h" #include "AliAODHandler.h" #include "AliAODInputHandler.h" #include "AliAODMCHeader.h" #include "AliAODMCParticle.h" #include "AliMCEventHandler.h" #include "AliMCEvent.h" #include "AliMCParticle.h" #include "AliStack.h" #include "AliAODcascade.h" #include "AliAnalyseLeadingTrackUE.h" #include "AliCentrality.h" #include "AliEventPoolManager.h" #include "AliExternalTrackParam.h" #include "AliInputEventHandler.h" #include "AliMultiplicity.h" #include "AliPID.h" #include "AliPIDResponse.h" #include "AliVParticle.h" #include "Riostream.h" /* #include "AliForwardSettings.h" #include "AliForwardFlowUtil.h" #include "AliForwardFlowResultStorage.h" #include "AliForwardGenericFramework.h" #include "AliForwardFlowRun2Task.h" #include "AliForwardQCumulantRun2.h" #include "AliForwardGenericFramework.h" */ //#include "AliFlowEventSimple.h" ///#include "AliFlowVector.h"/ //#include "AliFlowTrackSimple.h" //#include "AliAnalysisTaskMSP.h" //#include "AliFlowAnalysisWithMSP.h" #include "AliMultSelection.h" #include "AliFMDCorrSecondaryMap.h" #include "AliForwardCorrectionManager.h" //#include "AliForwardFlowResultStorage.h" //#include "AliForwardUtil.h" //#include "AliForwardTaskValidation.h" #include "AliAnalysisTaskSEpPbCorrelationsYS.h" using namespace std; ClassImp(AliAnalysisTaskSEpPbCorrelationsYS) ClassImp(AliAssociatedTrackYS) ClassImp(AliMixTrackYS) ClassImp(AliAssociatedVZEROYS) AliAnalysisTaskSEpPbCorrelationsYS::AliAnalysisTaskSEpPbCorrelationsYS() : AliAnalysisTaskSE(), fcollisiontype("pPb"), fDataType(kTRUE), frun2(kTRUE), fQA(kTRUE), fFMDcut(kTRUE), fFMDaddcut(kFALSE), fFMDcutmode(1), fptdiff(kFALSE), fmakehole(kFALSE), ffillcorrelation(kTRUE), fefficalib(kTRUE), fcuthighmult(0), fOnfly(kFALSE), fAnaMode("V0AV0C"), fasso("Phi"), fPID(kFALSE), fCentType("ZNA"), fNEntries(0), lCentrality(0), bSign(0), fZVertex(10.), fOutputList(0), fOutputList1(0), fOutputList2(0), fPIDResponse(0), ffilterbit(5), fnoClusters(70), fCutChargedDCAzMax(5), fCutChargedDCAxyMax(15), fPtMin(0.2), fPtMax(3.0), fEtaMax(0.8), fEtaMaxExtra(0.), fEtaMinExtra(-0.8), fEtaMaxV0(0.8), fEtaMinV0(0.), fdcaDaughtersToPrimVtx(0.06), fdcaBetweenDaughters(1.0), fRadiMin(0.5), fRadiMax(100), fcutcTauLam(30), fcutcTauK0(20), fcosMinK0s(0.97), fcosMinLambda(0.995), fMaxnSigmaTPCV0(5), hv0dcharge(0), fclustermin(70), fratiocluster(0.8), fEtaMaxDaughter(0.8), fEtaMinDaughter(0.), fHistMass_K0s(0), fHistMass_K0s_MC(0), fHistMass_Lambda(0), fHistMass_ALambda(0), fHistMass_ALambda_MC(0), fHistMassXiMinus(0), fHistMassXiPlus(0), fHistMassOmegaMinus(0), fHistMassOmegaPlus(0), fHistMass_bumpcorr(0), fHist_V0QA(0), fHist_CascadeQA(0), fHistMass_Lambda_MC(0), fEventCuts(0), fUtils(), fEvent(0), mcEvent(0), lPrimaryBestVtx(0), fPrimaryZVtx(0), fvzero(0), fPoolMgr(0), fPoolMgr1(0), poolmin(0), poolmax(0), fPoolMaxNEvents(2000), fPoolMinNTracks(50000), fMinEventsToMix(5), fNzVtxBins(0), fNCentBins(0), fMaxnSigmaTPCTOF(3.), fHistzvertex(0), fHistCentrality(0), fHistCentrality_beforecut(0), fHistV0vsTracks(0), fHistCentvsNv0mult(0), fHistV0multvsVz(0), fHistCentzvertex(0), fHistCentV0vsTracklets(0), fHistCentV0vsTrackletsbefore(0), fHistTraksvsVz(0), mixedDist(0), mixedDist2(0), fHistLeadQA(0), fHistPIDQA(0), fhistmcprim(0), fhmcprimvzeta(0), frefetaa(0), frefetac(0), frefvz(0), fhmcprimpdgcode(0), fh2_FMD_acceptance_prim(0), fh2_FMD_eta_phi_prim(0), fh2_FMD_acceptance(0), fh2_ITS_acceptance(0), fh2_SPD_multcorr(0), fh2_SPDV0_multcorr(0), fh2_SPDtrack_multcorr(0), fhtrackletsdphi(0), fh2_FMD_eta_phi(0), fh2_FMD_eta_phi_aftercut(0), fHist_NeventRun(0), fHist_V0AMultRun(0), fHist_V0CMultRun(0), fHist_FMDAMultRun(0), fHist_FMDCMultRun(0), fhistfmdphiacc(0), fhFMDmultchannel(0), fhistfmd(0), fhistits(0), fhSecFMD(0), fOutliers(0), fFMDV0(0), fFMDV0_post(0), fFMDV0A(0), fFMDV0A_post(0), fFMDV0C(0), fFMDV0C_post(0), fFMDV0same(0), fFMDV0same_post(0), fFMDV0Asame(0), fFMDV0Asame_post(0), fFMDV0Csame(0), fFMDV0Csame_post(0), fHist_vzeromult(0), fHist_vzeromultEqweighted(0), fHist2dmult(0), fHistVZERO(0), fHist_Stat(0), fHist_V0Stat(0), fHistPhiDTPCNSig(0), fHistPhiDTOFNSig(0), fHistPhiDTPCTOFNSig(0), fHistMass_PhiMeson(0), fHistMass_PhiMeson_MIX(0), fHist_PhiQA(0), fHistTriggerTrack(0), fHistReconstTrack(0), fHistTriggerTrackMix(0), fHistReconstTrackMix(0), fHistQna(0), fHistQnc(0), fHistQn(0), fHistQna_VZERO(0), fHistQnc_VZERO(0), fHistQn_VZERO(0), fHistVn(0), SP_TPCATPCC(0), SP_TPCATPCC_default(0), SP_V0AV0C_default(0), SP_V0ATPC_default(0), SP_V0CTPC_default(0), fHist_V0AV0C(0), fHist_V0ATPC(0), fHist_V0CTPC(0), SP_uTPCA(0), SP_uTPCC(0){ for (Int_t iBin = 0; iBin < 100; iBin++) { fZvtxBins[iBin] = 0.; fCentBins[iBin] = 0.; } for (Int_t i = 0; i < 3; i++) { tPrimaryVtxPosition[i] = 0; } for (Int_t i = 0; i < 6; i++) { fHistPosNsig[i] = 0; fHistNegNsig[i] = 0; fHistPosNsigQA[i] = 0; fHist_AP[i] = 0; } for(Int_t i=0;i<3;i++){ fh3NegNsig[i]=0; fh3PosNsig[i]=0; } for (Int_t i = 0; i < 6; i++) { fHistNsig[i]=0; fHistNsigcorr[i]=0; } for (Int_t i = 0; i < 4; i++) { fHistQAQB[i]=0; fHistQAQB_VZERO[i]=0; fHistCorrQna[i]=0; fHistCorrQnc[i]=0; } for (Int_t i = 0; i < 8; i++) { SP_uTPC_PP[i]=0; SP_uTPC[i]=0; SP_uTPC1[i]=0; SP_uTPC2[i]=0; SP_uTPC3[i]=0; SP_uVZEROA_PP[i]=0; SP_uVZEROA[i]=0; SP_uVZEROA1[i]=0; SP_uVZEROA2[i]=0; SP_uVZEROA3[i]=0; SP_uVZEROC_PP[i]=0; SP_uVZEROC[i]=0; SP_uVZEROC1[i]=0; SP_uVZEROC2[i]=0; SP_uVZEROC3[i]=0; } for(Int_t i=0;i<4;i++){ fhrefetaFMD[i]=0; fhrefphiFMD[i]=0; } for(Int_t i=0;i<10;i++){ fhcorr[i]=0; } for(Int_t i=0;i<31;i++){ fhFMDmult_runbyrun_cside[i]=0; } for(Int_t i=0;i<65;i++){ fhFMDmult_runbyrun_aside[i]=0; } } AliAnalysisTaskSEpPbCorrelationsYS::AliAnalysisTaskSEpPbCorrelationsYS(const char *name) : AliAnalysisTaskSE(name), fcollisiontype("pPb"), fDataType(kTRUE), frun2(kTRUE), fQA(kTRUE), fFMDcut(kTRUE), fFMDaddcut(kFALSE), fFMDcutmode(1), fptdiff(kFALSE), fmakehole(kFALSE), ffillcorrelation(kTRUE), fefficalib(kTRUE), fcuthighmult(0), fOnfly(kFALSE), fAnaMode("V0AV0C"), fasso("Phi"), fPID(kFALSE), fCentType("ZNA"), fNEntries(0), lCentrality(0), bSign(0), fZVertex(10.), fOutputList(0), fOutputList1(0), fOutputList2(0), fPIDResponse(0), ffilterbit(5), fnoClusters(70), fCutChargedDCAzMax(5), fCutChargedDCAxyMax(15), fPtMin(0.2), fPtMax(3.0), fEtaMax(0.8), fEtaMaxExtra(0.), fEtaMinExtra(-0.8), fEtaMaxV0(0.8), fEtaMinV0(0.), fdcaDaughtersToPrimVtx(0.06), fdcaBetweenDaughters(1.0), fRadiMin(0.5), fRadiMax(100), fcutcTauLam(30), fcutcTauK0(20), fcosMinK0s(0.97), fcosMinLambda(0.995), fMaxnSigmaTPCV0(5), hv0dcharge(0), fclustermin(70), fratiocluster(0.8), fEtaMaxDaughter(0.8), fEtaMinDaughter(0.), fHistMass_K0s(0), fHistMass_K0s_MC(0), fHistMass_Lambda(0), fHistMass_ALambda(0), fHistMass_ALambda_MC(0), fHistMassXiMinus(0), fHistMassXiPlus(0), fHistMassOmegaMinus(0), fHistMassOmegaPlus(0), fHistMass_bumpcorr(0), fHist_V0QA(0), fHist_CascadeQA(0), fHistMass_Lambda_MC(0), fEventCuts(0), fUtils(), fEvent(0), mcEvent(0), lPrimaryBestVtx(0), fPrimaryZVtx(0), fvzero(0), fPoolMgr(0), fPoolMgr1(0), poolmin(0), poolmax(0), fPoolMaxNEvents(2000), fPoolMinNTracks(50000), fMinEventsToMix(5), fNzVtxBins(0), fNCentBins(0), fMaxnSigmaTPCTOF(3.), fHistzvertex(0), fHistCentrality(0), fHistCentrality_beforecut(0), fHistV0vsTracks(0), fHistCentvsNv0mult(0), fHistV0multvsVz(0), fHistCentzvertex(0), fHistCentV0vsTracklets(0), fHistCentV0vsTrackletsbefore(0), fHistTraksvsVz(0), mixedDist(0), mixedDist2(0), fHistLeadQA(0), fHistPIDQA(0), fhistmcprim(0), fhmcprimvzeta(0), frefetaa(0), frefetac(0), frefvz(0), fhmcprimpdgcode(0), fh2_FMD_acceptance_prim(0), fh2_FMD_eta_phi_prim(0), fh2_FMD_acceptance(0), fh2_ITS_acceptance(0), fh2_SPD_multcorr(0), fh2_SPDV0_multcorr(0), fh2_SPDtrack_multcorr(0), fhtrackletsdphi(0), fh2_FMD_eta_phi(0), fh2_FMD_eta_phi_aftercut(0), fHist_NeventRun(0), fHist_V0AMultRun(0), fHist_V0CMultRun(0), fHist_FMDAMultRun(0), fHist_FMDCMultRun(0), fhistfmdphiacc(0), fhFMDmultchannel(0), fhistfmd(0), fhistits(0), fhSecFMD(0), fOutliers(0), fFMDV0(0), fFMDV0_post(0), fFMDV0A(0), fFMDV0A_post(0), fFMDV0C(0), fFMDV0C_post(0), fFMDV0same(0), fFMDV0same_post(0), fFMDV0Asame(0), fFMDV0Asame_post(0), fFMDV0Csame(0), fFMDV0Csame_post(0), fHist_vzeromult(0), fHist_vzeromultEqweighted(0), fHist2dmult(0), fHistVZERO(0), fHist_Stat(0), fHist_V0Stat(0), fHistPhiDTPCNSig(0), fHistPhiDTOFNSig(0), fHistPhiDTPCTOFNSig(0), fHistMass_PhiMeson(0), fHistMass_PhiMeson_MIX(0), fHist_PhiQA(0), fHistTriggerTrack(0), fHistReconstTrack(0), fHistTriggerTrackMix(0), fHistReconstTrackMix(0), fHistQna(0), fHistQnc(0), fHistQn(0), fHistQna_VZERO(0), fHistQnc_VZERO(0), fHistQn_VZERO(0), fHistVn(0), SP_TPCATPCC(0), SP_TPCATPCC_default(0), SP_V0AV0C_default(0), SP_V0ATPC_default(0), SP_V0CTPC_default(0), fHist_V0AV0C(0), fHist_V0ATPC(0), fHist_V0CTPC(0), SP_uTPCA(0), SP_uTPCC(0){ for (Int_t iBin = 0; iBin < 100; iBin++) { fZvtxBins[iBin] = 0.; fCentBins[iBin] = 0.; } for (Int_t i = 0; i < 3; i++) { tPrimaryVtxPosition[i] = 0; } for (Int_t i = 0; i < 6; i++) { fHistPosNsig[i] = 0; fHistNegNsig[i] = 0; fHistPosNsigQA[i] = 0 ; fHist_AP[i] = 0; } for(Int_t i=0;i<3;i++){ fh3NegNsig[i]=0; fh3PosNsig[i]=0; } for (Int_t i = 0; i < 6; i++) { fHistNsig[i] = 0; fHistNsigcorr[i]=0; } for (Int_t i = 0; i < 4; i++) { fHistQAQB[i]=0; fHistQAQB_VZERO[i]=0; fHistCorrQna[i]=0; fHistCorrQnc[i]=0; } for (Int_t i = 0; i < 8; i++) { SP_uTPC_PP[i]=0; SP_uTPC[i]=0; SP_uTPC1[i]=0; SP_uTPC2[i]=0; SP_uTPC3[i]=0; SP_uVZEROA_PP[i]=0; SP_uVZEROA[i]=0; SP_uVZEROA1[i]=0; SP_uVZEROA2[i]=0; SP_uVZEROA3[i]=0; SP_uVZEROC_PP[i]=0; SP_uVZEROC[i]=0; SP_uVZEROC1[i]=0; SP_uVZEROC2[i]=0; SP_uVZEROC3[i]=0; } for(Int_t i=0;i<4;i++){ fhrefetaFMD[i]=0; fhrefphiFMD[i]=0; } for(Int_t i=0;i<10;i++){ fhcorr[i]=0; } for(Int_t i=0;i<31;i++){ fhFMDmult_runbyrun_cside[i]=0; } for(Int_t i=0;i<65;i++){ fhFMDmult_runbyrun_aside[i]=0; } // DefineInput(1, AliForwardTaskValidation::Class()); DefineOutput(1, TList::Class()); DefineOutput(2, TList::Class()); DefineOutput(3, TList::Class()); } AliAnalysisTaskSEpPbCorrelationsYS::~AliAnalysisTaskSEpPbCorrelationsYS() { if (fOutputList && !AliAnalysisManager::GetAnalysisManager()->IsProofMode()) { delete fOutputList; fOutputList = 0x0; } if (fOutputList1 && !AliAnalysisManager::GetAnalysisManager()->IsProofMode()) { delete fOutputList1; fOutputList1 = 0x0; } if (fOutputList2 && !AliAnalysisManager::GetAnalysisManager()->IsProofMode()) { delete fOutputList2; fOutputList2 = 0x0; } if (fPIDResponse) { delete fPIDResponse; fPIDResponse = 0; } } void AliAnalysisTaskSEpPbCorrelationsYS::UserCreateOutputObjects() { fOutputList = new TList(); fOutputList->SetOwner(kTRUE); fOutputList->SetName("global"); DefineGeneralOutput(); PostData(1, fOutputList); fOutputList1 = new TList(); fOutputList1->SetOwner(kTRUE); fOutputList1->SetName("anahistos"); DefineCorrOutput(); DefineVZEROOutput(); PostData(2, fOutputList1); fOutputList2 = new TList(); fOutputList2->SetOwner(kTRUE); fOutputList2->SetName("QA"); DefinedQAHistos(); PostData(3, fOutputList2); // fStorage = new AliForwardFlowResultStorage("freja", fOutputList3); /* fStorage=new TList(); fStorage->SetOwner(kTRUE); fStorage->SetName("add"); PostData(4,fStorage); */ fEventCuts.AddQAplotsToList(fOutputList); frefetac=new TH1F("frefetac","frefetac",30,-3.4,-1.9); fOutputList2->Add(frefetac); frefetaa=new TH1F("frefetaa","frefetaa",62,1.9,5.0); fOutputList2->Add(frefetaa); frefvz=new TH1F("frefvz","z-vertex",10,-10,10); fOutputList2->Add(frefvz); /// TGrid::Connect("alien://"); //TFile*file=TFile::Open("alien:///alice/cern.ch/user/y/ysekiguc/correction.root"); // TFile*file=TFile::Open("/home/yuko/work/local_alicework/MCESDanalysis/draw_result/correction.root"); // if(!file) AliError("No correction factor"); //for(Int_t i=0;i<10;i++){ //fhcorr[i]=(TH2D*)file->Get(Form("fRefetaphiclone_%d",i)); // fOutputList2->Add(fhcorr[i]); // } if(fefficalib){ TGrid::Connect("alien://"); //TFile* file=TFile::Open("alien:///alice/cern.ch/user/y/ysekiguc/corrections/fcorrection_efficiency.root"); TFile*file=TFile::Open(Form("alien:///alice/cern.ch/user/y/ysekiguc/corrections/fcorrection_efficiency_%s_filterbit%d_3D.root",fcollisiontype.Data(),ffilterbit)); if(!file) AliError("No correction factor"); for(Int_t i=0;i<10;i++){ fhcorr[i]=(TH2D*)file->Get(Form("effi_%d",i)); } } fPoolMgr = new AliEventPoolManager(fPoolMaxNEvents, fPoolMinNTracks, fNCentBins,fCentBins, fNzVtxBins, fZvtxBins); if (!fPoolMgr) return; fPoolMgr->SetTargetValues(fPoolMinNTracks, 0.1, 5); fPoolMgr1 = new AliEventPoolManager(fPoolMaxNEvents, fPoolMinNTracks, fNCentBins,fCentBins, fNzVtxBins, fZvtxBins); if (!fPoolMgr1) return; fPoolMgr1->SetTargetValues(fPoolMinNTracks, 0.1, 5); } void AliAnalysisTaskSEpPbCorrelationsYS::DefineGeneralOutput() { fHist_Stat = new TH1F("fHist_Stat", "Stat Histogram", 14, -0.5, 13.5); fHist_Stat->GetXaxis()->SetBinLabel(1, "All Events"); fHist_Stat->GetXaxis()->SetBinLabel(2, "Analyzed Events"); fHist_Stat->GetXaxis()->SetBinLabel(3, "MultSelection OK"); fHist_Stat->GetXaxis()->SetBinLabel(4, "Vertex OK"); fHist_Stat->GetXaxis()->SetBinLabel(5, "Centrality OK"); fHist_Stat->GetXaxis()->SetBinLabel(6, "HAS AliAODForwardMult"); fHist_Stat->GetXaxis()->SetBinLabel(7, "FMD multi ok "); fHist_Stat->GetXaxis()->SetBinLabel(8, "FMD/V0 multi cut"); fOutputList->Add(fHist_Stat); fHist_V0Stat = new TH1F("fHist_V0Stat", "Stat Histogram", 16, -0.5, 15.5); fHist_V0Stat->GetXaxis()->SetBinLabel(1, "all"); fHist_V0Stat->GetXaxis()->SetBinLabel(2, "On-Fly"); fHist_V0Stat->GetXaxis()->SetBinLabel(3, "Off-Fly"); fHist_V0Stat->GetXaxis()->SetBinLabel(4, "V0 pseudorapidity"); fHist_V0Stat->GetXaxis()->SetBinLabel(5, "DCA Dau. tracks to PV"); fHist_V0Stat->GetXaxis()->SetBinLabel(6, "DCA dauthers"); fHist_V0Stat->GetXaxis()->SetBinLabel(7, "Fiducial volume"); fHist_V0Stat->GetXaxis()->SetBinLabel(8, "Pass IsAcceptedV0"); fHist_V0Stat->GetXaxis()->SetBinLabel(9, "track cut"); fHist_V0Stat->GetXaxis()->SetBinLabel(10, "charge"); fHist_V0Stat->GetXaxis()->SetBinLabel(11, "PID for K0s"); fHist_V0Stat->GetXaxis()->SetBinLabel(12, "ctau for k0s"); fHist_V0Stat->GetXaxis()->SetBinLabel(13, "AP cut for K0s"); fOutputList->Add(fHist_V0Stat); fHistzvertex = new TH1F("fHistzvertex", ";VZ;count", 60, -15, 15); fOutputList->Add(fHistzvertex); Double_t fmaxcent; Int_t fncentbin=100; if(fCentType=="Manual"){ if(fcollisiontype=="PbPb"){ fmaxcent=2000; fncentbin=1000; }else{ fmaxcent=200; } }else{ if (fcollisiontype.Contains("HMPP")) fmaxcent=1.; else fmaxcent=100.; } fHistCentrality = new TH1F("fHistCentrality", ";centrality;count", 100, 0, fmaxcent); fOutputList->Add(fHistCentrality); fHistCentrality_beforecut = new TH1F("fHistCentrality_beforecut", ";centrality;count", 100, 0, fmaxcent); fOutputList->Add(fHistCentrality_beforecut); fHistCentzvertex = new TH2F("fHistCentzvertex", "Cent;VZ;count", 100,0, fmaxcent, 60, -15, 15); fOutputList->Add(fHistCentzvertex); Int_t nspdtracks; if(fcollisiontype.Contains("HMPP")|| fcollisiontype.Contains("MBPP")|| fcollisiontype.Contains("pPb")) nspdtracks=200; else nspdtracks=3500; fHistCentV0vsTracklets=new TH2F("fHistCentV0vsTracklets","fHistCentV0vsTracklets",fncentbin,0,fmaxcent,nspdtracks,0,nspdtracks); if(fAnaMode!="FMDFMD") fOutputList->Add(fHistCentV0vsTracklets); fHistTraksvsVz=new TH2F("fHistTraksvsVz","fHistTraksvsVz",50,-10,10,nspdtracks,0,nspdtracks); fOutputList->Add(fHistTraksvsVz); //fHistCentV0vsTrackletsbefore=new TH2F("fHistCentV0vsTrackletsbefore","fHistCentV0vsTrackletsbefore",100,0,100,nspdtracks,0,nspdtracks); //fOutputList->Add(fHistCentV0vsTrackletsbefore); Int_t nv0mult; Int_t nbinv0mult=1000; if(fcollisiontype=="PbPb") { nv0mult=40000; }else{ nv0mult=5000; } fHistV0vsTracks=new TH2F("fHistV0vsTracks","fHistV0vsTracks",nbinv0mult,0,nv0mult,nspdtracks,0,nspdtracks); if(fAnaMode!="FMDFMD") fOutputList->Add(fHistV0vsTracks); fHistCentvsNv0mult=new TH2F("fHistCentvsNv0mult","fHistCentvsNv0mult",fncentbin,0,fmaxcent,nv0mult,0,nv0mult); fOutputList->Add(fHistCentvsNv0mult); fHistV0multvsVz=new TH2F("fHistV0multvsVz","fHistV0multvsVz",50,-10,10,nv0mult,0,nv0mult); fOutputList->Add(fHistV0multvsVz); TTree *settingsTree = new TTree("UEAnalysisSettings", "Analysis Settings in UE estimation"); settingsTree->Branch("fZVertex", &fZVertex, "fZVertex/D"); settingsTree->Branch("fEtaMax", &fEtaMax, "fEtaMax/D"); settingsTree->Branch("fPtMin", &fPtMin, "fPtMin/D"); settingsTree->Branch("fMaxnSigmaTPCTOF", &fMaxnSigmaTPCTOF, "fMaxnSigmaTPCTOF/D"); // settingsTree->Branch("fanamode",&fAnaMode,"fAnaMode/B"); // settingsTree->Branch("fanalysisasso",&fanalysisasso,"fanalysisasso/I"); // settingsTree->Branch("fanalysiscent",&fanalysiscent,"fanalysiscent/I"); settingsTree->Fill(); fOutputList->Add(settingsTree); } void AliAnalysisTaskSEpPbCorrelationsYS::DefineVZEROOutput() { Int_t ncent; if(fCentType=="Manual") ncent=20; else ncent=15; const Int_t nVZEROBins[3] = {10, 8, ncent}; Double_t binning_eta_vzero[11] = {-3.7, -3.2, -2.7, -2.2, -1.7, 0., 2.8, 3.4, 3.9, 4.5, 5.1}; Double_t binning_phi_vzero[9] = {0., 0.7853, 1.5707, 2.3561, 3.1415, 3.9269, 4.7123, 5.4977, 6.2831}; Double_t binning_cent[16] = {0., 0.1, 1., 2., 3., 5., 10., 20., 30., 40., 50., 60., 70., 80., 90., 100.1}; fHist_vzeromult = new TH2F("fHist_vzeromult", "fHist_vzeromult", 64, -0.5, 63.5, 500, 0, 500); fOutputList1->Add(fHist_vzeromult); fHist_vzeromultEqweighted = new TH2F("fHist_vzeromultEqweighted", "fHist_vzeromultEqweighted", 64, -0.5, 63.5, 500, 0, 500); fOutputList1->Add(fHist_vzeromultEqweighted); fHist2dmult = new TH3F("fHist2dmult", "fHist2dmult", 64, -0.5, 63.5, 500, 0, 500, 500, 0, 500); fOutputList1->Add(fHist2dmult); fHistVZERO = new AliTHn("fHistVZERO", "fHistVZERO", 1, 3, nVZEROBins); fHistVZERO->SetBinLimits(0, binning_eta_vzero); fHistVZERO->SetBinLimits(1, binning_phi_vzero); if(fCentType!="Manual") fHistVZERO->SetBinLimits(2, binning_cent); else fHistVZERO->SetBinLimits(2, 0, 200); fOutputList1->Add(fHistVZERO); } void AliAnalysisTaskSEpPbCorrelationsYS::DefinedQAHistos() { Int_t ncentmax; if(fCentType=="Manual") ncentmax=200; else ncentmax=100; mixedDist=new TH2F("mixedDist", ";centrality;tracks;events", 100, 0, ncentmax, 200, 0, fPoolMinNTracks*1.5 ); mixedDist2=new TH2F("mixedDist2", ";centrality;events;events", 100, 0,ncentmax, 100, 0, 1000) ; fOutputList2->Add(mixedDist); fOutputList2->Add(mixedDist2); const Int_t ipidBin[4] = {11, 40, 72, 15}; Double_t binning_pt_lead[12] = {0.2, 0.5, 0.75, 1.0, 1.25, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 8.0}; Double_t binning_eta[41] = {-1., -0.95, -0.9, -0.85, -0.8, -0.75, -0.7, -0.65, -0.6, -0.55, -0.5, -0.45, -0.4, -0.35, -0.3, -0.25, -0.2, -0.15, -0.1, -0.05, 0., 0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95, 1.0}; Double_t binning_dphi[73] = { -1.570796, -1.483530, -1.396263, -1.308997, -1.221730, -1.134464, -1.047198, -0.959931, -0.872665, -0.785398, -0.698132, -0.610865, -0.523599, -0.436332, -0.349066, -0.261799, -0.174533, -0.087266, 0.0, 0.087266, 0.174533, 0.261799, 0.349066, 0.436332, 0.523599, 0.610865, 0.698132, 0.785398, 0.872665, 0.959931, 1.047198, 1.134464, 1.221730, 1.308997, 1.396263, 1.483530, 1.570796, 1.658063, 1.745329, 1.832596, 1.919862, 2.007129, 2.094395, 2.181662, 2.268928, 2.356194, 2.443461, 2.530727, 2.617994, 2.705260, 2.792527, 2.879793, 2.967060, 3.054326, 3.141593, 3.228859, 3.316126, 3.403392, 3.490659, 3.577925, 3.665191, 3.752458, 3.839724, 3.926991, 4.014257, 4.101524, 4.188790, 4.276057, 4.363323, 4.450590, 4.537856, 4.625123, 4.712389}; Double_t binning_cent[16] = {0., 0.1, 1., 2., 3., 5., 10., 20., 30., 40., 50., 60., 70., 80., 90., 100.1}; Double_t binning_zvx[11] = {-10,-8,-6,-4,-2,0,2,4,6,8,10}; if(fasso=="PID" && fQA){ fHistPIDQA = new AliTHn("fHistPIDQA", "fHistPIDQA", 3, 4, ipidBin); fHistPIDQA->SetBinLimits(0, binning_pt_lead); fHistPIDQA->SetBinLimits(1, binning_eta); fHistPIDQA->SetBinLimits(2, binning_dphi); fHistPIDQA->SetBinLimits(3, binning_cent); fHistPIDQA->SetVarTitle(0, "pt"); fHistPIDQA->SetVarTitle(1, "eta"); fHistPIDQA->SetVarTitle(2, "phi"); fHistPIDQA->SetVarTitle(3, "centrality"); fOutputList1->Add(fHistPIDQA); } Double_t binning_cent_leadQA[13] = {0., 0.1, 5., 10., 20., 30., 40., 50., 60., 70., 80., 90., 100.1}; Int_t fncentbinqa; if(fCentType=="Manual") fncentbinqa=100; else fncentbinqa=12; const Int_t ipidBinQA[5] = {11, 40, 72, fncentbinqa,10}; fHistLeadQA = new AliTHn("fHistLeadQA", "fHistLeadQA", 1, 5, ipidBinQA); fHistLeadQA->SetBinLimits(0, binning_pt_lead); fHistLeadQA->SetBinLimits(1, binning_eta); fHistLeadQA->SetBinLimits(2, binning_dphi); if(fCentType=="Manual")fHistLeadQA->SetBinLimits(3,0,200); else fHistLeadQA->SetBinLimits(3, binning_cent_leadQA); fHistLeadQA->SetBinLimits(4,-10,10); fHistLeadQA->SetVarTitle(0, "pt"); fHistLeadQA->SetVarTitle(1, "eta"); fHistLeadQA->SetVarTitle(2, "phi"); fHistLeadQA->SetVarTitle(3, "centrality"); fHistLeadQA->SetVarTitle(4, "vz"); fOutputList1->Add(fHistLeadQA); const Int_t imcprimbin[4]={11,55,30,10}; Double_t binning_pt_mcprim[12] = {0.3, 0.5, 0.75, 1.0, 1.25, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 8.0}; if(!fDataType){ fhistmcprim=new AliTHn("fhistmcprim","fhistmcprim",1,4,imcprimbin); fhistmcprim->SetBinLimits(0,binning_pt_mcprim); fhistmcprim->SetBinLimits(1,-5.5,5.5); fhistmcprim->SetBinLimits(2,0.,2*TMath::Pi()); fhistmcprim->SetBinLimits(3,0.,100.); fhistmcprim->SetVarTitle(0,"pt"); fhistmcprim->SetVarTitle(1,"eta"); fhistmcprim->SetVarTitle(2,"phi"); fhistmcprim->SetVarTitle(3,"centrality"); fOutputList2->Add(fhistmcprim); fhmcprimvzeta=new TH2D("fhmcprimvzeta","fhmcprimvzeta",200,-4,6,20,-10,10); fOutputList2->Add(fhmcprimvzeta); fhmcprimpdgcode=new TH1D("fhmcprimpdgcode","fhmcprimpdgcode",4000,-0.5,3999.5); fOutputList2->Add(fhmcprimpdgcode); fh2_FMD_acceptance_prim=new TH2D("fh2_FMD_acceptance_prim","fh2_FMD_acceptance_prim",200,-4,6,200,-10,10); fOutputList2->Add(fh2_FMD_acceptance_prim); fh2_FMD_eta_phi_prim=new TH2D("fh2_FMD_eta_phi_prim","fh2_FMD_eta_phi_prim",200,-4,6,20,0,2*TMath::Pi()); fOutputList2->Add(fh2_FMD_eta_phi_prim); for(Int_t i=0;i<4;i++){ fhrefetaFMD[i]=new TH1D(Form("fhrefetaFMD_%d",i),Form("fhrefetaFMD_%d",i),200,-4,6); fhrefphiFMD[i]=new TH1D(Form("fhrefphiFMD_%d",i),Form("fhrefphiFMD_%d",i),100,0,2*TMath::Pi()); fOutputList2->Add(fhrefetaFMD[i]); fOutputList2->Add(fhrefphiFMD[i]); } } fHist_NeventRun=new TH1F("fHist_NeventRun","fHist_NeventRun",200,-0.5,199.5); fOutputList2->Add(fHist_NeventRun); fHist_V0AMultRun=new TH1F("fHist_V0AMultRun","fHist_V0AMultRun",200,-0.5,199.5); fOutputList2->Add(fHist_V0AMultRun); fHist_V0CMultRun=new TH1F("fHist_V0CMultRun","fHist_V0CMultRun",200,-0.5,199.5); fOutputList2->Add(fHist_V0CMultRun); fHist_FMDAMultRun=new TH1F("fHist_FMDAMultRun","fHist_FMDAMultRun",200,-0.5,199.5); fOutputList2->Add(fHist_FMDAMultRun); fHist_FMDCMultRun=new TH1F("fHist_FMDCMultRun","fHist_FMDCMultRun",200,-0.5,199.5); fOutputList2->Add(fHist_FMDCMultRun); fOutliers = new TH2D("fOutliers","Maximum #sigma from mean N_{ch} pr. bin",100, 0., 100., 500, 0., 5.); //((fFlags & kMC) ? 15. : 5. // Sigma <M> histogram fOutputList2->Add(fOutliers); Float_t nmutFoward; if(fcollisiontype=="PbPb"||fcollisiontype=="pPb") nmutFoward=2000.; else nmutFoward=1000.; fFMDV0 = new TH2F("FMDV0", "FMD vs V0 pre cut;FMD;V0;",2000, 0, 2*nmutFoward, 2000, 0, 2*nmutFoward); fOutputList2->Add(fFMDV0); fFMDV0_post=new TH2F("FMDV0_post", "FMD vs V0 post cut;FMD;V0;",2000, 0, 2*nmutFoward, 2000, 0, 2*nmutFoward); fOutputList2->Add(fFMDV0_post); fFMDV0A = new TH2F("FMDV0A", "FMD vs V0A;FMD;V0A;",1000, 0, nmutFoward, 1000, 0, nmutFoward); fOutputList2->Add(fFMDV0A); fFMDV0A_post = new TH2F("FMDV0A_post", "FMD vs V0A post cut;FMD;V0A;",1000, 0, nmutFoward, 1000, 0, nmutFoward); fOutputList2->Add(fFMDV0A_post); fFMDV0C = new TH2F("FMDV0C", "FMD vs V0C;FMD;V0C;",1000, 0, nmutFoward, 1000, 0, nmutFoward); fOutputList2->Add(fFMDV0C); fFMDV0C_post = new TH2F("FMDV0C_post", "FMD vs V0C post cut;FMD;V0C;",1000, 0, nmutFoward, 1000, 0, nmutFoward); fOutputList2->Add(fFMDV0C_post); fFMDV0same = new TH2F("FMDV0same", "FMD vs V0 pre cut;FMD;V0;",2000, 0, 2000, 2*nmutFoward, 0, 2*nmutFoward); fOutputList2->Add(fFMDV0same); fFMDV0same_post=new TH2F("FMDV0same_post", "FMD vs V0 post cut;FMD;V0;",2000, 0, 2000, 2*nmutFoward, 0, 2*nmutFoward); fOutputList2->Add(fFMDV0same_post); fFMDV0Asame = new TH2F("FMDV0Asame", "FMD vs V0A;FMD;V0A;",1000, 0, nmutFoward, 1000, 0, nmutFoward); fOutputList2->Add(fFMDV0Asame); fFMDV0Asame_post = new TH2F("FMDV0Asame_post", "FMD vs V0A post cut;FMD;V0A;",2000, 0, nmutFoward, 1000, 0, nmutFoward); fOutputList2->Add(fFMDV0Asame_post); fFMDV0Csame = new TH2F("FMDV0Csame", "FMD vs V0C;FMD;V0C;",1000, 0, nmutFoward, 1000, 0, nmutFoward); fOutputList2->Add(fFMDV0Csame); fFMDV0Csame_post = new TH2F("FMDV0Csame_post", "FMD vs V0C post cut;FMD;V0C;",1000, 0, nmutFoward, 1000, 0, nmutFoward); fOutputList2->Add(fFMDV0Csame_post); fh2_ITS_acceptance=new TH2D("fh2_ITS_acceptance","fh2_ITS_acceptance",200,-10,10,200,-4,6); fOutputList2->Add(fh2_ITS_acceptance); fh2_SPD_multcorr=new TH2F("fh2_SPD_multcorr","fh2_SPD_multcorr",400,0,400,2000,0,2000); fOutputList2->Add(fh2_SPD_multcorr); fh2_SPDV0_multcorr=new TH2F("fh2_SPDV0_multcorr","fh2_SPDV0_multcorr",400,0,400,2000,0,2000); fOutputList2->Add(fh2_SPDV0_multcorr); fh2_SPDtrack_multcorr=new TH2F("fh2_SPDtrack_multcorr","fh2_SPDtrack_multcorr",400,0,400,400,0,400); fOutputList2->Add(fh2_SPDtrack_multcorr); fhtrackletsdphi=new TH1F("fhtrackletsdphi","dphi tracklets",100,-100,100); fOutputList2->Add(fhtrackletsdphi); fh2_FMD_acceptance=new TH2D("fh2_FMD_acceptance","fh2_FMD_acceptance",200,-4,6,200,-10,10); fOutputList2->Add(fh2_FMD_acceptance); fh2_FMD_eta_phi=new TH2D("fh2_FMD_eta_phi","fh2_FMD_eta_phi",200,-4,6,20,0,2*TMath::Pi()); fOutputList2->Add(fh2_FMD_eta_phi); fh2_FMD_eta_phi_aftercut=new TH2D("fh2_FMD_eta_phi_aftercut","fh2_FMD_eta_phi_aftercut",200,-4,6,20,0,2*TMath::Pi()); fOutputList2->Add(fh2_FMD_eta_phi_aftercut); if(fCentType!="Manual")fhistfmdphiacc=new TH2D("fhistfmdphiacc","fhistfmdphiacc",200,-4,6,15,binning_cent); else fhistfmdphiacc=new TH2D("fhistfmdphiacc","fhistfmdphiacc",200,-4,6,20,0,200); fOutputList2->Add(fhistfmdphiacc); fhFMDmultchannel=new TH2F("fhFMDmultchannel","fhFMDmultchannel",200,-4,6,100,0,100); fOutputList2->Add(fhFMDmultchannel); for(Int_t i=0;i<31;i++){ fhFMDmult_runbyrun_cside[i]=new TH2D(Form("fhFMDmult_runbyrun_cside_%d",i),Form("fhFMDmult_runbyrun_%d",i),200,-0.5,199.5,100,0,100); // fOutputList2->Add(fhFMDmult_runbyrun_cside[i]); } for(Int_t i=0;i<65;i++){ fhFMDmult_runbyrun_aside[i]=new TH2D(Form("fhFMDmult_runbyrun_aside_%d",i),Form("fhFMDmult_runbyrun_%d",i),200,-0.5,199.5,100,0,100); // fOutputList2->Add(fhFMDmult_runbyrun_aside[i]); } Int_t ncentbinfmd; if(fCentType=="Manual") ncentbinfmd=20; else ncentbinfmd=15; const Int_t ifmdbin[4]={200,20,ncentbinfmd,10}; fhistfmd=new AliTHn("fhistfmd","fhistfmd",1,4,ifmdbin); fhistfmd->SetBinLimits(0,-4.,6.); fhistfmd->SetBinLimits(1,0.,2*TMath::Pi()); if(fCentType=="Manual")fhistfmd->SetBinLimits(2,0.,200.); // else fhistfmd->SetBinLimits(2,0.,100.); else fhistfmd->SetBinLimits(2,binning_cent); fhistfmd->SetBinLimits(3,-10.,10.); fhistfmd->SetVarTitle(0,"eta"); fhistfmd->SetVarTitle(1,"phi"); fhistfmd->SetVarTitle(2,"centrality"); fhistfmd->SetVarTitle(3,"vzy"); fOutputList2->Add(fhistfmd); const Int_t iitsbin[4]={200,20,20,40}; Double_t MinITS[4];//={-4,0.,0.,-10.}; MinITS[0]=-4.; MinITS[1]=0.; MinITS[2]=0.; MinITS[3]=-10.; Double_t MaxITS[4]; MaxITS[0]=6.; MaxITS[1]=2*TMath::Pi(); MaxITS[2]=100.; MaxITS[3]=10.; fhistits=new THnSparseF("fhistits","fhistits",4,iitsbin,MinITS,MaxITS); // fOutputList2->Add(fhistits); const Double_t binning_etafmd[51]={ -3.4,-3.3,-3.2,-3.1,-3.0, -2.9,-2.8,-2.7,-2.6,-2.5,-2.4,-2.3,-2.2,-2.1,-2.0, -1.9,-1.8,-1.7, 1.7,1.8,1.9, 2.0,2.1,2.2,2.3,2.4,2.5,2.6,2.7,2.8,2.9, 3.0,3.1,3.2,3.3,3.4,3.5,3.6,3.7,3.8,3.9, 4.0,4.1,4.2,4.3,4.4,4.5,4.6,4.7,4.8,4.9}; const Int_t binfmdsec[5]={160,50,15,20,10}; fhSecFMD= new AliTHn("fhSecFMD","fhSecFMD",2,5,binfmdsec); fhSecFMD->SetBinLimits(0,-4.025,3.975); fhSecFMD->SetBinLimits(1,binning_etafmd); fhSecFMD->SetBinLimits(2,binning_cent); fhSecFMD->SetBinLimits(3,-0.55*TMath::Pi(),1.45*TMath::Pi()); fhSecFMD->SetBinLimits(4,binning_zvx); fhSecFMD->SetVarTitle(0,"#Delta#eta"); fhSecFMD->SetVarTitle(1,"FMD Eta"); fhSecFMD->SetVarTitle(2,"centrality"); fhSecFMD->SetVarTitle(3,"#Delta#phi"); fhSecFMD->SetVarTitle(4,"z vertex"); fOutputList2->Add(fhSecFMD); if(fasso=="PID"){ for(Int_t i=0;i<6;i++){ fHistNsig[i]=new TH2D(Form("fHistNsig_%d",i),Form("HistNsig_%d",i), 160, 0., 8., 600, -30., 30); fOutputList2->Add(fHistNsig[i]); fHistNsigcorr[i]=new TH2D(Form("fHistNsigcorr_%d",i),"fHistNsigcorr",500,-10,10,500,-10,10); fOutputList2->Add(fHistNsigcorr[i]); } } if(fasso=="Phi"){ fHistPhiDTPCNSig = new TH2D("fHistPhiDTPCNSig", "fHistPhiDTPCNSig", 150, 0.,15., 200, -10., 10); fOutputList2->Add(fHistPhiDTPCNSig); fHistPhiDTOFNSig = new TH2D("fHistPhiDTOFNSig", "fHistPhiDTOFNSig", 150, 0.,15., 200, -10., 10); fOutputList2->Add(fHistPhiDTOFNSig); fHistPhiDTPCTOFNSig = new TH2D("fHistPhiDTPCTOFNSig", "fHistPhiDTPCTOFNSig",150, 0., 15., 200, -10., 10); fOutputList2->Add(fHistPhiDTPCTOFNSig); } Int_t nBins = 400; Double_t mphiMin = 1.02 - 0.1; Double_t mphiMax = 1.02 + 0.1; Int_t nCentralityBins = 20; Double_t centBins1[16] = {0., 1., 2., 3., 4., 5., 10., 20., 30., 40., 50., 60., 70., 80., 90., 100.0}; const Double_t *centralityBins = centBins1; Int_t nPtBinsV0 = 150; const Double_t PtBinsV0[12] = {0, 0.5, 0.75, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 8.0, 15.0}; Double_t mk0sMin = 0.5 - 0.1; Double_t mk0sMax = 0.5 + 0.1; Int_t netabins=4; const Int_t spBins[3] = {nBins, nPtBinsV0, nCentralityBins}; const Int_t spBinsV0[4] = {nBins, nPtBinsV0, nCentralityBins,netabins}; const Int_t spBinsBump[3] = {500, nPtBinsV0, nCentralityBins}; // v0 const Double_t spMink0s[4] = {mk0sMin, PtBinsV0[0], centralityBins[0],-0.8}; const Double_t spMaxk0s[4] = {mk0sMax, PtBinsV0[11], centralityBins[15],0.8}; Double_t mlambdaMin = 1.15 - 0.1; Double_t mlambdaMax = 1.15 + 0.1; const Double_t spMinLambda[4] = {mlambdaMin, PtBinsV0[0], centralityBins[0],-0.8}; const Double_t spMaxLambda[4] = {mlambdaMax, PtBinsV0[11],centralityBins[15],0.8}; const Double_t spMinBump[3] = {0, PtBinsV0[0], centralityBins[0]}; const Double_t spMaxBump[3] = {2.5, PtBinsV0[11], centralityBins[15]}; if(fasso=="V0"){ fHistMass_K0s = new THnSparseF("fHistMass_K0s", "mass for K0s", 4, spBinsV0, spMink0s, spMaxk0s); fOutputList2->Add(fHistMass_K0s); fHistMass_K0s_MC = new THnSparseF("fHistMass_K0s_MC", "mass for K0s", 4, spBinsV0, spMink0s, spMaxk0s); fOutputList2->Add(fHistMass_K0s_MC); fHistMass_Lambda = new THnSparseF("fHistMass_Lambda", "mass for Lambda", 4,spBinsV0, spMinLambda, spMaxLambda); fOutputList2->Add(fHistMass_Lambda); fHistMass_Lambda_MC = new THnSparseF("fHistMass_Lambda_MC", "MC mass for Lambda", 4,spBinsV0, spMinLambda, spMaxLambda); fOutputList2->Add(fHistMass_Lambda_MC); fHistMass_ALambda = new THnSparseF("fHistMass_ALambda", "mass for Anti Lambda", 4, spBinsV0,spMinLambda, spMaxLambda); fOutputList2->Add(fHistMass_ALambda); fHistMass_ALambda_MC = new THnSparseF("fHistMass_ALambda_MC", "mass for Anti Lambda", 4, spBinsV0,spMinLambda, spMaxLambda); fOutputList2->Add(fHistMass_ALambda_MC); fHistMass_bumpcorr =new TH2D("fHistMass_bumpcorr", "mass for Lambda bump correlation", 400,mlambdaMin, mlambdaMax, 1000, 0, 1); fOutputList2->Add(fHistMass_bumpcorr); const Int_t spBinsQAV0[4] = {40, 72, 7, 20}; const Double_t spMinV0QA[4] = {-1., 0, -0.5, 0.}; const Double_t spMaxV0QA[4] = {1., TMath::TwoPi(), 6.5, 100.0}; fHist_V0QA = new THnSparseF("fHist_V0QA", "QA for V0 particle", 4, spBinsQAV0, spMinV0QA, spMaxV0QA); fOutputList2->Add(fHist_V0QA); hv0dcharge = new TH1D("hv0dcharge", "hv0dcharge", 3, -0.5, 2.5); fOutputList2->Add(hv0dcharge); for (Int_t i = 0; i < 6; i++) { fHistPosNsig[i] = new TH2D(Form("fHistPosNsig_%d", i), "fHistPosNsig", 160, 0., 8., 600, -30., 30); fHistNegNsig[i] = new TH2D(Form("fHistNegNsig_%d", i), "fHistNegNsig", 160, 0., 8., 600, -30., 30); fOutputList2->Add(fHistPosNsig[i]); fOutputList2->Add(fHistNegNsig[i]); fHistPosNsigQA[i] = new TH2D(Form("fHistPosNsigQA_%d", i), "fHistPosNsigQA",160, 0., 8., 600, -30., 30); fOutputList2->Add(fHistPosNsigQA[i]); } for(Int_t i=0;i<3;i++){ fh3NegNsig[i]=new TH3D(Form("fh3NegNsig_%d",i),Form("fh3NegNsig_%d",i),40,0,8,200,-10,10,200,-10,10); fh3PosNsig[i]=new TH3D(Form("fh3PosNsig_%d",i),Form("fh3PosNsig_%d",i),40,0,8,200,-10,10,200,-10,10); fOutputList2->Add(fh3NegNsig[i]); fOutputList2->Add(fh3PosNsig[i]); } for (Int_t i = 0; i < 6; i++) { fHist_AP[i] = new TH2D(Form("fHist_AP_%d", i), Form("fHist_AP_%d", i), 200, -1, 1, 200, 0, 0.4); fOutputList2->Add(fHist_AP[i]); } } if(fasso=="Cascade"){ // QA Plot for Cascade Double_t mxiMin = 1.3 - 0.1; Double_t mxiMax = 1.3 + 0.1; Double_t momegaMin = 1.65 - 0.1; Double_t momegaMax = 1.65 + 0.1; const Double_t spMinXi[3] = {mxiMin, PtBinsV0[0], centralityBins[0]}; const Double_t spMaxXi[3] = {mxiMax, PtBinsV0[11], centralityBins[15]}; const Double_t spMinOmega[3] = {momegaMin, PtBinsV0[0], centralityBins[0]}; const Double_t spMaxOmega[3] = {momegaMax, PtBinsV0[11], centralityBins[15]}; fHistMassXiMinus = new THnSparseF("fHistMassXiMinus", "mass for Xi-", 3, spBins, spMinXi, spMaxXi); fHistMassXiPlus = new THnSparseF("fHistMassXiPlus", "mass for Xi+", 3, spBins, spMinXi, spMaxXi); fHistMassOmegaMinus = new THnSparseF("fHistMassOmegaMinus", "mass for Omega-", 3, spBins, spMinOmega, spMaxOmega); fHistMassOmegaPlus = new THnSparseF("fHistMassOmegaPlus", "mass for Omega+", 3, spBins, spMinOmega, spMaxOmega); fOutputList2->Add(fHistMassXiMinus); fOutputList2->Add(fHistMassXiPlus); fOutputList2->Add(fHistMassOmegaMinus); fOutputList2->Add(fHistMassOmegaPlus); const Int_t spBinsQACasc[5] = {20, 40, 72, 7, 20}; const Double_t spMinCascQA[5] = {0, -1., 0, -0.5, 0.}; const Double_t spMaxCascQA[5] = {10, 1., TMath::TwoPi(), 6.5, 100.0}; fHist_CascadeQA = new THnSparseF("fHist_CascadeQA", "QA for Cascade particle", 5, spBinsQACasc, spMinCascQA, spMaxCascQA); fOutputList2->Add(fHist_CascadeQA); } if(fasso=="Phi"){ // QA Plot for Phi meson const Double_t spMinPhi[3] = {mphiMin, PtBinsV0[0], centralityBins[0]}; const Double_t spMaxPhi[3] = {mphiMax, PtBinsV0[11], centralityBins[15]}; // Phimeson fHistMass_PhiMeson = new THnSparseF("fHistMass_PhiMeson", "mass for phi meson", 3, spBins, spMinPhi, spMaxPhi); fOutputList2->Add(fHistMass_PhiMeson); fHistMass_PhiMeson_MIX = new THnSparseF("fHistMass_PhiMeson_MIX", "mass for phi meson of mixed events", 3, spBins, spMinPhi, spMaxPhi); fOutputList2->Add(fHistMass_PhiMeson_MIX); const Int_t spBinsQA[4] = {40, 72, 7, 20}; const Double_t spMinPhiQA[4] = {-1., 0, -0.5, 0.}; const Double_t spMaxPhiQA[4] = {1., TMath::TwoPi(), 6.5, 100.0}; fHist_PhiQA = new THnSparseF("fHist_PhiQA", "QA for Phimeson", 4, spBinsQA, spMinPhiQA, spMaxPhiQA); fOutputList2->Add(fHist_PhiQA); } } void AliAnalysisTaskSEpPbCorrelationsYS::DefineCorrOutput() { Double_t binning_pt_assoc[12] = {0.2, 0.5, 0.75, 1.0, 1.25, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 8.0}; Double_t binning_pt_lead[12] = {0.2, 0.5, 0.75, 1.0, 1.25, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 8.0}; Double_t binning_cent[12] = {0., 5., 10., 20., 30., 40., 50., 60., 70., 80., 90., 100.1}; Double_t binning_deta[49] = { -2.4, -2.3, -2.2, -2.1, -2.0, -1.9, -1.8, -1.7, -1.6, -1.5, -1.4, -1.3, -1.2, -1.1, -1.0, -0.9, -0.8, -0.7, -0.6, -0.5, -0.4, -0.3, -0.2, -0.1, 0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2.0, 2.1, 2.2, 2.3, 2.4}; Double_t binning_dphi[73] = { -1.570796, -1.483530, -1.396263, -1.308997, -1.221730, -1.134464, -1.047198, -0.959931, -0.872665, -0.785398, -0.698132, -0.610865, -0.523599, -0.436332, -0.349066, -0.261799, -0.174533, -0.087266, 0.0, 0.087266, 0.174533, 0.261799, 0.349066, 0.436332, 0.523599, 0.610865, 0.698132, 0.785398, 0.872665, 0.959931, 1.047198, 1.134464, 1.221730, 1.308997, 1.396263, 1.483530, 1.570796, 1.658063, 1.745329, 1.832596, 1.919862, 2.007129, 2.094395, 2.181662, 2.268928, 2.356194, 2.443461, 2.530727, 2.617994, 2.705260, 2.792527, 2.879793, 2.967060, 3.054326, 3.141593, 3.228859, 3.316126, 3.403392, 3.490659, 3.577925, 3.665191, 3.752458, 3.839724, 3.926991, 4.014257, 4.101524, 4.188790, 4.276057, 4.363323, 4.450590, 4.537856, 4.625123, 4.712389}; //multiplicity const Double_t binning_mult_trig[10]={0,10,15,20,30,40,50,80,110,140};//multiplicity pp and pPb const Double_t binning_mult_pp[8]={0,10,15,20,30,60,80,110};//multiplicity pp and pPb const Double_t binning_mult_pbpb[10]={0,30,80,100,300,500,1000,1500,2000,2500};//multiplicity pp and pPb //centrality const Double_t binning_cent_fmdfmd_PbPb[9] = {0., 5., 10., 20., 30., 40., 50.,60.,70.}; const Double_t binning_cent_MBPP[8]={0.,0.1,1.,10.,20.,40.,60.,100.1};//MBpp centrality const Double_t binning_cent_trig[8] = {0., 5., 10., 20.,40., 60.,70.,100.1};//pPb centrality // const Double_t binning_cent_HMPP[12] = {0., 0.01,0.05,0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8,1.}; const Double_t binning_cent_HMPP[8]={0.,0.01,0.05,0.1, 0.2, 0.3, 0.4, 0.5}; //centrality bin Int_t ncentbin; if(fCentType=="Manual") { if(fcollisiontype.Contains("HMPP")||fcollisiontype.Contains("MBPP")) ncentbin=7; else ncentbin=9; }else { if (fcollisiontype=="PbPb") ncentbin=8; else ncentbin=7; } //triggered const Int_t nEvtVars = 2; const Int_t iEvtBin[2] = {11, 11}; Int_t nCFStepstrig=1; if(fasso=="hadron") nCFStepstrig=1; else if (fasso == "V0" || fasso == "Phi") nCFStepstrig = 7; else if (fasso == "Cascade") nCFStepstrig = 6; else if(fasso=="PID") nCFStepstrig=3; Double_t binning_eta_vzero[11]={-3.7,-3.2,-2.7,-2.2,-1.7,0.,2.8,3.4,3.9,4.5,5.1}; Double_t binning_phi_vzero[9]={0.,0.7853,1.5707,2.3561,3.1415,3.9269,4.7123,5.4977,6.2831}; //Bins for FMD const Double_t binning_etafmd[33]={ 1.7,1.8,1.9, 2.0,2.1,2.2,2.3,2.4,2.5,2.6,2.7,2.8,2.9, 3.0,3.1,3.2,3.3,3.4,3.5,3.6,3.7,3.8,3.9, 4.0,4.1,4.2,4.3,4.4,4.5,4.6,4.7,4.8,4.9}; const Double_t binning_etafmdc[18]={ -3.4,-3.3,-3.2,-3.1,-3.0, -2.9,-2.8,-2.7,-2.6,-2.5,-2.4,-2.3,-2.2,-2.1,-2.0, -1.9,-1.8,-1.7}; Double_t binning_zvx[11] = {-10,-8,-6,-4,-2,0,2,4,6,8,10}; if(fAnaMode=="V0AV0C"){ const Int_t nEvtVarsV0Leading=3; const Int_t iEvtBinV0Leading[3]={11,10,8}; fHistTriggerTrack= new AliTHn("fHistTriggerTrack", "fHistTriggerTrack", nCFStepstrig, nEvtVarsV0Leading, iEvtBinV0Leading); fHistTriggerTrack->SetBinLimits(0,binning_cent); fHistTriggerTrack->SetBinLimits(1,binning_eta_vzero); fHistTriggerTrack->SetBinLimits(2,binning_phi_vzero); fHistTriggerTrack->SetVarTitle(0,"centrality"); fHistTriggerTrack->SetVarTitle(1,"eta"); fHistTriggerTrack->SetVarTitle(2,"phi"); fHistTriggerTrackMix= new AliTHn("fHistTriggerTrackMix", "fHistTriggerTrackMix", nCFStepstrig, nEvtVarsV0Leading, iEvtBinV0Leading); fHistTriggerTrackMix->SetBinLimits(0,binning_cent); fHistTriggerTrackMix->SetBinLimits(1,binning_eta_vzero); fHistTriggerTrackMix->SetBinLimits(2,binning_phi_vzero); fHistTriggerTrackMix->SetVarTitle(0,"centrality"); fHistTriggerTrackMix->SetVarTitle(1,"eta"); fHistTriggerTrackMix->SetVarTitle(2,"phi"); }else if(fAnaMode=="FMDFMD" || fAnaMode=="FMDFMD_Ctrig"|| fAnaMode=="SECA" || fAnaMode=="SECC"){ const Int_t nEvtVarsV0Leading=3; Int_t nfmdbin; if(fAnaMode=="FMDFMD") nfmdbin=32; else nfmdbin=17; const Int_t iEvtBinV0Leading[3]={ncentbin,nfmdbin,10}; fHistTriggerTrack= new AliTHn("fHistTriggerTrack", "fHistTriggerTrack", nCFStepstrig, nEvtVarsV0Leading, iEvtBinV0Leading); if(fCentType=="Manual"){ if(fcollisiontype.Contains("HMPP")||fcollisiontype.Contains("MBPP")) fHistTriggerTrack->SetBinLimits(0,binning_mult_pp); else fHistTriggerTrack->SetBinLimits(0,binning_mult_trig); }else{ if(fcollisiontype.Contains("HMPP")) fHistTriggerTrack->SetBinLimits(0,binning_cent_HMPP); else if(fcollisiontype=="MBPP") fHistTriggerTrack->SetBinLimits(0, binning_cent_MBPP); else if(fcollisiontype=="PbPb") fHistTriggerTrack->SetBinLimits(0, binning_cent_fmdfmd_PbPb); else fHistTriggerTrack->SetBinLimits(0,binning_cent_trig); } if(fAnaMode=="FMDFMD") fHistTriggerTrack->SetBinLimits(1,binning_etafmd); else fHistTriggerTrack->SetBinLimits(1,binning_etafmdc); fHistTriggerTrack->SetBinLimits(2,-10.,10.); fHistTriggerTrack->SetVarTitle(0,"centrality"); fHistTriggerTrack->SetVarTitle(1,"eta"); fHistTriggerTrack->SetVarTitle(2,"z vertex"); const Int_t nEvtVarsV0Leadingmix=2; const Int_t iEvtBinV0Leadingmix[2]={11,32}; fHistTriggerTrackMix= new AliTHn("fHistTriggerTrackMix", "fHistTriggerTrackMix", nCFStepstrig, nEvtVarsV0Leadingmix, iEvtBinV0Leadingmix); fHistTriggerTrackMix->SetBinLimits(0,binning_cent); if(fAnaMode=="SECA" || fAnaMode=="FMDFMD") fHistTriggerTrackMix->SetBinLimits(1,binning_etafmd); else if(fAnaMode=="SECC") fHistTriggerTrackMix->SetBinLimits(1,binning_etafmdc); fHistTriggerTrackMix->SetVarTitle(0,"centrality"); fHistTriggerTrackMix->SetVarTitle(1,"eta"); // fHistTriggerTrackMix->SetVarTitle(2,"z vertex"); }else if(fAnaMode=="TPCFMD" ||fAnaMode=="TPCFMDC"||fAnaMode=="ITSFMD" || fAnaMode=="ITSFMDC"){ Double_t binning_pt_lead_trig[5] = {0.2, 0.5, 1.0, 3.0, 8.0}; const Int_t nEvtVarsFMD = 4; Int_t netabin; if(fAnaMode=="TPCFMD"||fAnaMode=="TPCFMDC") netabin=4; else netabin=18; /* Int_t ncentbin; if(fCentType=="Manual") { ncentbin=9; }else { if(fcollisiontype=="HMPP") ncentbin=11; else if (fcollisiontype=="PbPb") ncentbin=8; else ncentbin=7; } */ Int_t ntpcpt; if(fptdiff) ntpcpt=4; else ntpcpt=1; const Int_t iEvtBinFMD[4] = {ntpcpt,ncentbin,10,netabin}; Double_t binning_eta_tpcfmd[5]={-0.8,-0.4,-0.,0.4,0.8}; Double_t binning_eta_itsfmd[19]={-1.7, -1.6, -1.4, -1.2, -1.0, -0.8, -0.6, -0.4, -0.2, 0.,0.2, 0.4, 0.6, 0.8, 1.0, 1.2, 1.4, 1.6, 1.7}; fHistTriggerTrack = new AliTHn("fHistTriggerTrack", "fHistTriggerTrack", nCFStepstrig, nEvtVarsFMD, iEvtBinFMD); if(fptdiff)fHistTriggerTrack->SetBinLimits(0, binning_pt_lead_trig); else fHistTriggerTrack->SetBinLimits(0,fPtMin, fPtMax); if(fCentType=="Manual"){ if(fcollisiontype.Contains("HMPP")||fcollisiontype.Contains("MBPP")) fHistTriggerTrack->SetBinLimits(1,binning_mult_pp); else fHistTriggerTrack->SetBinLimits(1,binning_mult_trig); }else{ if(fcollisiontype.Contains("HMPP")) fHistTriggerTrack->SetBinLimits(1,binning_cent_HMPP); else if(fcollisiontype=="MBPP") fHistTriggerTrack->SetBinLimits(1,binning_cent_MBPP); else if(fcollisiontype=="PbPb") fHistTriggerTrack->SetBinLimits(1, binning_cent_fmdfmd_PbPb); else fHistTriggerTrack->SetBinLimits(1,binning_cent_trig); } fHistTriggerTrack->SetBinLimits(2, -10.,10.); if(fAnaMode=="TPCFMD"||fAnaMode=="TPCFMDC") fHistTriggerTrack->SetBinLimits(3, binning_eta_tpcfmd); else fHistTriggerTrack->SetBinLimits(3, binning_eta_itsfmd); fHistTriggerTrack->SetVarTitle(0, "leading p_{T} GeV/c"); fHistTriggerTrack->SetVarTitle(1, "centrality"); fHistTriggerTrack->SetVarTitle(2, "zvertex"); fHistTriggerTrack->SetVarTitle(3, "TPC/Eta eta"); fHistTriggerTrackMix = new AliTHn("fHistTriggerTrackMix", "fHistTriggerTrackMix", nCFStepstrig, nEvtVars, iEvtBin); fHistTriggerTrackMix->SetBinLimits(0, binning_pt_lead_trig); fHistTriggerTrackMix->SetBinLimits(1, binning_cent_trig); fHistTriggerTrackMix->SetVarTitle(0, "leading p_{T} GeV/c"); fHistTriggerTrackMix->SetVarTitle(1, "centrality"); }else{ const Int_t nEvtVars_tpctpc = 3; const Int_t iEvtBin_tpctpc[3] = {11, 11,20}; fHistTriggerTrack = new AliTHn("fHistTriggerTrack", "fHistTriggerTrack", nCFStepstrig, nEvtVars_tpctpc, iEvtBin_tpctpc); fHistTriggerTrack->SetBinLimits(0, binning_pt_lead); fHistTriggerTrack->SetBinLimits(1, binning_cent); fHistTriggerTrack->SetBinLimits(2, -10.,10.); fHistTriggerTrack->SetVarTitle(0, "leading p_{T} GeV/c"); fHistTriggerTrack->SetVarTitle(1, "centrality"); fHistTriggerTrack->SetVarTitle(2, "vz(cm)"); fHistTriggerTrackMix = new AliTHn("fHistTriggerTrackMix", "fHistTriggerTrackMix", nCFStepstrig, nEvtVars, iEvtBin); fHistTriggerTrackMix->SetBinLimits(0, binning_pt_lead); fHistTriggerTrackMix->SetBinLimits(1, binning_cent); fHistTriggerTrackMix->SetVarTitle(0, "leading p_{T} GeV/c"); fHistTriggerTrackMix->SetVarTitle(1, "centrality"); } fOutputList1->Add(fHistTriggerTrack); fOutputList1->Add(fHistTriggerTrackMix); const Int_t nTrackVars = 5; const Int_t iTrackBin[5] = {48, 11, 11, 15, 72}; ////////////////////////////////////////// //Containers two particle correlation ////////////////////////////////////////// Int_t nCFSteps = 1; if(fasso=="hadron") nCFSteps=1; else if (fasso == "V0" || fasso == "Phi") nCFSteps = 7; else if (fasso == "Cascade") nCFSteps = 6; else if(fasso=="PID") nCFSteps=3; Double_t binning_dphi_vzero[9]={-1.178097,-0.392699,0.392699,1.178097,1.963495,2.748893,3.534291,4.319689,5.105088}; if(fAnaMode=="TPCTPC") { Double_t binning_deta_tpctpc[33] = {-1.6, -1.5, -1.4, -1.3, -1.2, -1.1, -1.0, -0.9, -0.8, -0.7, -0.6, -0.5, -0.4, -0.3, -0.2, -0.1, 0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6}; const Double_t binning_cent_tpctpc[8]={0.,5.,10.,20.,40.,60.,70.,100.1}; const Int_t iTrackBin_TPCTPC[6] = {32, 11, 11, 7, 72, 10}; fHistReconstTrack = new AliTHn("fHistReconstTrack", "fHistReconstTrack", nCFSteps, 6, iTrackBin_TPCTPC); fHistReconstTrack->SetBinLimits(0, binning_deta_tpctpc); fHistReconstTrack->SetBinLimits(1, binning_pt_assoc); fHistReconstTrack->SetBinLimits(2, binning_pt_lead); fHistReconstTrack->SetBinLimits(3, binning_cent_tpctpc); fHistReconstTrack->SetBinLimits(4, binning_dphi); fHistReconstTrack->SetBinLimits(5, -10,10); fHistReconstTrack->SetVarTitle(0, "#Delta#eta"); fHistReconstTrack->SetVarTitle(1, "p_{T} GeV/c"); fHistReconstTrack->SetVarTitle(2, "leading p_{T} GeV/c"); fHistReconstTrack->SetVarTitle(3, "centrality"); fHistReconstTrack->SetVarTitle(4, "#Delta#phi"); fHistReconstTrack->SetVarTitle(5, "Vz"); fHistReconstTrackMix = new AliTHn("fHistReconstTrackMix", "fHistReconstTrackMix", nCFSteps, 6, iTrackBin_TPCTPC); fHistReconstTrackMix->SetBinLimits(0, binning_deta_tpctpc); fHistReconstTrackMix->SetBinLimits(1, binning_pt_assoc); fHistReconstTrackMix->SetBinLimits(2, binning_pt_lead); fHistReconstTrackMix->SetBinLimits(3, binning_cent_tpctpc); fHistReconstTrackMix->SetBinLimits(4, binning_dphi); fHistReconstTrackMix->SetBinLimits(5, -10,10); fHistReconstTrackMix->SetVarTitle(0, "#Delta#eta"); fHistReconstTrackMix->SetVarTitle(1, "p_{T} GeV/c"); fHistReconstTrackMix->SetVarTitle(2, "leading p_{T} GeV/c"); fHistReconstTrackMix->SetVarTitle(3, "centrality"); fHistReconstTrackMix->SetVarTitle(4, "#Delta#phi"); fHistReconstTrackMix->SetVarTitle(5, "Vz"); }else if(fAnaMode=="TPCV0A"||fAnaMode=="TPCV0C"){ const Int_t iTrackBin_VZEROA[5]={66,11,10,11,72}; const Int_t iTrackBin_VZEROC[5]={62,11,10,11,72}; Double_t binning_detaVZEROATPC[67]={-5.6,-5.55,-5.5,-5.45,-5.4,-5.35,-5.3,-5.25,-5.2,-5.15,-5.1,-5.05,-5.0,-4.95, -4.9,-4.85, -4.8, -4.75, -4.7, -4.65,-4.6,-4.55,-4.5,-4.45,-4.4,-4.35,-4.3, -4.25,-4.2,-4.15,-4.1,-4.05,-4.0,-3.95,-3.9,-3.85,-3.8,-3.75,-3.7,-3.65,-3.6,-3.55,-3.5,-3.45,-3.4,-3.35,-3.3,-3.25,-3.2,-3.15,-3.1,-3.05,-3.0,-2.95,-2.9,-2.85,-2.8,-2.75,-2.7,-2.65,-2.6,-2.55,-2.5,-2.45,-2.4,-2.35,-2.3}; Double_t binning_detaVZEROCTPC[63]={1.15, 1.2, 1.25,1.3,1.35,1.4,1.45,1.5,1.55,1.6,1.65,1.7,1.75,1.8,1.85,1.9,1.95,2.0,2.05,2.1,2.15,2.2,2.25,2.3, 2.35, 2.4, 2.45, 2.5, 2.55,2.6, 2.65, 2.7, 2.75, 2.8, 2.85,2.9, 2.95, 3.0, 3.05, 3.1,3.15, 3.2, 3.25, 3.3,3.35, 3.4, 3.45,3.5,3.55, 3.6,3.65, 3.7, 3.75,3.8, 3.85, 3.9,3.95, 4.0,4.05, 4.1,4.15, 4.2, 4.25}; if(fAnaMode=="TPCV0A"){ fHistReconstTrack = new AliTHn("fHistReconstTrack", "fHistReconstTrack", nCFSteps, nTrackVars, iTrackBin_VZEROA); fHistReconstTrack->SetBinLimits(0,binning_detaVZEROATPC); }else{ fHistReconstTrack = new AliTHn("fHistReconstTrack", "fHistReconstTrack", nCFSteps, nTrackVars, iTrackBin_VZEROC); fHistReconstTrack->SetBinLimits(0,binning_detaVZEROCTPC); } fHistReconstTrack->SetBinLimits(1,binning_pt_lead); fHistReconstTrack->SetBinLimits(2,binning_eta_vzero); fHistReconstTrack->SetBinLimits(3,binning_cent); fHistReconstTrack->SetBinLimits(4,binning_dphi); fHistReconstTrack->SetVarTitle(0,"#Delta#eta"); fHistReconstTrack->SetVarTitle(1,"p_{T} GeV/c"); fHistReconstTrack->SetVarTitle(2,"Vzero Eta"); fHistReconstTrack->SetVarTitle(3,"centrality"); fHistReconstTrack->SetVarTitle(4,"#Delta#phi"); if(fAnaMode=="TPCV0A"){ fHistReconstTrackMix= new AliTHn("fHistReconstTrackMix", "fHistReconstTrackMix", nCFSteps, nTrackVars,iTrackBin_VZEROA); fHistReconstTrackMix->SetBinLimits(0,binning_detaVZEROATPC); }else{ fHistReconstTrackMix= new AliTHn("fHistReconstTrackMix", "fHistReconstTrackMix", nCFSteps, nTrackVars,iTrackBin_VZEROC); fHistReconstTrackMix->SetBinLimits(0,binning_detaVZEROCTPC); } fHistReconstTrackMix->SetBinLimits(1,binning_pt_lead); fHistReconstTrackMix->SetBinLimits(2,binning_eta_vzero); fHistReconstTrackMix->SetBinLimits(3,binning_cent); fHistReconstTrackMix->SetBinLimits(4,binning_dphi); fHistReconstTrackMix->SetVarTitle(0,"#Delta#eta"); fHistReconstTrackMix->SetVarTitle(1,"p_{T} GeV/c"); fHistReconstTrackMix->SetVarTitle(2,"Vzero Eta"); fHistReconstTrackMix->SetVarTitle(3,"centrality"); fHistReconstTrackMix->SetVarTitle(4,"#Delta#phi"); }else if (fAnaMode=="TPCFMD" || fAnaMode=="TPCFMDC"){ const Double_t binning_etafmd_tpcfmda[30]={ 1.9, 2.0,2.1,2.2,2.3,2.4,2.5,2.6,2.7,2.8,2.9, 3.0,3.1,3.2,3.3,3.4,3.5,3.6,3.7,3.8,3.9, 4.0,4.1,4.2,4.3,4.4,4.5,4.6,4.7,4.8}; Double_t binning_detaFMDTPC[49]={ -5.7,-5.6,-5.5,-5.4,-5.3,-5.2,-5.1,-5.0, -4.9,-4.8,-4.7,-4.6,-4.5,-4.4,-4.3,-4.2,-4.1,-4., -3.9,-3.8,-3.7,-3.6,-3.5,-3.4,-3.3,-3.2,-3.1,-3., -2.9,-2.8,-2.7,-2.6,-2.5,-2.4,-2.3,-2.2,-2.1,-2., -1.9,-1.8,-1.7,-1.6,-1.5,-1.4,-1.3,-1.2,-1.1,-1., -0.9}; /* Double_t binning_detaFMDTPC[46]={-5.6,-5.5,-5.4,-5.3,-5.2,-5.1,-5.0, -4.9,-4.8,-4.7,-4.6,-4.5,-4.4,-4.3,-4.2,-4.1,-4., -3.9,-3.8,-3.7,-3.6,-3.5,-3.4,-3.3,-3.2,-3.1,-3., -2.9,-2.8,-2.7,-2.6,-2.5,-2.4,-2.3,-2.2,-2.1,-2., -1.9,-1.8,-1.7,-1.6,-1.5,-1.4,-1.3,-1.2,-1.1}; */ Double_t binning_detaFMDCTPC[34]={ 0.9, 1.0,1.1,1.2,1.3,1.4,1.5,1.6,1.7,1.8,1.9, 2.0,2.1,2.2,2.3,2.4,2.5,2.6,2.7,2.8,2.9, 3.0,3.1,3.2,3.3,3.4,3.5,3.6,3.7,3.8,3.9, 4.0,4.1,4.2}; Double_t binning_dphi_reduce[37] = { -1.570796, -1.396263, -1.221730, -1.047198, -0.872665, -0.698132, -0.523599, -0.349066, -0.174533, 0.0, 0.174533, 0.349066, 0.523599, 0.698132, 0.872665, 1.047198, 1.221730, 1.396263, 1.570796, 1.745329, 1.919862, 2.094395, 2.268928, 2.443461, 2.617994, 2.792527, 2.967060, 3.141593, 3.316126, 3.490659, 3.665191, 3.839724, 4.014257, 4.188790, 4.363323, 4.537856, 4.712389}; Int_t ndetatpcfmd; Int_t nfmdbin; if(fAnaMode=="TPCFMD") { // ndetatpcfmd=45; ndetatpcfmd=48; nfmdbin=29; }else{ ndetatpcfmd=33; nfmdbin=17; } Double_t binning_pt_fmdtpc[5] = {0.2, 0.5, 1.0, 3.0, 8.0}; /* Int_t ncentbin; if(fCentType=="Manual") { ncentbin=9; }else{ if(fcollisiontype=="PbPb") ncentbin=8; else ncentbin=7; } */ Int_t ntpcpt; Int_t nphibin=0; if(fptdiff){ ntpcpt=4; nphibin=36; }else{ ntpcpt=1; nphibin=72; } // const Int_t iTrackBin_tpcfmd[7]={ndetatpcfmd,1,nfmdbin,ncentbin,72,10,4}; Int_t nCFStepstpcfmd=1; const Int_t iTrackBin_tpcfmd[7]={ndetatpcfmd,ntpcpt,nfmdbin,ncentbin,nphibin,10,4}; fHistReconstTrack = new AliTHn("fHistReconstTrack", "fHistReconstTrack", nCFStepstpcfmd, 7, iTrackBin_tpcfmd); fHistReconstTrackMix= new AliTHn("fHistReconstTrackMix", "fHistReconstTrackMix", nCFStepstpcfmd, 7,iTrackBin_tpcfmd); if(fAnaMode=="TPCFMD") { fHistReconstTrack->SetBinLimits(0,binning_detaFMDTPC); fHistReconstTrack->SetBinLimits(2,binning_etafmd_tpcfmda); //Mixed Events fHistReconstTrackMix->SetBinLimits(0,binning_detaFMDTPC); fHistReconstTrackMix->SetBinLimits(2,binning_etafmd_tpcfmda); } else if(fAnaMode=="TPCFMDC") { fHistReconstTrack->SetBinLimits(0,binning_detaFMDCTPC); fHistReconstTrack->SetBinLimits(2,binning_etafmdc); //Mixed Events fHistReconstTrackMix->SetBinLimits(0,binning_detaFMDCTPC); fHistReconstTrackMix->SetBinLimits(2,binning_etafmdc); } if(fptdiff) fHistReconstTrack->SetBinLimits(1,binning_pt_fmdtpc); else fHistReconstTrack->SetBinLimits(1,fPtMin,fPtMax); if(fCentType=="Manual"){ if(fcollisiontype.Contains("HMPP")||fcollisiontype.Contains("MBPP")) fHistReconstTrack->SetBinLimits(3,binning_mult_pp); else fHistReconstTrack->SetBinLimits(3,binning_mult_trig); }else{ if(fcollisiontype.Contains("HMPP")) fHistReconstTrack->SetBinLimits(3,binning_cent_HMPP); else if(fcollisiontype=="MBPP")fHistReconstTrack->SetBinLimits(3,binning_cent_MBPP); else if (fcollisiontype=="PbPb") fHistReconstTrack->SetBinLimits(3,binning_cent_fmdfmd_PbPb); else fHistReconstTrack->SetBinLimits(3,binning_cent_trig); } if(fptdiff)fHistReconstTrack->SetBinLimits(4,binning_dphi_reduce); else fHistReconstTrack->SetBinLimits(4,binning_dphi); fHistReconstTrack->SetBinLimits(5,-10.,10.); fHistReconstTrack->SetBinLimits(6,-0.8,0.8); fHistReconstTrack->SetVarTitle(0,"#Delta#eta"); fHistReconstTrack->SetVarTitle(1,"p_{T} GeV/c"); fHistReconstTrack->SetVarTitle(2,"FMD Eta"); fHistReconstTrack->SetVarTitle(3,"centrality"); fHistReconstTrack->SetVarTitle(4,"#Delta#phi"); fHistReconstTrack->SetVarTitle(5,"z vertex"); fHistReconstTrack->SetVarTitle(6,"TPC eta"); if(fptdiff) fHistReconstTrackMix->SetBinLimits(1,binning_pt_fmdtpc); else fHistReconstTrackMix->SetBinLimits(1,fPtMin,fPtMax); if(fCentType=="Manual"){ if(fcollisiontype.Contains("HMPP")||fcollisiontype.Contains("MBPP")) fHistReconstTrackMix->SetBinLimits(3,binning_mult_pp); else fHistReconstTrackMix->SetBinLimits(3,binning_mult_trig); //fHistReconstTrackMix->SetBinLimits(3,binning_mult_trig); }else{ if(fcollisiontype.Contains("HMPP")) fHistReconstTrackMix->SetBinLimits(3,binning_cent_HMPP); else if(fcollisiontype=="MBPP")fHistReconstTrackMix->SetBinLimits(3,binning_cent_MBPP); else if(fcollisiontype=="PbPb" )fHistReconstTrackMix->SetBinLimits(3,binning_cent_fmdfmd_PbPb); else fHistReconstTrackMix->SetBinLimits(3,binning_cent_trig); } if(fptdiff)fHistReconstTrackMix->SetBinLimits(4,binning_dphi_reduce); else fHistReconstTrackMix->SetBinLimits(4,binning_dphi); fHistReconstTrackMix->SetBinLimits(5,-10.,10.); fHistReconstTrackMix->SetBinLimits(6,-0.8,0.8); fHistReconstTrackMix->SetVarTitle(0,"#Delta#eta"); fHistReconstTrackMix->SetVarTitle(1,"p_{T} GeV/c"); fHistReconstTrackMix->SetVarTitle(2,"FMD Eta"); fHistReconstTrackMix->SetVarTitle(3,"centrality"); fHistReconstTrackMix->SetVarTitle(4,"#Delta#phi"); fHistReconstTrackMix->SetVarTitle(5,"z vertex"); fHistReconstTrackMix->SetVarTitle(6,"TPC eta"); }else if(fAnaMode=="FMDFMD" ||fAnaMode=="FMDFMD_Ctrig"){ const Int_t nTrackVars_fmdfmd = 6; /* Int_t ncentbin; if(fCentType=="Manual") ncentbin=9; else{ if(fcollisiontype=="HMPP") ncentbin=7; else if(fcollisiontype=="PbPb") ncentbin=8; else ncentbin=7; } */ Int_t nfmdtrig; Int_t nfmdasso; if(fAnaMode=="FMDFMD"){ nfmdtrig=32; nfmdasso=17; }else{ nfmdtrig=17; nfmdasso=32; } const Int_t iTrackBin_fmdfmd[6]={49,nfmdasso,nfmdtrig,ncentbin,20,10}; fHistReconstTrack= new AliTHn("fHistReconstTrack", "fHistReconstTrack", nCFSteps, nTrackVars_fmdfmd,iTrackBin_fmdfmd); if(fAnaMode=="FMDFMD") fHistReconstTrack->SetBinLimits(0,3.425,8.325); else fHistReconstTrack->SetBinLimits(0,-8.325,-3.425); // fHistReconstTrack->SetBinLimits(0,3.525,8.325); if(fAnaMode=="FMDFMD"){ fHistReconstTrack->SetBinLimits(1,binning_etafmdc); fHistReconstTrack->SetBinLimits(2,binning_etafmd); }else{ fHistReconstTrack->SetBinLimits(1,binning_etafmd); fHistReconstTrack->SetBinLimits(2,binning_etafmdc); } if(fCentType=="Manual"){ //fHistReconstTrack->SetBinLimits(3,binning_mult_trig); if(fcollisiontype.Contains("HMPP")||fcollisiontype.Contains("MBPP")) fHistReconstTrack->SetBinLimits(3,binning_mult_pp); else fHistReconstTrack->SetBinLimits(3,binning_mult_trig); }else{ if(fcollisiontype.Contains("HMPP")) fHistReconstTrack->SetBinLimits(3,binning_cent_HMPP); else if(fcollisiontype=="MBPP")fHistReconstTrack->SetBinLimits(3,binning_cent_MBPP); else if(fcollisiontype=="PbPb")fHistReconstTrack->SetBinLimits(3,binning_cent_fmdfmd_PbPb); else fHistReconstTrack->SetBinLimits(3,binning_cent_trig); } fHistReconstTrack->SetBinLimits(4,-0.55*TMath::Pi(),1.45*TMath::Pi()); fHistReconstTrack->SetBinLimits(5,-10.,10.); fHistReconstTrack->SetVarTitle(0,"#Delta#eta"); fHistReconstTrack->SetVarTitle(1,"FMD(Asso) Eta"); fHistReconstTrack->SetVarTitle(2,"FMD(Trigger) Eta"); fHistReconstTrack->SetVarTitle(3,"centrality"); fHistReconstTrack->SetVarTitle(4,"#Delta#phi"); fHistReconstTrack->SetVarTitle(5,"z vertex"); fHistReconstTrackMix= new AliTHn("fHistReconstTrackMix", "fHistReconstTrackMix", nCFSteps, nTrackVars_fmdfmd,iTrackBin_fmdfmd); if(fAnaMode=="FMDFMD")fHistReconstTrackMix->SetBinLimits(0,3.425,8.325); else fHistReconstTrackMix->SetBinLimits(0,-8.325,-3.425); //fHistReconstTrackMix->SetBinLimits(0,3.525,8.325); if(fAnaMode=="FMDFMD"){ fHistReconstTrackMix->SetBinLimits(1,binning_etafmdc); fHistReconstTrackMix->SetBinLimits(2,binning_etafmd); }else{ fHistReconstTrackMix->SetBinLimits(1,binning_etafmd); fHistReconstTrackMix->SetBinLimits(2,binning_etafmdc); } if(fCentType=="Manual"){ //fHistReconstTrackMix->SetBinLimits(3,binning_mult_trig); if(fcollisiontype.Contains("HMPP")||fcollisiontype.Contains("MBPP")) fHistReconstTrackMix->SetBinLimits(3,binning_mult_pp); else fHistReconstTrackMix->SetBinLimits(3,binning_mult_trig); }else{ if(fcollisiontype.Contains("HMPP"))fHistReconstTrackMix->SetBinLimits(3,binning_cent_HMPP); else if(fcollisiontype=="MBPP")fHistReconstTrackMix->SetBinLimits(3,binning_cent_MBPP); else if(fcollisiontype=="PbPb")fHistReconstTrackMix->SetBinLimits(3,binning_cent_fmdfmd_PbPb); else fHistReconstTrackMix->SetBinLimits(3,binning_cent_trig); } // fHistReconstTrackMix->SetBinLimits(4,-0.551*TMath::Pi(),1.449*TMath::Pi()); fHistReconstTrackMix->SetBinLimits(4,-0.55*TMath::Pi(),1.45*TMath::Pi()); fHistReconstTrackMix->SetBinLimits(5,-10,10.); fHistReconstTrackMix->SetVarTitle(0,"#Delta#eta"); fHistReconstTrackMix->SetVarTitle(1,"FMD(Asso) Eta"); fHistReconstTrackMix->SetVarTitle(2,"FMD(Trigger) Eta"); fHistReconstTrackMix->SetVarTitle(3,"centrality"); fHistReconstTrackMix->SetVarTitle(4,"#Delta#phi"); fHistReconstTrackMix->SetVarTitle(5,"z vertex"); }else if(fAnaMode=="SECA" || fAnaMode=="SECC"){ const Int_t nTrackVars_fmdfmd = 5; const Double_t binning_cent_fmdfmd[12]={0.,5.,10.,20.,30.,40.,50.,60.,70.,80.,90.,100.1}; Int_t binsec; if(fAnaMode=="SECA") binsec=64; else binsec=34; const Int_t iTrackBin_fmdfmd[5]={130,binsec,11,20,10}; fHistReconstTrack= new AliTHn("fHistReconstTrack", "fHistReconstTrack", nCFSteps, nTrackVars_fmdfmd,iTrackBin_fmdfmd); fHistReconstTrack->SetBinLimits(0,-3.275,3.225); if(fAnaMode=="SECA") fHistReconstTrack->SetBinLimits(1,1.7,4.9); else if (fAnaMode=="SECC") fHistReconstTrack->SetBinLimits(1,-3.4,-1.7); fHistReconstTrack->SetBinLimits(2,binning_cent_fmdfmd); fHistReconstTrack->SetBinLimits(3,-0.55*TMath::Pi(),1.45*TMath::Pi()); fHistReconstTrack->SetBinLimits(4,binning_zvx); fHistReconstTrack->SetVarTitle(0,"#Delta#eta"); fHistReconstTrack->SetVarTitle(1,"FMD(Trigger) Eta"); fHistReconstTrack->SetVarTitle(2,"centrality"); fHistReconstTrack->SetVarTitle(3,"#Delta#phi"); fHistReconstTrack->SetVarTitle(4,"z vertex"); fHistReconstTrackMix= new AliTHn("fHistReconstTrackMix", "fHistReconstTrackMix", nCFSteps, nTrackVars_fmdfmd,iTrackBin_fmdfmd); fHistReconstTrackMix->SetBinLimits(0,-3.275,3.225); if(fAnaMode=="SECA") fHistReconstTrackMix->SetBinLimits(1,1.7,4.9); else if(fAnaMode=="SECC") fHistReconstTrackMix->SetBinLimits(1,-3.4,-1.7); fHistReconstTrackMix->SetBinLimits(2,binning_cent_fmdfmd); fHistReconstTrackMix->SetBinLimits(3,-0.55*TMath::Pi(),1.45*TMath::Pi()); fHistReconstTrackMix->SetBinLimits(4,binning_zvx); fHistReconstTrackMix->SetVarTitle(0,"#Delta#eta"); fHistReconstTrackMix->SetVarTitle(1,"FMD(Trigger) Eta"); fHistReconstTrackMix->SetVarTitle(2,"centrality"); fHistReconstTrackMix->SetVarTitle(3,"#Delta#phi"); fHistReconstTrackMix->SetVarTitle(4,"z vertex"); }else if(fAnaMode=="V0AV0C"){ const Int_t nTrackVars_v0av0c = 4; const Int_t iTrackBin_VZEROAVZEROC[4]={10,10,11,8}; fHistReconstTrack= new AliTHn("fHistReconstTrack", "fHistReconstTrack", nCFSteps, nTrackVars_v0av0c,iTrackBin_VZEROAVZEROC); fHistReconstTrack->SetBinLimits(0,binning_eta_vzero); fHistReconstTrack->SetBinLimits(1,binning_eta_vzero); fHistReconstTrack->SetBinLimits(2,binning_cent); fHistReconstTrack->SetBinLimits(3,binning_dphi_vzero); fHistReconstTrack->SetVarTitle(0,"Vzero(Asso) Eta"); fHistReconstTrack->SetVarTitle(1,"Vzero(Trigger) Eta"); fHistReconstTrack->SetVarTitle(2,"centrality"); fHistReconstTrack->SetVarTitle(3,"#Delta#phi"); fHistReconstTrackMix= new AliTHn("fHistReconstTrackMix", "fHistReconstTrackMix", nCFSteps, nTrackVars_v0av0c,iTrackBin_VZEROAVZEROC); fHistReconstTrackMix->SetBinLimits(0,binning_eta_vzero); fHistReconstTrackMix->SetBinLimits(1,binning_eta_vzero); fHistReconstTrackMix->SetBinLimits(2,binning_cent); fHistReconstTrackMix->SetBinLimits(3,binning_dphi_vzero); fHistReconstTrackMix->SetVarTitle(0,"Vzero(Asso) Eta"); fHistReconstTrackMix->SetVarTitle(1,"Vzero(Trigger) Eta"); fHistReconstTrackMix->SetVarTitle(2,"centrality"); fHistReconstTrackMix->SetVarTitle(3,"#Delta#phi"); }else if(fAnaMode=="ITSFMD" || fAnaMode=="ITSFMDC"){ Double_t binning_detaFMDITS[66]={ -6.6,-6.5,-6.4,-6.3,-6.2,-6.1,-6.0, -5.9,-5.8,-5.7,-5.6,-5.5,-5.4,-5.3,-5.2,-5.1,-5.0, -4.9,-4.8,-4.7,-4.6,-4.5,-4.4,-4.3,-4.2,-4.1,-4., -3.9,-3.8,-3.7,-3.6,-3.5,-3.4,-3.3,-3.2,-3.1,-3., -2.9,-2.8,-2.7,-2.6,-2.5,-2.4,-2.3,-2.2,-2.1,-2., -1.9,-1.8,-1.7,-1.6,-1.5,-1.4,-1.3,-1.2,-1.1,-1., -0.9,-0.8,-0.7,-0.6,-0.5,-0.4,-0.3,-0.2,-0.1}; Double_t binning_detaFMDCITS[50]={ 0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9, 1.0,1.1,1.2,1.3,1.4,1.5,1.6,1.7,1.8,1.9, 2.0,2.1,2.2,2.3,2.4,2.5,2.6,2.7,2.8,2.9, 3.0,3.1,3.2,3.3,3.4,3.5,3.6,3.7,3.8,3.9, 4.0,4.1,4.2,4.3,4.4,4.5,4.6,4.7,4.8,4.9, 5.0}; Double_t binning_dphi_itsfmd[37] = { -1.570796, -1.396263, -1.221730, -1.047198, -0.872665, -0.698132, -0.523599, -0.349066, -0.174533, 0.0, 0.174533, 0.349066, 0.523599, 0.698132, 0.872665, 1.047198, 1.221730, 1.396263, 1.570796, 1.745329, 1.919862, 2.094395, 2.268928, 2.443461, 2.617994, 2.792527, 2.967060, 3.141593, 3.316126, 3.490659, 3.665191, 3.839724, 4.014257, 4.188790, 4.363323, 4.537856, 4.712389}; Double_t binning_cent_its[8]={0.,5.,10.,20.,40.,60.,80.,100.}; Int_t nbinitsfmddeltaeta; Int_t nbinetafmd; if(fAnaMode=="ITSFMD"){ nbinitsfmddeltaeta=65; nbinetafmd=32; }else{// if(fAnaMode=="ITSFMDC"){ nbinitsfmddeltaeta=49; nbinetafmd=17; } const Int_t iTrackBin_tpcfmd[6]={nbinitsfmddeltaeta,7,nbinetafmd,36,20,6}; Double_t binning_zvx_fmdits[2]={-10,10}; // Double_t binning_itseta[19]={-1.7, -1.6, -1.4, -1.2, -1.0, -0.8, -0.6, -0.4, -0.2, 0.,0.2, 0.4, 0.6, 0.8, 1.0, 1.2, 1.4, 1.6, 1.7}; Double_t binning_itseta[7]={-1.7,-1.2,-0.6,0.,0.6,1.2,1.7}; fHistReconstTrack = new AliTHn("fHistReconstTrack", "fHistReconstTrack", nCFSteps, 6, iTrackBin_tpcfmd); if(fAnaMode=="ITSFMD") { fHistReconstTrack->SetBinLimits(0,binning_detaFMDITS); fHistReconstTrack->SetBinLimits(2,binning_etafmd); }else if(fAnaMode=="ITSFMDC") { fHistReconstTrack->SetBinLimits(0,binning_detaFMDCITS); fHistReconstTrack->SetBinLimits(2,binning_etafmdc); } fHistReconstTrack->SetBinLimits(1,binning_cent_its); fHistReconstTrack->SetBinLimits(3,binning_dphi_itsfmd); fHistReconstTrack->SetBinLimits(4,-10.,10.); fHistReconstTrack->SetBinLimits(5,binning_itseta); fHistReconstTrack->SetVarTitle(0,"#Delta#eta"); fHistReconstTrack->SetVarTitle(2,"FMD Eta"); fHistReconstTrack->SetVarTitle(1,"centrality"); fHistReconstTrack->SetVarTitle(3,"#Delta#phi"); fHistReconstTrack->SetVarTitle(4,"z vertex"); fHistReconstTrack->SetVarTitle(5,"ITS Eta"); fHistReconstTrackMix= new AliTHn("fHistReconstTrackMix", "fHistReconstTrackMix", nCFSteps, 6,iTrackBin_tpcfmd); if(fAnaMode=="ITSFMD") { fHistReconstTrackMix->SetBinLimits(0,binning_detaFMDITS); fHistReconstTrackMix->SetBinLimits(2,binning_etafmd); }else if(fAnaMode=="ITSFMDC") { fHistReconstTrackMix->SetBinLimits(0,binning_detaFMDCITS); fHistReconstTrackMix->SetBinLimits(2,binning_etafmdc); } fHistReconstTrackMix->SetBinLimits(1,binning_cent_its); fHistReconstTrackMix->SetBinLimits(3,binning_dphi_itsfmd); fHistReconstTrackMix->SetBinLimits(4,-10.,10.); fHistReconstTrackMix->SetBinLimits(5,binning_itseta); fHistReconstTrackMix->SetVarTitle(0,"#Delta#eta"); fHistReconstTrackMix->SetVarTitle(1,"centrality"); fHistReconstTrackMix->SetVarTitle(2,"FMD Eta"); fHistReconstTrackMix->SetVarTitle(3,"#Delta#phi"); fHistReconstTrackMix->SetVarTitle(4,"z vertex"); fHistReconstTrackMix->SetVarTitle(5,"ITS Eta"); } fOutputList1->Add(fHistReconstTrack); fOutputList1->Add(fHistReconstTrackMix); if(fAnaMode=="SP"){ fHistQna=new TH2D("fHistQna","fHistQna",200,0.,10.,10,0,100); fOutputList1->Add(fHistQna); fHistQnc=new TH2D("fHistQnc","fHistQnc",200,0.,10.,10,0,100); fOutputList1->Add(fHistQnc); fHistQn=new TH2D("fHistQn","fHistQn",200,0.,10.,10,0,100); fOutputList1->Add(fHistQn); fHistQna_VZERO=new TH2D("fHistQna_VZERO","fHistQna_VZERO",200,0.,10.,10,0,100); fOutputList1->Add(fHistQna_VZERO); fHistQnc_VZERO=new TH2D("fHistQnc_VZERO","fHistQnc_VZERO",200,0.,10.,10,0,100); fOutputList1->Add(fHistQnc_VZERO); fHistQn_VZERO=new TH2D("fHistQn_VZERO","fHistQn_VZERO",200,0.,10.,10,0,100); fOutputList1->Add(fHistQn_VZERO); fHistVn=new TH1D("fHistVn","fHistVn",200,-1.,1.); fOutputList1->Add(fHistVn); for(Int_t i=0;i<4;i++){ fHistQAQB[i]=new TH1D(Form("fHistQAQB_%d",i),Form("fHistQAQB_%d",i),400,-2.,2.); fOutputList1->Add(fHistQAQB[i]); fHistQAQB_VZERO[i]=new TH1D(Form("fHistQAQB_VZERO_%d",i),Form("fHistQAQB_VZERO_%d",i),400,-2.,2.); fOutputList1->Add(fHistQAQB_VZERO[i]); fHistCorrQna[i]=new TH2D(Form("fHistCorrQna_%d",i),"fHistCorrQna",200,0.,10.,200,0,10); fOutputList1->Add(fHistCorrQna[i]); fHistCorrQnc[i]=new TH2D(Form("fHistCorrQnc_%d",i),"fHistCorrQnc",200,0.,10.,200,0,10); fOutputList1->Add(fHistCorrQnc[i]); } Double_t binning_cent_QAQC[5]={0.,20.,40.,60.,100.}; SP_TPCATPCC = new TProfile("SP_TPCATPCC","QAQC",4,binning_cent_QAQC,-3,+3,"s"); fOutputList1->Add(SP_TPCATPCC); SP_TPCATPCC_default = new TProfile("SP_TPCATPCC_default","QAQC",4,binning_cent_QAQC,-3,+3); fOutputList1->Add(SP_TPCATPCC_default); SP_V0AV0C_default = new TProfile("SP_V0AV0C_default","QAQC",4,binning_cent_QAQC,-3,+3); fOutputList1->Add(SP_V0AV0C_default); SP_V0ATPC_default = new TProfile("SP_V0ATPC_default","QAQC",4,binning_cent_QAQC,-3,+3); fOutputList1->Add(SP_V0ATPC_default); SP_V0CTPC_default = new TProfile("SP_V0CTPC_default","QAQC",4,binning_cent_QAQC,-3,+3); fOutputList1->Add(SP_V0CTPC_default); fHist_V0AV0C = new TH1F("fHist_V0AV0C","QAQC",200,-1,1); fOutputList1->Add(fHist_V0AV0C); fHist_V0ATPC= new TH1F("fHist_V0ATPC","QAQC",200,-1,1); fOutputList1->Add(fHist_V0ATPC); fHist_V0CTPC = new TH1F("fHist_V0CTPC","QAQC",200,-1,1); fOutputList1->Add(fHist_V0CTPC); SP_uTPCA = new TProfile("SP_uTPCA","u x Q_{TPCA}",11,binning_pt_assoc,-3,+3); fOutputList1->Add(SP_uTPCA); SP_uTPCC = new TProfile("SP_uTPCC","u x Q_{TPCC}",11,binning_pt_assoc,-3,+3); fOutputList1->Add(SP_uTPCC); Int_t nbin_uTPC=11; Double_t binning_pt_assoc_uTPC[12] = {0.3, 0.5, 0.75, 1.0, 1.25, 1.5,2.0, 2.5, 3.0, 3.5, 4.0, 8.0}; Int_t nbin_uTPCPhi=4; Double_t binning_pt_assoc_uTPCPhi[5] = {0., 0.5, 2.0, 4.0, 8.0}; Int_t nbin_uTPCCas=3; Double_t binning_pt_assoc_uTPCCas[4] = {0., 1., 4., 8.}; for(Int_t i=0;i<8;i++){ SP_uVZEROA_PP[i] = new TProfile(Form("SP_uVZEROA_PP_%d",i),"u x Q_{TPC}",nbin_uTPC,binning_pt_assoc_uTPC,-3,+3); fOutputList1->Add(SP_uVZEROA_PP[i]); SP_uVZEROA[i] = new TProfile(Form("SP_uVZEROA_%d",i),"u x Q_{TPC}",nbin_uTPC,binning_pt_assoc_uTPC,-3,+3); fOutputList1->Add(SP_uVZEROA[i]); SP_uVZEROA1[i] = new TProfile(Form("SP_uVZEROA1_%d",i),"u x Q_{TPC}",nbin_uTPC,binning_pt_assoc_uTPC,-3,+3); fOutputList1->Add(SP_uVZEROA1[i]); SP_uVZEROA2[i] = new TProfile(Form("SP_uVZEROA2_%d",i),"u x Q_{TPC}",nbin_uTPC,binning_pt_assoc_uTPC,-3,+3); fOutputList1->Add(SP_uVZEROA2[i]); SP_uVZEROA3[i] = new TProfile(Form("SP_uVZEROA3_%d",i),"u x Q_{TPC}",nbin_uTPC,binning_pt_assoc_uTPC,-3,+3); fOutputList1->Add(SP_uVZEROA3[i]); SP_uVZEROC_PP[i] = new TProfile(Form("SP_uVZEROC_PP_%d",i),"u x Q_{TPC}",nbin_uTPC,binning_pt_assoc_uTPC,-3,+3); fOutputList1->Add(SP_uVZEROC_PP[i]); SP_uVZEROC[i] = new TProfile(Form("SP_uVZEROC_%d",i),"u x Q_{TPC}",nbin_uTPC,binning_pt_assoc_uTPC,-3,+3); fOutputList1->Add(SP_uVZEROC[i]); SP_uVZEROC1[i] = new TProfile(Form("SP_uVZEROC1_%d",i),"u x Q_{TPC}",nbin_uTPC,binning_pt_assoc_uTPC,-3,+3); fOutputList1->Add(SP_uVZEROC1[i]); SP_uVZEROC2[i] = new TProfile(Form("SP_uVZEROC2_%d",i),"u x Q_{TPC}",nbin_uTPC,binning_pt_assoc_uTPC,-3,+3); fOutputList1->Add(SP_uVZEROC2[i]); SP_uVZEROC3[i] = new TProfile(Form("SP_uVZEROC3_%d",i),"u x Q_{TPC}",nbin_uTPC,binning_pt_assoc_uTPC,-3,+3); fOutputList1->Add(SP_uVZEROC3[i]); } if(fasso=="PID" || fasso=="hadron" || fasso=="V0"){ for(Int_t i=0;i<8;i++){ SP_uTPC_PP[i] = new TProfile(Form("SP_uTPC_PP_%d",i),"u x Q_{TPC}",nbin_uTPC,binning_pt_assoc_uTPC,-3,+3); fOutputList1->Add(SP_uTPC_PP[i]); SP_uTPC[i] = new TProfile(Form("SP_uTPC_%d",i),"u x Q_{TPC}",nbin_uTPC,binning_pt_assoc_uTPC,-3,+3); fOutputList1->Add(SP_uTPC[i]); SP_uTPC1[i] = new TProfile(Form("SP_uTPC1_%d",i),"u x Q_{TPC}",nbin_uTPC,binning_pt_assoc_uTPC,-3,+3); fOutputList1->Add(SP_uTPC1[i]); SP_uTPC2[i] = new TProfile(Form("SP_uTPC2_%d",i),"u x Q_{TPC}",nbin_uTPC,binning_pt_assoc_uTPC,-3,+3); fOutputList1->Add(SP_uTPC2[i]); SP_uTPC3[i] = new TProfile(Form("SP_uTPC3_%d",i),"u x Q_{TPC}",nbin_uTPC,binning_pt_assoc_uTPC,-3,+3); fOutputList1->Add(SP_uTPC3[i]); } }else if(fasso=="Phi"){ for(Int_t i=0;i<8;i++){ SP_uTPC_PP[i] = new TProfile(Form("SP_uTPC_PP_%d",i),"u x Q_{TPC}",nbin_uTPC,binning_pt_assoc_uTPCPhi,-3,+3); fOutputList1->Add(SP_uTPC_PP[i]); SP_uTPC[i] = new TProfile(Form("SP_uTPC_%d",i),"u x Q_{TPC}",nbin_uTPCPhi,binning_pt_assoc_uTPCPhi,-3,+3); fOutputList1->Add(SP_uTPC[i]); SP_uTPC1[i] = new TProfile(Form("SP_uTPC1_%d",i),"u x Q_{TPC}",nbin_uTPCPhi,binning_pt_assoc_uTPCPhi,-3,+3); fOutputList1->Add(SP_uTPC1[i]); SP_uTPC2[i] = new TProfile(Form("SP_uTPC2_%d",i),"u x Q_{TPC}",nbin_uTPCPhi,binning_pt_assoc_uTPCPhi,-3,+3); fOutputList1->Add(SP_uTPC2[i]); SP_uTPC3[i] = new TProfile(Form("SP_uTPC3_%d",i),"u x Q_{TPC}",nbin_uTPCPhi,binning_pt_assoc_uTPCPhi,-3,+3); fOutputList1->Add(SP_uTPC3[i]); } }else if(fasso=="Cascade"){ for(Int_t i=0;i<8;i++){ SP_uTPC_PP[i] = new TProfile(Form("SP_uTPC_PP_%d",i),"u x Q_{TPC}",nbin_uTPC,binning_pt_assoc_uTPCCas,-3,+3); fOutputList1->Add(SP_uTPC_PP[i]); SP_uTPC[i] = new TProfile(Form("SP_uTPC_%d",i),"u x Q_{TPC}",nbin_uTPCCas,binning_pt_assoc_uTPCCas,-3,+3); fOutputList1->Add(SP_uTPC[i]); SP_uTPC1[i] = new TProfile(Form("SP_uTPC1_%d",i),"u x Q_{TPC}",nbin_uTPCCas,binning_pt_assoc_uTPCCas,-3,+3); fOutputList1->Add(SP_uTPC1[i]); SP_uTPC2[i] = new TProfile(Form("SP_uTPC2_%d",i),"u x Q_{TPC}",nbin_uTPCCas,binning_pt_assoc_uTPCCas,-3,+3); fOutputList1->Add(SP_uTPC2[i]); SP_uTPC3[i] = new TProfile(Form("SP_uTPC3_%d",i),"u x Q_{TPC}",nbin_uTPCCas,binning_pt_assoc_uTPCCas,-3,+3); fOutputList1->Add(SP_uTPC3[i]); } } } } void AliAnalysisTaskSEpPbCorrelationsYS::UserExec(Option_t *) { DumpTObjTable("Start analysis"); AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); AliInputEventHandler *inEvMain = (AliInputEventHandler *)(mgr->GetInputEventHandler()); if (!inEvMain) return; if(fasso!="hadron"){ fPIDResponse = inEvMain->GetPIDResponse(); if (!fPIDResponse) return; } if(!fDataType){ AliMCEventHandler* mctruth = (AliMCEventHandler*)(mgr->GetMCtruthEventHandler()); if(!mctruth) return; mcEvent=mctruth->MCEvent();//AliMCEvent } fEvent = dynamic_cast<AliAODEvent *>(inEvMain->GetEvent()); if (!fEvent) { AliWarning("ERROR: fEvent not available \n"); return; } fHist_Stat->Fill(0); if(fcollisiontype=="pPb" || fcollisiontype=="PP"|| fcollisiontype=="PbPb"){ if (!fEventCuts.AcceptEvent(fEvent)) { PostData(1, fOutputList); PostData(2, fOutputList1); PostData(3, fOutputList2); return; } }else if(fcollisiontype=="HMPPV0"){ UInt_t maskIsSelected = inEvMain->IsEventSelected(); Bool_t isSelected = kFALSE; isSelected = ((maskIsSelected & AliVEvent::kHighMultV0)== AliVEvent::kHighMultV0); if (!isSelected) { PostData(1, fOutputList); PostData(2, fOutputList1); PostData(3, fOutputList2); return; } }else if(fcollisiontype=="HMPPSPD"){ UInt_t maskIsSelected = inEvMain->IsEventSelected(); Bool_t isSelected = kFALSE; isSelected = ((maskIsSelected & AliVEvent::kHighMultSPD)== AliVEvent::kHighMultSPD); if (!isSelected) { PostData(1, fOutputList); PostData(2, fOutputList1); PostData(3, fOutputList2); return; } }else if (fcollisiontype.Contains("MBPP")){ UInt_t maskIsSelected = inEvMain->IsEventSelected(); Bool_t isSelected = kFALSE; isSelected = ((maskIsSelected & AliVEvent::kINT7)== AliVEvent::kINT7);//Both for data and if (!isSelected) { PostData(1, fOutputList); PostData(2, fOutputList1); PostData(3, fOutputList2); return; } } /*else if(fcollisiontype=="PbPb"){ //same way as Freja // Get the event validation object AliForwardTaskValidation* ev_val = dynamic_cast<AliForwardTaskValidation*>(this->GetInputData(1)); if (!ev_val->IsValidEvent()){ PostData(1, fOutputList); PostData(2, fOutputList1); PostData(3, fOutputList2); return; } } */ /* //Vertex Bool_t IsGoodVtx=kFALSE; Bool_t IsValidVtx=kFALSE; const AliVVertex* spdVtx = fEvent->GetPrimaryVertexSPD() ; if( spdVtx ){ if( spdVtx->GetNContributors() > 0.5 ) IsValidVtx = kTRUE; auto fZ = spdVtx->GetZ(); auto zbin = binZ.FindBin(fZ) -1; if( fabs(fZ) < 10 && !(zbin < 0 )) IsGoodVtx = kTRUE; } if(!IsGoodVtx || !IsValidVtx){ PostData(1, fOutputList); PostData(2, fOutputList1); PostData(3, fOutputList2); return; } */ //Pile up if(fcollisiontype.Contains("MBPP") || fcollisiontype.Contains("HMPP")){ Bool_t IsNotPileup = kFALSE; if( !fEvent->IsPileupFromSPDInMultBins() ) IsNotPileup = kTRUE; if(!IsNotPileup){ PostData(1, fOutputList); PostData(2, fOutputList1); PostData(3, fOutputList2); return; } fHist_Stat->Fill(8); } fHist_Stat->Fill(1); AliMultSelection *multSelection = (AliMultSelection *)fEvent->FindListObject("MultSelection"); if(!multSelection) return; fHist_Stat->Fill(2); //Pileu rejection by MultSelection if(fcollisiontype.Contains("HMPP") || fcollisiontype.Contains("MBPP")){ Bool_t IsSelectedFromAliMultSelection=kFALSE; if( multSelection->GetThisEventIsNotPileup() && multSelection->GetThisEventIsNotPileupInMultBins() && multSelection->GetThisEventHasNoInconsistentVertices() && multSelection->GetThisEventPassesTrackletVsCluster() ){ IsSelectedFromAliMultSelection = kTRUE; } if(!IsSelectedFromAliMultSelection) { PostData(1, fOutputList); PostData(2, fOutputList1); PostData(3, fOutputList2); return; } fHist_Stat->Fill(9); } // if(fcollisiontype.Contains("HMPP")AliMultSelectionTask::SetHighMultQABinning(kTRUE); lPrimaryBestVtx = fEvent->GetPrimaryVertex(); if(fcollisiontype.Contains("HMPP") || fcollisiontype.Contains("MBPP")){ Int_t nTracksPrim = lPrimaryBestVtx->GetNContributors(); if (nTracksPrim < 0.5) { PostData(1, fOutputList); PostData(2, fOutputList1); PostData(3, fOutputList2); return; } fHist_Stat->Fill(10); } if ((TMath::Abs(lPrimaryBestVtx->GetZ())) >= fZVertex) { PostData(1, fOutputList); PostData(2, fOutputList1); PostData(3, fOutputList2); return; } tPrimaryVtxPosition[0] = lPrimaryBestVtx->GetX(); tPrimaryVtxPosition[1] = lPrimaryBestVtx->GetY(); tPrimaryVtxPosition[2] = lPrimaryBestVtx->GetZ(); fPrimaryZVtx = lPrimaryBestVtx->GetZ(); fHist_Stat->Fill(3); bSign = 0.; bSign = (InputEvent()->GetMagneticField() > 0) ? 1 : -1; /* AliVMultiplicity *tracklets = ((AliAODEvent*)fEvent)->GetTracklets(); if (!tracklets) return; Int_t nTracklets = tracklets->GetNumberOfTracklets(); */ // Multiplicity Object if(fcollisiontype=="HMPPSPD" && fcuthighmult>0){ AliVMultiplicity *tracklets = ((AliAODEvent*)fEvent)->GetTracklets(); // if (!tracklets) return; Int_t nTracklets = tracklets->GetNumberOfTracklets(); Int_t nITScluster= tracklets->GetNumberOfITSClusters(0)+tracklets->GetNumberOfITSClusters(1); Int_t nTracks = fEvent->GetNumberOfTracks(); fh2_SPD_multcorr->Fill(nTracklets,nITScluster); fh2_SPDtrack_multcorr->Fill(nTracklets,nTracks); if(nTracklets<fcuthighmult){ PostData(1, fOutputList); PostData(2, fOutputList1); PostData(3, fOutputList2); return; } } if(fcollisiontype=="HMPPV0" && fcuthighmult>0){ Double_t fCentrality = multSelection->GetMultiplicityPercentile("V0M"); if(fCentrality>fcuthighmult){ PostData(1, fOutputList); PostData(2, fOutputList1); PostData(3, fOutputList2); return; } } if(fCentType=="Manual"){ TObjArray *selectedTracksLeading = new TObjArray; selectedTracksLeading->SetOwner(kTRUE); selectedTracksLeading=GetAcceptedTracksLeading(fEvent,kFALSE,selectedTracksLeading); Int_t nTracks=selectedTracksLeading->GetEntriesFast(); lCentrality=nTracks; selectedTracksLeading->Clear(); delete selectedTracksLeading; }else{ lCentrality = multSelection->GetMultiplicityPercentile(fCentType); Int_t qual = multSelection->GetEvSelCode(); if (qual == 199) lCentrality = -999; if (lCentrality < 0. || lCentrality > 100. - 0.0000001) return; } Double_t *CentBins = fCentBins; poolmin = CentBins[0]; poolmax = CentBins[fNCentBins]; fHist_Stat->Fill(4); // fHistCentV0vsTrackletsbefore->Fill(lCentrality,nTracklets); /* fUtils=new AliAnalysisUtils; //if(fcollisiontype=="pp") if(fUtils->IsPileUpSPD(fEvent)) return; if(fUtils->IsPileUpMV(fEvent)) return; //if(fUtils->IsPileUpSPD(fEvent)) return; // if(fEvent->IsPileupFromSPD(5,0.8,3.,2.,5.)) return; // SPD vertex selection const AliAODVertex* vtxSPD = dynamic_cast<const AliAODVertex*>(fEvent->GetPrimaryVertexSPD()); Double_t cov[6] = {0}; vtxSPD->GetCovarianceMatrix(cov); Double_t zRes = TMath::Sqrt(cov[5]); if ( vtxSPD->IsFromVertexerZ() && (zRes > dMaxResol)) return; fHist_Stat->Fill(6); */ /* if(fcollisiontype=="PbPb"){ if(!NotSPDClusterVsTrackletBG()) { PostData(1, fOutputList); PostData(2, fOutputList1); PostData(3, fOutputList2); return; } fHist_Stat->Fill(12); } */ fHistCentrality_beforecut->Fill(lCentrality); // fHist_Stat->Fill(5); DumpTObjTable("After event selection"); MakeAna(); PostData(1, fOutputList); PostData(2, fOutputList1); PostData(3, fOutputList2); } void AliAnalysisTaskSEpPbCorrelationsYS::Terminate(Option_t *) { // AliInfo(Form("Number of Correlation DumpTObjTable("End of the analysis"); Printf("Entries======================%d",fNEntries); if (fPoolMgr) delete fPoolMgr; // PoolMgr->ClearPools(); if (fPoolMgr1) delete fPoolMgr1; // fPoolMgr1->ClearPools(); } void AliAnalysisTaskSEpPbCorrelationsYS::MakeAna() { DumpTObjTable("start correlation analysis"); fvzero = fEvent->GetVZEROData(); if(!fvzero){ PostData(1, fOutputList); PostData(2, fOutputList1); PostData(3, fOutputList2); return; } Double_t eta_min; Double_t eta_max; Double_t eta_ave; Double_t phi_vzero; Double_t mult_vzero; Double_t mult_vzero_eq; Float_t nV0A_hits_fmdacc=0; Float_t nV0C_hits_fmdacc=0; for (Int_t imod = 0; imod < 64; imod++) { eta_min = fvzero->GetVZEROEtaMin(imod); eta_max = fvzero->GetVZEROEtaMax(imod); phi_vzero = fvzero->GetVZEROAvgPhi(imod); mult_vzero = fvzero->GetMultiplicity(imod); mult_vzero_eq = fEvent->GetVZEROEqMultiplicity(imod); eta_ave = (eta_min + eta_max) / 2.; if(eta_ave>2.8 && eta_ave<5.03) nV0A_hits_fmdacc+=mult_vzero_eq; else if(eta_ave>-3.4 && eta_ave<-2.01) nV0C_hits_fmdacc+=mult_vzero_eq; fHist_vzeromult->Fill(imod, mult_vzero); fHist_vzeromultEqweighted->Fill(imod, mult_vzero_eq); fHist2dmult->Fill(imod, mult_vzero_eq, mult_vzero); } Float_t nFMD_fwd_hits=0; Float_t nFMD_bwd_hits=0; Float_t nFMD_fwdV0acc_hits=0; Float_t nFMD_bwdV0acc_hits=0; AliAODForwardMult*aodForward=static_cast<AliAODForwardMult*>(fEvent->FindListObject("Forward")); if(!aodForward) {//HasFMD PostData(1, fOutputList); PostData(2, fOutputList1); PostData(3, fOutputList2); return; } fHist_Stat->Fill(5); // Shape of d2Ndetadphi: 200, -4, 6, 20, 0, 2pi TH2D& d2Ndetadphi = aodForward->GetHistogram(); TH1*hphiacceptance=aodForward->GetPhiAcceptance(); Int_t nEta = d2Ndetadphi.GetXaxis()->GetNbins(); Int_t nPhi = d2Ndetadphi.GetYaxis()->GetNbins(); Double_t pt = 0; for (Int_t iEta = 1; iEta <= nEta; iEta++) { Int_t valid = Int_t(d2Ndetadphi.GetBinContent(iEta, 0)); if (!valid) { continue; } Float_t eta = d2Ndetadphi.GetXaxis()->GetBinCenter(iEta); Float_t phiacc=hphiacceptance->GetBinContent(iEta); fhistfmdphiacc->Fill(eta,lCentrality,phiacc); for (Int_t iPhi = 1; iPhi <= nPhi; iPhi++) { // Bin content is most likely number of particles! Float_t phi = d2Ndetadphi.GetYaxis()->GetBinCenter(iPhi); Float_t mostProbableN = d2Ndetadphi.GetBinContent(iEta, iPhi); fh2_FMD_acceptance->Fill(eta,tPrimaryVtxPosition[2],mostProbableN); if (mostProbableN > 0) { if(eta>0){ nFMD_fwd_hits+=mostProbableN; if(2.8<eta && eta<5.03) nFMD_fwdV0acc_hits+=mostProbableN; }else{ nFMD_bwd_hits+=mostProbableN; if(-3.4<eta && eta<-2.01) nFMD_bwdV0acc_hits+=mostProbableN; } fh2_FMD_eta_phi->Fill(eta,phi,mostProbableN); } } } Float_t nV0A_hits = fvzero->GetMTotV0A(); Float_t nV0C_hits = fvzero->GetMTotV0C(); fFMDV0->Fill(nFMD_bwd_hits + nFMD_fwd_hits, nV0C_hits + nV0A_hits); fFMDV0A->Fill(nFMD_fwd_hits, nV0A_hits); fFMDV0C->Fill(nFMD_bwd_hits, nV0C_hits); fFMDV0same->Fill(nFMD_bwdV0acc_hits + nFMD_fwdV0acc_hits, nV0C_hits_fmdacc + nV0A_hits_fmdacc); fFMDV0Asame->Fill(nFMD_fwdV0acc_hits, nV0A_hits_fmdacc); fFMDV0Csame->Fill(nFMD_bwdV0acc_hits, nV0C_hits_fmdacc); if(nFMD_fwd_hits==0 || nFMD_bwd_hits==0){ delete hphiacceptance; PostData(1, fOutputList); PostData(2, fOutputList1); PostData(3, fOutputList2); return; } fHist_Stat->Fill(6); if(fFMDaddcut && (fcollisiontype.Contains("HMPP")||fcollisiontype=="MBPP")){ if(!HasValidFMDYS(d2Ndetadphi)){ delete hphiacceptance; PostData(1, fOutputList); PostData(2, fOutputList1); PostData(3, fOutputList2); return; } fHist_Stat->Fill(11); } if(fCentType=="Manual")fh2_SPDV0_multcorr->Fill(lCentrality,nV0C_hits+nV0A_hits); /* fHist_NeventRun->Fill(ConvertRunNumber(fEvent->GetRunNumber())); fHist_V0AMultRun->Fill(ConvertRunNumber(fEvent->GetRunNumber()),nV0A_hits); fHist_V0CMultRun->Fill(ConvertRunNumber(fEvent->GetRunNumber()),nV0C_hits); fHist_FMDAMultRun->Fill(ConvertRunNumber(fEvent->GetRunNumber()),nFMD_fwd_hits); fHist_FMDCMultRun->Fill(ConvertRunNumber(fEvent->GetRunNumber()),nFMD_bwd_hits); */ if(fFMDcut){ Double_t FMDcutapar0=0.; Double_t FMDcutapar1=0.; Double_t FMDcutcpar0=0.; Double_t FMDcutcpar1=0.; switch(fFMDcutmode){ case 1: FMDcutapar0=1.3; FMDcutapar1=200; FMDcutcpar0=2.; FMDcutcpar1=200; break; case 2: FMDcutapar0=1.3; FMDcutapar1=600; FMDcutcpar0=2.; FMDcutcpar1=600; break; case 3: FMDcutapar0=1.5; FMDcutapar1=100; FMDcutcpar0=2.3; FMDcutcpar1=100; break; case 4: FMDcutapar0=1.5; FMDcutapar1=300; FMDcutcpar0=2.3; FMDcutcpar1=300; break; case 5: FMDcutapar0=1.3; FMDcutapar1=400; FMDcutcpar0=2.; FMDcutcpar1=400; break; case 6: FMDcutapar0=1.75; FMDcutapar1=150; FMDcutcpar0=1.4; FMDcutcpar1=120; break; case 7: FMDcutapar0=1.64755; FMDcutapar1=119.602; FMDcutcpar0=2.73426; FMDcutcpar1=150.31; break; case 8: FMDcutapar0=1.64755; FMDcutapar1=159.47; FMDcutcpar0=2.73426; FMDcutcpar1=200.413; break; case 9: FMDcutapar0=1.2031; FMDcutapar1=73.123; FMDcutcpar0=2.25453; FMDcutcpar1=104.941; break; case 10: FMDcutapar0=1.2031; FMDcutapar1=97.4973; FMDcutcpar0=2.25453; FMDcutcpar1=139.921; break; case 11://pp 2 sigma cut FMDcutapar0=1.2031; FMDcutapar1=48.7486; FMDcutcpar0=2.25453; FMDcutcpar1=69.9606; break; case 12://Pbp 2 sigma cut FMDcutapar0=1.64755; FMDcutapar1=79.7346; FMDcutcpar0=2.73426; FMDcutcpar1=100.20667; break; case 13://pPb 1 sigma cut FMDcutapar0=1.64755; FMDcutapar1=39.8673; FMDcutcpar0=2.73426; FMDcutcpar1=50.1033; break; default: break; } if(fcollisiontype=="PbPb") { if ((nV0A_hits_fmdacc + nV0C_hits_fmdacc) < 1.5*(nFMD_fwdV0acc_hits + nFMD_bwdV0acc_hits) - 20) { // if ((nV0A_hits_fmdacc < FMDcutapar0*nFMD_fwdV0acc_hits-FMDcutapar1)||(nV0C_hits_fmdacc<FMDcutcpar0*nFMD_bwdV0acc_hits-FMDcutcpar1) ){ delete hphiacceptance; PostData(1, fOutputList); PostData(2, fOutputList1); PostData(3, fOutputList2); return; } }else{ if((nV0A_hits<(FMDcutapar0*nFMD_fwd_hits-FMDcutapar1)) || (nV0C_hits<(FMDcutcpar0*nFMD_bwd_hits-FMDcutcpar1)) ){ delete hphiacceptance; PostData(1, fOutputList); PostData(2, fOutputList1); PostData(3, fOutputList2); return; } } } fHist_Stat->Fill(7); DumpTObjTable("End of FMD vs V0 cuts"); fFMDV0_post->Fill(nFMD_bwd_hits + nFMD_fwd_hits, nV0C_hits + nV0A_hits); fFMDV0A_post->Fill(nFMD_fwd_hits, nV0A_hits); fFMDV0C_post->Fill(nFMD_bwd_hits, nV0C_hits); fFMDV0same_post->Fill(nFMD_bwdV0acc_hits + nFMD_fwdV0acc_hits, nV0C_hits_fmdacc + nV0A_hits_fmdacc); fFMDV0Asame_post->Fill(nFMD_fwdV0acc_hits, nV0A_hits_fmdacc); fFMDV0Csame_post->Fill(nFMD_bwdV0acc_hits, nV0C_hits_fmdacc); TObjArray *selectedTracksLeading = new TObjArray; selectedTracksLeading->SetOwner(kTRUE); TObjArray *selectedTracksAssociated = new TObjArray; selectedTracksAssociated->SetOwner(kTRUE); for (Int_t iEta = 1; iEta <= nEta; iEta++) { Int_t valid = Int_t(d2Ndetadphi.GetBinContent(iEta, 0)); if (!valid) { continue; } Float_t eta = d2Ndetadphi.GetXaxis()->GetBinCenter(iEta); Float_t phiacc=hphiacceptance->GetBinContent(iEta); fhistfmdphiacc->Fill(eta,lCentrality,phiacc); for (Int_t iPhi = 1; iPhi <= nPhi; iPhi++) { // Bin content is most likely number of particles! Float_t phi = d2Ndetadphi.GetYaxis()->GetBinCenter(iPhi); Float_t mostProbableN = d2Ndetadphi.GetBinContent(iEta, iPhi); if(fmakehole){ if((eta>-2.9 && eta<-2.7) && (5*2*TMath::Pi()/20.<phi && 7*2*TMath::Pi()/20.>phi)) continue; if((eta>-2.7 && eta<-2.5) && (1*2*TMath::Pi()/20.<phi && 2*2*TMath::Pi()/20.>phi)) continue; if((eta>-2.1 && eta<-1.9) && (17*2*TMath::Pi()/20.<phi && 20*2*TMath::Pi()/20.>phi)) continue; } if (mostProbableN > 0) { if(eta>0){ Int_t nfmdetabin1=frefetaa->FindBin(eta); if(fAnaMode=="TPCFMD" || fAnaMode=="ITSFMD") selectedTracksAssociated->Add(new AliAssociatedTrackYS(-999,eta,phi,-999,-999,-999,-999,-999,mostProbableN)); else if(fAnaMode=="FMDFMD") selectedTracksLeading->Add(new AliAssociatedTrackYS(-999,eta,phi,-999,-999,-999,-999,-999,mostProbableN)); else if(fAnaMode=="FMDFMD_Ctrig") selectedTracksAssociated->Add(new AliAssociatedTrackYS(-999,eta,phi,-999,-999,-999,-999,-999,mostProbableN)); }else if(eta<0){ Int_t nfmdetabin=frefetac->FindBin(eta); if(fAnaMode=="TPCFMDC" || fAnaMode=="ITSFMDC" ||fAnaMode=="FMDFMD") selectedTracksAssociated->Add(new AliAssociatedTrackYS(-999,eta,phi,-999,-999,-999,-999,-999,mostProbableN)); else if(fAnaMode=="FMDFMD_Ctrig") selectedTracksLeading->Add(new AliAssociatedTrackYS(-999,eta,phi,-999,-999,-999,-999,-999,mostProbableN)); } fhFMDmultchannel->Fill(eta,mostProbableN); Double_t cont[4]={eta,phi,lCentrality,fPrimaryZVtx}; fhistfmd->Fill(cont,0,mostProbableN); fh2_FMD_eta_phi_aftercut->Fill(eta,phi,mostProbableN); } } } if(hphiacceptance) delete hphiacceptance; Double_t vzeroqa[3]; for (Int_t imod = 0; imod < 64; imod++) { eta_min = fvzero->GetVZEROEtaMin(imod); eta_max = fvzero->GetVZEROEtaMax(imod); phi_vzero = fvzero->GetVZEROAvgPhi(imod); mult_vzero = fvzero->GetMultiplicity(imod); mult_vzero_eq = fEvent->GetVZEROEqMultiplicity(imod); eta_ave = (eta_min + eta_max) / 2.; vzeroqa[0] = eta_ave; vzeroqa[1] = phi_vzero; vzeroqa[2] = lCentrality; fHistVZERO->Fill(vzeroqa, 0, (Double_t)mult_vzero_eq); } DumpTObjTable("End of fill fmd tracks"); fHistCentrality->Fill(lCentrality); fHistzvertex->Fill(tPrimaryVtxPosition[2]); fHistCentzvertex->Fill(lCentrality, tPrimaryVtxPosition[2]); fHistCentvsNv0mult->Fill(lCentrality,nV0A_hits+nV0C_hits); if(fAnaMode=="TPCTPC"){ if(fasso=="hadron") selectedTracksAssociated=GetAcceptedTracksLeading(fEvent,kFALSE,selectedTracksAssociated); else if (fasso == "Phi") selectedTracksAssociated = GetAcceptedTracksAssociated(fEvent); else if (fasso == "V0") selectedTracksAssociated = GetAcceptedV0Tracks(fEvent); else if (fasso == "PID") selectedTracksAssociated = GetAcceptedTracksPID(fEvent); else if (fasso == "Cascade") selectedTracksAssociated = GetAcceptedCascadeTracks(fEvent); } // Leading Particle if(fAnaMode=="TPCFMD" || fAnaMode=="TPCTPC" || fAnaMode=="TPCFMDC"){ selectedTracksLeading=GetAcceptedTracksLeading(fEvent,kTRUE,selectedTracksLeading); }else if(fAnaMode=="ITSFMD" || fAnaMode=="ITSFMDC"){ // AliVMultiplicity *tracklets = ((AliAODEvent*)fEvent)->GetTracklets(); // if (!tracklets) return; // Int_t nTracklets = tracklets->GetNumberOfTracklets(); AliVMultiplicity *tracklets = ((AliAODEvent*)fEvent)->GetTracklets(); if (!tracklets) return; Int_t nTracklets = tracklets->GetNumberOfTracklets(); Int_t nITScluster= tracklets->GetNumberOfITSClusters(0)+tracklets->GetNumberOfITSClusters(1); Int_t nTracks = fEvent->GetNumberOfTracks(); // fh2_SPD_multcorr->Fill(nTracklets,nITScluster); // fh2_SPDV0_multcorr->Fill(nTracklets,fvzero->GetMTotV0A()+fvzero->GetMTotV0C()); fh2_SPDtrack_multcorr->Fill(nTracklets,nTracks); for (Int_t i = 0; i < nTracklets; i++) { Double_t dphi = tracklets->GetDeltaPhi(i); fhtrackletsdphi->Fill(1000*dphi); if (TMath::Abs(dphi) * 1000 > 5.) { continue; } Double_t theta = tracklets->GetTheta(i); Double_t etaits = -TMath::Log(TMath::Tan(theta/2)); Double_t etalow=log(7.6)-log(sqrt((-13.8-fPrimaryZVtx)*(-13.8-fPrimaryZVtx)+7.6*7.6)-(-13.8-fPrimaryZVtx)); Double_t etahigh=log(7.6)-log(sqrt((14.4-fPrimaryZVtx)*(14.4-fPrimaryZVtx)+7.6*7.6)-(14.4-fPrimaryZVtx)); if(etaits<etalow || etaits>etahigh) continue; if (etaits < -1.7 || etaits > 1.7) { continue; } Double_t phiits = tracklets->GetPhi(i); phiits+=dphi*39./34.;//same value as Cvetan's analysis if (phiits<0) phiits+=TMath::TwoPi(); if (phiits>TMath::TwoPi()) phiits-=TMath::TwoPi(); fh2_ITS_acceptance->Fill(tPrimaryVtxPosition[2],etaits); Double_t itsqa[4]={etaits,phiits,lCentrality,tPrimaryVtxPosition[2]}; // fhistits->Fill(itsqa); selectedTracksLeading->Add(new AliAssociatedTrackYS(-999, etaits, phiits, -999, 0, -999,-999, 0, 1)); } } Int_t nTracks; if(fAnaMode!="FMDFMD") { nTracks=selectedTracksLeading->GetEntriesFast(); // else nTracks= fEvent->GetNumberOfTracks(); fHistCentV0vsTracklets->Fill(lCentrality,nTracks); fHistV0vsTracks->Fill(nV0C_hits+nV0A_hits,nTracks); fHistTraksvsVz->Fill(fPrimaryZVtx,nTracks); fHistV0multvsVz->Fill(fPrimaryZVtx,nV0C_hits+nV0A_hits); } DumpTObjTable("End of TPC/ITS track fill"); if(ffillcorrelation){ FillCorrelationTracks(lCentrality,selectedTracksLeading,selectedTracksAssociated,fHistTriggerTrack,fHistReconstTrack,kFALSE,0.02,0.8,bSign,0); FillCorrelationTracksMixing(lCentrality,lPrimaryBestVtx->GetZ(),poolmax,poolmin,selectedTracksLeading,selectedTracksAssociated,fHistTriggerTrackMix,fHistReconstTrackMix,kFALSE,0.02,0.8,bSign,0); } DumpTObjTable("End of fill Correlation"); selectedTracksLeading->Clear(); delete selectedTracksLeading; selectedTracksAssociated->Clear(); delete selectedTracksAssociated; DumpTObjTable("after delete TObjects"); fNEntries++; } TObjArray* AliAnalysisTaskSEpPbCorrelationsYS::GetFMDhitsYS(Bool_t Aside){ TObjArray *tracks1 = new TObjArray; tracks1->SetOwner(kTRUE); AliAODForwardMult* aodForward =static_cast<AliAODForwardMult*>(fEvent->FindListObject("Forward")); // Shape of d2Ndetadphi: 200, -4, 6, q20, 0, 2pi const TH2D& d2Ndetadphi = aodForward->GetHistogram(); Int_t nEta = d2Ndetadphi.GetXaxis()->GetNbins(); Int_t nPhi = d2Ndetadphi.GetYaxis()->GetNbins(); //AliAnalysisTaskValidation::Tracks ret_vector; // FMD has no pt resolution! Float_t pt = 0; for (Int_t iEta = 1; iEta <= nEta; iEta++) { Int_t valid = Int_t(d2Ndetadphi.GetBinContent(iEta, 0)); if (!valid) { // No data expected for this eta continue; } Float_t eta = d2Ndetadphi.GetXaxis()->GetBinCenter(iEta); for (Int_t iPhi = 1; iPhi <= nPhi; iPhi++) { // Bin content is most likely number of particles! Float_t mostProbableN = d2Ndetadphi.GetBinContent(iEta, iPhi); if (mostProbableN > 0) { Float_t phi = d2Ndetadphi.GetYaxis()->GetBinCenter(iPhi); if(Aside){ if(eta<0) continue; } else{ if(eta>0) continue; } tracks1->Add(new AliAssociatedVZEROYS(mostProbableN,eta,phi,0,0,0)); Double_t cont[3]={eta,phi,lCentrality}; fhistfmd->Fill(cont,0,mostProbableN); fh2_FMD_acceptance->Fill(eta,tPrimaryVtxPosition[2]); fh2_FMD_eta_phi->Fill(eta,phi,mostProbableN); } } } /* TObjArray *tracks1 = new TObjArray; tracks1->SetOwner(kTRUE); Int_t i=0; for (auto const &track: ret_vector) { //cout<<i<<" "<<track.eta<<" "<<track.phi<<" "<<track.weight<<endl; if(Aside==kTRUE){ if(track.eta>0) tracks1->Add(new AliAssociatedVZEROYS(track.eta,track.phi,track.weight,0,0,0)); } else{ if(track.eta<0) tracks1->Add(new AliAssociatedVZEROYS(track.eta,track.phi,track.weight,0,0,0)); } i++; } */ return tracks1; // std::random_device rd; // std::default_random_engine engine{rd()}; // std::shuffle(std::begin(ret_vector), std::end(ret_vector), engine); // return ret_vector; } void AliAnalysisTaskSEpPbCorrelationsYS::CalculateSP(){ /* //Scalar Product Int_t fHarmonic=2; Double_t fQTPCCCos,fQTPCCSin,fQTPCC; Double_t fQTPCACos,fQTPCASin,fQTPCA; Double_t fQTPCCos,fQTPCSin,fQTPC; Double_t fQTPCCCosArray[3],fQTPCCSinArray[3]; Double_t fQTPCACosArray[3],fQTPCASinArray[3]; fQTPCCCos=0; fQTPCCSin=0; fQTPCC=0; fQTPCACos=0; fQTPCASin=0; fQTPCA=0; fQTPCCos=0; fQTPCSin=0; fQTPC=0; for(Int_t i=0;i<selectedTracksLeading->GetEntriesFast();i++){ AliAssociatedTrackYS* trackRP=(AliAssociatedTrackYS*)selectedTracksLeading->At(i); if(!trackRP) continue; Double_t phiRP=trackRP->Phi(); Double_t ptRP=trackRP->Pt(); Double_t etaRP=trackRP->Eta(); Double_t w=1.; fQTPCCos+=w*TMath::Cos(fHarmonic*phiRP); fQTPCSin+=w*TMath::Sin(fHarmonic*phiRP); fQTPC+=w; if(etaRP<0.4 && etaRP>-0.4) continue; if(etaRP<0){ fQTPCCCos+=w*TMath::Cos(fHarmonic*phiRP); fQTPCCSin+=w*TMath::Sin(fHarmonic*phiRP); fQTPCC+=w; }else{ fQTPCACos+=w*TMath::Cos(fHarmonic*phiRP); fQTPCASin+=w*TMath::Sin(fHarmonic*phiRP); fQTPCA+=w; } if(etaRP<0) { fQTPCCCosArray[0]=fQTPCCCos; fQTPCCSinArray[0]=fQTPCCSin; } if(etaRP>0) { fQTPCACosArray[0]=fQTPCACos; fQTPCASinArray[0]=fQTPCASin; } if(etaRP<-0.4) { fQTPCCCosArray[1]=fQTPCCCos; fQTPCCSinArray[1]=fQTPCCSin; } if(etaRP>0.4) { fQTPCACosArray[1]=fQTPCACos; fQTPCASinArray[1]=fQTPCASin; } } Double_t tpc_qmcos=fQTPCCos/fQTPC; Double_t tpc_qmsin=fQTPCSin/fQTPC; Double_t tpcc_qmcos=fQTPCCCos/fQTPCC; Double_t tpcc_qmsin=fQTPCCSin/fQTPCC; Double_t tpca_qmcos=fQTPCACos/fQTPCA; Double_t tpca_qmsin=fQTPCASin/fQTPCA; Double_t qna=TMath::Sqrt((fQTPCACos*fQTPCACos+fQTPCASin*fQTPCASin)/fQTPCA); if(fQTPCA>1)fHistQna->Fill(qna,lCentrality); Double_t qnc=TMath::Sqrt((fQTPCCCos*fQTPCCCos+fQTPCCSin*fQTPCCSin)/fQTPCC); if(fQTPCC>1)fHistQnc->Fill(qnc,lCentrality); Double_t qn=TMath::Sqrt((fQTPCCos*fQTPCCos+fQTPCSin*fQTPCSin)/fQTPC); if(fQTPC>1)fHistQn->Fill(qn,lCentrality); // cout<<fQTPCCos<<" "<<fQTPCSin<<" "<<fQTPC<<" "<<qn<<endl; Double_t qaqc=tpca_qmcos*tpcc_qmcos+tpca_qmsin*tpcc_qmsin;//Q_a*Q_b/(M_a*M_b) //Double_t qaqcsqrt=TMath::Sqrt(tpca_qmcos*tpcc_qmcos+tpca_qmsin*tpcc_qmsin);//Q_a*Q_b/(M_a*M_b) if(fQTPCC>0 && fQTPCA>0) { fHistVn->Fill(qaqc); if(lCentrality>=0. && lCentrality<20.) fHistQAQB[0]->Fill(qaqc); if(lCentrality>=20. && lCentrality<40.) fHistQAQB[1]->Fill(qaqc); if(lCentrality>=40. && lCentrality<60.) fHistQAQB[2]->Fill(qaqc); if(lCentrality>=60. && lCentrality<100.) fHistQAQB[3]->Fill(qaqc); SP_TPCATPCC->Fill(lCentrality,qaqc); SP_TPCATPCC_default->Fill(lCentrality,qaqc); } //VZERO fvzero = fEvent->GetVZEROData(); Double_t eta_min; Double_t eta_max; Double_t eta_ave; Double_t phi_vzero; Double_t mult_vzero; Double_t vzeroqa[3]; Double_t mult_vzero_eq; Double_t fQVZEROCCos,fQVZEROCSin,fQVZEROC; Double_t fQVZEROACos,fQVZEROASin,fQVZEROA; Double_t fQVZEROCos,fQVZEROSin,fQVZERO; fQVZEROCCos=0; fQVZEROCSin=0; fQVZEROC=0; fQVZEROACos=0; fQVZEROASin=0; fQVZEROA=0; fQVZEROCos=0; fQVZEROSin=0; fQVZERO=0; for (Int_t imod = 0; imod < 64; imod++) { eta_min = fvzero->GetVZEROEtaMin(imod); eta_max = fvzero->GetVZEROEtaMax(imod); phi_vzero = fvzero->GetVZEROAvgPhi(imod); mult_vzero = fvzero->GetMultiplicity(imod); mult_vzero_eq = fEvent->GetVZEROEqMultiplicity(imod); eta_ave = (eta_min + eta_max) / 2.; fHist_vzeromult->Fill(imod, mult_vzero); fHist_vzeromultEqweighted->Fill(imod, mult_vzero_eq); fHist2dmult->Fill(imod, mult_vzero_eq, mult_vzero); vzeroqa[0] = eta_ave; vzeroqa[1] = phi_vzero; vzeroqa[2] = lCentrality; if (fQA) fHistVZERO->Fill(vzeroqa, 0, (Double_t)mult_vzero_eq); Double_t phiRPVZERO=phi_vzero; Double_t etaRPVZERO=eta_ave; Double_t w=mult_vzero; fQVZEROCos+=w*TMath::Cos(fHarmonic*phiRPVZERO); fQVZEROSin+=w*TMath::Sin(fHarmonic*phiRPVZERO); fQVZERO+=w; if(etaRPVZERO<0){ fQVZEROCCos+=w*TMath::Cos(fHarmonic*phiRPVZERO); fQVZEROCSin+=w*TMath::Sin(fHarmonic*phiRPVZERO); fQVZEROC+=w; }else{ fQVZEROACos+=w*TMath::Cos(fHarmonic*phiRPVZERO); fQVZEROASin+=w*TMath::Sin(fHarmonic*phiRPVZERO); fQVZEROA+=w; } if(imod>31) selectedTrackV0A->Add(new AliAssociatedVZEROYS(mult_vzero_eq,eta_ave,phi_vzero,0.0,0,0)); if(imod<32) selectedTrackV0C->Add(new AliAssociatedVZEROYS(mult_vzero_eq,eta_ave,phi_vzero,0.0,0,0)); } Double_t vzeroc_qmcos=fQVZEROCCos/fQVZEROC; Double_t vzeroc_qmsin=fQVZEROCSin/fQVZEROC; Double_t vzeroa_qmcos=fQVZEROACos/fQVZEROA; Double_t vzeroa_qmsin=fQVZEROASin/fQVZEROA; Double_t qna_vzero=TMath::Sqrt((fQVZEROACos*fQVZEROACos+fQVZEROASin*fQVZEROASin)/fQVZEROA); if(fQVZEROA>1) fHistQna_VZERO->Fill(qna_vzero,lCentrality); Double_t qnc_vzero=TMath::Sqrt((fQVZEROCCos*fQVZEROCCos+fQVZEROCSin*fQVZEROCSin)/fQVZEROC); if(fQVZEROC>1) fHistQnc_VZERO->Fill(qnc_vzero,lCentrality); Double_t qn_vzero=TMath::Sqrt((fQVZEROCos*fQVZEROCos+fQVZEROSin*fQVZEROSin)/fQVZERO); if(fQVZERO>1) fHistQn_VZERO->Fill(qn_vzero,lCentrality); Double_t qaqc_vzero=vzeroa_qmcos*vzeroc_qmcos+vzeroa_qmsin*vzeroc_qmsin;//Q_a*Q_b/(M_a*M_b) Double_t qaqc_vzeroatpc=vzeroa_qmcos*tpc_qmcos+vzeroa_qmsin*tpc_qmsin;//Q_a*Q_b/(M_a*M_b) Double_t qaqc_vzeroctpc=vzeroc_qmcos*tpc_qmcos+vzeroc_qmsin*tpc_qmsin;//Q_a*Q_b/(M_a*M_b) if(fQVZEROC>1 && fQTPCC>1) { if(lCentrality>=0. && lCentrality<20.) fHistCorrQnc[0]->Fill(qnc,qnc_vzero); if(lCentrality>=20. && lCentrality<40.) fHistCorrQnc[1]->Fill(qnc,qnc_vzero); if(lCentrality>=40. && lCentrality<60. ) fHistCorrQnc[2]->Fill(qnc,qnc_vzero); if(lCentrality>=60. && lCentrality<100. ) fHistCorrQnc[3]->Fill(qnc,qnc_vzero); } if(fQVZEROA>1 && fQTPCA>1) { if(lCentrality>=0. && lCentrality<20.) fHistCorrQna[0]->Fill(qna,qna_vzero); if(lCentrality>=20. && lCentrality<40.) fHistCorrQna[1]->Fill(qna,qna_vzero); if(lCentrality>=40. && lCentrality<60. ) fHistCorrQna[2]->Fill(qna,qna_vzero); if(lCentrality>=60. && lCentrality<100. ) fHistCorrQna[3]->Fill(qna,qna_vzero); } if(fQVZEROC>0 && fQVZEROA>0) { if(lCentrality>=0. && lCentrality<20.) fHistQAQB_VZERO[0]->Fill(qaqc_vzero); if(lCentrality>=20. && lCentrality<40.) fHistQAQB_VZERO[1]->Fill(qaqc_vzero); if(lCentrality>=40. && lCentrality<60.) fHistQAQB_VZERO[2]->Fill(qaqc_vzero); if(lCentrality>=60. && lCentrality<100.) fHistQAQB_VZERO[3]->Fill(qaqc_vzero); fHist_V0AV0C->Fill(qaqc_vzero); SP_V0AV0C_default->Fill(lCentrality,qaqc_vzero,1); } if(fQVZEROC>0 && fQTPC>0){ fHist_V0CTPC->Fill(qaqc_vzeroctpc); SP_V0CTPC_default->Fill(lCentrality,qaqc_vzeroctpc,1); } if(fQVZEROA>0 && fQTPC>0){ fHist_V0ATPC->Fill(qaqc_vzeroatpc); SP_V0ATPC_default->Fill(lCentrality,qaqc_vzeroatpc,1); } //Calculate uQ Double_t uQ=0; Double_t uQ_vzeroa=0; Double_t uQ_vzeroc=0; for(Int_t i=0;i<selectedTracksAssociated->GetEntriesFast();i++){ AliAssociatedTrackYS* trackPOI=(AliAssociatedTrackYS*)selectedTracksAssociated->At(i); Double_t phi=trackPOI->Phi(); Double_t eta=trackPOI->Eta(); Double_t pt=trackPOI->Pt(); Int_t SpAssoc=trackPOI->WhichCandidate(); Double_t cosn = TMath::Cos(fHarmonic*phi); Double_t sinn = TMath::Sin(fHarmonic*phi); //VZERO-TPC-VZERO uQ_vzeroa=cosn*vzeroa_qmcos+sinn*vzeroa_qmsin; uQ_vzeroc=cosn*vzeroc_qmcos+sinn*vzeroc_qmsin; Double_t w=1; if(fQVZEROA>0){ SP_uVZEROA_PP[SpAssoc]->Fill(pt,uQ_vzeroa,1); if(lCentrality>=0. && lCentrality<20.) SP_uVZEROA[SpAssoc]->Fill(pt,uQ_vzeroa,w); if(lCentrality>=20. && lCentrality<40.) SP_uVZEROA1[SpAssoc]->Fill(pt,uQ_vzeroa,w); if(lCentrality>=40. && lCentrality<60.) SP_uVZEROA2[SpAssoc]->Fill(pt,uQ_vzeroa,w); if(lCentrality>=60. && lCentrality<100.) SP_uVZEROA3[SpAssoc]->Fill(pt,uQ_vzeroa,w); } if(fQVZEROC>0){ SP_uVZEROC_PP[SpAssoc]->Fill(pt,uQ_vzeroa,1); if(lCentrality>=0. && lCentrality<20.) SP_uVZEROC[SpAssoc]->Fill(pt,uQ_vzeroc,w); if(lCentrality>=20. && lCentrality<40.) SP_uVZEROC1[SpAssoc]->Fill(pt,uQ_vzeroc,w); if(lCentrality>=40. && lCentrality<60.) SP_uVZEROC2[SpAssoc]->Fill(pt,uQ_vzeroc,w); if(lCentrality>=60. && lCentrality<100.) SP_uVZEROC3[SpAssoc]->Fill(pt,uQ_vzeroc,w); } //TPC-TPC if(fQTPCC<1 || fQTPCA<1) continue; if( eta<0.4 && eta>-0.4 ) continue; if(eta<0){ uQ=(cosn*tpca_qmcos+sinn*tpca_qmsin); //u x Q/M_a SP_uTPCA->Fill(pt,uQ,1); }else{ uQ=(cosn*tpcc_qmcos+sinn*tpcc_qmsin); SP_uTPCC->Fill(pt,uQ,1); } SP_uTPC_PP[SpAssoc]->Fill(pt,uQ,1); if(lCentrality>=0. && lCentrality<20.) SP_uTPC[SpAssoc]->Fill(pt,uQ,1); if(lCentrality>=20. && lCentrality<40.) SP_uTPC1[SpAssoc]->Fill(pt,uQ,1); if(lCentrality>=40. && lCentrality<60.) SP_uTPC2[SpAssoc]->Fill(pt,uQ,1); if(lCentrality>=60. && lCentrality<100.) SP_uTPC3[SpAssoc]->Fill(pt,uQ,1); } */ } TObjArray *AliAnalysisTaskSEpPbCorrelationsYS::GetAcceptedTracksLeading(AliAODEvent *fAOD,Bool_t leading,TObjArray*tracks) { //TObjArray *tracks = new TObjArray; //tracks->SetOwner(kTRUE); Int_t nTracks = fAOD->GetNumberOfTracks(); Double_t pidqa[5]; for (Int_t i = 0; i < nTracks; i++) { AliAODTrack *aodTrack = dynamic_cast<AliAODTrack *>(fAOD->GetTrack(i)); if (!aodTrack) continue; if (!IsAcceptedTrack(aodTrack)) continue; // if (aodTrack->Eta()<fEtaMinExtra || aodTrack->Eta()>fEtaMaxExtra) continue; if (aodTrack->Charge() == 0) continue; Float_t trackpt=aodTrack->Pt(); Float_t tracketa=aodTrack->Eta(); Float_t trackphi=aodTrack->Phi(); Float_t efficiency=1.; Float_t efficiencyerr=-1; Int_t ivzbin=frefvz->GetXaxis()->FindBin(fPrimaryZVtx); if(fefficalib){ Int_t iPt=fhcorr[ivzbin-1]->GetXaxis()->FindBin(trackpt); Int_t iEta=fhcorr[ivzbin-1]->GetYaxis()->FindBin(tracketa); // Int_t iPhi=fhcorr[ivzbin-1]->GetZaxis()->FindBin(trackphi); // efficiency=fhcorr[ivzbin-1]->GetBinContent(iPt,iEta,iPhi); efficiency=fhcorr[ivzbin-1]->GetBinContent(iPt,iEta); efficiencyerr=fhcorr[ivzbin-1]->GetBinError(iPt,iEta); if(efficiency==0.) { return 0; } }else{ efficiency=1.; } if(leading){ pidqa[0]=trackpt; pidqa[1]=tracketa; pidqa[2]=RangePhi(trackphi); pidqa[3]=lCentrality; pidqa[4]=fPrimaryZVtx; fHistLeadQA->Fill(pidqa,0,1./efficiency); } Int_t SpAsso=0; tracks->Add(new AliAssociatedTrackYS(aodTrack->Charge(), tracketa, trackphi, trackpt, aodTrack->GetID(), -999, -999, SpAsso, 1./efficiency)); } return tracks; } TObjArray *AliAnalysisTaskSEpPbCorrelationsYS::GetAcceptedTracksPID(AliAODEvent *fAOD) { TObjArray *tracks = new TObjArray; tracks->SetOwner(kTRUE); Int_t nTracks = fAOD->GetNumberOfTracks(); Double_t pidqa[4]; for (Int_t i = 0; i < nTracks; i++) { AliAODTrack *aodTrack = dynamic_cast<AliAODTrack *>(fAOD->GetTrack(i)); Int_t SpPID=-999; if (!aodTrack) continue; if (!IsAcceptedTrack(aodTrack)) continue; if (aodTrack->Charge() == 0) continue; Double_t nSigmaKaonTPC = fPIDResponse->NumberOfSigmasTPC(aodTrack, AliPID::kKaon); Double_t nSigmaPionTPC = fPIDResponse->NumberOfSigmasTPC(aodTrack, AliPID::kPion); Double_t nSigmaProtonTPC = fPIDResponse->NumberOfSigmasTPC(aodTrack, AliPID::kProton); Double_t nSigmaKaonTOF = fPIDResponse->NumberOfSigmasTOF(aodTrack, AliPID::kKaon); Double_t nSigmaPionTOF = fPIDResponse->NumberOfSigmasTOF(aodTrack, AliPID::kPion); Double_t nSigmaProtonTOF = fPIDResponse->NumberOfSigmasTOF(aodTrack, AliPID::kProton); fHistNsig[0]->Fill(aodTrack->Pt(),nSigmaPionTPC); fHistNsig[1]->Fill(aodTrack->Pt(),nSigmaKaonTPC); fHistNsig[2]->Fill(aodTrack->Pt(),nSigmaProtonTPC); fHistNsig[3]->Fill(aodTrack->Pt(),nSigmaPionTOF); fHistNsig[4]->Fill(aodTrack->Pt(),nSigmaKaonTOF); fHistNsig[5]->Fill(aodTrack->Pt(),nSigmaProtonTOF); fHistNsigcorr[3]->Fill(nSigmaPionTPC,nSigmaPionTOF); fHistNsigcorr[4]->Fill(nSigmaKaonTPC,nSigmaKaonTOF); fHistNsigcorr[5]->Fill(nSigmaProtonTPC,nSigmaProtonTOF); Double_t d2nsigmakaon = nSigmaKaonTPC * nSigmaKaonTPC + nSigmaKaonTOF * nSigmaKaonTOF; Double_t d2nsigmapion = nSigmaPionTPC * nSigmaPionTPC + nSigmaPionTOF * nSigmaPionTOF; Double_t d2nsigmaproton = nSigmaProtonTPC * nSigmaProtonTPC + nSigmaProtonTOF * nSigmaProtonTOF; Bool_t fPIDTOF = kTRUE; if (fPIDResponse->CheckPIDStatus(AliPIDResponse::kTOF, fAOD->GetTrack(i)) == 0) fPIDTOF = kFALSE; else fPIDTOF = kTRUE; Double_t nSigmaKaonTOFTPC; Double_t nSigmaPionTOFTPC; Double_t nSigmaProtonTOFTPC; if (fPIDTOF && aodTrack->Pt() > 0.5) { nSigmaKaonTOFTPC = TMath::Sqrt(d2nsigmakaon); nSigmaPionTOFTPC = TMath::Sqrt(d2nsigmapion); nSigmaProtonTOFTPC = TMath::Sqrt(d2nsigmaproton); } else { nSigmaKaonTOFTPC = TMath::Abs(nSigmaKaonTPC); nSigmaPionTOFTPC = TMath::Abs(nSigmaPionTPC); nSigmaProtonTOFTPC = TMath::Abs(nSigmaProtonTPC); } if ((nSigmaKaonTOFTPC < fMaxnSigmaTPCTOF) && (nSigmaKaonTOFTPC < nSigmaPionTOFTPC) && (nSigmaKaonTOFTPC < nSigmaProtonTOFTPC)) SpPID = 0; if ((nSigmaPionTOFTPC < fMaxnSigmaTPCTOF) && (nSigmaPionTOFTPC < nSigmaKaonTOFTPC) && (nSigmaPionTOFTPC < nSigmaProtonTOFTPC)) SpPID = 1; if ((nSigmaProtonTOFTPC < fMaxnSigmaTPCTOF) && (nSigmaProtonTOFTPC < nSigmaKaonTOFTPC) && (nSigmaProtonTOFTPC < nSigmaPionTOFTPC)) SpPID = 2; pidqa[0]=aodTrack->Pt(); pidqa[1]=aodTrack->Eta(); pidqa[2]=RangePhi(aodTrack->Phi()); pidqa[3]=lCentrality; if(SpPID<0) continue; if(fQA) fHistPIDQA->Fill(pidqa, SpPID); if(SpPID==1) fHistNsigcorr[0]->Fill(nSigmaPionTPC,nSigmaPionTOF); if(SpPID==0) fHistNsigcorr[1]->Fill(nSigmaKaonTPC,nSigmaKaonTOF); if(SpPID==2) fHistNsigcorr[2]->Fill(nSigmaProtonTPC,nSigmaProtonTOF); tracks->Add(new AliAssociatedTrackYS(aodTrack->Charge(), aodTrack->Eta(), aodTrack->Phi(), aodTrack->Pt(), aodTrack->GetID(), -999, -999, SpPID, 1)); } return tracks; } TObjArray *AliAnalysisTaskSEpPbCorrelationsYS::GetAcceptedTracksAssociated(AliAODEvent *fAODEvent) { TObjArray *tracks = new TObjArray; tracks->SetOwner(kTRUE); TObjArray *dtrack = new TObjArray; dtrack->SetOwner(kTRUE); Int_t nTracks = fAODEvent->GetNumberOfTracks(); for (Int_t i = 0; i < nTracks - 1; i++) { AliAODTrack *aodTrack1 = dynamic_cast<AliAODTrack *>(fAODEvent->GetTrack(i)); if (!aodTrack1) continue; Double_t nSigmaKaonTPC_phi1 = fPIDResponse->NumberOfSigmasTPC(aodTrack1, AliPID::kKaon); Double_t nSigmaKaonTOF_phi1 = fPIDResponse->NumberOfSigmasTOF(aodTrack1, AliPID::kKaon); Double_t nSigmaPionTPC_phi1 = fPIDResponse->NumberOfSigmasTPC(aodTrack1, AliPID::kPion); Double_t nSigmaPionTOF_phi1 = fPIDResponse->NumberOfSigmasTOF(aodTrack1, AliPID::kPion); Double_t nSigmaProtonTPC_phi1 = fPIDResponse->NumberOfSigmasTPC(aodTrack1, AliPID::kProton); Double_t nSigmaProtonTOF_phi1 = fPIDResponse->NumberOfSigmasTOF(aodTrack1, AliPID::kProton); Double_t d2sigmaphi1kaontpctof = nSigmaKaonTPC_phi1 * nSigmaKaonTPC_phi1 + nSigmaKaonTOF_phi1 * nSigmaKaonTOF_phi1; Double_t d2sigmaphi1piontpctof = nSigmaPionTPC_phi1 * nSigmaPionTPC_phi1 + nSigmaPionTOF_phi1 * nSigmaPionTOF_phi1; Double_t d2sigmaphi1protontpctof = nSigmaProtonTPC_phi1 * nSigmaProtonTPC_phi1 + nSigmaProtonTOF_phi1 * nSigmaProtonTOF_phi1; Bool_t fPIDTOF_phi1; if (fPIDResponse->CheckPIDStatus(AliPIDResponse::kTOF, aodTrack1) == 0) fPIDTOF_phi1 = kFALSE; else fPIDTOF_phi1 = kTRUE; Double_t nSigmaKaonTOFTPC_phi1; Double_t nSigmaPionTOFTPC_phi1; Double_t nSigmaProtonTOFTPC_phi1; if (fPIDTOF_phi1 && aodTrack1->Pt() > 0.5) { nSigmaKaonTOFTPC_phi1 = TMath::Sqrt(d2sigmaphi1kaontpctof); nSigmaPionTOFTPC_phi1 = TMath::Sqrt(d2sigmaphi1piontpctof); nSigmaProtonTOFTPC_phi1 = TMath::Sqrt(d2sigmaphi1protontpctof); } else { nSigmaKaonTOFTPC_phi1 = TMath::Abs(nSigmaKaonTPC_phi1); nSigmaPionTOFTPC_phi1 = TMath::Abs(nSigmaPionTPC_phi1); nSigmaProtonTOFTPC_phi1 = TMath::Abs(nSigmaProtonTPC_phi1); } if (!IsAcceptedPhiDaughterTrack(aodTrack1)) continue; fHistPhiDTPCNSig->Fill(aodTrack1->Pt(), nSigmaKaonTPC_phi1); fHistPhiDTOFNSig->Fill(aodTrack1->Pt(), nSigmaKaonTOF_phi1); fHistPhiDTPCTOFNSig->Fill(aodTrack1->Pt(), TMath::Sqrt(d2sigmaphi1kaontpctof)); Bool_t isKaon1 = kFALSE; // if(nSigmaKaonTOFTPC_phi1<5.0 && // nSigmaKaonTOFTPC_phi1<nSigmaPionTOFTPC_phi1 && // nSigmaKaonTOFTPC_phi1<nSigmaProtonTOFTPC_phi1) isKaon1=kTRUE; if (TMath::Abs(nSigmaKaonTPC_phi1) < 5.0 && TMath::Abs(nSigmaKaonTPC_phi1) < TMath::Abs(nSigmaPionTPC_phi1) && TMath::Abs(nSigmaKaonTPC_phi1) < TMath::Abs(nSigmaProtonTPC_phi1)) isKaon1 = kTRUE; if (!isKaon1) continue; dtrack->Add(new AliMixTrackYS( aodTrack1->Charge(), aodTrack1->Eta(), aodTrack1->Phi(), aodTrack1->Pt(), aodTrack1->Px(), aodTrack1->Py(), aodTrack1->Pz())); for (Int_t j = i + 1; j < nTracks; j++) { AliAODTrack *aodTrack2 = dynamic_cast<AliAODTrack *>(fAODEvent->GetTrack(j)); if (!aodTrack2) continue; Double_t nSigmaKaonTPC_phi2 = fPIDResponse->NumberOfSigmasTPC(aodTrack2, AliPID::kKaon); Double_t nSigmaKaonTOF_phi2 = fPIDResponse->NumberOfSigmasTOF(aodTrack2, AliPID::kKaon); Double_t nSigmaPionTPC_phi2 = fPIDResponse->NumberOfSigmasTPC(aodTrack2, AliPID::kPion); Double_t nSigmaPionTOF_phi2 = fPIDResponse->NumberOfSigmasTOF(aodTrack2, AliPID::kPion); Double_t nSigmaProtonTPC_phi2 = fPIDResponse->NumberOfSigmasTPC(aodTrack2, AliPID::kProton); Double_t nSigmaProtonTOF_phi2 = fPIDResponse->NumberOfSigmasTOF(aodTrack2, AliPID::kProton); Double_t d2sigmaphi2kaontpctof = nSigmaKaonTPC_phi2 * nSigmaKaonTPC_phi2 + nSigmaKaonTOF_phi2 * nSigmaKaonTOF_phi2; Double_t d2sigmaphi2piontpctof = nSigmaPionTPC_phi2 * nSigmaPionTPC_phi2 + nSigmaPionTOF_phi2 * nSigmaPionTOF_phi2; Double_t d2sigmaphi2protontpctof = nSigmaProtonTPC_phi2 * nSigmaProtonTPC_phi2 + nSigmaProtonTOF_phi2 * nSigmaProtonTOF_phi2; Bool_t fPIDTOF_phi2; if (fPIDResponse->CheckPIDStatus(AliPIDResponse::kTOF, aodTrack2) == 0) fPIDTOF_phi2 = kFALSE; else fPIDTOF_phi2 = kTRUE; Double_t nSigmaKaonTOFTPC_phi2; Double_t nSigmaPionTOFTPC_phi2; Double_t nSigmaProtonTOFTPC_phi2; if (fPIDTOF_phi2 && aodTrack2->Pt() > 0.5) { nSigmaKaonTOFTPC_phi2 = TMath::Sqrt(d2sigmaphi2kaontpctof); nSigmaPionTOFTPC_phi2 = TMath::Sqrt(d2sigmaphi2piontpctof); nSigmaProtonTOFTPC_phi2 = TMath::Sqrt(d2sigmaphi2protontpctof); } else { nSigmaKaonTOFTPC_phi2 = TMath::Abs(nSigmaKaonTPC_phi2); nSigmaPionTOFTPC_phi2 = TMath::Abs(nSigmaPionTPC_phi2); nSigmaProtonTOFTPC_phi2 = TMath::Abs(nSigmaProtonTPC_phi2); } Bool_t isKaon2 = kFALSE; // if(nSigmaKaonTOFTPC_phi2<5.0 && // nSigmaKaonTOFTPC_phi2<nSigmaPionTOFTPC_phi2 && // nSigmaKaonTOFTPC_phi2<nSigmaProtonTOFTPC_phi2) isKaon2=kTRUE; if (TMath::Abs(nSigmaKaonTPC_phi2) < 5.0 && TMath::Abs(nSigmaKaonTPC_phi2) < TMath::Abs(nSigmaPionTPC_phi2) && TMath::Abs(nSigmaKaonTPC_phi2) < TMath::Abs(nSigmaProtonTPC_phi2)) isKaon2 = kTRUE; if (!isKaon2) continue; if (!IsAcceptedPhiDaughterTrack(aodTrack2)) continue; if (aodTrack1->GetID() == aodTrack2->GetID()) continue; if (aodTrack1->Charge() == aodTrack2->Charge()) continue; Double_t mass_phi; Double_t px_phi = aodTrack1->Px() + aodTrack2->Px(); Double_t py_phi = aodTrack1->Py() + aodTrack2->Py(); Double_t pz_phi = aodTrack1->Pz() + aodTrack2->Pz(); Double_t p_phi = TMath::Sqrt(px_phi * px_phi + py_phi * py_phi + pz_phi * pz_phi); Double_t phi_phi = atan2(py_phi, px_phi); if (phi_phi < 0.) phi_phi += 2 * TMath::Pi(); Double_t px1 = aodTrack1->Px(); Double_t py1 = aodTrack1->Py(); Double_t pz1 = aodTrack1->Pz(); Double_t E1 = TMath::Sqrt(px1 * px1 + py1 * py1 + pz1 * pz1 + 0.493677 * 0.493677); Double_t px2 = aodTrack2->Px(); Double_t py2 = aodTrack2->Py(); Double_t pz2 = aodTrack2->Pz(); Double_t E2 = TMath::Sqrt(px2 * px2 + py2 * py2 + pz2 * pz2 + 0.493677 * 0.493677); mass_phi = TMath::Sqrt((E1 + E2) * (E1 + E2) - (px1 + px2) * (px1 + px2) - (py1 + py2) * (py1 + py2) - (pz1 + pz2) * (pz1 + pz2)); Double_t pt_phi = TMath::Sqrt((px1 + px2) * (px1 + px2) + (py1 + py2) * (py1 + py2)); // if(pt_phi<0.5) continue; Double_t eta_phi = 0.5 * log((p_phi + pz_phi) / (p_phi - pz_phi)); Double_t PhiQA[3] = {mass_phi, pt_phi, lCentrality}; fHistMass_PhiMeson->Fill(PhiQA); if (TMath::Abs(eta_phi) > 0.8) continue; Int_t SpPhi = -999.; const Double_t fPhiMass = TDatabasePDG::Instance()->GetParticle(333)->Mass(); if (TMath::Abs(mass_phi - fPhiMass) < 0.006) SpPhi = 0; // same for step if (mass_phi > 0.99 && mass_phi < fPhiMass - 0.006) SpPhi = 1; // same as step if (mass_phi > fPhiMass + 0.006 && mass_phi < fPhiMass + 0.018) SpPhi = 2; // same as step if (mass_phi > fPhiMass + 0.018 && mass_phi < fPhiMass + 0.030) SpPhi = 3; // same as step if (mass_phi > fPhiMass + 0.030 && mass_phi < fPhiMass + 0.042) SpPhi = 4; // same as step if (mass_phi > fPhiMass + 0.042 && mass_phi < fPhiMass + 0.054) SpPhi = 5; // same as step if (mass_phi > fPhiMass + 0.054 && mass_phi < fPhiMass + 0.066) SpPhi = 6; // same as step if(SpPhi<0) continue; tracks->Add(new AliAssociatedTrackYS(0, eta_phi, phi_phi, pt_phi, -999, aodTrack1->GetID(), aodTrack2->GetID(), SpPhi, 1)); Double_t spPhiQA[4] = {eta_phi, phi_phi, (Float_t)SpPhi, lCentrality}; fHist_PhiQA->Fill(spPhiQA); } } // Mixed Event Double_t pvxMix = fPrimaryZVtx; Double_t counterMix = 0; AliEventPool *pool = fPoolMgr1->GetEventPool(lCentrality, pvxMix); if (!pool) AliFatal(Form("No pool found for centrality = %f, zVtx = %f", lCentrality,pvxMix)); if (pool->IsReady() || pool->NTracksInPool() > fPoolMinNTracks || pool->GetCurrentNEvents() > fMinEventsToMix) { Int_t nMix = pool->GetCurrentNEvents(); for (Int_t jMix = 0; jMix < nMix; jMix++) { TObjArray *mixEvents = pool->GetEvent(jMix); for (Int_t i = 0; i < dtrack->GetEntriesFast(); i++) { AliMixTrackYS *dtrack1 = (AliMixTrackYS *)dtrack->At(i); if (!dtrack1) continue; Double_t pdx1 = dtrack1->Px(); Double_t pdy1 = dtrack1->Py(); Double_t pdz1 = dtrack1->Pz(); Double_t Ed1 = TMath::Sqrt(pdx1 * pdx1 + pdy1 * pdy1 + pdz1 * pdz1 + 0.493677 * 0.493677); counterMix++; for (Int_t j = 0; j < mixEvents->GetEntriesFast(); j++) { AliMixTrackYS *dtrack2 = (AliMixTrackYS *)mixEvents->At(j); if (!dtrack2) continue; if (dtrack1->Charge() == dtrack2->Charge()) continue; Double_t pdx2 = dtrack2->Px(); Double_t pdy2 = dtrack2->Py(); Double_t pdz2 = dtrack2->Pz(); Double_t Ed2 = TMath::Sqrt(pdx2 * pdx2 + pdy2 * pdy2 + pdz2 * pdz2 + 0.493677 * 0.493677); Double_t mass_phi_mix = TMath::Sqrt( (Ed1 + Ed2) * (Ed1 + Ed2) - (pdx1 + pdx2) * (pdx1 + pdx2) - (pdy1 + pdy2) * (pdy1 + pdy2) - (pdz1 + pdz2) * (pdz1 + pdz2)); Double_t pt_phi_mix = TMath::Sqrt((pdx1 + pdx2) * (pdx1 + pdx2) + (pdy1 + pdy2) * (pdy1 + pdy2)); // if(pt_phi_mix<0.5) continue; Double_t px_phi_mix = pdx1 + pdx2; Double_t py_phi_mix = pdy1 + pdy2; Double_t pz_phi_mix = pdz1 + pdz2; Double_t p_phi_mix = TMath::Sqrt(px_phi_mix * px_phi_mix + py_phi_mix * py_phi_mix + pz_phi_mix * pz_phi_mix); Double_t phi_phi_mix = atan2(py_phi_mix, px_phi_mix); if (phi_phi_mix < 0.) phi_phi_mix += 2 * TMath::Pi(); Double_t eta_phi_mix = 0.5 * log((p_phi_mix + pz_phi_mix) / (p_phi_mix - pz_phi_mix)); if (TMath::Abs(eta_phi_mix) > 0.8) continue; Double_t PhiQAMix[3] = {mass_phi_mix, pt_phi_mix, lCentrality}; fHistMass_PhiMeson_MIX->Fill(PhiQAMix, 1. / (Double_t)nMix); } } } } TObjArray *tracksClone = new TObjArray; tracksClone->SetOwner(kTRUE); for (Int_t i = 0; i < dtrack->GetEntriesFast(); i++) { AliMixTrackYS *particle = (AliMixTrackYS *)dtrack->At(i); tracksClone->Add(new AliMixTrackYS( particle->Charge(), particle->Eta(), particle->Phi(), particle->Pt(), particle->Px(), particle->Py(), particle->Pz())); } pool->UpdatePool(tracksClone); return tracks; } TObjArray *AliAnalysisTaskSEpPbCorrelationsYS::GetAcceptedV0Tracks(const AliAODEvent *fAODEvent) { TObjArray *tracks = new TObjArray; tracks->SetOwner(kTRUE); // V0Particles Int_t nv0s = fAODEvent->GetNumberOfV0s(); for (Int_t iv0 = 0; iv0 < nv0s; iv0++) { AliAODv0 *aodv0 = dynamic_cast<AliAODv0 *>(fAODEvent->GetV0(iv0)); if (!aodv0) { AliError(Form("ERROR: Could not retrieve aodv0 %d", iv0)); continue; } fHist_V0Stat->Fill(0); if(!IsAcceptedV0(aodv0)) continue; fHist_V0Stat->Fill(7); // c*taup;ppp; const Double_t kLambdaMass = TDatabasePDG::Instance()->GetParticle(3122)->Mass(); const Double_t kK0Mass = TDatabasePDG::Instance()->GetParticle(311)->Mass(); // Double_t cutcTauLam = fcutctau*7.89;//c*mean life time=2.632*2.9979 cm // Double_t cutcTauK0 = fcutctau*2.68; //c*mean life time=0.8954*2.9979 cm // life time < 20(K0s), 30(lambda) fcutcTauLam=3.8*7.89; fcutcTauK0=5*2.68; Bool_t cutK0ctau = IsAcceptedDecayLength(aodv0,kK0Mass,fcutcTauK0); Bool_t cutLambdactau =IsAcceptedDecayLength(aodv0,kLambdaMass,fcutcTauLam); Bool_t cutAntiLambdactau = IsAcceptedDecayLength(aodv0,kLambdaMass,fcutcTauLam); // cpa Double_t cpa = aodv0->CosPointingAngle(fAODEvent->GetPrimaryVertex()); fcosMinK0s=0.97; fcosMinLambda=0.99; Bool_t cpaK0s = cpa > fcosMinK0s; Bool_t cpaLambda = cpa > fcosMinLambda; const AliAODTrack* myTrackPos=0; const AliAODTrack* myTrackNeg=0; AliAODTrack *myTrackPosTest = dynamic_cast<AliAODTrack *>(aodv0->GetDaughter(0)); // The first dauther track, which should be positive AliAODTrack *myTrackNegTest = dynamic_cast<AliAODTrack *>(aodv0->GetDaughter(1)); // The second dauther track, which should be negative if (!myTrackPosTest || !myTrackNegTest) { Printf("strange analysis::UserExec:: Error:Could not retreive one of the daughter track\n"); continue; } if (!IsAcceptedDaughterTrack(myTrackPosTest) || !IsAcceptedDaughterTrack(myTrackNegTest)) continue; Double_t alpha=aodv0->AlphaV0(); Double_t qt = aodv0->PtArmV0(); fHist_V0Stat->Fill(8); if ((myTrackPosTest->Charge() == 1) && (myTrackNegTest->Charge() == -1)) { hv0dcharge->Fill(0); myTrackPos = myTrackPosTest; myTrackNeg = myTrackNegTest; } if ((myTrackPosTest->Charge() == -1) && (myTrackNegTest->Charge() == 1)) { hv0dcharge->Fill(1); myTrackPos = myTrackNegTest; myTrackNeg = myTrackPosTest; } if (myTrackPosTest->Charge() == myTrackNegTest->Charge()) { hv0dcharge->Fill(2); continue; } fHist_AP[0]->Fill(alpha,qt); fHist_V0Stat->Fill(9); // PID Cut // Positive tracks Double_t nSigmaPosPionTPC = fPIDResponse->NumberOfSigmasTPC(myTrackPos, AliPID::kPion); Double_t nSigmaPosPionTOF = fPIDResponse->NumberOfSigmasTOF(myTrackPos, AliPID::kPion); Double_t nSigmaPosKaonTPC = fPIDResponse->NumberOfSigmasTPC(myTrackPos, AliPID::kKaon); Double_t nSigmaPosKaonTOF = fPIDResponse->NumberOfSigmasTOF(myTrackPos, AliPID::kKaon); Double_t nSigmaPosProtonTPC = fPIDResponse->NumberOfSigmasTPC(myTrackPos, AliPID::kProton); Double_t nSigmaPosProtonTOF = fPIDResponse->NumberOfSigmasTOF(myTrackPos, AliPID::kProton); // negative tracks Double_t nSigmaNegPionTPC = fPIDResponse->NumberOfSigmasTPC(myTrackNeg, AliPID::kPion); Double_t nSigmaNegPionTOF = fPIDResponse->NumberOfSigmasTOF(myTrackNeg, AliPID::kPion); Double_t nSigmaNegKaonTPC = fPIDResponse->NumberOfSigmasTPC(myTrackNeg, AliPID::kKaon); Double_t nSigmaNegKaonTOF = fPIDResponse->NumberOfSigmasTOF(myTrackNeg, AliPID::kKaon); Double_t nSigmaNegProtonTPC = fPIDResponse->NumberOfSigmasTPC(myTrackNeg, AliPID::kProton); Double_t nSigmaNegProtonTOF = fPIDResponse->NumberOfSigmasTOF(myTrackNeg, AliPID::kProton); Bool_t bpPion = TMath::Abs(nSigmaPosPionTPC) <= fMaxnSigmaTPCV0; Bool_t bpProton = TMath::Abs(nSigmaPosProtonTPC) <= fMaxnSigmaTPCV0; Bool_t bnPion = TMath::Abs(nSigmaNegPionTPC) <= fMaxnSigmaTPCV0; Bool_t bnProton = TMath::Abs(nSigmaNegProtonTPC) <= fMaxnSigmaTPCV0; Bool_t bpPion_tof = TMath::Abs(nSigmaPosPionTPC) <= 4.; Bool_t bpProton_tof = TMath::Abs(nSigmaPosProtonTPC) <=4; Bool_t bnPion_tof = TMath::Abs(nSigmaNegPionTOF) <= 4; Bool_t bnProton_tof = TMath::Abs(nSigmaNegProtonTOF) <=4; Bool_t fTOFV0=kTRUE; if(fTOFV0 && myTrackPos->Pt()>0.3 && fPIDResponse->CheckPIDStatus(AliPIDResponse::kTOF, myTrackPos) != 0){ bpPion=bpPion && bpPion_tof; bpProton=bpProton && bpProton_tof; } if(fTOFV0 && myTrackNeg->Pt()>0.3 && fPIDResponse->CheckPIDStatus(AliPIDResponse::kTOF, myTrackNeg) != 0){ bnPion=bnPion && bnPion_tof; bnProton=bnProton && bnProton_tof; } // Arme ntros podoranski cutOD Bool_t k0APcut = (aodv0->PtArmV0() > (TMath::Abs(0.2 * aodv0->AlphaV0()))); Bool_t kGammaconvcut = !(TMath::Power(aodv0->AlphaV0() / 0.95, 2) + TMath::Power(aodv0->PtArmV0() / 0.05, 2) < 1); if (k0APcut) fHist_AP[4]->Fill(aodv0->AlphaV0(), aodv0->PtArmV0()); if (kGammaconvcut) fHist_AP[5]->Fill(aodv0->AlphaV0(), aodv0->PtArmV0()); Bool_t fPIDV0=kFALSE; //if(fPIDV0 && fTOFV0) if ((myTrackPos->Pt()>0.3 && fPIDResponse->CheckPIDStatus(AliPIDResponse::kTOF, myTrackPos) == 0) || (myTrackNeg->Pt()>0.3 && fPIDResponse->CheckPIDStatus(AliPIDResponse::kTOF, myTrackNeg) == 0)) continue; fHistPosNsig[0]->Fill(myTrackPos->Pt(), nSigmaPosPionTPC); fHistPosNsig[1]->Fill(myTrackPos->Pt(), nSigmaPosProtonTPC); fHistPosNsig[2]->Fill(myTrackPos->Pt(), nSigmaPosKaonTPC); fHistPosNsig[3]->Fill(myTrackPos->Pt(), nSigmaPosPionTOF); fHistPosNsig[4]->Fill(myTrackPos->Pt(), nSigmaPosProtonTOF); fHistPosNsig[5]->Fill(myTrackPos->Pt(), nSigmaPosKaonTOF); fHistNegNsig[0]->Fill(myTrackNeg->Pt(), nSigmaNegPionTPC); fHistNegNsig[1]->Fill(myTrackNeg->Pt(), nSigmaNegProtonTPC); fHistNegNsig[2]->Fill(myTrackNeg->Pt(), nSigmaNegKaonTPC); fHistNegNsig[3]->Fill(myTrackNeg->Pt(), nSigmaNegPionTOF); fHistNegNsig[4]->Fill(myTrackNeg->Pt(), nSigmaNegProtonTOF); fHistNegNsig[5]->Fill(myTrackNeg->Pt(), nSigmaNegKaonTOF); /* if (fQA) { if (!kGammaconvcut) fHistPosNsigQA[0]->Fill(myTrackPos->Pt(),nSigmaPosPionTPC); // Nsigma of Pion if the AP diagram indicate gamma conversion } */ Bool_t cutK0Pid = (bpPion && bnPion); Bool_t cutLambdaPid = (bpProton && bnPion); Bool_t cutAntiLambdaPid = (bpPion && bnProton); // Mass cut Double_t lInvMassLambda = aodv0->MassLambda(); Double_t lInvMassK0 = aodv0->MassK0Short(); Double_t lInvMassAntiLambda = aodv0->MassAntiLambda(); const Double_t kProtonMass = TDatabasePDG::Instance()->GetParticle(2212)->Mass(); const Double_t kPionMass = TDatabasePDG::Instance()->GetParticle(211)->Mass(); Double_t mispidmass= -999.; if (fQA) { // QA to evaluate bump Double_t px1 = myTrackPos->Px(); Double_t py1 = myTrackPos->Py(); Double_t pz1 = myTrackPos->Pz(); Double_t px2 = myTrackNeg->Px(); Double_t py2 = myTrackNeg->Py(); Double_t pz2 = myTrackNeg->Pz(); Double_t px_v0 = px1 + px2; Double_t py_v0 = py1 + py2; Double_t pz_v0 = pz1 + pz2; Double_t p2_v0 = px_v0 * px_v0 + py_v0 * py_v0 + pz_v0 * pz_v0; Double_t E_pos_proton = TMath::Sqrt(px1 * px1 + py1 * py1 + pz1 * pz1 + kProtonMass * kProtonMass); Double_t E_neg_proton = TMath::Sqrt(px2 * px2 + py2 * py2 + pz2 * pz2 + kProtonMass * kProtonMass); Double_t E_neg_pion = TMath::Sqrt(px2 * px2 + py2 * py2 + pz2 * pz2 + kPionMass * kPionMass); Double_t E_pos_pion = TMath::Sqrt(px1 * px1 + py1 * py1 + pz1 * pz1 + kPionMass * kPionMass); mispidmass = TMath::Sqrt((E_pos_pion + E_neg_pion) * (E_pos_pion + E_neg_pion) - p2_v0); } Bool_t mispid=TMath::Abs(mispidmass-kK0Mass)<0.01; Bool_t cutMassLambda = ((lInvMassLambda > 1.05) && (lInvMassLambda < 1.25)); Bool_t cutMassAntiLambda = ((lInvMassAntiLambda > 1.05) && (lInvMassAntiLambda < 1.25)); Bool_t cutMassK0 = (lInvMassK0 > 0.4) && (lInvMassK0 < 0.6); if(cutK0Pid){ fHist_V0Stat->Fill(10); if(cutK0ctau){ fHist_V0Stat->Fill(11); if(k0APcut&&kGammaconvcut) fHist_V0Stat->Fill(12); } } if(cutLambdaPid){ fHist_V0Stat->Fill(13); if(cutLambdactau){ fHist_V0Stat->Fill(14); if(!k0APcut&&kGammaconvcut) fHist_V0Stat->Fill(15); } } /* Bool_t IDK0s = cutK0ctau && cpaK0s && k0APcut && (!cutMassLambda) && (!cutMassAntiLambda);//&& kGammaconvcut; Bool_t IDLa = cutLambdactau && cpaLambda && !k0APcut && (!cutMassK0); //&& kGammaconvcut; Bool_t IDALa = cutAntiLambdactau && cpaLambda && !k0APcut && (!cutMassK0);// && kGammaconvcut; */ /* if(fPIDV0){ IDK0s=IDK0s && cutK0Pid ; IDLa= IDLa && cutLambdaPid && !mispid; IDALa= IDALa && cutAntiLambdaPid && !mispid; } */ Bool_t IDK0s = cutK0ctau && cpaK0s && k0APcut; Bool_t IDLa = cutLambdactau && cpaLambda && !k0APcut; Bool_t IDALa = cutAntiLambdactau && cpaLambda && !k0APcut; if (IDK0s) fHist_AP[1]->Fill(aodv0->AlphaV0(), aodv0->PtArmV0()); if (IDLa || IDALa) fHist_AP[2]->Fill(aodv0->AlphaV0(), aodv0->PtArmV0()); Double_t K0sMassQA[4] = {lInvMassK0, aodv0->Pt(), lCentrality,aodv0->Eta()}; if (IDK0s) fHistMass_K0s->Fill(K0sMassQA); Double_t LambdaMassQA[4] = {lInvMassLambda, aodv0->Pt(), lCentrality,aodv0->Eta()}; if (IDLa) fHistMass_Lambda->Fill(LambdaMassQA); Double_t ALambdaMassQA[4] = {lInvMassAntiLambda, aodv0->Pt(), lCentrality,aodv0->Eta()}; if (IDALa) fHistMass_ALambda->Fill(ALambdaMassQA); if (cutLambdaPid && cutLambdactau && cpaLambda && !k0APcut && kGammaconvcut && mispidmass > 0) fHistMass_bumpcorr->Fill(lInvMassLambda, mispidmass); Int_t SpV0 = -999; if ((IDK0s && (TMath::Abs(lInvMassK0 - kK0Mass) < 0.01))) SpV0 = 0; // same for step if (IDK0s && (lInvMassK0 > 0.40) && (lInvMassK0 < 0.44)) SpV0 = 1; // same as step if (IDK0s && (lInvMassK0 > 0.44) && (lInvMassK0 < kK0Mass - 0.01)) SpV0 = 2; // same as step if (IDK0s && (lInvMassK0 > kK0Mass + 0.01) && (lInvMassK0 < 0.56)) SpV0 = 3; // same as step if (IDK0s && (lInvMassK0 > 0.56) && (lInvMassK0 < 0.60)) SpV0 = 4; // same as step if ((IDLa && TMath::Abs(lInvMassLambda - kLambdaMass) < 0.005) || (IDALa && TMath::Abs(lInvMassAntiLambda - kLambdaMass) < 0.005)) SpV0 = 5; // same as step if ((IDLa && (lInvMassLambda > kLambdaMass + 0.005) && (lInvMassLambda < 1.25)) || (IDALa && (lInvMassAntiLambda > kLambdaMass + 0.005) && (lInvMassAntiLambda < 1.25))) SpV0 = 6; // same as step if (SpV0 < 0) continue; Double_t spV0QA[4] = {aodv0->Eta(), aodv0->Phi(), (Float_t)SpV0, lCentrality}; fHist_V0QA->Fill(spV0QA); if (fQA) { if (IDK0s){ fHistPosNsigQA[0]->Fill(myTrackPos->Pt(), nSigmaPosPionTPC); fHistPosNsigQA[1]->Fill(myTrackNeg->Pt(), nSigmaNegPionTPC); fh3NegNsig[0]->Fill(myTrackNeg->Pt(),nSigmaNegPionTPC,nSigmaNegPionTOF); fh3PosNsig[0]->Fill(myTrackPos->Pt(),nSigmaPosPionTPC,nSigmaPosPionTOF); } if (IDLa){ fHistPosNsigQA[2]->Fill(myTrackPos->Pt(), nSigmaPosProtonTPC); fHistPosNsigQA[3]->Fill(myTrackNeg->Pt(), nSigmaNegPionTPC); fh3NegNsig[1]->Fill(myTrackNeg->Pt(),nSigmaNegPionTPC,nSigmaNegPionTOF); fh3PosNsig[1]->Fill(myTrackPos->Pt(),nSigmaPosProtonTPC,nSigmaPosProtonTOF); } if (IDALa){ fHistPosNsigQA[4]->Fill(myTrackPos->Pt(), nSigmaPosPionTPC); fHistPosNsigQA[5]->Fill(myTrackNeg->Pt(), nSigmaNegProtonTPC); fh3NegNsig[2]->Fill(myTrackNeg->Pt(),nSigmaNegProtonTPC,nSigmaNegProtonTOF); fh3PosNsig[2]->Fill(myTrackPos->Pt(),nSigmaPosPionTPC,nSigmaPosPionTOF); } } tracks->Add(new AliAssociatedTrackYS(aodv0->Charge(), aodv0->Eta(), aodv0->Phi(), aodv0->Pt(),aodv0->GetID(), myTrackPos->GetID(), myTrackNeg->GetID(), SpV0, 1)); if(!fDataType){ TClonesArray *mcArray1 = (TClonesArray*)fAODEvent->FindListObject(AliAODMCParticle::StdBranchName()); if(!mcArray1){ Printf("No MC particle branch found"); continue; } Int_t MotherOfMotherPdg =0; Int_t myTrackPosLabel = TMath::Abs(myTrackPos->GetLabel()); Int_t myTrackNegLabel = TMath::Abs(myTrackNeg->GetLabel()); AliAODMCParticle *mcPosTrack = (AliAODMCParticle*)mcArray1->At(myTrackPosLabel); if (!mcPosTrack) continue; //check if positive daughter track is MC particle AliAODMCParticle *mcNegTrack = (AliAODMCParticle*)mcArray1->At(myTrackNegLabel); if (!mcNegTrack) continue; //check if negative daughter track is MC particle Int_t PosTrackPdg = mcPosTrack->GetPdgCode(); Int_t NegTrackPdg = mcNegTrack->GetPdgCode(); Int_t myTrackPosMotherLabel = mcPosTrack->GetMother(); Int_t myTrackNegMotherLabel = mcNegTrack->GetMother(); if ((myTrackPosMotherLabel<0)||(myTrackNegMotherLabel<0)) continue; // check if dauter tracks have mother track if (myTrackPosMotherLabel!=myTrackNegMotherLabel) continue; // require the same mother particle for positive and negative daughter tracks AliAODMCParticle *mcPosMother = (AliAODMCParticle*)mcArray1->At(myTrackPosMotherLabel); if (!mcPosMother) continue; Int_t MotherPdg = mcPosMother->GetPdgCode(); Int_t MotherOfMother = mcPosMother->GetMother(); Bool_t IsK0FromMC = (mcPosMother->IsPhysicalPrimary())&&(MotherPdg==310)&&(PosTrackPdg==211)&&(NegTrackPdg==-211); //Moter track is K0 short, Pos is Pion, Neg is Pion Bool_t IsLambdaFromMC = (mcPosMother->IsPhysicalPrimary())&&(MotherPdg==3122)&&(PosTrackPdg==2212)&&(NegTrackPdg==-211); //Moter track is Lambda, Pos is Proton, Neg is Pion Bool_t IsAntiLambdaFromMC = (mcPosMother->IsPhysicalPrimary())&&(MotherPdg==-3122)&&(PosTrackPdg==211)&&(NegTrackPdg==-2212); //Moter track is Anti-Lambda, Pos is pion, Neg is Proton if(IsK0FromMC) fHistMass_K0s_MC->Fill(K0sMassQA); if(IsLambdaFromMC) fHistMass_Lambda_MC->Fill(LambdaMassQA); if(IsAntiLambdaFromMC) fHistMass_ALambda_MC->Fill(ALambdaMassQA); } } return tracks; } TObjArray *AliAnalysisTaskSEpPbCorrelationsYS::GetAcceptedCascadeTracks(AliAODEvent *fAODEvent) { // To select Cascade Particle TObjArray *tracks = new TObjArray; tracks->SetOwner(kTRUE); Int_t nCascades = fAODEvent->GetNumberOfCascades(); Double_t lInvMassXiMinus=-999.; Double_t lInvMassXiPlus=-999.; Double_t lInvMassOmegaMinus=-999.; Double_t lInvMassOmegaPlus=-999.; for (Int_t icasc = 0; icasc < nCascades; icasc++) { AliAODcascade *casc = fAODEvent->GetCascade(icasc); if (!casc) continue; const AliAODTrack *myTrackCascPos=0; const AliAODTrack *myTrackCascNeg=0; // const AliAODTrack*myTrackCascBach; AliAODTrack *myTrackCascPosTest = dynamic_cast<AliAODTrack *>(casc->GetDaughter(0)); AliAODTrack *myTrackCascNegTest = dynamic_cast<AliAODTrack *>(casc->GetDaughter(1)); const AliAODTrack *myTrackCascBach = dynamic_cast<AliAODTrack *>(casc->GetDecayVertexXi()->GetDaughter(0)); // myTrackCascBach=myTrackCascBachTest; if ((myTrackCascPosTest->Charge() == 1) && (myTrackCascNegTest->Charge() == -1)) { myTrackCascPos = myTrackCascPosTest; myTrackCascNeg = myTrackCascNegTest; } if ((myTrackCascPosTest->Charge() == -1) && (myTrackCascNegTest->Charge() == 1)) { myTrackCascPos = myTrackCascNegTest; myTrackCascNeg = myTrackCascPosTest; } if (!myTrackCascPos || !myTrackCascNeg || !myTrackCascBach) { AliWarning("ERROR: Could not retrieve one of the 3 AOD daughter tracks of the cascade ..."); continue; } UInt_t lIdxPosCasc = (UInt_t)TMath::Abs(myTrackCascPos->GetID()); UInt_t lIdxNegCasc = (UInt_t)TMath::Abs(myTrackCascNeg->GetID()); UInt_t lCascBachIdx = (UInt_t)TMath::Abs(myTrackCascBach->GetID()); if (lCascBachIdx == lIdxNegCasc) { AliWarning("Pb / Idx(Bach. track) = Idx(Neg. track) ... continue!"); continue; } if (lCascBachIdx == lIdxPosCasc) { AliWarning("Pb / Idx(Bach. track) = Idx(Pos. track) ... continue!"); continue; } // if (!IsAcceptedCascade(casc)) continue; Double_t lInvMassxi = casc->MassXi(); Double_t lInvMassomega = casc->MassOmega(); Short_t lChargeXi = casc->ChargeXi(); if (!IsAcceptedDaughterTrack(myTrackCascPos) || !IsAcceptedDaughterTrack(myTrackCascNeg) || !IsAcceptedDaughterTrack(myTrackCascBach)) continue; Double_t lCasx = casc->DecayVertexXiX(); Double_t lCasy = casc->DecayVertexXiY(); Double_t lCasz = casc->DecayVertexXiZ(); const Double_t kximass = TDatabasePDG::Instance()->GetParticle(3312)->Mass(); const Double_t komegamass = TDatabasePDG::Instance()->GetParticle(3334)->Mass(); Bool_t topoXi=IsAcceptedCascade(casc); Bool_t topoOmega=IsAcceptedCascadeOmega(casc); if(!topoXi && !topoOmega) continue; Double_t cutctauxi = 6 * 4.91; Double_t cutctauomega = 6 * 2.461; Double_t lCasDecayLength = TMath::Sqrt(TMath::Power(lCasx - tPrimaryVtxPosition[0], 2) + TMath::Power(lCasy - tPrimaryVtxPosition[1], 2) + TMath::Power(lCasz - tPrimaryVtxPosition[2], 2)); Double_t lPCas = TMath::Sqrt((casc->MomXiX()) * (casc->MomXiX()) +(casc->MomXiY()) * (casc->MomXiY()) +(casc->MomXiZ()) * (casc->MomXiZ())); Double_t lctauXi = (lCasDecayLength * kximass) / lPCas; Double_t lctauOmega = (lCasDecayLength * komegamass) / lPCas; // Bool_t cutXictau=(lctauXi < cutctauxi); // Bool_t cutOmegactau=(lctauOmega<cutctauomega); Bool_t cutXictau = kTRUE; Bool_t cutOmegactau = kTRUE; if (lChargeXi < 0) lInvMassXiMinus = lInvMassxi; if (lChargeXi > 0) lInvMassXiPlus = lInvMassxi; if (lChargeXi < 0) lInvMassOmegaMinus = lInvMassomega; if (lChargeXi > 0) lInvMassOmegaPlus = lInvMassomega; Float_t nSigmaCascBachKaonTPC = fPIDResponse->NumberOfSigmasTPC(myTrackCascBach, AliPID::kKaon); Float_t nSigmaCascBachPionTPC = fPIDResponse->NumberOfSigmasTPC(myTrackCascBach, AliPID::kPion); Float_t nSigmaCascBachProtonTPC = fPIDResponse->NumberOfSigmasTPC(myTrackCascBach, AliPID::kProton); Float_t nSigmaCascBachKaonTOF = fPIDResponse->NumberOfSigmasTOF(myTrackCascBach, AliPID::kKaon); Float_t nSigmaCascBachPionTOF = fPIDResponse->NumberOfSigmasTOF(myTrackCascBach, AliPID::kPion); Float_t nSigmaCascBachProtonTOF = fPIDResponse->NumberOfSigmasTOF(myTrackCascBach, AliPID::kProton); Float_t nSigmaCascPosKaonTPC = fPIDResponse->NumberOfSigmasTPC(myTrackCascPos, AliPID::kKaon); Float_t nSigmaCascPosPionTPC = fPIDResponse->NumberOfSigmasTPC(myTrackCascPos, AliPID::kPion); Float_t nSigmaCascPosProtonTPC = fPIDResponse->NumberOfSigmasTPC(myTrackCascPos, AliPID::kProton); Float_t nSigmaCascPosKaonTOF = fPIDResponse->NumberOfSigmasTOF(myTrackCascPos, AliPID::kKaon); Float_t nSigmaCascPosPionTOF = fPIDResponse->NumberOfSigmasTOF(myTrackCascPos, AliPID::kPion); Float_t nSigmaCascPosProtonTOF = fPIDResponse->NumberOfSigmasTOF(myTrackCascPos, AliPID::kProton); Float_t nSigmaCascNegKaonTPC = fPIDResponse->NumberOfSigmasTPC(myTrackCascNeg, AliPID::kKaon); Float_t nSigmaCascNegPionTPC = fPIDResponse->NumberOfSigmasTPC(myTrackCascNeg, AliPID::kPion); Float_t nSigmaCascNegProtonTPC = fPIDResponse->NumberOfSigmasTPC(myTrackCascNeg, AliPID::kProton); Float_t nSigmaCascNegKaonTOF = fPIDResponse->NumberOfSigmasTOF(myTrackCascNeg, AliPID::kKaon); Float_t nSigmaCascNegPionTOF = fPIDResponse->NumberOfSigmasTOF(myTrackCascNeg, AliPID::kPion); Float_t nSigmaCascNegProtonTOF = fPIDResponse->NumberOfSigmasTOF(myTrackCascNeg, AliPID::kProton); Float_t d2sigmacascbachkaontpctof = nSigmaCascBachKaonTPC * nSigmaCascBachKaonTPC + nSigmaCascBachKaonTOF * nSigmaCascBachKaonTOF; Float_t d2sigmacascbachpiontpctof = nSigmaCascBachPionTPC * nSigmaCascBachPionTPC + nSigmaCascBachPionTOF * nSigmaCascBachPionTOF; Float_t d2sigmacascbachprotontpctof = nSigmaCascBachProtonTPC * nSigmaCascBachProtonTPC + nSigmaCascBachProtonTOF * nSigmaCascBachProtonTOF; Float_t d2sigmacascposkaontpctof = nSigmaCascPosKaonTPC * nSigmaCascPosKaonTPC + nSigmaCascPosKaonTOF * nSigmaCascPosKaonTOF; Float_t d2sigmacascpospiontpctof = nSigmaCascPosPionTPC * nSigmaCascPosPionTPC + nSigmaCascPosPionTOF * nSigmaCascPosPionTOF; Float_t d2sigmacascposprotontpctof = nSigmaCascPosProtonTPC * nSigmaCascPosProtonTPC + nSigmaCascPosProtonTOF * nSigmaCascPosProtonTOF; Float_t d2sigmacascnegkaontpctof = nSigmaCascNegKaonTPC * nSigmaCascNegKaonTPC + nSigmaCascNegKaonTOF * nSigmaCascNegKaonTPC; Float_t d2sigmacascnegpiontpdtof = nSigmaCascNegPionTPC * nSigmaCascNegPionTPC + nSigmaCascNegPionTOF * nSigmaCascNegPionTOF; Float_t d2sigmacascnegprotontpctof = nSigmaCascNegProtonTPC * nSigmaCascNegProtonTPC + nSigmaCascNegProtonTOF * nSigmaCascNegProtonTOF; Bool_t fPIDTOF_cascbach; Bool_t fPIDTOF_cascpos; Bool_t fPIDTOF_cascneg; if (fPIDResponse->CheckPIDStatus(AliPIDResponse::kTOF, myTrackCascBach) == 0) fPIDTOF_cascbach = kFALSE; else fPIDTOF_cascbach = kTRUE; if (fPIDResponse->CheckPIDStatus(AliPIDResponse::kTOF, myTrackCascPos) == 0) fPIDTOF_cascpos = kFALSE; else fPIDTOF_cascpos = kTRUE; if (fPIDResponse->CheckPIDStatus(AliPIDResponse::kTOF, myTrackCascNeg) == 0) fPIDTOF_cascneg = kFALSE; else fPIDTOF_cascneg = kTRUE; Float_t nSigmaCascBachKaonTOFTPC; Float_t nSigmaCascBachPionTOFTPC; Float_t nSigmaCascBachProtonTOFTPC; Float_t nSigmaCascPosKaonTOFTPC; Float_t nSigmaCascPosPionTOFTPC; Float_t nSigmaCascPosProtonTOFTPC; Float_t nSigmaCascNegKaonTOFTPC; Float_t nSigmaCascNegPionTOFTPC; Float_t nSigmaCascNegProtonTOFTPC; if (fPIDTOF_cascbach && myTrackCascBach->Pt() > 0.5) { nSigmaCascBachKaonTOFTPC = TMath::Sqrt(d2sigmacascbachkaontpctof); nSigmaCascBachPionTOFTPC = TMath::Sqrt(d2sigmacascbachpiontpctof); nSigmaCascBachProtonTOFTPC = TMath::Sqrt(d2sigmacascbachprotontpctof); } else { nSigmaCascBachKaonTOFTPC = TMath::Abs(nSigmaCascBachKaonTPC); nSigmaCascBachPionTOFTPC = TMath::Abs(nSigmaCascBachPionTPC); nSigmaCascBachProtonTOFTPC = TMath::Abs(nSigmaCascBachProtonTPC); } if (fPIDTOF_cascpos && myTrackCascPos->Pt() > 0.5) { nSigmaCascPosKaonTOFTPC = TMath::Sqrt(d2sigmacascbachkaontpctof); nSigmaCascPosPionTOFTPC = TMath::Sqrt(d2sigmacascbachpiontpctof); nSigmaCascPosProtonTOFTPC = TMath::Sqrt(d2sigmacascbachprotontpctof); } else { nSigmaCascPosKaonTOFTPC = TMath::Abs(nSigmaCascPosKaonTPC); nSigmaCascPosPionTOFTPC = TMath::Abs(nSigmaCascPosPionTPC); nSigmaCascPosProtonTOFTPC = TMath::Abs(nSigmaCascPosProtonTPC); } if (fPIDTOF_cascpos && myTrackCascNeg->Pt() > 0.5) { nSigmaCascNegKaonTOFTPC = TMath::Sqrt(d2sigmacascbachkaontpctof); nSigmaCascNegPionTOFTPC = TMath::Sqrt(d2sigmacascbachpiontpctof); nSigmaCascNegProtonTOFTPC = TMath::Sqrt(d2sigmacascbachprotontpctof); } else { nSigmaCascNegKaonTOFTPC = TMath::Abs(nSigmaCascNegKaonTPC); nSigmaCascNegPionTOFTPC = TMath::Abs(nSigmaCascNegPionTPC); nSigmaCascNegProtonTOFTPC = TMath::Abs(nSigmaCascNegProtonTPC); } Int_t SpPID_cascbach = 999; // 1:kaon 2:pion 3:proton Int_t SpPID_cascpos = 999; Int_t SpPID_cascneg = 999; /* if( (nSigmaCascBachKaonTOFTPC<5.0) && (nSigmaCascBachKaonTOFTPC<nSigmaCascBachPionTOFTPC) && (nSigmaCascBachKaonTOFTPC<nSigmaCascBachProtonTOFTPC) ) SpPID_cascbach=1; if( (nSigmaCascBachPionTOFTPC<5.0) && (nSigmaCascBachPionTOFTPC<nSigmaCascBachKaonTOFTPC) && (nSigmaCascBachPionTOFTPC<nSigmaCascBachProtonTOFTPC) ) SpPID_cascbach=2; if( (nSigmaCascPosPionTOFTPC<5.0) && (nSigmaCascPosPionTOFTPC<nSigmaCascPosKaonTOFTPC) && (nSigmaCascPosPionTOFTPC<nSigmaCascPosProtonTOFTPC) ) SpPID_cascpos=2; if( (nSigmaCascPosProtonTOFTPC<5.0) && (nSigmaCascPosPionTOFTPC<nSigmaCascPosKaonTOFTPC) && (nSigmaCascPosProtonTOFTPC<nSigmaCascPosPionTOFTPC) ) SpPID_cascpos=3; if( (nSigmaCascNegPionTOFTPC<5.0) && (nSigmaCascNegPionTOFTPC<nSigmaCascNegKaonTOFTPC) && (nSigmaCascNegPionTOFTPC<nSigmaCascNegProtonTOFTPC) ) SpPID_cascneg=2; if( (nSigmaCascNegProtonTOFTPC<5.0) && (nSigmaCascNegPionTOFTPC<nSigmaCascNegKaonTOFTPC) && (nSigmaCascNegProtonTOFTPC<nSigmaCascNegPionTOFTPC) ) SpPID_cascneg=3; */ if (TMath::Abs(nSigmaCascBachKaonTPC) < 5.0) SpPID_cascbach = 1; if (TMath::Abs(nSigmaCascBachPionTPC) < 5.0) SpPID_cascbach = 2; if (TMath::Abs(nSigmaCascPosPionTPC) < 5.0) SpPID_cascpos = 2; if (TMath::Abs(nSigmaCascPosProtonTPC) < 5.0) SpPID_cascpos = 3; if (TMath::Abs(nSigmaCascNegPionTPC) < 5.0) SpPID_cascneg = 2; if (TMath::Abs(nSigmaCascNegProtonTPC) < 5.0) SpPID_cascneg = 3; Bool_t cutXiMinusPID = (SpPID_cascbach == 2 && SpPID_cascneg == 2 && SpPID_cascpos == 3); Bool_t cutXiPlusPID = (SpPID_cascbach == 2 && SpPID_cascneg == 3 && SpPID_cascpos == 2); Bool_t cutOmegaMinusPID = (SpPID_cascbach == 1 && SpPID_cascneg == 2 && SpPID_cascpos == 3); Bool_t cutOmegaPlusPID = (SpPID_cascbach == 1 && SpPID_cascneg == 3 && SpPID_cascpos == 2); Bool_t cutMassXi = ((lInvMassxi > 1.2) && (lInvMassxi < 1.4)); Bool_t cutMassOmega = ((lInvMassomega > 1.55) && (lInvMassomega < 1.75)); Bool_t cutXiMinussc = cutXictau && cutXiMinusPID && topoXi && (!cutMassOmega); Bool_t cutXiPlussc = cutXictau && cutXiPlusPID && topoXi && (!cutMassOmega); Bool_t cutOmegaMinussc = cutOmegactau && cutOmegaMinusPID && topoOmega && (!cutMassXi); Bool_t cutOmegaPlussc = cutOmegactau && cutOmegaPlusPID && topoOmega && (!cutMassXi); Double_t lPtCas = TMath::Sqrt((casc->MomXiX()) * (casc->MomXiX()) + (casc->MomXiY()) * (casc->MomXiY())); Double_t spXiMinus[3] = {lInvMassXiMinus, lPtCas, lCentrality}; Double_t spXiPlus[3] = {lInvMassXiPlus, lPtCas, lCentrality}; Double_t spOmegaMinus[3] = {lInvMassOmegaMinus, lPtCas, lCentrality}; Double_t spOmegaPlus[3] = {lInvMassOmegaPlus, lPtCas, lCentrality}; if (cutXiMinussc && cutMassXi) fHistMassXiMinus->Fill(spXiMinus); if (cutXiPlussc && cutMassXi) fHistMassXiPlus->Fill(spXiPlus); if (cutOmegaMinussc && cutMassOmega) fHistMassOmegaMinus->Fill(spOmegaMinus); if (cutOmegaPlussc && cutMassOmega) fHistMassOmegaPlus->Fill(spOmegaPlus); // if (cutOmegaMinussc) cout << lInvMassOmegaMinus << endl; Double_t etaCas = 0.5 * TMath::Log((lPCas + casc->MomXiZ()) / (lPCas - casc->MomXiZ())); if (TMath::Abs(etaCas) > 0.8) continue; Double_t phiCas = TMath::ATan2(casc->MomXiY(), casc->MomXiX()); if (phiCas < 0.) phiCas += 2 * TMath::Pi(); Int_t SpCas = -999; Bool_t IDXi = (cutXiMinussc || cutXiPlussc) && cutMassXi; Bool_t IDOmega = (cutOmegaMinussc || cutOmegaPlussc) && cutMassOmega; Bool_t XiSignal = ((lInvMassxi > 1.314) && (lInvMassxi < 1.33)); Bool_t XiSignalBg1 = ((lInvMassxi < 1.314) && (lInvMassxi > 1.2)); Bool_t XiSignalBg2 = ((lInvMassxi > 1.33) && (lInvMassxi < 1.4)); Bool_t OmegaSignal = ((lInvMassomega > 1.667) && (lInvMassomega < 1.678)); Bool_t OmegaSignalBg1 = ((lInvMassomega < 1.667) && (lInvMassomega > 1.55)); Bool_t OmegaSignalBg2 = ((lInvMassomega > 1.678) && (lInvMassomega < 1.75)); if (IDXi && XiSignal) SpCas = 0; if (IDXi && XiSignalBg1) SpCas = 1; if (IDXi && XiSignalBg2) SpCas = 2; if (IDOmega && OmegaSignal) SpCas = 3; if (IDOmega && OmegaSignalBg1) SpCas = 4; if (IDOmega && OmegaSignalBg2) SpCas = 5; if(SpCas<0) continue; Double_t spCascadeQA[5] = {casc->Pt(),casc->Eta(), casc->Phi(), (Float_t)SpCas, lCentrality}; fHist_CascadeQA->Fill(spCascadeQA); tracks->Add(new AliAssociatedTrackYS(1., etaCas, phiCas, lPtCas, myTrackCascPos->GetID(),myTrackCascNeg->GetID(), myTrackCascBach->GetID(), SpCas, 1)); } return tracks; } Bool_t AliAnalysisTaskSEpPbCorrelationsYS::IsAcceptedCascade( const AliAODcascade *casc) { if (!casc) return kFALSE; /* AliAODTrack *ptrack = (AliAODTrack*) (casc->GetDaughter(0)); AliAODTrack *ntrack = (AliAODTrack*) (casc->GetDaughter(1)); AliAODTrack *btrack = (AliAODTrack*) (casc->GetDecayVertexXi()->GetDaughter(0)); if(!ptrack||!ntrack||!btrack) return kFALSE; */ const Double_t mLPDG = TDatabasePDG::Instance()->GetParticle(3122)->Mass(); const Double_t mxiPDG = TDatabasePDG::Instance()->GetParticle(3312)->Mass(); const Double_t momegaPDG = TDatabasePDG::Instance()->GetParticle(3334)->Mass(); Double_t massLambda=-1.; Double_t massAntiLambda=-1.; if(casc->ChargeXi()<0){ massLambda = casc->MassLambda(); if(TMath::Abs(massLambda-mLPDG)>0.00775) return kFALSE; }else{ massAntiLambda = casc->MassAntiLambda(); if(TMath::Abs(massAntiLambda-mLPDG)>0.00775) return kFALSE; } Double_t lPosXi[3]; lPosXi[0] = casc->DecayVertexXiX(); lPosXi[1] = casc->DecayVertexXiY(); lPosXi[2] = casc->DecayVertexXiZ(); Double_t decayvertXi = TMath::Sqrt(lPosXi[0] * lPosXi[0] + lPosXi[1] * lPosXi[1]); Double_t lPosV0[3]; lPosV0[0] = casc->DecayVertexV0X(); lPosV0[1] = casc->DecayVertexV0Y(); lPosV0[2] = casc->DecayVertexV0Z(); Double_t decayvertV0 = TMath::Sqrt(lPosV0[0] * lPosV0[0] + lPosV0[1] * lPosV0[1]); if (decayvertV0 < 1.55) return kFALSE; // Decay vertex V0 if (decayvertXi < 0.29) return kFALSE; // Decay Vertex Xi Double_t lDcaXiDaughters = casc->DcaXiDaughters(); Double_t lDcaV0Daughters = casc->DcaV0Daughters(); if (lDcaXiDaughters > 1.83) return kFALSE; // DCA between Xi Daughters if (lDcaV0Daughters > 1.33) return kFALSE; // DCA between V0 Daughters Double_t lDcaBachToPrimVertex = casc->DcaBachToPrimVertex(); Double_t lDcaV0ToPrimVertex = casc->DcaV0ToPrimVertex(); Double_t lDcaPosToPrimVertex = casc->DcaPosToPrimVertex(); Double_t lDcaNegToPrimVertex = casc->DcaNegToPrimVertex(); if (lDcaBachToPrimVertex < 0.0146) return kFALSE; // DCA between Bach track and Primary vertex if (lDcaV0ToPrimVertex < 0.02) return kFALSE; // DCA between V0 deday vertex and primary vertex if (lDcaPosToPrimVertex < 0.061) return kFALSE; // DCA between Pos track and Primary vertex if (lDcaNegToPrimVertex < 0.061) return kFALSE; // DCA between Neg track and Primary vertex Double_t lXiCosineOfPointingAngle = casc->CosPointingAngleXi(tPrimaryVtxPosition[0], tPrimaryVtxPosition[1], tPrimaryVtxPosition[2]); Double_t lV0CosineOfPointingAngleXi = casc->CosPointingAngle(lPosXi); if (lXiCosineOfPointingAngle < 0.9813) return kFALSE; // Pointing angle of Xi if (lV0CosineOfPointingAngleXi < 0.97) return kFALSE; /// Pointing angle of V0 return kTRUE; } Bool_t AliAnalysisTaskSEpPbCorrelationsYS::IsAcceptedCascadeOmega(const AliAODcascade *casc) { if (!casc) return kFALSE; const Double_t mLPDG = TDatabasePDG::Instance()->GetParticle(3122)->Mass(); const Double_t mxiPDG = TDatabasePDG::Instance()->GetParticle(3312)->Mass(); const Double_t momegaPDG = TDatabasePDG::Instance()->GetParticle(3334)->Mass(); Double_t massLambda=-1.; Double_t massAntiLambda=-1.; if(casc->ChargeXi()<0){ massLambda = casc->MassLambda(); if(TMath::Abs(massLambda-mLPDG)>0.00775) return kFALSE; }else{ massAntiLambda = casc->MassAntiLambda(); if(TMath::Abs(massAntiLambda-mLPDG)>0.00775) return kFALSE; } Double_t lPosXi[3]; lPosXi[0] = casc->DecayVertexXiX(); lPosXi[1] = casc->DecayVertexXiY(); lPosXi[2] = casc->DecayVertexXiZ(); Double_t decayvertXi = TMath::Sqrt(lPosXi[0] * lPosXi[0] + lPosXi[1] * lPosXi[1]); Double_t lPosV0[3]; lPosV0[0] = casc->DecayVertexV0X(); lPosV0[1] = casc->DecayVertexV0Y(); lPosV0[2] = casc->DecayVertexV0Z(); Double_t decayvertV0 = TMath::Sqrt(lPosV0[0] * lPosV0[0] + lPosV0[1] * lPosV0[1]); if (decayvertV0 < 1.918) return kFALSE; // Decay vertex V0 if (decayvertXi < 0.59) return kFALSE; // Decay Vertex Xi Double_t lDcaXiDaughters = casc->DcaXiDaughters(); Double_t lDcaV0Daughters = casc->DcaV0Daughters(); if (lDcaXiDaughters > 1.091) return kFALSE; // DCA between Xi Daughters if (lDcaV0Daughters > 1.206) return kFALSE; // DCA between V0 Daughters Double_t lDcaBachToPrimVertex = casc->DcaBachToPrimVertex(); Double_t lDcaV0ToPrimVertex = casc->DcaV0ToPrimVertex(); Double_t lDcaPosToPrimVertex = casc->DcaPosToPrimVertex(); Double_t lDcaNegToPrimVertex = casc->DcaNegToPrimVertex(); if (lDcaBachToPrimVertex < 0.041) return kFALSE; // DCA between Bach track and Primary vertex if (lDcaV0ToPrimVertex < 0.068) return kFALSE; // DCA between V0 deday vertex and primary vertex if (lDcaPosToPrimVertex < 0.061) return kFALSE; // DCA between Pos track and Primary vertex if (lDcaNegToPrimVertex < 0.061) return kFALSE; // DCA between Neg track and Primary vertex Double_t lXiCosineOfPointingAngle = casc->CosPointingAngleXi(tPrimaryVtxPosition[0], tPrimaryVtxPosition[1], tPrimaryVtxPosition[2]); Double_t lV0CosineOfPointingAngleXi = casc->CosPointingAngle(lPosXi); if (lXiCosineOfPointingAngle < 0.9811) return kFALSE; // Pointing angle of Xi if (lV0CosineOfPointingAngleXi < 0.933) return kFALSE; /// Pointing angle of V0 return kTRUE; } Bool_t AliAnalysisTaskSEpPbCorrelationsYS::IsAcceptedPhiDaughterTrack(const AliAODTrack *aodTrack) { if (!aodTrack->TestFilterMask(BIT(ffilterbit))) return kFALSE; if (aodTrack->Pt() < 0.15) return kFALSE; if (TMath::Abs(aodTrack->Eta()) > 0.8) return kFALSE; if (aodTrack->Charge() == 0) return kFALSE; return kTRUE; } Bool_t AliAnalysisTaskSEpPbCorrelationsYS::IsAcceptedDaughterTrack(const AliAODTrack *itrack) {//apply for V0s and Cascade if (TMath::Abs(itrack->Eta()) > 0.8) return kFALSE; // if(itrack->Eta()>fEtaMaxDaughter || itrack->Eta()<fEtaMinDaughter) return kFALSE; if (!itrack->IsOn(AliAODTrack::kTPCrefit)) return kFALSE; Float_t nCrossedRowsTPC = itrack->GetTPCClusterInfo(2, 1); if (nCrossedRowsTPC < fclustermin) return kFALSE; Int_t findable = itrack->GetTPCNclsF(); if (findable <= 0) return kFALSE; if (nCrossedRowsTPC / findable < fratiocluster) return kFALSE; if (itrack->GetKinkIndex(0) > 0) return kFALSE; // if(itrack->Pt()<0.15) return kFALSE; if(itrack->Pt()<0.1) return kFALSE; return kTRUE; } Bool_t AliAnalysisTaskSEpPbCorrelationsYS::IsAcceptedTrack(const AliAODTrack *aodTrack) { if (!aodTrack) return kFALSE; // if(!aodTrack->TestFilterMask(BIT(5))) return kFALSE; // standard cut with // tight DCA cut if(fcollisiontype=="PbPb"){ if (!aodTrack->TestFilterBit(ffilterbit)) return kFALSE; Float_t nCrossedRowsTPC =aodTrack->GetTPCClusterInfo(2,1); if (nCrossedRowsTPC < fnoClusters) return kFALSE; if(fCutChargedDCAzMax > 0. ||fCutChargedDCAxyMax > 0.){ Double_t dTrackXYZ[3] = {0.,0.,0.}; Double_t dVertexXYZ[3] = {0.,0.,0.}; Double_t dDCAXYZ[3] = {0.,0.,0.}; aodTrack->GetXYZ(dTrackXYZ); lPrimaryBestVtx->GetXYZ(dVertexXYZ); for(Short_t i(0); i < 3; i++) { dDCAXYZ[i] = dTrackXYZ[i] - dVertexXYZ[i]; } if(fCutChargedDCAzMax > 0. && TMath::Abs(dDCAXYZ[2]) >fCutChargedDCAzMax) return kFALSE; if(fCutChargedDCAxyMax > 0. && TMath::Sqrt(dDCAXYZ[0]*dDCAXYZ[0] + dDCAXYZ[1]*dDCAXYZ[1]) > fCutChargedDCAxyMax) return kFALSE; } }else{ // if(aodTrack->TestFilterMask(BIT(5))!=aodTrack->TestFilterBit(32)) cout<<"bad!!!!!!!!!!!!!!!!!!!!!!!!!!!!"<<endl; // if (!aodTrack->TestFilterMask(BIT(ffilterbit))) return kFALSE; if (!aodTrack->TestFilterBit(ffilterbit)) return kFALSE; } /* if (!aodTrack->IsOn(AliAODTrack::kTPCrefit)) return kFALSE; Float_t nCrossedRowsTPC =aodTrack->GetTPCClusterInfo(2,1); if (nCrossedRowsTPC < 70) return kFALSE; Int_t findable=aodTrack->GetTPCNclsF(); if (findable <= 0)return kFALSE; if (nCrossedRowsTPC/findable < 0.8) return kFALSE; */ if (aodTrack->Pt() < fPtMin) return kFALSE; if(aodTrack->Pt()>8.) return kFALSE; if(!fptdiff) {if (aodTrack->Pt() > fPtMax) return kFALSE;} if (TMath::Abs(aodTrack->Eta()) > fEtaMax) return kFALSE; return kTRUE; } Bool_t AliAnalysisTaskSEpPbCorrelationsYS::IsAcceptedV0(const AliAODv0 *aodV0) { /* Pseudo rapidity V0 < 0.8 daughter tracks DCA to P >0.06cm DCA between daughters <1 sigma V0 2D decay radius from 0.5cm to 200cm */ if (!aodV0) return kFALSE; if(aodV0->GetOnFlyStatus()) fHist_V0Stat->Fill(1); //Onfly else fHist_V0Stat->Fill(2); //Onfly if (fOnfly) { if (!aodV0->GetOnFlyStatus()) return kFALSE; // onfly reconstraction only } else { if (aodV0->GetOnFlyStatus()) return kFALSE; // ofline reconstraction only } Double_t leta_v0 = aodV0->PseudoRapV0(); if (TMath::Abs(leta_v0) > 0.8) return kFALSE; // default 0.8 // if (leta_v0 < fEtaMinV0 || fEtaMaxV0<leta_v0) return kFALSE; // default 0.8 else fHist_V0Stat->Fill(3); // DCA to primary vertex Float_t xyn = aodV0->DcaNegToPrimVertex(); Float_t xyp = aodV0->DcaPosToPrimVertex(); if ((TMath::Abs(xyn) > fdcaDaughtersToPrimVtx) || (TMath::Abs(xyp) > fdcaDaughtersToPrimVtx)) fHist_V0Stat->Fill(4); if (TMath::Abs(xyn) < fdcaDaughtersToPrimVtx) return kFALSE; // default 0.06 if (TMath::Abs(xyp) < fdcaDaughtersToPrimVtx) return kFALSE; // default 0.06 // DCA between dauther tracks Double_t dca = aodV0->DcaV0Daughters(); if (dca > fdcaBetweenDaughters) return kFALSE; // default 1.0 else fHist_V0Stat->Fill(5); // Fiducial volume Double_t xyz[3]; aodV0->GetSecondaryVtx(xyz); Double_t r2 = xyz[0] * xyz[0] + xyz[1] * xyz[1]; if (r2 > fRadiMin * fRadiMin && r2 < fRadiMax * fRadiMax) fHist_V0Stat->Fill(6); if (r2 < fRadiMin * fRadiMin) return kFALSE; // default 0.5 cm if (r2 > fRadiMax * fRadiMax) return kFALSE; // default 100cm return kTRUE; } Bool_t AliAnalysisTaskSEpPbCorrelationsYS::IsAcceptedDecayLength(const AliAODv0*aodv0,Double_t mass,Double_t maxctau){ Double_t lDVx = aodv0->GetSecVtxX(); Double_t lDVy = aodv0->GetSecVtxY(); Double_t lDVz = aodv0->GetSecVtxZ(); Double_t lV0DecayLength =TMath::Sqrt(TMath::Power(lDVx - tPrimaryVtxPosition[0], 2) + TMath::Power(lDVy - tPrimaryVtxPosition[1], 2) + TMath::Power(lDVz - tPrimaryVtxPosition[2], 2)); Double_t lPV0 = TMath::Sqrt((aodv0->Pt()) * (aodv0->Pt()) +(aodv0->Pz()) * (aodv0->Pz())); Double_t lcTau = (lV0DecayLength * mass) / lPV0; if(lcTau>maxctau) return kFALSE; return kTRUE; } void AliAnalysisTaskSEpPbCorrelationsYS::FillCorrelationTracks( Double_t centrality, TObjArray *triggerArray, TObjArray *selectedTrackArray,AliTHn *triggerHist, AliTHn *associateHist, Bool_t twoTrackEfficiencyCut, Float_t twoTrackEfficiencyCutValue, Float_t fTwoTrackCutMinRadius,Float_t bSign, Int_t step) { twoTrackEfficiencyCut=kFALSE; twoTrackEfficiencyCutValue=0; fTwoTrackCutMinRadius=0; bSign=0; step=1;//default if (!triggerHist || !associateHist) return; if(fAnaMode=="TPCTPC"){ Double_t binscontTrig[3]; Double_t binscont[6]; for (Int_t i = 0; i < triggerArray->GetEntriesFast(); i++) { AliAssociatedTrackYS *trigger = (AliAssociatedTrackYS *)triggerArray->At(i); if (!trigger) continue; Float_t triggerPt = trigger->Pt(); Float_t triggerEta = trigger->Eta(); Float_t triggerPhi = trigger->Phi(); Int_t trigFirstID = trigger->GetIDFirstDaughter(); Int_t trigSecondID = trigger->GetIDSecondDaughter(); Int_t trigID = trigger->GetID(); binscontTrig[0] = triggerPt; binscontTrig[1] = centrality; binscontTrig[2] = fPrimaryZVtx; Float_t triggermultiplicity=trigger->Multiplicity(); /* Float_t efficiency=999; Int_t ivzbin=frefvz->GetXaxis()->FindBin(fPrimaryZVtx); if(fefficalib){ Int_t iPt=fhcorr[ivzbin-1]->GetXaxis()->FindBin(triggerPt); Int_t iEta=fhcorr[ivzbin-1]->GetYaxis()->FindBin(triggerEta); Int_t iPhi=fhcorr[ivzbin-1]->GetZaxis()->FindBin(triggerPhi); efficiency=fhcorr[ivzbin-1]->GetBinContent(iPt,iEta,iPhi); }else efficiency=1.; if(efficiency==0.) continue; */ // triggerHist->Fill(binscontTrig,0,1./efficiency); triggerHist->Fill(binscontTrig,0,triggermultiplicity); for (Int_t j = 0; j < selectedTrackArray->GetEntriesFast(); j++) { AliAssociatedTrackYS *associate = (AliAssociatedTrackYS*)selectedTrackArray->At(j); if (!associate) continue; Int_t AssoFirstID = associate->GetIDFirstDaughter(); Int_t AssoSecondID = associate->GetIDSecondDaughter(); if (fasso == "V0" || fasso == "Phi"){ if (trigID == AssoFirstID || trigID == AssoSecondID){ continue; } } if (fasso == "hadron" || fasso=="PID") { if (triggerPt < associate->Pt()) continue; if (trigID == associate->GetID()) continue; } if (fasso == "Cascade") if (trigID == associate->GetID() || trigID == AssoFirstID || trigID == AssoSecondID) continue; binscont[0] = triggerEta - associate->Eta(); binscont[1] = associate->Pt(); binscont[2] = triggerPt; binscont[3] = centrality; binscont[4] = RangePhi(triggerPhi - associate->Phi()); binscont[5] = fPrimaryZVtx; Float_t assomultiplicity=associate->Multiplicity(); /* Float_t efficiency1=999.; if(fefficalib){ Int_t iPt1=fhcorr[ivzbin-1]->GetXaxis()->FindBin(associate->Pt()); Int_t iEta1=fhcorr[ivzbin-1]->GetYaxis()->FindBin(associate->Eta()); Int_t iPhi1=fhcorr[ivzbin-1]->GetZaxis()->FindBin(associate->Phi()); efficiency1=fhcorr[ivzbin-1]->GetBinContent(iPt1,iEta1,iPhi1); }else efficiency1=1.; if(efficiency1==0.) continue; */ Int_t SpAsso = associate->WhichCandidate(); if (fasso == "V0" || fasso == "Phi" || fasso == "Cascade" || (fasso == "PID")) { if (SpAsso < 0) continue; associateHist->Fill(binscont, SpAsso); }else if(fasso=="hadron"){ // associateHist->Fill(binscont, 0,1./(efficiency*efficiency1)); associateHist->Fill(binscont, 0,triggermultiplicity*assomultiplicity); } } } }else if (fAnaMode=="TPCV0A" || fAnaMode=="TPCV0C" || fAnaMode=="TPCFMD" || fAnaMode=="TPCFMDC"){ Double_t binscontTrig[4]; Double_t binscont[7]; for(Int_t i=0;i<triggerArray->GetEntriesFast();i++){ AliAssociatedTrackYS* trigger = (AliAssociatedTrackYS*) triggerArray->At(i); if(!trigger)continue; Float_t triggerEta = trigger->Eta(); Float_t triggerPhi = trigger->Phi(); Float_t triggerPt = trigger->Pt(); binscontTrig[0]=triggerPt; binscontTrig[1]=centrality; binscontTrig[2]=fPrimaryZVtx; binscontTrig[3]=triggerEta; Float_t triggermultiplicity=trigger->Multiplicity(); Int_t SpAsso= trigger->WhichCandidate(); // triggerHist->Fill(binscontTrig,0,1./efficiency); triggerHist->Fill(binscontTrig,0,triggermultiplicity); for (Int_t j=0; j<selectedTrackArray->GetEntriesFast(); j++){ AliAssociatedTrackYS* associate = (AliAssociatedTrackYS*) selectedTrackArray->At(j); if(!associate)continue; Float_t associatemultiplicity=associate->Multiplicity(); Float_t assophi=associate->Phi(); Float_t assoeta=associate->Eta(); binscont[0]=triggerEta-associate->Eta(); binscont[1]=triggerPt; binscont[2]=associate->Eta(); binscont[3]=centrality; binscont[4]=RangePhi(triggerPhi-associate->Phi()); binscont[5]=fPrimaryZVtx; binscont[6]=triggerEta; // associateHist->Fill(binscont, 0, (Double_t)associate->Multiplicity()/efficienc); associateHist->Fill(binscont, 0, (Double_t)associate->Multiplicity()*triggermultiplicity); } } }else if (fAnaMode=="ITSFMD" || fAnaMode=="ITSFMDC"){ Double_t binscontTrig[4]; Double_t binscont[6]; for(Int_t i=0;i<triggerArray->GetEntriesFast();i++){ AliAssociatedTrackYS* trigger = (AliAssociatedTrackYS*) triggerArray->At(i); if(!trigger)continue; Float_t triggerEta = trigger->Eta(); Float_t triggerPhi = trigger->Phi(); Float_t triggerPt = 0.5; binscontTrig[0]=triggerPt; binscontTrig[1]=centrality; binscontTrig[2]=fPrimaryZVtx; binscontTrig[3]=triggerEta; Int_t SpAsso= trigger->WhichCandidate(); triggerHist->Fill(binscontTrig,SpAsso); for (Int_t j=0; j<selectedTrackArray->GetEntriesFast(); j++){ AliAssociatedTrackYS* associate = (AliAssociatedTrackYS*) selectedTrackArray->At(j); if(!associate)continue; Float_t associatemultiplicity=associate->Multiplicity(); Float_t assophi=associate->Phi(); Float_t assoeta=associate->Eta(); binscont[0]=triggerEta-associate->Eta(); binscont[1]=centrality; binscont[2]=associate->Eta(); binscont[3]=RangePhi(triggerPhi-associate->Phi()); binscont[4]=fPrimaryZVtx; binscont[5]=triggerEta; associateHist->Fill(binscont, 0, (Double_t)associate->Multiplicity()); } } } else if(fAnaMode=="FMDFMD"|| fAnaMode=="FMDFMD_Ctrig"){ Double_t binscontTrig[3]; Double_t binscont[6]; for(Int_t i=0;i<triggerArray->GetEntriesFast();i++){ AliAssociatedTrackYS* trigger = (AliAssociatedTrackYS*) triggerArray->At(i); if(!trigger)continue; Float_t triggerMultiplicity= trigger->Multiplicity(); Float_t triggerEta = trigger->Eta(); Float_t triggerPhi = trigger->Phi(); binscontTrig[0]=centrality; binscontTrig[1]=triggerEta; binscontTrig[2]=fPrimaryZVtx; triggerHist->Fill(binscontTrig,0,(Double_t)triggerMultiplicity); for (Int_t j=0; j<selectedTrackArray->GetEntriesFast(); j++){ AliAssociatedTrackYS* associate = (AliAssociatedTrackYS*) selectedTrackArray->At(j); if(!associate)continue; Float_t assophi=associate->Phi(); Float_t assoeta=associate->Eta(); Float_t mult=associate->Multiplicity()*triggerMultiplicity; binscont[0]=triggerEta-associate->Eta(); binscont[1]=associate->Eta(); binscont[2]=triggerEta; binscont[3]=centrality; binscont[4]=RangePhi_FMD(triggerPhi-associate->Phi()); binscont[5]=fPrimaryZVtx; Float_t dphivzero=triggerPhi-associate->Phi(); if(triggerPhi==assophi && triggerEta==assoeta) continue; associateHist->Fill(binscont,0,(Double_t)mult); } } }else if(fAnaMode=="SECA"||fAnaMode=="SECC"){ Double_t binscontTrig[3]; Double_t binscont[5]; for(Int_t i=0;i<triggerArray->GetEntriesFast();i++){ AliAssociatedTrackYS* trigger = (AliAssociatedTrackYS*) triggerArray->At(i); if(!trigger)continue; Float_t triggerMultiplicity= trigger->Multiplicity(); Float_t triggerEta = trigger->Eta(); Float_t triggerPhi = trigger->Phi(); binscontTrig[0]=centrality; binscontTrig[1]=triggerEta; binscontTrig[2]=fPrimaryZVtx; triggerHist->Fill(binscontTrig,0,(Double_t)triggerMultiplicity); for (Int_t j=0; j<selectedTrackArray->GetEntriesFast(); j++){ AliAssociatedTrackYS* associate = (AliAssociatedTrackYS*) selectedTrackArray->At(j); if(!associate)continue; Float_t assophi=associate->Phi(); Float_t assoeta=associate->Eta(); Float_t mult=associate->Multiplicity()*triggerMultiplicity; binscont[0]=triggerEta-associate->Eta(); binscont[1]=triggerEta; binscont[2]=centrality; binscont[3]=RangePhi_FMD(triggerPhi-associate->Phi()); binscont[4]=fPrimaryZVtx; // if(triggerEta>2.7 && triggerEta<2.8)cout<<triggerEta<<" "<<associate->Eta()<<" "<<binscont[0]<<endl; Float_t dphivzero=triggerPhi-associate->Phi(); if(triggerPhi==assophi && triggerEta==assoeta) continue; associateHist->Fill(binscont,0,(Double_t)mult); } } }else if(fAnaMode=="V0AV0C"){ Double_t binscont1[4]; Double_t binscontTrig1[3]; for(Int_t i=0;i<triggerArray->GetEntriesFast();i++){ AliAssociatedTrackYS* trigger = (AliAssociatedTrackYS*) triggerArray->At(i); if(!trigger)continue; Double_t triggerMultiplicity= trigger->Multiplicity(); Double_t triggerEta = trigger->Eta(); Double_t triggerPhi = trigger->Phi(); binscontTrig1[0]=centrality; binscontTrig1[1]=triggerEta; binscontTrig1[2]=triggerPhi; triggerHist->Fill(binscontTrig1,0,(Double_t)triggerMultiplicity); for (Int_t j=0; j<selectedTrackArray->GetEntriesFast(); j++){ AliAssociatedTrackYS* associate = (AliAssociatedTrackYS*) selectedTrackArray->At(j); if(!associate)continue; Double_t associatemultiplicity=associate->Multiplicity(); Double_t assophi=associate->Phi(); Double_t assoeta=associate->Eta(); binscont1[0]=associate->Eta(); binscont1[1]=triggerEta; binscont1[2]=centrality; binscont1[3]=RangePhi2(triggerPhi-associate->Phi()); if(triggerPhi==assophi && triggerEta==assoeta) continue; Double_t dphivzero=triggerPhi-associate->Phi(); associateHist->Fill(binscont1,0,(Double_t)triggerMultiplicity*associatemultiplicity); } } } } void AliAnalysisTaskSEpPbCorrelationsYS::FillCorrelationTracksMixing(Double_t centrality, Double_t pvxMix, Double_t poolmax, Double_t poolmin, TObjArray *triggerArray, TObjArray *selectedTrackArray, AliTHn *triggerHist, AliTHn *associateHist, Bool_t twoTrackEfficiencyCut, Float_t twoTrackEfficiencyCutValue, Float_t fTwoTrackCutMinRadius, Float_t bSign, Int_t step) { Bool_t twoTrackEfficiencyCut_1= twoTrackEfficiencyCut; Double_t twoTrackEfficiencyCutValue_1= twoTrackEfficiencyCutValue; Double_t fTwoTrackCutMinRadius1=fTwoTrackCutMinRadius; Float_t bSign1=bSign; Int_t step1=step; Double_t poolmax1=poolmax; Double_t poolmin1=poolmin; /* if (!triggerHist || !associateHist){ return; } */ Double_t counterMix = 0; AliEventPool *pool = fPoolMgr->GetEventPool(centrality, pvxMix); if (!pool){ AliFatal(Form("No pool found for centrality = %f, zVtx = %f", centrality, pvxMix)); } if (pool->IsReady() || pool->NTracksInPool() > fPoolMinNTracks || pool->GetCurrentNEvents() > fMinEventsToMix) { mixedDist ->Fill(centrality, pool->NTracksInPool()); mixedDist2->Fill(centrality, pool->GetCurrentNEvents()); Int_t nMix = pool->GetCurrentNEvents(); for (Int_t jMix = 0; jMix < nMix; jMix++) { TObjArray *mixEvents = pool->GetEvent(jMix); if(fAnaMode=="TPCTPC"){ Double_t binscontTrig[2]; Double_t binscont[6]; for (Int_t i = 0; i < triggerArray->GetEntriesFast(); i++) { AliAssociatedTrackYS *trig = (AliAssociatedTrackYS *)triggerArray->At(i); if (!trig) continue; Double_t triggerPhi = trig->Phi(); Double_t triggerEta = trig->Eta(); Double_t triggerPt = trig->Pt(); counterMix++; binscontTrig[0] = triggerPt; binscontTrig[1] = centrality; Double_t triggermultiplicity=trig->Multiplicity(); /* Float_t efficiency; Int_t ivzbin=frefvz->GetXaxis()->FindBin(fPrimaryZVtx); if(fefficalib){ Int_t iPt=fhcorr[ivzbin-1]->GetXaxis()->FindBin(triggerPt); Int_t iEta=fhcorr[ivzbin-1]->GetYaxis()->FindBin(triggerEta); Int_t iPhi=fhcorr[ivzbin-1]->GetZaxis()->FindBin(triggerPhi); efficiency=fhcorr[ivzbin-1]->GetBinContent(iPt,iEta,iPhi); }else efficiency=1.; if(efficiency==0.) continue; */ triggerHist->Fill(binscontTrig, 0,triggermultiplicity); for (Int_t j = 0; j < mixEvents->GetEntriesFast(); j++) { AliAssociatedTrackYS *associate = (AliAssociatedTrackYS *)mixEvents->At(j); if (!associate) continue; //if (triggerPt < associate->Pt()) continue; //if (trigID == associate->GetID()) continue; binscont[0] = triggerEta - associate->Eta(); binscont[1] = associate->Pt(); binscont[2] = triggerPt; binscont[3] = centrality; binscont[4] = RangePhi(triggerPhi - associate->Phi()); binscont[5] = pvxMix; Double_t assomultiplicity=associate->Multiplicity(); /* Float_t efficiency1; if(fefficalib){ Int_t iPt1=fhcorr[ivzbin-1]->GetXaxis()->FindBin(associate->Pt()); Int_t iEta1=fhcorr[ivzbin-1]->GetYaxis()->FindBin(associate->Eta()); Int_t iPhi1=fhcorr[ivzbin-1]->GetZaxis()->FindBin(associate->Phi()); efficiency1=fhcorr[ivzbin-1]->GetBinContent(iPt1,iEta1,iPhi1); }else efficiency1=1.; if(efficiency1==0.) continue; */ Int_t SpAsso = associate->WhichCandidate(); if (fasso == "V0" || fasso == "Phi" || fasso == "Cascade" || (fasso == "PID")) { if (SpAsso < 0) continue; associateHist->Fill(binscont, SpAsso, 1. / (Double_t)nMix); }else if(fasso=="hadron"){ associateHist->Fill(binscont, 0,triggermultiplicity*assomultiplicity/(Double_t)nMix); } } } }else if(fAnaMode=="TPCV0A" || fAnaMode=="TPCV0C" || fAnaMode=="TPCFMD" || fAnaMode=="TPCFMDC"){ Double_t binscontTrig[2]; Double_t binscont[7]; //Double_t binscont[6]; for(Int_t i=0;i<triggerArray->GetEntriesFast();i++){ AliAssociatedTrackYS* trigger =(AliAssociatedTrackYS*) triggerArray->At(i); if(!trigger)continue; Double_t triggerPt = trigger->Pt(); Double_t triggerEta = trigger->Eta(); Double_t triggerPhi = trigger->Phi(); Int_t SpAsso=trigger->WhichCandidate(); counterMix++; binscontTrig[0]=triggerPt; binscontTrig[1]=centrality; Int_t ivzbin=frefvz->GetXaxis()->FindBin(fPrimaryZVtx); Double_t triggermultiplicity=trigger->Multiplicity(); /* Float_t efficiency=999.; if(fefficalib){ Int_t iPt=fhcorr[ivzbin-1]->GetXaxis()->FindBin(triggerPt); Int_t iEta=fhcorr[ivzbin-1]->GetYaxis()->FindBin(triggerEta); Int_t iPhi=fhcorr[ivzbin-1]->GetZaxis()->FindBin(triggerPhi); efficiency=fhcorr[ivzbin-1]->GetBinContent(iPt,iEta,iPhi); }else efficiency=1.; if(efficiency==0.) continue; */ triggerHist->Fill(binscontTrig,SpAsso,triggermultiplicity); for (Int_t j=0; j<mixEvents->GetEntriesFast(); j++){ AliAssociatedTrackYS* associate=(AliAssociatedTrackYS*) mixEvents->At(j); if(!associate)continue; binscont[0]=triggerEta-associate->Eta(); binscont[1]=triggerPt; binscont[2]=associate->Eta(); binscont[3]=centrality; binscont[4]=RangePhi(triggerPhi-associate->Phi()); binscont[5]=pvxMix; binscont[6]=triggerEta; /* Int_t nstep=999; if(triggerEta<-0.4) nstep=0; else if(triggerEta>-0.4 && triggerEta<0) nstep=1; else if(triggerEta>0 && triggerEta<0.4) nstep=2; else if(triggerEta>0.4 && triggerEta<0.8) nstep=3; */ associateHist->Fill(binscont, 0,(Double_t)associate->Multiplicity()*triggermultiplicity/(Double_t)nMix); } } }else if(fAnaMode=="ITSFMD" || fAnaMode=="ITSFMDC"){ Double_t binscontTrig[2]; Double_t binscont[6]; for(Int_t i=0;i<triggerArray->GetEntriesFast();i++){ AliAssociatedTrackYS* trigger =(AliAssociatedTrackYS*) triggerArray->At(i); if(!trigger)continue; Double_t triggerPt = 0.5; Double_t triggerEta = trigger->Eta(); Double_t triggerPhi = trigger->Phi(); Int_t SpAsso=trigger->WhichCandidate(); counterMix++; binscontTrig[0]=triggerPt; binscontTrig[1]=centrality; triggerHist->Fill(binscontTrig,SpAsso); for (Int_t j=0; j<mixEvents->GetEntriesFast(); j++){ AliAssociatedTrackYS* associate=(AliAssociatedTrackYS*) mixEvents->At(j); if(!associate)continue; binscont[0]=triggerEta-associate->Eta(); binscont[1]=centrality; binscont[2]=associate->Eta(); binscont[3]=RangePhi(triggerPhi-associate->Phi()); binscont[4]=pvxMix; binscont[5]=triggerEta; associateHist->Fill(binscont, 0,(Double_t)associate->Multiplicity()/(Double_t)nMix); } } }else if(fAnaMode=="FMDFMD"||fAnaMode=="FMDFMD_Ctrig"){ Double_t binscontTrig[2]; Double_t binscont[6]; for(Int_t i=0;i<triggerArray->GetEntriesFast();i++){ AliAssociatedTrackYS* trigger = (AliAssociatedTrackYS*) triggerArray->At(i); if(!trigger)continue; Float_t triggerMultiplicity= trigger->Multiplicity(); Float_t triggerEta = trigger->Eta(); Float_t triggerPhi = trigger->Phi(); counterMix++; binscontTrig[0]=centrality; binscontTrig[1]=triggerEta; triggerHist->Fill(binscontTrig,step,(Double_t)triggerMultiplicity); for (Int_t j=0; j<mixEvents->GetEntriesFast(); j++){ AliAssociatedTrackYS* associate = (AliAssociatedTrackYS*) mixEvents->At(j); if(!associate)continue; // Double_t associatemultiplicity=associate->Multiplicity(); Float_t assophi=associate->Phi(); Float_t assoeta=associate->Eta(); Float_t mult=triggerMultiplicity*associate->Multiplicity(); binscont[0]=triggerEta-associate->Eta(); binscont[1]=associate->Eta(); binscont[2]=triggerEta; binscont[3]=centrality; binscont[4]=RangePhi_FMD(triggerPhi-associate->Phi()); binscont[5]=pvxMix; // if(triggerPhi==assophi && triggerEta==assoeta) continue; // associateHist->Fill(binscont,0,(Double_t)triggerMultiplicity*associatemultiplicity/(Double_t)nMix); associateHist->Fill(binscont,0,mult/(Double_t)nMix); } } }else if(fAnaMode=="SECA"||fAnaMode=="SECC"){ Double_t binscontTrig[2]; Double_t binscont[5]; for(Int_t i=0;i<triggerArray->GetEntriesFast();i++){ AliAssociatedTrackYS* trigger = (AliAssociatedTrackYS*) triggerArray->At(i); if(!trigger)continue; Float_t triggerMultiplicity= trigger->Multiplicity(); Float_t triggerEta = trigger->Eta(); Float_t triggerPhi = trigger->Phi(); counterMix++; binscontTrig[0]=centrality; binscontTrig[1]=triggerEta; triggerHist->Fill(binscontTrig,step,(Double_t)triggerMultiplicity); for (Int_t j=0; j<mixEvents->GetEntriesFast(); j++){ AliAssociatedTrackYS* associate = (AliAssociatedTrackYS*) mixEvents->At(j); if(!associate)continue; // Double_t associatemultiplicity=associate->Multiplicity(); Float_t assophi=associate->Phi(); Float_t assoeta=associate->Eta(); Float_t mult=triggerMultiplicity*associate->Multiplicity(); binscont[0]=triggerEta-associate->Eta(); binscont[1]=triggerEta; binscont[2]=centrality; binscont[3]=RangePhi_FMD(triggerPhi-associate->Phi()); binscont[4]=pvxMix; // if(triggerPhi==assophi && triggerEta==assoeta) continue; // associateHist->Fill(binscont,0,(Double_t)triggerMultiplicity*associatemultiplicity/(Double_t)nMix); associateHist->Fill(binscont,0,mult/(Double_t)nMix); } } }else if (fAnaMode=="V0AV0C"){ Double_t binscont1[4]; Double_t binscontTrig1[3]; for(Int_t i=0;i<triggerArray->GetEntriesFast();i++){ AliAssociatedTrackYS* trigger = (AliAssociatedTrackYS*) triggerArray->At(i); if(!trigger)continue; Double_t triggerMultiplicity= trigger->Multiplicity(); Double_t triggerEta = trigger->Eta(); Double_t triggerPhi = trigger->Phi(); counterMix++; binscontTrig1[0]=centrality; binscontTrig1[1]=triggerEta; binscontTrig1[2]=triggerPhi; triggerHist->Fill(binscontTrig1,step,(Double_t)triggerMultiplicity); for (Int_t j=0; j<mixEvents->GetEntriesFast(); j++){ AliAssociatedTrackYS* associate = (AliAssociatedTrackYS*) mixEvents->At(j); if(!associate)continue; Double_t associatemultiplicity=associate->Multiplicity(); Double_t assophi=associate->Phi(); Double_t assoeta=associate->Eta(); binscont1[0]=associate->Eta(); binscont1[1]=triggerEta; binscont1[2]=centrality; binscont1[3]=RangePhi2(triggerPhi-associate->Phi()); if(triggerPhi==assophi && triggerEta==assoeta) continue; associateHist->Fill(binscont1,0,(Double_t)triggerMultiplicity*associatemultiplicity/(Double_t)nMix); } } } } } TObjArray* tracksClone=CloneTrack(selectedTrackArray); pool->UpdatePool(tracksClone); } TObjArray* AliAnalysisTaskSEpPbCorrelationsYS::CloneTrack(TObjArray*selectedTrackArray){ TObjArray *tracksClone = new TObjArray; tracksClone->SetOwner(kTRUE); for (Int_t i = 0; i < selectedTrackArray->GetEntriesFast(); i++) { AliAssociatedTrackYS *particle = (AliAssociatedTrackYS *)selectedTrackArray->At(i); tracksClone->Add(new AliAssociatedTrackYS(particle->Charge(), particle->Eta(), particle->Phi(), particle->Pt(), particle->GetID(), particle->GetIDFirstDaughter(), particle->GetIDSecondDaughter(), particle->WhichCandidate(), particle->Multiplicity())); } return tracksClone; } Double_t AliAnalysisTaskSEpPbCorrelationsYS::RangePhi(Double_t DPhi) { if (DPhi < -TMath::Pi() / 2) DPhi += 2 * TMath::Pi(); if (DPhi > 3 * TMath::Pi() / 2) DPhi -= 2*TMath::Pi(); return DPhi; } Double_t AliAnalysisTaskSEpPbCorrelationsYS::RangePhi_FMD(Double_t DPhi) { //if (DPhi < (-TMath::Pi() / 2 -0.0001)) DPhi += 2 * TMath::Pi(); //if (DPhi > (3 * TMath::Pi() / 2-0.0001)) DPhi -= 2*TMath::Pi(); DPhi = TMath::ATan2(TMath::Sin(DPhi), TMath::Cos(DPhi)); if (DPhi < (-0.5*TMath::Pi()-0.0001)) DPhi += 2 * TMath::Pi(); return DPhi; } Double_t AliAnalysisTaskSEpPbCorrelationsYS::RangePhi2(Double_t DPhi) { DPhi = TMath::ATan2(TMath::Sin(DPhi), TMath::Cos(DPhi)); if (DPhi < -1.178097) DPhi += 2 * TMath::Pi(); return DPhi; } void AliAnalysisTaskSEpPbCorrelationsYS::DumpTObjTable(const char* note) { /* if(note) { printf("TObjectTable::%s",note); } gObjectTable->Print(); */ } Int_t AliAnalysisTaskSEpPbCorrelationsYS::ConvertRunNumber(Int_t run){ if( (265308<run && run< 265526) || (267160<run && run<267167)){ switch(run){ case 265309 : return 0; case 265332 : return 1; case 265334 : return 2; case 265336 : return 3; case 265338 : return 4; case 265339 : return 5; case 265342 : return 6; case 265343 : return 7; case 265344 : return 8; case 265377 : return 9; case 265378 : return 10; case 265381 : return 11; case 265383 : return 12; case 265384 : return 13; case 265385 : return 14; case 265387 : return 15; case 265388 : return 16; case 265419 : return 17; case 265420 : return 18; case 265421 : return 19; case 265422 : return 20; case 265424 : return 21; case 265425 : return 22; case 265426 : return 23; case 265427 : return 24; case 265435 : return 25; case 265499 : return 26; case 265500 : return 27; case 265501 : return 28; case 265521 : return 29; case 265525 : return 30; case 267166 : return 31; //16t case 267165 : return 32; //16t case 267164 : return 33; //16t case 267163 : return 34; //16t case 267161 : return 35; //16t default : return 199; } } else if(run> 280281 && run<281962){ switch(run){ case 281961 : return 0; // case 281959 : return 1; case 281956 : return 1; case 281953:return 2; case 281940:return 3; case 281939:return 4; case 281932:return 5; case 281931:return 6; case 281928:return 7; case 281920:return 8; case 281918:return 9; case 281915:return 10;// case 281895:return 11;// case 281894:return 12;// case 281892:return 13;// case 281633:return 14;// case 281583:return 15; // case 281581:return 12; // case 281580:return 13; case 281574:return 16; case 281569:return 17; case 281568:return 18; case 281562:return 19; case 281557:return 20; case 281511:return 21; case 281509:return 22; case 281477:return 23; case 281475:return 24; case 281450:return 25; case 281449:return 26; case 281444:return 27; case 281443:return 28; case 281441:return 29; case 281415:return 30; case 281321:return 31; case 281301:return 32; case 281277:return 33; case 281275:return 34; case 281273:return 35; case 281271:return 36; case 281243:return 37; case 281242:return 38; case 281241:return 39; case 281240:return 40; case 281213:return 41; case 281212:return 42; case 281191:return 43; case 281190:return 44; case 281189:return 45; case 281181:return 46; case 281180:return 47;// case 281179:return 48; case 281081:return 49; case 281080:return 50; case 281062:return 51; case 281061:return 52; case 281060:return 53; case 280999:return 54; case 280998:return 55; case 280997:return 56; case 280994:return 57; case 280990:return 58; case 280947:return 59; case 280940:return 60; case 280936:return 61; case 280897:return 62; case 280890:return 63;// case 280881:return 64;// case 280880:return 65; case 280856:return 66; case 280849:return 67; case 280848:return 68; case 280847:return 69; case 280845:return 70;// case 280844:return 71; case 280842:return 72; case 280793:return 73; case 280792:return 74; case 280787:return 75; case 280786:return 76; case 280768:return 77; case 280767:return 78; case 280766:return 79; case 280765:return 80; case 280764:return 81; case 280763:return 82; case 280762:return 83; case 280761:return 84; case 280757:return 85; case 280756:return 86; case 280755:return 87; case 280754:return 88; case 280753:return 89; case 280729:return 90; case 280706:return 91; case 280705:return 92; case 280681:return 93; case 280679:return 94; // case 280676:return 88; // case 280673:return 89; case 280671:return 95; // case 280650:return 91; // case 280648:return 92; case 280647:return 96; case 280645:return 97; case 280639:return 98; case 280637:return 99; case 280636:return 100; case 280634:return 101; case 280613:return 102; case 280583:return 103; case 280581:return 104; case 280576:return 105;// case 280575:return 106;// case 280574:return 107; case 280551:return 108; case 280550:return 109; case 280547:return 110; case 280546:return 111; case 280519:return 112; case 280518:return 113; case 280499:return 114; case 280448:return 115; case 280447:return 116; case 280446:return 117; case 280445:return 118; case 280443:return 119; case 280419:return 120; case 280415:return 121; case 280413:return 122;// case 280406:return 123; case 280405:return 124; case 280403:return 125; case 280375:return 126; case 280374:return 127; // case 280352:return 122; case 280351:return 128; case 280350:return 129; case 280349:return 130; case 280348:return 131; case 280312:return 132; case 280310:return 133; case 280290:return 134; case 280286:return 135; case 280285:return 136; case 280284:return 137; case 280283:return 138; case 280282:return 139; default : return 199; } } else if (run>274689 && run<286509){ switch(run){ //LHC17k case 276508:return 0; case 276507:return 1; case 276506:return 2; case 276462:return 3; case 276439:return 4; case 276438:return 5; case 276437:return 6; case 276435:return 7; case 276351:return 8; case 276348:return 9; case 276312:return 10; case 276307:return 11; case 276302:return 12; case 276297:return 13; case 276294:return 14; case 276292:return 15; case 276291:return 16; case 276290:return 17; case 276259:return 18; case 276257:return 19; case 276230:return 20; case 276205:return 21; case 276178:return 22; case 276170:return 23; case 276104:return 24; case 276102:return 25; case 276099:return 26; case 276098:return 27; case 276097:return 28; case 276045:return 29; case 276041:return 30; case 276040:return 31; case 276020:return 32; case 276019:return 33; case 276017:return 34; case 276013:return 35; case 276012:return 36; case 275925:return 37; case 275924:return 38; case 275847:return 39; case 275664:return 40; case 275661:return 41; case 275657:return 42; case 275650:return 43; case 275648:return 44; case 275647:return 45; case 275624:return 46; case 275623:return 47; case 275622:return 48; case 275621:return 49; case 275617:return 50; case 275612:return 51; case 275559:return 52; case 275558:return 53; case 275515:return 54; case 275472:return 55; case 275471:return 56; case 275467:return 57; case 275459:return 58; case 275457:return 59; case 275456:return 60; case 275453:return 61; case 275452:return 62; case 275448:return 63; case 275443:return 64; case 275406:return 65; case 275404:return 66; case 275401:return 67; case 275395:return 68; case 275394:return 69; case 275372:return 70; case 275369:return 71; case 275361:return 72; case 275360:return 73; case 275333:return 74; case 275332:return 75; case 275328:return 76; case 275326:return 77; case 275324:return 78; case 275322:return 79; case 275314:return 80; case 275283:return 81; case 275247:return 82; case 275246:return 83; case 275245:return 84; case 275239:return 85; case 275188:return 86; case 275184:return 87; case 275180:return 88; case 275177:return 89; case 275174:return 90; case 275173:return 91; case 275151:return 92; case 275150:return 93; case 275149:return 94; case 275076:return 95; case 275075:return 96; case 275073:return 97; case 275068:return 98; case 275067:return 99; case 274979:return 100; case 274978:return 101; case 274886:return 102; case 274882:return 103; case 274878:return 104; case 274877:return 105; case 274822:return 106; case 274821:return 107; case 274817:return 108; case 274815:return 109; case 274811:return 110; case 274807:return 111; case 274806:return 112; case 274803:return 113; case 274802:return 114; case 274801:return 115; case 274708:return 116; case 274690:return 117; default:return 199; } } else if (run> 271867 && run<273104){ switch(run){ //LHC17h case 273103:return 0; case 273100:return 1; case 273099:return 2; case 272949:return 3; case 272947:return 4; case 272939:return 5; case 272935:return 6; case 272934:return 7; case 272933:return 8; case 272932:return 9; case 272905:return 10; case 272903:return 11; case 272871:return 12; case 272870:return 13; case 272836:return 14; case 272833:return 15; case 272829:return 16; case 272828:return 17; case 272784:return 18; case 272782:return 19; case 272764:return 20; case 272763:return 21; case 272760:return 22; case 272749:return 23; case 272747:return 24; case 272746:return 25; case 272712:return 26; case 272692:return 27; case 272610:return 28; case 272608:return 29; case 272607:return 30; case 272585:return 31; case 272577:return 32; case 272575:return 33; case 272574:return 34; case 272521:return 35; case 272468:return 36; case 272463:return 37; case 272462:return 38; case 272461:return 39; case 272413:return 40; case 272411:return 41; case 272400:return 42; case 272399:return 43; case 272395:return 44; case 272394:return 45; case 272389:return 46; case 272388:return 47; case 272360:return 48; case 272359:return 49; case 272335:return 50; case 272194:return 51; case 272156:return 52; case 272155:return 53; case 272154:return 54; case 272153:return 55; case 272152:return 56; case 272123:return 57; case 272101:return 58; case 272100:return 59; case 272041:return 60; case 272040:return 61; case 272039:return 62; case 272038:return 63; case 272036:return 64; case 271886:return 65; case 271881:return 66; case 271880:return 67; case 271874:return 68; case 271873:return 69; case 271871:return 70; case 271870:return 71; case 271868:return 72; default:return 199; } } else if (run>273590 && run<27443){ switch(run){ //LHC17k case 274442:return 0; case 274390:return 1; case 274389:return 2; case 274388:return 3; case 274387:return 4; case 274386:return 5; case 274385:return 6; case 274364:return 7; case 274363:return 8; case 274360:return 9; case 274352:return 10; case 274351:return 11; case 274329:return 12; case 274283:return 13; case 274281:return 14; case 274280:return 15; case 274278:return 16; case 274276:return 17; case 274271:return 18; case 274270:return 19; case 274269:return 20; case 274268:return 21; case 274266:return 22; case 274264:return 23; case 274263:return 24; case 274259:return 25; case 274258:return 26; case 274232:return 27; case 274212:return 28; case 274174:return 29; case 274148:return 30; case 274147:return 31; case 274125:return 32; case 274094:return 33; case 274092:return 34; case 274064:return 35; case 274058:return 36; case 273986:return 37; case 273985:return 38; case 273946:return 39; case 273943:return 40; case 273942:return 41; case 273918:return 42; case 273889:return 43; case 273887:return 44; case 273886:return 45; case 273885:return 46; case 273825:return 47; case 273824:return 48; case 273719:return 49; case 273711:return 50; case 273709:return 51; case 273695:return 52; case 273690:return 53; case 273689:return 54; case 273687:return 55; case 273654:return 56; case 273653:return 57; case 273593:return 58; case 273592:return 59; case 273591:return 60; default :return 199; } } else if (run>274652 && run<274672){ switch(run){ //LHC17j case 274671:return 0; case 274669:return 1; case 274667:return 2; case 274657:return 3; case 274653:return 4; default:return 199; } } else{ return 199; } } Bool_t AliAnalysisTaskSEpPbCorrelationsYS::HasValidFMDYS(TH2D h){ // AliMultSelection *MultSelection = dynamic_cast< AliMultSelection* >(InputEvent()->FindListObject("MultSelection")); //AliMultSelection *MultSelection = (AliMultSelection*)fInputEvent->FindListObject("MultSelection"); // Double_t cent = MultSelection->GetMultiplicityPercentile("V0M"); //if (useEvent) return useEvent; Int_t nBadBins = 0; Int_t phibins = h.GetNbinsY(); Double_t totalFMDpar = 0; // Outlier cut calculations Double_t fSigmaCut = 4.0; for (Int_t etaBin = 1; etaBin <= h.GetNbinsX(); etaBin++) { Double_t eta = h.GetXaxis()->GetBinCenter(etaBin); Double_t runAvg = 0; Double_t avgSqr = 0; Double_t max = 0; Int_t nInAvg = 0; for (Int_t phiBin = 0; phiBin <= phibins; phiBin++) { if ( fabs(eta) > 1.7) { if (phiBin == 0 && h.GetBinContent(etaBin, 0) == 0) break; } Double_t weight = h.GetBinContent(etaBin, phiBin); if (!weight){ weight = 0; } totalFMDpar += weight; // We calculate the average Nch per. bin avgSqr += weight*weight; runAvg += weight; nInAvg++; if (weight == 0) continue; if (weight > max) { max = weight; } } // End of phi loop if (nInAvg > 0) { runAvg /= nInAvg; avgSqr /= nInAvg; Double_t stdev = (nInAvg > 1 ? TMath::Sqrt(nInAvg/(nInAvg-1))*TMath::Sqrt(avgSqr - runAvg*runAvg) : 0); Double_t nSigma = (stdev == 0 ? 0 : (max-runAvg)/stdev); fOutliers->Fill(lCentrality,nSigma); //std::cout << "sigma = " << nSigma << std::endl; // if (fSigmaCut > 0. && nSigma >= fSigmaCut) nBadBins++; else nBadBins = 0; // We still finish the loop, for fOutliers to make sense, // but we do no keep the event for analysis if (nBadBins > 3) return kFALSE; //if (nBadBins > 3) std::cout << "NUMBER OF BAD BINS > 3" << std::endl; } } // End of eta bin // if (totalFMDpar < 10) return kFALSE; return kTRUE; } change multiplicity bin /************************************************************************************************** * Leading Charged Track+V0 Correlations.(Works for Real Data) * * Yuko Sekiguchi * Center for Nuclear Study(CNS) , University of Tokyo * * Email:y_sekiguchi@cns.s.u-tokyo.ac.jp * **************************************************************************************************/ #include "AliAnalysisManager.h" #include "TGrid.h" #include "AliLog.h" #include <TChain.h> #include <TDatabasePDG.h> #include <TFile.h> #include <TH1.h> #include <TH2.h> #include <TH3.h> #include <TList.h> #include <TLorentzVector.h> #include <TMap.h> #include <TMath.h> #include <TObjArray.h> #include <TPDGCode.h> #include <TParameter.h> #include <TROOT.h> #include <TRandom.h> #include <TTree.h> #include <TProfile.h> #include <TObjectTable.h> #include "AliAnalysisUtils.h" #include "AliAODTrack.h" #include "AliAODTracklets.h" #include "AliCFContainer.h" #include "AliGenEventHeader.h" #include "AliTHn.h" #include "AliAODEvent.h" #include "AliESDAD.h" #include "AliESDEvent.h" #include "AliVAD.h" #include "AliAODForwardMult.h" #include "AliAODVertex.h" #include "AliAODv0.h" #include "AliESDVertex.h" //#include "AliAODPid.h" #include "AliAODHandler.h" #include "AliAODInputHandler.h" #include "AliAODMCHeader.h" #include "AliAODMCParticle.h" #include "AliMCEventHandler.h" #include "AliMCEvent.h" #include "AliMCParticle.h" #include "AliStack.h" #include "AliAODcascade.h" #include "AliAnalyseLeadingTrackUE.h" #include "AliCentrality.h" #include "AliEventPoolManager.h" #include "AliExternalTrackParam.h" #include "AliInputEventHandler.h" #include "AliMultiplicity.h" #include "AliPID.h" #include "AliPIDResponse.h" #include "AliVParticle.h" #include "Riostream.h" /* #include "AliForwardSettings.h" #include "AliForwardFlowUtil.h" #include "AliForwardFlowResultStorage.h" #include "AliForwardGenericFramework.h" #include "AliForwardFlowRun2Task.h" #include "AliForwardQCumulantRun2.h" #include "AliForwardGenericFramework.h" */ //#include "AliFlowEventSimple.h" ///#include "AliFlowVector.h"/ //#include "AliFlowTrackSimple.h" //#include "AliAnalysisTaskMSP.h" //#include "AliFlowAnalysisWithMSP.h" #include "AliMultSelection.h" #include "AliFMDCorrSecondaryMap.h" #include "AliForwardCorrectionManager.h" //#include "AliForwardFlowResultStorage.h" //#include "AliForwardUtil.h" //#include "AliForwardTaskValidation.h" #include "AliAnalysisTaskSEpPbCorrelationsYS.h" using namespace std; ClassImp(AliAnalysisTaskSEpPbCorrelationsYS) ClassImp(AliAssociatedTrackYS) ClassImp(AliMixTrackYS) ClassImp(AliAssociatedVZEROYS) AliAnalysisTaskSEpPbCorrelationsYS::AliAnalysisTaskSEpPbCorrelationsYS() : AliAnalysisTaskSE(), fcollisiontype("pPb"), fDataType(kTRUE), frun2(kTRUE), fQA(kTRUE), fFMDcut(kTRUE), fFMDaddcut(kFALSE), fFMDcutmode(1), fptdiff(kFALSE), fmakehole(kFALSE), ffillcorrelation(kTRUE), fefficalib(kTRUE), fcuthighmult(0), fOnfly(kFALSE), fAnaMode("V0AV0C"), fasso("Phi"), fPID(kFALSE), fCentType("ZNA"), fNEntries(0), lCentrality(0), bSign(0), fZVertex(10.), fOutputList(0), fOutputList1(0), fOutputList2(0), fPIDResponse(0), ffilterbit(5), fnoClusters(70), fCutChargedDCAzMax(5), fCutChargedDCAxyMax(15), fPtMin(0.2), fPtMax(3.0), fEtaMax(0.8), fEtaMaxExtra(0.), fEtaMinExtra(-0.8), fEtaMaxV0(0.8), fEtaMinV0(0.), fdcaDaughtersToPrimVtx(0.06), fdcaBetweenDaughters(1.0), fRadiMin(0.5), fRadiMax(100), fcutcTauLam(30), fcutcTauK0(20), fcosMinK0s(0.97), fcosMinLambda(0.995), fMaxnSigmaTPCV0(5), hv0dcharge(0), fclustermin(70), fratiocluster(0.8), fEtaMaxDaughter(0.8), fEtaMinDaughter(0.), fHistMass_K0s(0), fHistMass_K0s_MC(0), fHistMass_Lambda(0), fHistMass_ALambda(0), fHistMass_ALambda_MC(0), fHistMassXiMinus(0), fHistMassXiPlus(0), fHistMassOmegaMinus(0), fHistMassOmegaPlus(0), fHistMass_bumpcorr(0), fHist_V0QA(0), fHist_CascadeQA(0), fHistMass_Lambda_MC(0), fEventCuts(0), fUtils(), fEvent(0), mcEvent(0), lPrimaryBestVtx(0), fPrimaryZVtx(0), fvzero(0), fPoolMgr(0), fPoolMgr1(0), poolmin(0), poolmax(0), fPoolMaxNEvents(2000), fPoolMinNTracks(50000), fMinEventsToMix(5), fNzVtxBins(0), fNCentBins(0), fMaxnSigmaTPCTOF(3.), fHistzvertex(0), fHistCentrality(0), fHistCentrality_beforecut(0), fHistV0vsTracks(0), fHistCentvsNv0mult(0), fHistV0multvsVz(0), fHistCentzvertex(0), fHistCentV0vsTracklets(0), fHistCentV0vsTrackletsbefore(0), fHistTraksvsVz(0), mixedDist(0), mixedDist2(0), fHistLeadQA(0), fHistPIDQA(0), fhistmcprim(0), fhmcprimvzeta(0), frefetaa(0), frefetac(0), frefvz(0), fhmcprimpdgcode(0), fh2_FMD_acceptance_prim(0), fh2_FMD_eta_phi_prim(0), fh2_FMD_acceptance(0), fh2_ITS_acceptance(0), fh2_SPD_multcorr(0), fh2_SPDV0_multcorr(0), fh2_SPDtrack_multcorr(0), fhtrackletsdphi(0), fh2_FMD_eta_phi(0), fh2_FMD_eta_phi_aftercut(0), fHist_NeventRun(0), fHist_V0AMultRun(0), fHist_V0CMultRun(0), fHist_FMDAMultRun(0), fHist_FMDCMultRun(0), fhistfmdphiacc(0), fhFMDmultchannel(0), fhistfmd(0), fhistits(0), fhSecFMD(0), fOutliers(0), fFMDV0(0), fFMDV0_post(0), fFMDV0A(0), fFMDV0A_post(0), fFMDV0C(0), fFMDV0C_post(0), fFMDV0same(0), fFMDV0same_post(0), fFMDV0Asame(0), fFMDV0Asame_post(0), fFMDV0Csame(0), fFMDV0Csame_post(0), fHist_vzeromult(0), fHist_vzeromultEqweighted(0), fHist2dmult(0), fHistVZERO(0), fHist_Stat(0), fHist_V0Stat(0), fHistPhiDTPCNSig(0), fHistPhiDTOFNSig(0), fHistPhiDTPCTOFNSig(0), fHistMass_PhiMeson(0), fHistMass_PhiMeson_MIX(0), fHist_PhiQA(0), fHistTriggerTrack(0), fHistReconstTrack(0), fHistTriggerTrackMix(0), fHistReconstTrackMix(0), fHistQna(0), fHistQnc(0), fHistQn(0), fHistQna_VZERO(0), fHistQnc_VZERO(0), fHistQn_VZERO(0), fHistVn(0), SP_TPCATPCC(0), SP_TPCATPCC_default(0), SP_V0AV0C_default(0), SP_V0ATPC_default(0), SP_V0CTPC_default(0), fHist_V0AV0C(0), fHist_V0ATPC(0), fHist_V0CTPC(0), SP_uTPCA(0), SP_uTPCC(0){ for (Int_t iBin = 0; iBin < 100; iBin++) { fZvtxBins[iBin] = 0.; fCentBins[iBin] = 0.; } for (Int_t i = 0; i < 3; i++) { tPrimaryVtxPosition[i] = 0; } for (Int_t i = 0; i < 6; i++) { fHistPosNsig[i] = 0; fHistNegNsig[i] = 0; fHistPosNsigQA[i] = 0; fHist_AP[i] = 0; } for(Int_t i=0;i<3;i++){ fh3NegNsig[i]=0; fh3PosNsig[i]=0; } for (Int_t i = 0; i < 6; i++) { fHistNsig[i]=0; fHistNsigcorr[i]=0; } for (Int_t i = 0; i < 4; i++) { fHistQAQB[i]=0; fHistQAQB_VZERO[i]=0; fHistCorrQna[i]=0; fHistCorrQnc[i]=0; } for (Int_t i = 0; i < 8; i++) { SP_uTPC_PP[i]=0; SP_uTPC[i]=0; SP_uTPC1[i]=0; SP_uTPC2[i]=0; SP_uTPC3[i]=0; SP_uVZEROA_PP[i]=0; SP_uVZEROA[i]=0; SP_uVZEROA1[i]=0; SP_uVZEROA2[i]=0; SP_uVZEROA3[i]=0; SP_uVZEROC_PP[i]=0; SP_uVZEROC[i]=0; SP_uVZEROC1[i]=0; SP_uVZEROC2[i]=0; SP_uVZEROC3[i]=0; } for(Int_t i=0;i<4;i++){ fhrefetaFMD[i]=0; fhrefphiFMD[i]=0; } for(Int_t i=0;i<10;i++){ fhcorr[i]=0; } for(Int_t i=0;i<31;i++){ fhFMDmult_runbyrun_cside[i]=0; } for(Int_t i=0;i<65;i++){ fhFMDmult_runbyrun_aside[i]=0; } } AliAnalysisTaskSEpPbCorrelationsYS::AliAnalysisTaskSEpPbCorrelationsYS(const char *name) : AliAnalysisTaskSE(name), fcollisiontype("pPb"), fDataType(kTRUE), frun2(kTRUE), fQA(kTRUE), fFMDcut(kTRUE), fFMDaddcut(kFALSE), fFMDcutmode(1), fptdiff(kFALSE), fmakehole(kFALSE), ffillcorrelation(kTRUE), fefficalib(kTRUE), fcuthighmult(0), fOnfly(kFALSE), fAnaMode("V0AV0C"), fasso("Phi"), fPID(kFALSE), fCentType("ZNA"), fNEntries(0), lCentrality(0), bSign(0), fZVertex(10.), fOutputList(0), fOutputList1(0), fOutputList2(0), fPIDResponse(0), ffilterbit(5), fnoClusters(70), fCutChargedDCAzMax(5), fCutChargedDCAxyMax(15), fPtMin(0.2), fPtMax(3.0), fEtaMax(0.8), fEtaMaxExtra(0.), fEtaMinExtra(-0.8), fEtaMaxV0(0.8), fEtaMinV0(0.), fdcaDaughtersToPrimVtx(0.06), fdcaBetweenDaughters(1.0), fRadiMin(0.5), fRadiMax(100), fcutcTauLam(30), fcutcTauK0(20), fcosMinK0s(0.97), fcosMinLambda(0.995), fMaxnSigmaTPCV0(5), hv0dcharge(0), fclustermin(70), fratiocluster(0.8), fEtaMaxDaughter(0.8), fEtaMinDaughter(0.), fHistMass_K0s(0), fHistMass_K0s_MC(0), fHistMass_Lambda(0), fHistMass_ALambda(0), fHistMass_ALambda_MC(0), fHistMassXiMinus(0), fHistMassXiPlus(0), fHistMassOmegaMinus(0), fHistMassOmegaPlus(0), fHistMass_bumpcorr(0), fHist_V0QA(0), fHist_CascadeQA(0), fHistMass_Lambda_MC(0), fEventCuts(0), fUtils(), fEvent(0), mcEvent(0), lPrimaryBestVtx(0), fPrimaryZVtx(0), fvzero(0), fPoolMgr(0), fPoolMgr1(0), poolmin(0), poolmax(0), fPoolMaxNEvents(2000), fPoolMinNTracks(50000), fMinEventsToMix(5), fNzVtxBins(0), fNCentBins(0), fMaxnSigmaTPCTOF(3.), fHistzvertex(0), fHistCentrality(0), fHistCentrality_beforecut(0), fHistV0vsTracks(0), fHistCentvsNv0mult(0), fHistV0multvsVz(0), fHistCentzvertex(0), fHistCentV0vsTracklets(0), fHistCentV0vsTrackletsbefore(0), fHistTraksvsVz(0), mixedDist(0), mixedDist2(0), fHistLeadQA(0), fHistPIDQA(0), fhistmcprim(0), fhmcprimvzeta(0), frefetaa(0), frefetac(0), frefvz(0), fhmcprimpdgcode(0), fh2_FMD_acceptance_prim(0), fh2_FMD_eta_phi_prim(0), fh2_FMD_acceptance(0), fh2_ITS_acceptance(0), fh2_SPD_multcorr(0), fh2_SPDV0_multcorr(0), fh2_SPDtrack_multcorr(0), fhtrackletsdphi(0), fh2_FMD_eta_phi(0), fh2_FMD_eta_phi_aftercut(0), fHist_NeventRun(0), fHist_V0AMultRun(0), fHist_V0CMultRun(0), fHist_FMDAMultRun(0), fHist_FMDCMultRun(0), fhistfmdphiacc(0), fhFMDmultchannel(0), fhistfmd(0), fhistits(0), fhSecFMD(0), fOutliers(0), fFMDV0(0), fFMDV0_post(0), fFMDV0A(0), fFMDV0A_post(0), fFMDV0C(0), fFMDV0C_post(0), fFMDV0same(0), fFMDV0same_post(0), fFMDV0Asame(0), fFMDV0Asame_post(0), fFMDV0Csame(0), fFMDV0Csame_post(0), fHist_vzeromult(0), fHist_vzeromultEqweighted(0), fHist2dmult(0), fHistVZERO(0), fHist_Stat(0), fHist_V0Stat(0), fHistPhiDTPCNSig(0), fHistPhiDTOFNSig(0), fHistPhiDTPCTOFNSig(0), fHistMass_PhiMeson(0), fHistMass_PhiMeson_MIX(0), fHist_PhiQA(0), fHistTriggerTrack(0), fHistReconstTrack(0), fHistTriggerTrackMix(0), fHistReconstTrackMix(0), fHistQna(0), fHistQnc(0), fHistQn(0), fHistQna_VZERO(0), fHistQnc_VZERO(0), fHistQn_VZERO(0), fHistVn(0), SP_TPCATPCC(0), SP_TPCATPCC_default(0), SP_V0AV0C_default(0), SP_V0ATPC_default(0), SP_V0CTPC_default(0), fHist_V0AV0C(0), fHist_V0ATPC(0), fHist_V0CTPC(0), SP_uTPCA(0), SP_uTPCC(0){ for (Int_t iBin = 0; iBin < 100; iBin++) { fZvtxBins[iBin] = 0.; fCentBins[iBin] = 0.; } for (Int_t i = 0; i < 3; i++) { tPrimaryVtxPosition[i] = 0; } for (Int_t i = 0; i < 6; i++) { fHistPosNsig[i] = 0; fHistNegNsig[i] = 0; fHistPosNsigQA[i] = 0 ; fHist_AP[i] = 0; } for(Int_t i=0;i<3;i++){ fh3NegNsig[i]=0; fh3PosNsig[i]=0; } for (Int_t i = 0; i < 6; i++) { fHistNsig[i] = 0; fHistNsigcorr[i]=0; } for (Int_t i = 0; i < 4; i++) { fHistQAQB[i]=0; fHistQAQB_VZERO[i]=0; fHistCorrQna[i]=0; fHistCorrQnc[i]=0; } for (Int_t i = 0; i < 8; i++) { SP_uTPC_PP[i]=0; SP_uTPC[i]=0; SP_uTPC1[i]=0; SP_uTPC2[i]=0; SP_uTPC3[i]=0; SP_uVZEROA_PP[i]=0; SP_uVZEROA[i]=0; SP_uVZEROA1[i]=0; SP_uVZEROA2[i]=0; SP_uVZEROA3[i]=0; SP_uVZEROC_PP[i]=0; SP_uVZEROC[i]=0; SP_uVZEROC1[i]=0; SP_uVZEROC2[i]=0; SP_uVZEROC3[i]=0; } for(Int_t i=0;i<4;i++){ fhrefetaFMD[i]=0; fhrefphiFMD[i]=0; } for(Int_t i=0;i<10;i++){ fhcorr[i]=0; } for(Int_t i=0;i<31;i++){ fhFMDmult_runbyrun_cside[i]=0; } for(Int_t i=0;i<65;i++){ fhFMDmult_runbyrun_aside[i]=0; } // DefineInput(1, AliForwardTaskValidation::Class()); DefineOutput(1, TList::Class()); DefineOutput(2, TList::Class()); DefineOutput(3, TList::Class()); } AliAnalysisTaskSEpPbCorrelationsYS::~AliAnalysisTaskSEpPbCorrelationsYS() { if (fOutputList && !AliAnalysisManager::GetAnalysisManager()->IsProofMode()) { delete fOutputList; fOutputList = 0x0; } if (fOutputList1 && !AliAnalysisManager::GetAnalysisManager()->IsProofMode()) { delete fOutputList1; fOutputList1 = 0x0; } if (fOutputList2 && !AliAnalysisManager::GetAnalysisManager()->IsProofMode()) { delete fOutputList2; fOutputList2 = 0x0; } if (fPIDResponse) { delete fPIDResponse; fPIDResponse = 0; } } void AliAnalysisTaskSEpPbCorrelationsYS::UserCreateOutputObjects() { fOutputList = new TList(); fOutputList->SetOwner(kTRUE); fOutputList->SetName("global"); DefineGeneralOutput(); PostData(1, fOutputList); fOutputList1 = new TList(); fOutputList1->SetOwner(kTRUE); fOutputList1->SetName("anahistos"); DefineCorrOutput(); DefineVZEROOutput(); PostData(2, fOutputList1); fOutputList2 = new TList(); fOutputList2->SetOwner(kTRUE); fOutputList2->SetName("QA"); DefinedQAHistos(); PostData(3, fOutputList2); // fStorage = new AliForwardFlowResultStorage("freja", fOutputList3); /* fStorage=new TList(); fStorage->SetOwner(kTRUE); fStorage->SetName("add"); PostData(4,fStorage); */ fEventCuts.AddQAplotsToList(fOutputList); frefetac=new TH1F("frefetac","frefetac",30,-3.4,-1.9); fOutputList2->Add(frefetac); frefetaa=new TH1F("frefetaa","frefetaa",62,1.9,5.0); fOutputList2->Add(frefetaa); frefvz=new TH1F("frefvz","z-vertex",10,-10,10); fOutputList2->Add(frefvz); /// TGrid::Connect("alien://"); //TFile*file=TFile::Open("alien:///alice/cern.ch/user/y/ysekiguc/correction.root"); // TFile*file=TFile::Open("/home/yuko/work/local_alicework/MCESDanalysis/draw_result/correction.root"); // if(!file) AliError("No correction factor"); //for(Int_t i=0;i<10;i++){ //fhcorr[i]=(TH2D*)file->Get(Form("fRefetaphiclone_%d",i)); // fOutputList2->Add(fhcorr[i]); // } if(fefficalib){ TGrid::Connect("alien://"); //TFile* file=TFile::Open("alien:///alice/cern.ch/user/y/ysekiguc/corrections/fcorrection_efficiency.root"); TFile*file=TFile::Open(Form("alien:///alice/cern.ch/user/y/ysekiguc/corrections/fcorrection_efficiency_%s_filterbit%d_3D.root",fcollisiontype.Data(),ffilterbit)); if(!file) AliError("No correction factor"); for(Int_t i=0;i<10;i++){ fhcorr[i]=(TH2D*)file->Get(Form("effi_%d",i)); } } fPoolMgr = new AliEventPoolManager(fPoolMaxNEvents, fPoolMinNTracks, fNCentBins,fCentBins, fNzVtxBins, fZvtxBins); if (!fPoolMgr) return; fPoolMgr->SetTargetValues(fPoolMinNTracks, 0.1, 5); fPoolMgr1 = new AliEventPoolManager(fPoolMaxNEvents, fPoolMinNTracks, fNCentBins,fCentBins, fNzVtxBins, fZvtxBins); if (!fPoolMgr1) return; fPoolMgr1->SetTargetValues(fPoolMinNTracks, 0.1, 5); } void AliAnalysisTaskSEpPbCorrelationsYS::DefineGeneralOutput() { fHist_Stat = new TH1F("fHist_Stat", "Stat Histogram", 14, -0.5, 13.5); fHist_Stat->GetXaxis()->SetBinLabel(1, "All Events"); fHist_Stat->GetXaxis()->SetBinLabel(2, "Analyzed Events"); fHist_Stat->GetXaxis()->SetBinLabel(3, "MultSelection OK"); fHist_Stat->GetXaxis()->SetBinLabel(4, "Vertex OK"); fHist_Stat->GetXaxis()->SetBinLabel(5, "Centrality OK"); fHist_Stat->GetXaxis()->SetBinLabel(6, "HAS AliAODForwardMult"); fHist_Stat->GetXaxis()->SetBinLabel(7, "FMD multi ok "); fHist_Stat->GetXaxis()->SetBinLabel(8, "FMD/V0 multi cut"); fOutputList->Add(fHist_Stat); fHist_V0Stat = new TH1F("fHist_V0Stat", "Stat Histogram", 16, -0.5, 15.5); fHist_V0Stat->GetXaxis()->SetBinLabel(1, "all"); fHist_V0Stat->GetXaxis()->SetBinLabel(2, "On-Fly"); fHist_V0Stat->GetXaxis()->SetBinLabel(3, "Off-Fly"); fHist_V0Stat->GetXaxis()->SetBinLabel(4, "V0 pseudorapidity"); fHist_V0Stat->GetXaxis()->SetBinLabel(5, "DCA Dau. tracks to PV"); fHist_V0Stat->GetXaxis()->SetBinLabel(6, "DCA dauthers"); fHist_V0Stat->GetXaxis()->SetBinLabel(7, "Fiducial volume"); fHist_V0Stat->GetXaxis()->SetBinLabel(8, "Pass IsAcceptedV0"); fHist_V0Stat->GetXaxis()->SetBinLabel(9, "track cut"); fHist_V0Stat->GetXaxis()->SetBinLabel(10, "charge"); fHist_V0Stat->GetXaxis()->SetBinLabel(11, "PID for K0s"); fHist_V0Stat->GetXaxis()->SetBinLabel(12, "ctau for k0s"); fHist_V0Stat->GetXaxis()->SetBinLabel(13, "AP cut for K0s"); fOutputList->Add(fHist_V0Stat); fHistzvertex = new TH1F("fHistzvertex", ";VZ;count", 60, -15, 15); fOutputList->Add(fHistzvertex); Double_t fmaxcent; Int_t fncentbin=100; if(fCentType=="Manual"){ if(fcollisiontype=="PbPb"){ fmaxcent=3000; fncentbin=1000; }else{ fmaxcent=200; } }else{ if (fcollisiontype.Contains("HMPP")) fmaxcent=1.; else fmaxcent=100.; } fHistCentrality = new TH1F("fHistCentrality", ";centrality;count", 100, 0, fmaxcent); fOutputList->Add(fHistCentrality); fHistCentrality_beforecut = new TH1F("fHistCentrality_beforecut", ";centrality;count", 100, 0, fmaxcent); fOutputList->Add(fHistCentrality_beforecut); fHistCentzvertex = new TH2F("fHistCentzvertex", "Cent;VZ;count", 100,0, fmaxcent, 60, -15, 15); fOutputList->Add(fHistCentzvertex); Int_t nspdtracks; if(fcollisiontype.Contains("HMPP")|| fcollisiontype.Contains("MBPP")|| fcollisiontype.Contains("pPb")) nspdtracks=200; else nspdtracks=3500; fHistCentV0vsTracklets=new TH2F("fHistCentV0vsTracklets","fHistCentV0vsTracklets",fncentbin,0,fmaxcent,nspdtracks,0,nspdtracks); if(fAnaMode!="FMDFMD") fOutputList->Add(fHistCentV0vsTracklets); fHistTraksvsVz=new TH2F("fHistTraksvsVz","fHistTraksvsVz",50,-10,10,nspdtracks,0,nspdtracks); fOutputList->Add(fHistTraksvsVz); //fHistCentV0vsTrackletsbefore=new TH2F("fHistCentV0vsTrackletsbefore","fHistCentV0vsTrackletsbefore",100,0,100,nspdtracks,0,nspdtracks); //fOutputList->Add(fHistCentV0vsTrackletsbefore); Int_t nv0mult; Int_t nbinv0mult=1000; if(fcollisiontype=="PbPb") { nv0mult=50000; }else{ nv0mult=5000; } fHistV0vsTracks=new TH2F("fHistV0vsTracks","fHistV0vsTracks",nbinv0mult,0,nv0mult,nspdtracks,0,nspdtracks); if(fAnaMode!="FMDFMD") fOutputList->Add(fHistV0vsTracks); fHistCentvsNv0mult=new TH2F("fHistCentvsNv0mult","fHistCentvsNv0mult",fncentbin,0,fmaxcent,nv0mult,0,nv0mult); fOutputList->Add(fHistCentvsNv0mult); fHistV0multvsVz=new TH2F("fHistV0multvsVz","fHistV0multvsVz",50,-10,10,nv0mult,0,nv0mult); fOutputList->Add(fHistV0multvsVz); TTree *settingsTree = new TTree("UEAnalysisSettings", "Analysis Settings in UE estimation"); settingsTree->Branch("fZVertex", &fZVertex, "fZVertex/D"); settingsTree->Branch("fEtaMax", &fEtaMax, "fEtaMax/D"); settingsTree->Branch("fPtMin", &fPtMin, "fPtMin/D"); settingsTree->Branch("fMaxnSigmaTPCTOF", &fMaxnSigmaTPCTOF, "fMaxnSigmaTPCTOF/D"); // settingsTree->Branch("fanamode",&fAnaMode,"fAnaMode/B"); // settingsTree->Branch("fanalysisasso",&fanalysisasso,"fanalysisasso/I"); // settingsTree->Branch("fanalysiscent",&fanalysiscent,"fanalysiscent/I"); settingsTree->Fill(); fOutputList->Add(settingsTree); } void AliAnalysisTaskSEpPbCorrelationsYS::DefineVZEROOutput() { Int_t ncent; if(fCentType=="Manual") ncent=20; else ncent=15; const Int_t nVZEROBins[3] = {10, 8, ncent}; Double_t binning_eta_vzero[11] = {-3.7, -3.2, -2.7, -2.2, -1.7, 0., 2.8, 3.4, 3.9, 4.5, 5.1}; Double_t binning_phi_vzero[9] = {0., 0.7853, 1.5707, 2.3561, 3.1415, 3.9269, 4.7123, 5.4977, 6.2831}; Double_t binning_cent[16] = {0., 0.1, 1., 2., 3., 5., 10., 20., 30., 40., 50., 60., 70., 80., 90., 100.1}; fHist_vzeromult = new TH2F("fHist_vzeromult", "fHist_vzeromult", 64, -0.5, 63.5, 500, 0, 500); fOutputList1->Add(fHist_vzeromult); fHist_vzeromultEqweighted = new TH2F("fHist_vzeromultEqweighted", "fHist_vzeromultEqweighted", 64, -0.5, 63.5, 500, 0, 500); fOutputList1->Add(fHist_vzeromultEqweighted); fHist2dmult = new TH3F("fHist2dmult", "fHist2dmult", 64, -0.5, 63.5, 500, 0, 500, 500, 0, 500); fOutputList1->Add(fHist2dmult); fHistVZERO = new AliTHn("fHistVZERO", "fHistVZERO", 1, 3, nVZEROBins); fHistVZERO->SetBinLimits(0, binning_eta_vzero); fHistVZERO->SetBinLimits(1, binning_phi_vzero); if(fCentType!="Manual") fHistVZERO->SetBinLimits(2, binning_cent); else fHistVZERO->SetBinLimits(2, 0, 200); fOutputList1->Add(fHistVZERO); } void AliAnalysisTaskSEpPbCorrelationsYS::DefinedQAHistos() { Int_t ncentmax; if(fCentType=="Manual") ncentmax=200; else ncentmax=100; mixedDist=new TH2F("mixedDist", ";centrality;tracks;events", 100, 0, ncentmax, 200, 0, fPoolMinNTracks*1.5 ); mixedDist2=new TH2F("mixedDist2", ";centrality;events;events", 100, 0,ncentmax, 100, 0, 1000) ; fOutputList2->Add(mixedDist); fOutputList2->Add(mixedDist2); const Int_t ipidBin[4] = {11, 40, 72, 15}; Double_t binning_pt_lead[12] = {0.2, 0.5, 0.75, 1.0, 1.25, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 8.0}; Double_t binning_eta[41] = {-1., -0.95, -0.9, -0.85, -0.8, -0.75, -0.7, -0.65, -0.6, -0.55, -0.5, -0.45, -0.4, -0.35, -0.3, -0.25, -0.2, -0.15, -0.1, -0.05, 0., 0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95, 1.0}; Double_t binning_dphi[73] = { -1.570796, -1.483530, -1.396263, -1.308997, -1.221730, -1.134464, -1.047198, -0.959931, -0.872665, -0.785398, -0.698132, -0.610865, -0.523599, -0.436332, -0.349066, -0.261799, -0.174533, -0.087266, 0.0, 0.087266, 0.174533, 0.261799, 0.349066, 0.436332, 0.523599, 0.610865, 0.698132, 0.785398, 0.872665, 0.959931, 1.047198, 1.134464, 1.221730, 1.308997, 1.396263, 1.483530, 1.570796, 1.658063, 1.745329, 1.832596, 1.919862, 2.007129, 2.094395, 2.181662, 2.268928, 2.356194, 2.443461, 2.530727, 2.617994, 2.705260, 2.792527, 2.879793, 2.967060, 3.054326, 3.141593, 3.228859, 3.316126, 3.403392, 3.490659, 3.577925, 3.665191, 3.752458, 3.839724, 3.926991, 4.014257, 4.101524, 4.188790, 4.276057, 4.363323, 4.450590, 4.537856, 4.625123, 4.712389}; Double_t binning_cent[16] = {0., 0.1, 1., 2., 3., 5., 10., 20., 30., 40., 50., 60., 70., 80., 90., 100.1}; Double_t binning_zvx[11] = {-10,-8,-6,-4,-2,0,2,4,6,8,10}; if(fasso=="PID" && fQA){ fHistPIDQA = new AliTHn("fHistPIDQA", "fHistPIDQA", 3, 4, ipidBin); fHistPIDQA->SetBinLimits(0, binning_pt_lead); fHistPIDQA->SetBinLimits(1, binning_eta); fHistPIDQA->SetBinLimits(2, binning_dphi); fHistPIDQA->SetBinLimits(3, binning_cent); fHistPIDQA->SetVarTitle(0, "pt"); fHistPIDQA->SetVarTitle(1, "eta"); fHistPIDQA->SetVarTitle(2, "phi"); fHistPIDQA->SetVarTitle(3, "centrality"); fOutputList1->Add(fHistPIDQA); } Double_t binning_cent_leadQA[13] = {0., 0.1, 5., 10., 20., 30., 40., 50., 60., 70., 80., 90., 100.1}; Int_t fncentbinqa; if(fCentType=="Manual") fncentbinqa=100; else fncentbinqa=12; const Int_t ipidBinQA[5] = {11, 40, 72, fncentbinqa,10}; fHistLeadQA = new AliTHn("fHistLeadQA", "fHistLeadQA", 1, 5, ipidBinQA); fHistLeadQA->SetBinLimits(0, binning_pt_lead); fHistLeadQA->SetBinLimits(1, binning_eta); fHistLeadQA->SetBinLimits(2, binning_dphi); if(fCentType=="Manual")fHistLeadQA->SetBinLimits(3,0,200); else fHistLeadQA->SetBinLimits(3, binning_cent_leadQA); fHistLeadQA->SetBinLimits(4,-10,10); fHistLeadQA->SetVarTitle(0, "pt"); fHistLeadQA->SetVarTitle(1, "eta"); fHistLeadQA->SetVarTitle(2, "phi"); fHistLeadQA->SetVarTitle(3, "centrality"); fHistLeadQA->SetVarTitle(4, "vz"); fOutputList1->Add(fHistLeadQA); const Int_t imcprimbin[4]={11,55,30,10}; Double_t binning_pt_mcprim[12] = {0.3, 0.5, 0.75, 1.0, 1.25, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 8.0}; if(!fDataType){ fhistmcprim=new AliTHn("fhistmcprim","fhistmcprim",1,4,imcprimbin); fhistmcprim->SetBinLimits(0,binning_pt_mcprim); fhistmcprim->SetBinLimits(1,-5.5,5.5); fhistmcprim->SetBinLimits(2,0.,2*TMath::Pi()); fhistmcprim->SetBinLimits(3,0.,100.); fhistmcprim->SetVarTitle(0,"pt"); fhistmcprim->SetVarTitle(1,"eta"); fhistmcprim->SetVarTitle(2,"phi"); fhistmcprim->SetVarTitle(3,"centrality"); fOutputList2->Add(fhistmcprim); fhmcprimvzeta=new TH2D("fhmcprimvzeta","fhmcprimvzeta",200,-4,6,20,-10,10); fOutputList2->Add(fhmcprimvzeta); fhmcprimpdgcode=new TH1D("fhmcprimpdgcode","fhmcprimpdgcode",4000,-0.5,3999.5); fOutputList2->Add(fhmcprimpdgcode); fh2_FMD_acceptance_prim=new TH2D("fh2_FMD_acceptance_prim","fh2_FMD_acceptance_prim",200,-4,6,200,-10,10); fOutputList2->Add(fh2_FMD_acceptance_prim); fh2_FMD_eta_phi_prim=new TH2D("fh2_FMD_eta_phi_prim","fh2_FMD_eta_phi_prim",200,-4,6,20,0,2*TMath::Pi()); fOutputList2->Add(fh2_FMD_eta_phi_prim); for(Int_t i=0;i<4;i++){ fhrefetaFMD[i]=new TH1D(Form("fhrefetaFMD_%d",i),Form("fhrefetaFMD_%d",i),200,-4,6); fhrefphiFMD[i]=new TH1D(Form("fhrefphiFMD_%d",i),Form("fhrefphiFMD_%d",i),100,0,2*TMath::Pi()); fOutputList2->Add(fhrefetaFMD[i]); fOutputList2->Add(fhrefphiFMD[i]); } } fHist_NeventRun=new TH1F("fHist_NeventRun","fHist_NeventRun",200,-0.5,199.5); fOutputList2->Add(fHist_NeventRun); fHist_V0AMultRun=new TH1F("fHist_V0AMultRun","fHist_V0AMultRun",200,-0.5,199.5); fOutputList2->Add(fHist_V0AMultRun); fHist_V0CMultRun=new TH1F("fHist_V0CMultRun","fHist_V0CMultRun",200,-0.5,199.5); fOutputList2->Add(fHist_V0CMultRun); fHist_FMDAMultRun=new TH1F("fHist_FMDAMultRun","fHist_FMDAMultRun",200,-0.5,199.5); fOutputList2->Add(fHist_FMDAMultRun); fHist_FMDCMultRun=new TH1F("fHist_FMDCMultRun","fHist_FMDCMultRun",200,-0.5,199.5); fOutputList2->Add(fHist_FMDCMultRun); fOutliers = new TH2D("fOutliers","Maximum #sigma from mean N_{ch} pr. bin",100, 0., 100., 500, 0., 5.); //((fFlags & kMC) ? 15. : 5. // Sigma <M> histogram fOutputList2->Add(fOutliers); Float_t nmutFoward; if(fcollisiontype=="PbPb"||fcollisiontype=="pPb") nmutFoward=2000.; else nmutFoward=1000.; fFMDV0 = new TH2F("FMDV0", "FMD vs V0 pre cut;FMD;V0;",2000, 0, 2*nmutFoward, 2000, 0, 2*nmutFoward); fOutputList2->Add(fFMDV0); fFMDV0_post=new TH2F("FMDV0_post", "FMD vs V0 post cut;FMD;V0;",2000, 0, 2*nmutFoward, 2000, 0, 2*nmutFoward); fOutputList2->Add(fFMDV0_post); fFMDV0A = new TH2F("FMDV0A", "FMD vs V0A;FMD;V0A;",1000, 0, nmutFoward, 1000, 0, nmutFoward); fOutputList2->Add(fFMDV0A); fFMDV0A_post = new TH2F("FMDV0A_post", "FMD vs V0A post cut;FMD;V0A;",1000, 0, nmutFoward, 1000, 0, nmutFoward); fOutputList2->Add(fFMDV0A_post); fFMDV0C = new TH2F("FMDV0C", "FMD vs V0C;FMD;V0C;",1000, 0, nmutFoward, 1000, 0, nmutFoward); fOutputList2->Add(fFMDV0C); fFMDV0C_post = new TH2F("FMDV0C_post", "FMD vs V0C post cut;FMD;V0C;",1000, 0, nmutFoward, 1000, 0, nmutFoward); fOutputList2->Add(fFMDV0C_post); fFMDV0same = new TH2F("FMDV0same", "FMD vs V0 pre cut;FMD;V0;",2000, 0, 2000, 2*nmutFoward, 0, 2*nmutFoward); fOutputList2->Add(fFMDV0same); fFMDV0same_post=new TH2F("FMDV0same_post", "FMD vs V0 post cut;FMD;V0;",2000, 0, 2000, 2*nmutFoward, 0, 2*nmutFoward); fOutputList2->Add(fFMDV0same_post); fFMDV0Asame = new TH2F("FMDV0Asame", "FMD vs V0A;FMD;V0A;",1000, 0, nmutFoward, 1000, 0, nmutFoward); fOutputList2->Add(fFMDV0Asame); fFMDV0Asame_post = new TH2F("FMDV0Asame_post", "FMD vs V0A post cut;FMD;V0A;",2000, 0, nmutFoward, 1000, 0, nmutFoward); fOutputList2->Add(fFMDV0Asame_post); fFMDV0Csame = new TH2F("FMDV0Csame", "FMD vs V0C;FMD;V0C;",1000, 0, nmutFoward, 1000, 0, nmutFoward); fOutputList2->Add(fFMDV0Csame); fFMDV0Csame_post = new TH2F("FMDV0Csame_post", "FMD vs V0C post cut;FMD;V0C;",1000, 0, nmutFoward, 1000, 0, nmutFoward); fOutputList2->Add(fFMDV0Csame_post); fh2_ITS_acceptance=new TH2D("fh2_ITS_acceptance","fh2_ITS_acceptance",200,-10,10,200,-4,6); fOutputList2->Add(fh2_ITS_acceptance); fh2_SPD_multcorr=new TH2F("fh2_SPD_multcorr","fh2_SPD_multcorr",400,0,400,2000,0,2000); fOutputList2->Add(fh2_SPD_multcorr); fh2_SPDV0_multcorr=new TH2F("fh2_SPDV0_multcorr","fh2_SPDV0_multcorr",400,0,400,2000,0,2000); fOutputList2->Add(fh2_SPDV0_multcorr); fh2_SPDtrack_multcorr=new TH2F("fh2_SPDtrack_multcorr","fh2_SPDtrack_multcorr",400,0,400,400,0,400); fOutputList2->Add(fh2_SPDtrack_multcorr); fhtrackletsdphi=new TH1F("fhtrackletsdphi","dphi tracklets",100,-100,100); fOutputList2->Add(fhtrackletsdphi); fh2_FMD_acceptance=new TH2D("fh2_FMD_acceptance","fh2_FMD_acceptance",200,-4,6,200,-10,10); fOutputList2->Add(fh2_FMD_acceptance); fh2_FMD_eta_phi=new TH2D("fh2_FMD_eta_phi","fh2_FMD_eta_phi",200,-4,6,20,0,2*TMath::Pi()); fOutputList2->Add(fh2_FMD_eta_phi); fh2_FMD_eta_phi_aftercut=new TH2D("fh2_FMD_eta_phi_aftercut","fh2_FMD_eta_phi_aftercut",200,-4,6,20,0,2*TMath::Pi()); fOutputList2->Add(fh2_FMD_eta_phi_aftercut); if(fCentType!="Manual")fhistfmdphiacc=new TH2D("fhistfmdphiacc","fhistfmdphiacc",200,-4,6,15,binning_cent); else fhistfmdphiacc=new TH2D("fhistfmdphiacc","fhistfmdphiacc",200,-4,6,20,0,200); fOutputList2->Add(fhistfmdphiacc); fhFMDmultchannel=new TH2F("fhFMDmultchannel","fhFMDmultchannel",200,-4,6,100,0,100); fOutputList2->Add(fhFMDmultchannel); for(Int_t i=0;i<31;i++){ fhFMDmult_runbyrun_cside[i]=new TH2D(Form("fhFMDmult_runbyrun_cside_%d",i),Form("fhFMDmult_runbyrun_%d",i),200,-0.5,199.5,100,0,100); // fOutputList2->Add(fhFMDmult_runbyrun_cside[i]); } for(Int_t i=0;i<65;i++){ fhFMDmult_runbyrun_aside[i]=new TH2D(Form("fhFMDmult_runbyrun_aside_%d",i),Form("fhFMDmult_runbyrun_%d",i),200,-0.5,199.5,100,0,100); // fOutputList2->Add(fhFMDmult_runbyrun_aside[i]); } Int_t ncentbinfmd; if(fCentType=="Manual") ncentbinfmd=20; else ncentbinfmd=15; const Int_t ifmdbin[4]={200,20,ncentbinfmd,10}; fhistfmd=new AliTHn("fhistfmd","fhistfmd",1,4,ifmdbin); fhistfmd->SetBinLimits(0,-4.,6.); fhistfmd->SetBinLimits(1,0.,2*TMath::Pi()); if(fCentType=="Manual")fhistfmd->SetBinLimits(2,0.,200.); // else fhistfmd->SetBinLimits(2,0.,100.); else fhistfmd->SetBinLimits(2,binning_cent); fhistfmd->SetBinLimits(3,-10.,10.); fhistfmd->SetVarTitle(0,"eta"); fhistfmd->SetVarTitle(1,"phi"); fhistfmd->SetVarTitle(2,"centrality"); fhistfmd->SetVarTitle(3,"vzy"); fOutputList2->Add(fhistfmd); const Int_t iitsbin[4]={200,20,20,40}; Double_t MinITS[4];//={-4,0.,0.,-10.}; MinITS[0]=-4.; MinITS[1]=0.; MinITS[2]=0.; MinITS[3]=-10.; Double_t MaxITS[4]; MaxITS[0]=6.; MaxITS[1]=2*TMath::Pi(); MaxITS[2]=100.; MaxITS[3]=10.; fhistits=new THnSparseF("fhistits","fhistits",4,iitsbin,MinITS,MaxITS); // fOutputList2->Add(fhistits); const Double_t binning_etafmd[51]={ -3.4,-3.3,-3.2,-3.1,-3.0, -2.9,-2.8,-2.7,-2.6,-2.5,-2.4,-2.3,-2.2,-2.1,-2.0, -1.9,-1.8,-1.7, 1.7,1.8,1.9, 2.0,2.1,2.2,2.3,2.4,2.5,2.6,2.7,2.8,2.9, 3.0,3.1,3.2,3.3,3.4,3.5,3.6,3.7,3.8,3.9, 4.0,4.1,4.2,4.3,4.4,4.5,4.6,4.7,4.8,4.9}; const Int_t binfmdsec[5]={160,50,15,20,10}; fhSecFMD= new AliTHn("fhSecFMD","fhSecFMD",2,5,binfmdsec); fhSecFMD->SetBinLimits(0,-4.025,3.975); fhSecFMD->SetBinLimits(1,binning_etafmd); fhSecFMD->SetBinLimits(2,binning_cent); fhSecFMD->SetBinLimits(3,-0.55*TMath::Pi(),1.45*TMath::Pi()); fhSecFMD->SetBinLimits(4,binning_zvx); fhSecFMD->SetVarTitle(0,"#Delta#eta"); fhSecFMD->SetVarTitle(1,"FMD Eta"); fhSecFMD->SetVarTitle(2,"centrality"); fhSecFMD->SetVarTitle(3,"#Delta#phi"); fhSecFMD->SetVarTitle(4,"z vertex"); fOutputList2->Add(fhSecFMD); if(fasso=="PID"){ for(Int_t i=0;i<6;i++){ fHistNsig[i]=new TH2D(Form("fHistNsig_%d",i),Form("HistNsig_%d",i), 160, 0., 8., 600, -30., 30); fOutputList2->Add(fHistNsig[i]); fHistNsigcorr[i]=new TH2D(Form("fHistNsigcorr_%d",i),"fHistNsigcorr",500,-10,10,500,-10,10); fOutputList2->Add(fHistNsigcorr[i]); } } if(fasso=="Phi"){ fHistPhiDTPCNSig = new TH2D("fHistPhiDTPCNSig", "fHistPhiDTPCNSig", 150, 0.,15., 200, -10., 10); fOutputList2->Add(fHistPhiDTPCNSig); fHistPhiDTOFNSig = new TH2D("fHistPhiDTOFNSig", "fHistPhiDTOFNSig", 150, 0.,15., 200, -10., 10); fOutputList2->Add(fHistPhiDTOFNSig); fHistPhiDTPCTOFNSig = new TH2D("fHistPhiDTPCTOFNSig", "fHistPhiDTPCTOFNSig",150, 0., 15., 200, -10., 10); fOutputList2->Add(fHistPhiDTPCTOFNSig); } Int_t nBins = 400; Double_t mphiMin = 1.02 - 0.1; Double_t mphiMax = 1.02 + 0.1; Int_t nCentralityBins = 20; Double_t centBins1[16] = {0., 1., 2., 3., 4., 5., 10., 20., 30., 40., 50., 60., 70., 80., 90., 100.0}; const Double_t *centralityBins = centBins1; Int_t nPtBinsV0 = 150; const Double_t PtBinsV0[12] = {0, 0.5, 0.75, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 8.0, 15.0}; Double_t mk0sMin = 0.5 - 0.1; Double_t mk0sMax = 0.5 + 0.1; Int_t netabins=4; const Int_t spBins[3] = {nBins, nPtBinsV0, nCentralityBins}; const Int_t spBinsV0[4] = {nBins, nPtBinsV0, nCentralityBins,netabins}; const Int_t spBinsBump[3] = {500, nPtBinsV0, nCentralityBins}; // v0 const Double_t spMink0s[4] = {mk0sMin, PtBinsV0[0], centralityBins[0],-0.8}; const Double_t spMaxk0s[4] = {mk0sMax, PtBinsV0[11], centralityBins[15],0.8}; Double_t mlambdaMin = 1.15 - 0.1; Double_t mlambdaMax = 1.15 + 0.1; const Double_t spMinLambda[4] = {mlambdaMin, PtBinsV0[0], centralityBins[0],-0.8}; const Double_t spMaxLambda[4] = {mlambdaMax, PtBinsV0[11],centralityBins[15],0.8}; const Double_t spMinBump[3] = {0, PtBinsV0[0], centralityBins[0]}; const Double_t spMaxBump[3] = {2.5, PtBinsV0[11], centralityBins[15]}; if(fasso=="V0"){ fHistMass_K0s = new THnSparseF("fHistMass_K0s", "mass for K0s", 4, spBinsV0, spMink0s, spMaxk0s); fOutputList2->Add(fHistMass_K0s); fHistMass_K0s_MC = new THnSparseF("fHistMass_K0s_MC", "mass for K0s", 4, spBinsV0, spMink0s, spMaxk0s); fOutputList2->Add(fHistMass_K0s_MC); fHistMass_Lambda = new THnSparseF("fHistMass_Lambda", "mass for Lambda", 4,spBinsV0, spMinLambda, spMaxLambda); fOutputList2->Add(fHistMass_Lambda); fHistMass_Lambda_MC = new THnSparseF("fHistMass_Lambda_MC", "MC mass for Lambda", 4,spBinsV0, spMinLambda, spMaxLambda); fOutputList2->Add(fHistMass_Lambda_MC); fHistMass_ALambda = new THnSparseF("fHistMass_ALambda", "mass for Anti Lambda", 4, spBinsV0,spMinLambda, spMaxLambda); fOutputList2->Add(fHistMass_ALambda); fHistMass_ALambda_MC = new THnSparseF("fHistMass_ALambda_MC", "mass for Anti Lambda", 4, spBinsV0,spMinLambda, spMaxLambda); fOutputList2->Add(fHistMass_ALambda_MC); fHistMass_bumpcorr =new TH2D("fHistMass_bumpcorr", "mass for Lambda bump correlation", 400,mlambdaMin, mlambdaMax, 1000, 0, 1); fOutputList2->Add(fHistMass_bumpcorr); const Int_t spBinsQAV0[4] = {40, 72, 7, 20}; const Double_t spMinV0QA[4] = {-1., 0, -0.5, 0.}; const Double_t spMaxV0QA[4] = {1., TMath::TwoPi(), 6.5, 100.0}; fHist_V0QA = new THnSparseF("fHist_V0QA", "QA for V0 particle", 4, spBinsQAV0, spMinV0QA, spMaxV0QA); fOutputList2->Add(fHist_V0QA); hv0dcharge = new TH1D("hv0dcharge", "hv0dcharge", 3, -0.5, 2.5); fOutputList2->Add(hv0dcharge); for (Int_t i = 0; i < 6; i++) { fHistPosNsig[i] = new TH2D(Form("fHistPosNsig_%d", i), "fHistPosNsig", 160, 0., 8., 600, -30., 30); fHistNegNsig[i] = new TH2D(Form("fHistNegNsig_%d", i), "fHistNegNsig", 160, 0., 8., 600, -30., 30); fOutputList2->Add(fHistPosNsig[i]); fOutputList2->Add(fHistNegNsig[i]); fHistPosNsigQA[i] = new TH2D(Form("fHistPosNsigQA_%d", i), "fHistPosNsigQA",160, 0., 8., 600, -30., 30); fOutputList2->Add(fHistPosNsigQA[i]); } for(Int_t i=0;i<3;i++){ fh3NegNsig[i]=new TH3D(Form("fh3NegNsig_%d",i),Form("fh3NegNsig_%d",i),40,0,8,200,-10,10,200,-10,10); fh3PosNsig[i]=new TH3D(Form("fh3PosNsig_%d",i),Form("fh3PosNsig_%d",i),40,0,8,200,-10,10,200,-10,10); fOutputList2->Add(fh3NegNsig[i]); fOutputList2->Add(fh3PosNsig[i]); } for (Int_t i = 0; i < 6; i++) { fHist_AP[i] = new TH2D(Form("fHist_AP_%d", i), Form("fHist_AP_%d", i), 200, -1, 1, 200, 0, 0.4); fOutputList2->Add(fHist_AP[i]); } } if(fasso=="Cascade"){ // QA Plot for Cascade Double_t mxiMin = 1.3 - 0.1; Double_t mxiMax = 1.3 + 0.1; Double_t momegaMin = 1.65 - 0.1; Double_t momegaMax = 1.65 + 0.1; const Double_t spMinXi[3] = {mxiMin, PtBinsV0[0], centralityBins[0]}; const Double_t spMaxXi[3] = {mxiMax, PtBinsV0[11], centralityBins[15]}; const Double_t spMinOmega[3] = {momegaMin, PtBinsV0[0], centralityBins[0]}; const Double_t spMaxOmega[3] = {momegaMax, PtBinsV0[11], centralityBins[15]}; fHistMassXiMinus = new THnSparseF("fHistMassXiMinus", "mass for Xi-", 3, spBins, spMinXi, spMaxXi); fHistMassXiPlus = new THnSparseF("fHistMassXiPlus", "mass for Xi+", 3, spBins, spMinXi, spMaxXi); fHistMassOmegaMinus = new THnSparseF("fHistMassOmegaMinus", "mass for Omega-", 3, spBins, spMinOmega, spMaxOmega); fHistMassOmegaPlus = new THnSparseF("fHistMassOmegaPlus", "mass for Omega+", 3, spBins, spMinOmega, spMaxOmega); fOutputList2->Add(fHistMassXiMinus); fOutputList2->Add(fHistMassXiPlus); fOutputList2->Add(fHistMassOmegaMinus); fOutputList2->Add(fHistMassOmegaPlus); const Int_t spBinsQACasc[5] = {20, 40, 72, 7, 20}; const Double_t spMinCascQA[5] = {0, -1., 0, -0.5, 0.}; const Double_t spMaxCascQA[5] = {10, 1., TMath::TwoPi(), 6.5, 100.0}; fHist_CascadeQA = new THnSparseF("fHist_CascadeQA", "QA for Cascade particle", 5, spBinsQACasc, spMinCascQA, spMaxCascQA); fOutputList2->Add(fHist_CascadeQA); } if(fasso=="Phi"){ // QA Plot for Phi meson const Double_t spMinPhi[3] = {mphiMin, PtBinsV0[0], centralityBins[0]}; const Double_t spMaxPhi[3] = {mphiMax, PtBinsV0[11], centralityBins[15]}; // Phimeson fHistMass_PhiMeson = new THnSparseF("fHistMass_PhiMeson", "mass for phi meson", 3, spBins, spMinPhi, spMaxPhi); fOutputList2->Add(fHistMass_PhiMeson); fHistMass_PhiMeson_MIX = new THnSparseF("fHistMass_PhiMeson_MIX", "mass for phi meson of mixed events", 3, spBins, spMinPhi, spMaxPhi); fOutputList2->Add(fHistMass_PhiMeson_MIX); const Int_t spBinsQA[4] = {40, 72, 7, 20}; const Double_t spMinPhiQA[4] = {-1., 0, -0.5, 0.}; const Double_t spMaxPhiQA[4] = {1., TMath::TwoPi(), 6.5, 100.0}; fHist_PhiQA = new THnSparseF("fHist_PhiQA", "QA for Phimeson", 4, spBinsQA, spMinPhiQA, spMaxPhiQA); fOutputList2->Add(fHist_PhiQA); } } void AliAnalysisTaskSEpPbCorrelationsYS::DefineCorrOutput() { Double_t binning_pt_assoc[12] = {0.2, 0.5, 0.75, 1.0, 1.25, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 8.0}; Double_t binning_pt_lead[12] = {0.2, 0.5, 0.75, 1.0, 1.25, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 8.0}; Double_t binning_cent[12] = {0., 5., 10., 20., 30., 40., 50., 60., 70., 80., 90., 100.1}; Double_t binning_deta[49] = { -2.4, -2.3, -2.2, -2.1, -2.0, -1.9, -1.8, -1.7, -1.6, -1.5, -1.4, -1.3, -1.2, -1.1, -1.0, -0.9, -0.8, -0.7, -0.6, -0.5, -0.4, -0.3, -0.2, -0.1, 0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2.0, 2.1, 2.2, 2.3, 2.4}; Double_t binning_dphi[73] = { -1.570796, -1.483530, -1.396263, -1.308997, -1.221730, -1.134464, -1.047198, -0.959931, -0.872665, -0.785398, -0.698132, -0.610865, -0.523599, -0.436332, -0.349066, -0.261799, -0.174533, -0.087266, 0.0, 0.087266, 0.174533, 0.261799, 0.349066, 0.436332, 0.523599, 0.610865, 0.698132, 0.785398, 0.872665, 0.959931, 1.047198, 1.134464, 1.221730, 1.308997, 1.396263, 1.483530, 1.570796, 1.658063, 1.745329, 1.832596, 1.919862, 2.007129, 2.094395, 2.181662, 2.268928, 2.356194, 2.443461, 2.530727, 2.617994, 2.705260, 2.792527, 2.879793, 2.967060, 3.054326, 3.141593, 3.228859, 3.316126, 3.403392, 3.490659, 3.577925, 3.665191, 3.752458, 3.839724, 3.926991, 4.014257, 4.101524, 4.188790, 4.276057, 4.363323, 4.450590, 4.537856, 4.625123, 4.712389}; //multiplicity // const Double_t binning_mult_trig[10]={0,10,15,20,30,40,50,80,110,140};//multiplicity pp and pPb const Double_t binning_mult_trig[]={0,10,15,20,30,40,60,140};//multiplicity pp and pPb const Double_t binning_mult_pp[]={0,10,15,20,30,60,80,110};//multiplicity pp and pPb const Double_t binning_mult_pbpb[]={0,30,60,150,300,1000,1500,2000,2500};//multiplicity pp and pPb //centrality const Double_t binning_cent_fmdfmd_PbPb[9] = {0., 5., 10., 20., 30., 40., 50.,60.,70.}; const Double_t binning_cent_MBPP[8]={0.,0.1,1.,10.,20.,40.,60.,100.1};//MBpp centrality const Double_t binning_cent_trig[8] = {0., 5., 10., 20.,40., 60.,70.,100.1};//pPb centrality // const Double_t binning_cent_HMPP[12] = {0., 0.01,0.05,0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8,1.}; const Double_t binning_cent_HMPP[8]={0.,0.01,0.05,0.1, 0.2, 0.3, 0.4, 0.5}; //centrality bin Int_t ncentbin; if(fCentType=="Manual") { if(fcollisiontype.Contains("HMPP")||fcollisiontype.Contains("MBPP")) ncentbin=7; else if(fcollisiontype=="PbPb") ncentbin=8; else ncentbin=7;//sizeof(binning_mult_trig)/sizeof(Double_t)-1; }else { if (fcollisiontype=="PbPb") ncentbin=8; else ncentbin=7; } //triggered const Int_t nEvtVars = 2; const Int_t iEvtBin[2] = {11, 11}; Int_t nCFStepstrig=1; if(fasso=="hadron") nCFStepstrig=1; else if (fasso == "V0" || fasso == "Phi") nCFStepstrig = 7; else if (fasso == "Cascade") nCFStepstrig = 6; else if(fasso=="PID") nCFStepstrig=3; Double_t binning_eta_vzero[11]={-3.7,-3.2,-2.7,-2.2,-1.7,0.,2.8,3.4,3.9,4.5,5.1}; Double_t binning_phi_vzero[9]={0.,0.7853,1.5707,2.3561,3.1415,3.9269,4.7123,5.4977,6.2831}; //Bins for FMD const Double_t binning_etafmd[33]={ 1.7,1.8,1.9, 2.0,2.1,2.2,2.3,2.4,2.5,2.6,2.7,2.8,2.9, 3.0,3.1,3.2,3.3,3.4,3.5,3.6,3.7,3.8,3.9, 4.0,4.1,4.2,4.3,4.4,4.5,4.6,4.7,4.8,4.9}; const Double_t binning_etafmdc[18]={ -3.4,-3.3,-3.2,-3.1,-3.0, -2.9,-2.8,-2.7,-2.6,-2.5,-2.4,-2.3,-2.2,-2.1,-2.0, -1.9,-1.8,-1.7}; Double_t binning_zvx[11] = {-10,-8,-6,-4,-2,0,2,4,6,8,10}; if(fAnaMode=="V0AV0C"){ const Int_t nEvtVarsV0Leading=3; const Int_t iEvtBinV0Leading[3]={11,10,8}; fHistTriggerTrack= new AliTHn("fHistTriggerTrack", "fHistTriggerTrack", nCFStepstrig, nEvtVarsV0Leading, iEvtBinV0Leading); fHistTriggerTrack->SetBinLimits(0,binning_cent); fHistTriggerTrack->SetBinLimits(1,binning_eta_vzero); fHistTriggerTrack->SetBinLimits(2,binning_phi_vzero); fHistTriggerTrack->SetVarTitle(0,"centrality"); fHistTriggerTrack->SetVarTitle(1,"eta"); fHistTriggerTrack->SetVarTitle(2,"phi"); fHistTriggerTrackMix= new AliTHn("fHistTriggerTrackMix", "fHistTriggerTrackMix", nCFStepstrig, nEvtVarsV0Leading, iEvtBinV0Leading); fHistTriggerTrackMix->SetBinLimits(0,binning_cent); fHistTriggerTrackMix->SetBinLimits(1,binning_eta_vzero); fHistTriggerTrackMix->SetBinLimits(2,binning_phi_vzero); fHistTriggerTrackMix->SetVarTitle(0,"centrality"); fHistTriggerTrackMix->SetVarTitle(1,"eta"); fHistTriggerTrackMix->SetVarTitle(2,"phi"); }else if(fAnaMode=="FMDFMD" || fAnaMode=="FMDFMD_Ctrig"|| fAnaMode=="SECA" || fAnaMode=="SECC"){ const Int_t nEvtVarsV0Leading=3; Int_t nfmdbin; if(fAnaMode=="FMDFMD") nfmdbin=32; else nfmdbin=17; const Int_t iEvtBinV0Leading[3]={ncentbin,nfmdbin,10}; fHistTriggerTrack= new AliTHn("fHistTriggerTrack", "fHistTriggerTrack", nCFStepstrig, nEvtVarsV0Leading, iEvtBinV0Leading); if(fCentType=="Manual"){ if(fcollisiontype.Contains("HMPP")||fcollisiontype.Contains("MBPP")) fHistTriggerTrack->SetBinLimits(0,binning_mult_pp); else if(fcollisiontype=="PbPb") fHistTriggerTrack->SetBinLimits(0,binning_mult_pbpb); else fHistTriggerTrack->SetBinLimits(0,binning_mult_trig); }else{ if(fcollisiontype.Contains("HMPP")) fHistTriggerTrack->SetBinLimits(0,binning_cent_HMPP); else if(fcollisiontype=="MBPP") fHistTriggerTrack->SetBinLimits(0, binning_cent_MBPP); else if(fcollisiontype=="PbPb") fHistTriggerTrack->SetBinLimits(0, binning_cent_fmdfmd_PbPb); else fHistTriggerTrack->SetBinLimits(0,binning_cent_trig); } if(fAnaMode=="FMDFMD") fHistTriggerTrack->SetBinLimits(1,binning_etafmd); else fHistTriggerTrack->SetBinLimits(1,binning_etafmdc); fHistTriggerTrack->SetBinLimits(2,-10.,10.); fHistTriggerTrack->SetVarTitle(0,"centrality"); fHistTriggerTrack->SetVarTitle(1,"eta"); fHistTriggerTrack->SetVarTitle(2,"z vertex"); const Int_t nEvtVarsV0Leadingmix=2; const Int_t iEvtBinV0Leadingmix[2]={11,32}; fHistTriggerTrackMix= new AliTHn("fHistTriggerTrackMix", "fHistTriggerTrackMix", nCFStepstrig, nEvtVarsV0Leadingmix, iEvtBinV0Leadingmix); fHistTriggerTrackMix->SetBinLimits(0,binning_cent); if(fAnaMode=="SECA" || fAnaMode=="FMDFMD") fHistTriggerTrackMix->SetBinLimits(1,binning_etafmd); else if(fAnaMode=="SECC") fHistTriggerTrackMix->SetBinLimits(1,binning_etafmdc); fHistTriggerTrackMix->SetVarTitle(0,"centrality"); fHistTriggerTrackMix->SetVarTitle(1,"eta"); // fHistTriggerTrackMix->SetVarTitle(2,"z vertex"); }else if(fAnaMode=="TPCFMD" ||fAnaMode=="TPCFMDC"||fAnaMode=="ITSFMD" || fAnaMode=="ITSFMDC"){ Double_t binning_pt_lead_trig[5] = {0.2, 0.5, 1.0, 3.0, 8.0}; const Int_t nEvtVarsFMD = 4; Int_t netabin; if(fAnaMode=="TPCFMD"||fAnaMode=="TPCFMDC") netabin=4; else netabin=18; /* Int_t ncentbin; if(fCentType=="Manual") { ncentbin=9; }else { if(fcollisiontype=="HMPP") ncentbin=11; else if (fcollisiontype=="PbPb") ncentbin=8; else ncentbin=7; } */ Int_t ntpcpt; if(fptdiff) ntpcpt=4; else ntpcpt=1; const Int_t iEvtBinFMD[4] = {ntpcpt,ncentbin,10,netabin}; Double_t binning_eta_tpcfmd[5]={-0.8,-0.4,-0.,0.4,0.8}; Double_t binning_eta_itsfmd[19]={-1.7, -1.6, -1.4, -1.2, -1.0, -0.8, -0.6, -0.4, -0.2, 0.,0.2, 0.4, 0.6, 0.8, 1.0, 1.2, 1.4, 1.6, 1.7}; fHistTriggerTrack = new AliTHn("fHistTriggerTrack", "fHistTriggerTrack", nCFStepstrig, nEvtVarsFMD, iEvtBinFMD); if(fptdiff)fHistTriggerTrack->SetBinLimits(0, binning_pt_lead_trig); else fHistTriggerTrack->SetBinLimits(0,fPtMin, fPtMax); if(fCentType=="Manual"){ if(fcollisiontype.Contains("HMPP")||fcollisiontype.Contains("MBPP")) fHistTriggerTrack->SetBinLimits(1,binning_mult_pp); else if(fcollisiontype=="PbPb") fHistTriggerTrack->SetBinLimits(1,binning_mult_pbpb); else fHistTriggerTrack->SetBinLimits(1,binning_mult_trig); }else{ if(fcollisiontype.Contains("HMPP")) fHistTriggerTrack->SetBinLimits(1,binning_cent_HMPP); else if(fcollisiontype=="MBPP") fHistTriggerTrack->SetBinLimits(1,binning_cent_MBPP); else if(fcollisiontype=="PbPb") fHistTriggerTrack->SetBinLimits(1, binning_cent_fmdfmd_PbPb); else fHistTriggerTrack->SetBinLimits(1,binning_cent_trig); } fHistTriggerTrack->SetBinLimits(2, -10.,10.); if(fAnaMode=="TPCFMD"||fAnaMode=="TPCFMDC") fHistTriggerTrack->SetBinLimits(3, binning_eta_tpcfmd); else fHistTriggerTrack->SetBinLimits(3, binning_eta_itsfmd); fHistTriggerTrack->SetVarTitle(0, "leading p_{T} GeV/c"); fHistTriggerTrack->SetVarTitle(1, "centrality"); fHistTriggerTrack->SetVarTitle(2, "zvertex"); fHistTriggerTrack->SetVarTitle(3, "TPC/Eta eta"); fHistTriggerTrackMix = new AliTHn("fHistTriggerTrackMix", "fHistTriggerTrackMix", nCFStepstrig, nEvtVars, iEvtBin); fHistTriggerTrackMix->SetBinLimits(0, binning_pt_lead_trig); fHistTriggerTrackMix->SetBinLimits(1, binning_cent_trig); fHistTriggerTrackMix->SetVarTitle(0, "leading p_{T} GeV/c"); fHistTriggerTrackMix->SetVarTitle(1, "centrality"); }else{ const Int_t nEvtVars_tpctpc = 3; const Int_t iEvtBin_tpctpc[3] = {11, 11,20}; fHistTriggerTrack = new AliTHn("fHistTriggerTrack", "fHistTriggerTrack", nCFStepstrig, nEvtVars_tpctpc, iEvtBin_tpctpc); fHistTriggerTrack->SetBinLimits(0, binning_pt_lead); fHistTriggerTrack->SetBinLimits(1, binning_cent); fHistTriggerTrack->SetBinLimits(2, -10.,10.); fHistTriggerTrack->SetVarTitle(0, "leading p_{T} GeV/c"); fHistTriggerTrack->SetVarTitle(1, "centrality"); fHistTriggerTrack->SetVarTitle(2, "vz(cm)"); fHistTriggerTrackMix = new AliTHn("fHistTriggerTrackMix", "fHistTriggerTrackMix", nCFStepstrig, nEvtVars, iEvtBin); fHistTriggerTrackMix->SetBinLimits(0, binning_pt_lead); fHistTriggerTrackMix->SetBinLimits(1, binning_cent); fHistTriggerTrackMix->SetVarTitle(0, "leading p_{T} GeV/c"); fHistTriggerTrackMix->SetVarTitle(1, "centrality"); } fOutputList1->Add(fHistTriggerTrack); fOutputList1->Add(fHistTriggerTrackMix); const Int_t nTrackVars = 5; const Int_t iTrackBin[5] = {48, 11, 11, 15, 72}; ////////////////////////////////////////// //Containers two particle correlation ////////////////////////////////////////// Int_t nCFSteps = 1; if(fasso=="hadron") nCFSteps=1; else if (fasso == "V0" || fasso == "Phi") nCFSteps = 7; else if (fasso == "Cascade") nCFSteps = 6; else if(fasso=="PID") nCFSteps=3; Double_t binning_dphi_vzero[9]={-1.178097,-0.392699,0.392699,1.178097,1.963495,2.748893,3.534291,4.319689,5.105088}; if(fAnaMode=="TPCTPC") { Double_t binning_deta_tpctpc[33] = {-1.6, -1.5, -1.4, -1.3, -1.2, -1.1, -1.0, -0.9, -0.8, -0.7, -0.6, -0.5, -0.4, -0.3, -0.2, -0.1, 0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6}; const Double_t binning_cent_tpctpc[8]={0.,5.,10.,20.,40.,60.,70.,100.1}; const Int_t iTrackBin_TPCTPC[6] = {32, 11, 11, 7, 72, 10}; fHistReconstTrack = new AliTHn("fHistReconstTrack", "fHistReconstTrack", nCFSteps, 6, iTrackBin_TPCTPC); fHistReconstTrack->SetBinLimits(0, binning_deta_tpctpc); fHistReconstTrack->SetBinLimits(1, binning_pt_assoc); fHistReconstTrack->SetBinLimits(2, binning_pt_lead); fHistReconstTrack->SetBinLimits(3, binning_cent_tpctpc); fHistReconstTrack->SetBinLimits(4, binning_dphi); fHistReconstTrack->SetBinLimits(5, -10,10); fHistReconstTrack->SetVarTitle(0, "#Delta#eta"); fHistReconstTrack->SetVarTitle(1, "p_{T} GeV/c"); fHistReconstTrack->SetVarTitle(2, "leading p_{T} GeV/c"); fHistReconstTrack->SetVarTitle(3, "centrality"); fHistReconstTrack->SetVarTitle(4, "#Delta#phi"); fHistReconstTrack->SetVarTitle(5, "Vz"); fHistReconstTrackMix = new AliTHn("fHistReconstTrackMix", "fHistReconstTrackMix", nCFSteps, 6, iTrackBin_TPCTPC); fHistReconstTrackMix->SetBinLimits(0, binning_deta_tpctpc); fHistReconstTrackMix->SetBinLimits(1, binning_pt_assoc); fHistReconstTrackMix->SetBinLimits(2, binning_pt_lead); fHistReconstTrackMix->SetBinLimits(3, binning_cent_tpctpc); fHistReconstTrackMix->SetBinLimits(4, binning_dphi); fHistReconstTrackMix->SetBinLimits(5, -10,10); fHistReconstTrackMix->SetVarTitle(0, "#Delta#eta"); fHistReconstTrackMix->SetVarTitle(1, "p_{T} GeV/c"); fHistReconstTrackMix->SetVarTitle(2, "leading p_{T} GeV/c"); fHistReconstTrackMix->SetVarTitle(3, "centrality"); fHistReconstTrackMix->SetVarTitle(4, "#Delta#phi"); fHistReconstTrackMix->SetVarTitle(5, "Vz"); }else if(fAnaMode=="TPCV0A"||fAnaMode=="TPCV0C"){ const Int_t iTrackBin_VZEROA[5]={66,11,10,11,72}; const Int_t iTrackBin_VZEROC[5]={62,11,10,11,72}; Double_t binning_detaVZEROATPC[67]={-5.6,-5.55,-5.5,-5.45,-5.4,-5.35,-5.3,-5.25,-5.2,-5.15,-5.1,-5.05,-5.0,-4.95, -4.9,-4.85, -4.8, -4.75, -4.7, -4.65,-4.6,-4.55,-4.5,-4.45,-4.4,-4.35,-4.3, -4.25,-4.2,-4.15,-4.1,-4.05,-4.0,-3.95,-3.9,-3.85,-3.8,-3.75,-3.7,-3.65,-3.6,-3.55,-3.5,-3.45,-3.4,-3.35,-3.3,-3.25,-3.2,-3.15,-3.1,-3.05,-3.0,-2.95,-2.9,-2.85,-2.8,-2.75,-2.7,-2.65,-2.6,-2.55,-2.5,-2.45,-2.4,-2.35,-2.3}; Double_t binning_detaVZEROCTPC[63]={1.15, 1.2, 1.25,1.3,1.35,1.4,1.45,1.5,1.55,1.6,1.65,1.7,1.75,1.8,1.85,1.9,1.95,2.0,2.05,2.1,2.15,2.2,2.25,2.3, 2.35, 2.4, 2.45, 2.5, 2.55,2.6, 2.65, 2.7, 2.75, 2.8, 2.85,2.9, 2.95, 3.0, 3.05, 3.1,3.15, 3.2, 3.25, 3.3,3.35, 3.4, 3.45,3.5,3.55, 3.6,3.65, 3.7, 3.75,3.8, 3.85, 3.9,3.95, 4.0,4.05, 4.1,4.15, 4.2, 4.25}; if(fAnaMode=="TPCV0A"){ fHistReconstTrack = new AliTHn("fHistReconstTrack", "fHistReconstTrack", nCFSteps, nTrackVars, iTrackBin_VZEROA); fHistReconstTrack->SetBinLimits(0,binning_detaVZEROATPC); }else{ fHistReconstTrack = new AliTHn("fHistReconstTrack", "fHistReconstTrack", nCFSteps, nTrackVars, iTrackBin_VZEROC); fHistReconstTrack->SetBinLimits(0,binning_detaVZEROCTPC); } fHistReconstTrack->SetBinLimits(1,binning_pt_lead); fHistReconstTrack->SetBinLimits(2,binning_eta_vzero); fHistReconstTrack->SetBinLimits(3,binning_cent); fHistReconstTrack->SetBinLimits(4,binning_dphi); fHistReconstTrack->SetVarTitle(0,"#Delta#eta"); fHistReconstTrack->SetVarTitle(1,"p_{T} GeV/c"); fHistReconstTrack->SetVarTitle(2,"Vzero Eta"); fHistReconstTrack->SetVarTitle(3,"centrality"); fHistReconstTrack->SetVarTitle(4,"#Delta#phi"); if(fAnaMode=="TPCV0A"){ fHistReconstTrackMix= new AliTHn("fHistReconstTrackMix", "fHistReconstTrackMix", nCFSteps, nTrackVars,iTrackBin_VZEROA); fHistReconstTrackMix->SetBinLimits(0,binning_detaVZEROATPC); }else{ fHistReconstTrackMix= new AliTHn("fHistReconstTrackMix", "fHistReconstTrackMix", nCFSteps, nTrackVars,iTrackBin_VZEROC); fHistReconstTrackMix->SetBinLimits(0,binning_detaVZEROCTPC); } fHistReconstTrackMix->SetBinLimits(1,binning_pt_lead); fHistReconstTrackMix->SetBinLimits(2,binning_eta_vzero); fHistReconstTrackMix->SetBinLimits(3,binning_cent); fHistReconstTrackMix->SetBinLimits(4,binning_dphi); fHistReconstTrackMix->SetVarTitle(0,"#Delta#eta"); fHistReconstTrackMix->SetVarTitle(1,"p_{T} GeV/c"); fHistReconstTrackMix->SetVarTitle(2,"Vzero Eta"); fHistReconstTrackMix->SetVarTitle(3,"centrality"); fHistReconstTrackMix->SetVarTitle(4,"#Delta#phi"); }else if (fAnaMode=="TPCFMD" || fAnaMode=="TPCFMDC"){ const Double_t binning_etafmd_tpcfmda[30]={ 1.9, 2.0,2.1,2.2,2.3,2.4,2.5,2.6,2.7,2.8,2.9, 3.0,3.1,3.2,3.3,3.4,3.5,3.6,3.7,3.8,3.9, 4.0,4.1,4.2,4.3,4.4,4.5,4.6,4.7,4.8}; Double_t binning_detaFMDTPC[49]={ -5.7,-5.6,-5.5,-5.4,-5.3,-5.2,-5.1,-5.0, -4.9,-4.8,-4.7,-4.6,-4.5,-4.4,-4.3,-4.2,-4.1,-4., -3.9,-3.8,-3.7,-3.6,-3.5,-3.4,-3.3,-3.2,-3.1,-3., -2.9,-2.8,-2.7,-2.6,-2.5,-2.4,-2.3,-2.2,-2.1,-2., -1.9,-1.8,-1.7,-1.6,-1.5,-1.4,-1.3,-1.2,-1.1,-1., -0.9}; /* Double_t binning_detaFMDTPC[46]={-5.6,-5.5,-5.4,-5.3,-5.2,-5.1,-5.0, -4.9,-4.8,-4.7,-4.6,-4.5,-4.4,-4.3,-4.2,-4.1,-4., -3.9,-3.8,-3.7,-3.6,-3.5,-3.4,-3.3,-3.2,-3.1,-3., -2.9,-2.8,-2.7,-2.6,-2.5,-2.4,-2.3,-2.2,-2.1,-2., -1.9,-1.8,-1.7,-1.6,-1.5,-1.4,-1.3,-1.2,-1.1}; */ Double_t binning_detaFMDCTPC[34]={ 0.9, 1.0,1.1,1.2,1.3,1.4,1.5,1.6,1.7,1.8,1.9, 2.0,2.1,2.2,2.3,2.4,2.5,2.6,2.7,2.8,2.9, 3.0,3.1,3.2,3.3,3.4,3.5,3.6,3.7,3.8,3.9, 4.0,4.1,4.2}; Double_t binning_dphi_reduce[37] = { -1.570796, -1.396263, -1.221730, -1.047198, -0.872665, -0.698132, -0.523599, -0.349066, -0.174533, 0.0, 0.174533, 0.349066, 0.523599, 0.698132, 0.872665, 1.047198, 1.221730, 1.396263, 1.570796, 1.745329, 1.919862, 2.094395, 2.268928, 2.443461, 2.617994, 2.792527, 2.967060, 3.141593, 3.316126, 3.490659, 3.665191, 3.839724, 4.014257, 4.188790, 4.363323, 4.537856, 4.712389}; Int_t ndetatpcfmd; Int_t nfmdbin; if(fAnaMode=="TPCFMD") { // ndetatpcfmd=45; ndetatpcfmd=48; nfmdbin=29; }else{ ndetatpcfmd=33; nfmdbin=17; } Double_t binning_pt_fmdtpc[5] = {0.2, 0.5, 1.0, 3.0, 8.0}; /* Int_t ncentbin; if(fCentType=="Manual") { ncentbin=9; }else{ if(fcollisiontype=="PbPb") ncentbin=8; else ncentbin=7; } */ Int_t ntpcpt; Int_t nphibin=0; if(fptdiff){ ntpcpt=4; nphibin=36; }else{ ntpcpt=1; nphibin=72; } // const Int_t iTrackBin_tpcfmd[7]={ndetatpcfmd,1,nfmdbin,ncentbin,72,10,4}; Int_t nCFStepstpcfmd=1; const Int_t iTrackBin_tpcfmd[7]={ndetatpcfmd,ntpcpt,nfmdbin,ncentbin,nphibin,10,4}; fHistReconstTrack = new AliTHn("fHistReconstTrack", "fHistReconstTrack", nCFStepstpcfmd, 7, iTrackBin_tpcfmd); fHistReconstTrackMix= new AliTHn("fHistReconstTrackMix", "fHistReconstTrackMix", nCFStepstpcfmd, 7,iTrackBin_tpcfmd); if(fAnaMode=="TPCFMD") { fHistReconstTrack->SetBinLimits(0,binning_detaFMDTPC); fHistReconstTrack->SetBinLimits(2,binning_etafmd_tpcfmda); //Mixed Events fHistReconstTrackMix->SetBinLimits(0,binning_detaFMDTPC); fHistReconstTrackMix->SetBinLimits(2,binning_etafmd_tpcfmda); } else if(fAnaMode=="TPCFMDC") { fHistReconstTrack->SetBinLimits(0,binning_detaFMDCTPC); fHistReconstTrack->SetBinLimits(2,binning_etafmdc); //Mixed Events fHistReconstTrackMix->SetBinLimits(0,binning_detaFMDCTPC); fHistReconstTrackMix->SetBinLimits(2,binning_etafmdc); } if(fptdiff) fHistReconstTrack->SetBinLimits(1,binning_pt_fmdtpc); else fHistReconstTrack->SetBinLimits(1,fPtMin,fPtMax); if(fCentType=="Manual"){ if(fcollisiontype.Contains("HMPP")||fcollisiontype.Contains("MBPP")) fHistReconstTrack->SetBinLimits(3,binning_mult_pp); else if(fcollisiontype=="PbPb") fHistReconstTrack->SetBinLimits(3,binning_mult_pbpb); else fHistReconstTrack->SetBinLimits(3,binning_mult_trig); }else{ if(fcollisiontype.Contains("HMPP")) fHistReconstTrack->SetBinLimits(3,binning_cent_HMPP); else if(fcollisiontype=="MBPP")fHistReconstTrack->SetBinLimits(3,binning_cent_MBPP); else if (fcollisiontype=="PbPb") fHistReconstTrack->SetBinLimits(3,binning_cent_fmdfmd_PbPb); else fHistReconstTrack->SetBinLimits(3,binning_cent_trig); } if(fptdiff)fHistReconstTrack->SetBinLimits(4,binning_dphi_reduce); else fHistReconstTrack->SetBinLimits(4,binning_dphi); fHistReconstTrack->SetBinLimits(5,-10.,10.); fHistReconstTrack->SetBinLimits(6,-0.8,0.8); fHistReconstTrack->SetVarTitle(0,"#Delta#eta"); fHistReconstTrack->SetVarTitle(1,"p_{T} GeV/c"); fHistReconstTrack->SetVarTitle(2,"FMD Eta"); fHistReconstTrack->SetVarTitle(3,"centrality"); fHistReconstTrack->SetVarTitle(4,"#Delta#phi"); fHistReconstTrack->SetVarTitle(5,"z vertex"); fHistReconstTrack->SetVarTitle(6,"TPC eta"); if(fptdiff) fHistReconstTrackMix->SetBinLimits(1,binning_pt_fmdtpc); else fHistReconstTrackMix->SetBinLimits(1,fPtMin,fPtMax); if(fCentType=="Manual"){ if(fcollisiontype.Contains("HMPP")||fcollisiontype.Contains("MBPP")) fHistReconstTrackMix->SetBinLimits(3,binning_mult_pp); else if(fcollisiontype=="PbPb") fHistReconstTrackMix->SetBinLimits(3,binning_mult_pbpb); else fHistReconstTrackMix->SetBinLimits(3,binning_mult_trig); //fHistReconstTrackMix->SetBinLimits(3,binning_mult_trig); }else{ if(fcollisiontype.Contains("HMPP")) fHistReconstTrackMix->SetBinLimits(3,binning_cent_HMPP); else if(fcollisiontype=="MBPP")fHistReconstTrackMix->SetBinLimits(3,binning_cent_MBPP); else if(fcollisiontype=="PbPb" )fHistReconstTrackMix->SetBinLimits(3,binning_cent_fmdfmd_PbPb); else fHistReconstTrackMix->SetBinLimits(3,binning_cent_trig); } if(fptdiff)fHistReconstTrackMix->SetBinLimits(4,binning_dphi_reduce); else fHistReconstTrackMix->SetBinLimits(4,binning_dphi); fHistReconstTrackMix->SetBinLimits(5,-10.,10.); fHistReconstTrackMix->SetBinLimits(6,-0.8,0.8); fHistReconstTrackMix->SetVarTitle(0,"#Delta#eta"); fHistReconstTrackMix->SetVarTitle(1,"p_{T} GeV/c"); fHistReconstTrackMix->SetVarTitle(2,"FMD Eta"); fHistReconstTrackMix->SetVarTitle(3,"centrality"); fHistReconstTrackMix->SetVarTitle(4,"#Delta#phi"); fHistReconstTrackMix->SetVarTitle(5,"z vertex"); fHistReconstTrackMix->SetVarTitle(6,"TPC eta"); }else if(fAnaMode=="FMDFMD" ||fAnaMode=="FMDFMD_Ctrig"){ const Int_t nTrackVars_fmdfmd = 6; /* Int_t ncentbin; if(fCentType=="Manual") ncentbin=9; else{ if(fcollisiontype=="HMPP") ncentbin=7; else if(fcollisiontype=="PbPb") ncentbin=8; else ncentbin=7; } */ Int_t nfmdtrig; Int_t nfmdasso; if(fAnaMode=="FMDFMD"){ nfmdtrig=32; nfmdasso=17; }else{ nfmdtrig=17; nfmdasso=32; } const Int_t iTrackBin_fmdfmd[6]={49,nfmdasso,nfmdtrig,ncentbin,20,10}; fHistReconstTrack= new AliTHn("fHistReconstTrack", "fHistReconstTrack", nCFSteps, nTrackVars_fmdfmd,iTrackBin_fmdfmd); if(fAnaMode=="FMDFMD") fHistReconstTrack->SetBinLimits(0,3.425,8.325); else fHistReconstTrack->SetBinLimits(0,-8.325,-3.425); // fHistReconstTrack->SetBinLimits(0,3.525,8.325); if(fAnaMode=="FMDFMD"){ fHistReconstTrack->SetBinLimits(1,binning_etafmdc); fHistReconstTrack->SetBinLimits(2,binning_etafmd); }else{ fHistReconstTrack->SetBinLimits(1,binning_etafmd); fHistReconstTrack->SetBinLimits(2,binning_etafmdc); } if(fCentType=="Manual"){ //fHistReconstTrack->SetBinLimits(3,binning_mult_trig); if(fcollisiontype.Contains("HMPP")||fcollisiontype.Contains("MBPP")) fHistReconstTrack->SetBinLimits(3,binning_mult_pp); else if(fcollisiontype=="PbPb") fHistReconstTrack->SetBinLimits(3,binning_mult_pbpb); else fHistReconstTrack->SetBinLimits(3,binning_mult_trig); }else{ if(fcollisiontype.Contains("HMPP")) fHistReconstTrack->SetBinLimits(3,binning_cent_HMPP); else if(fcollisiontype=="MBPP")fHistReconstTrack->SetBinLimits(3,binning_cent_MBPP); else if(fcollisiontype=="PbPb")fHistReconstTrack->SetBinLimits(3,binning_cent_fmdfmd_PbPb); else fHistReconstTrack->SetBinLimits(3,binning_cent_trig); } fHistReconstTrack->SetBinLimits(4,-0.55*TMath::Pi(),1.45*TMath::Pi()); fHistReconstTrack->SetBinLimits(5,-10.,10.); fHistReconstTrack->SetVarTitle(0,"#Delta#eta"); fHistReconstTrack->SetVarTitle(1,"FMD(Asso) Eta"); fHistReconstTrack->SetVarTitle(2,"FMD(Trigger) Eta"); fHistReconstTrack->SetVarTitle(3,"centrality"); fHistReconstTrack->SetVarTitle(4,"#Delta#phi"); fHistReconstTrack->SetVarTitle(5,"z vertex"); fHistReconstTrackMix= new AliTHn("fHistReconstTrackMix", "fHistReconstTrackMix", nCFSteps, nTrackVars_fmdfmd,iTrackBin_fmdfmd); if(fAnaMode=="FMDFMD")fHistReconstTrackMix->SetBinLimits(0,3.425,8.325); else fHistReconstTrackMix->SetBinLimits(0,-8.325,-3.425); //fHistReconstTrackMix->SetBinLimits(0,3.525,8.325); if(fAnaMode=="FMDFMD"){ fHistReconstTrackMix->SetBinLimits(1,binning_etafmdc); fHistReconstTrackMix->SetBinLimits(2,binning_etafmd); }else{ fHistReconstTrackMix->SetBinLimits(1,binning_etafmd); fHistReconstTrackMix->SetBinLimits(2,binning_etafmdc); } if(fCentType=="Manual"){ //fHistReconstTrackMix->SetBinLimits(3,binning_mult_trig); if(fcollisiontype.Contains("HMPP")||fcollisiontype.Contains("MBPP")) fHistReconstTrackMix->SetBinLimits(3,binning_mult_pp); else if(fcollisiontype=="PbPb") fHistReconstTrackMix->SetBinLimits(3,binning_mult_pbpb); else fHistReconstTrackMix->SetBinLimits(3,binning_mult_trig); }else{ if(fcollisiontype.Contains("HMPP"))fHistReconstTrackMix->SetBinLimits(3,binning_cent_HMPP); else if(fcollisiontype=="MBPP")fHistReconstTrackMix->SetBinLimits(3,binning_cent_MBPP); else if(fcollisiontype=="PbPb")fHistReconstTrackMix->SetBinLimits(3,binning_cent_fmdfmd_PbPb); else fHistReconstTrackMix->SetBinLimits(3,binning_cent_trig); } // fHistReconstTrackMix->SetBinLimits(4,-0.551*TMath::Pi(),1.449*TMath::Pi()); fHistReconstTrackMix->SetBinLimits(4,-0.55*TMath::Pi(),1.45*TMath::Pi()); fHistReconstTrackMix->SetBinLimits(5,-10,10.); fHistReconstTrackMix->SetVarTitle(0,"#Delta#eta"); fHistReconstTrackMix->SetVarTitle(1,"FMD(Asso) Eta"); fHistReconstTrackMix->SetVarTitle(2,"FMD(Trigger) Eta"); fHistReconstTrackMix->SetVarTitle(3,"centrality"); fHistReconstTrackMix->SetVarTitle(4,"#Delta#phi"); fHistReconstTrackMix->SetVarTitle(5,"z vertex"); }else if(fAnaMode=="SECA" || fAnaMode=="SECC"){ const Int_t nTrackVars_fmdfmd = 5; const Double_t binning_cent_fmdfmd[12]={0.,5.,10.,20.,30.,40.,50.,60.,70.,80.,90.,100.1}; Int_t binsec; if(fAnaMode=="SECA") binsec=64; else binsec=34; const Int_t iTrackBin_fmdfmd[5]={130,binsec,11,20,10}; fHistReconstTrack= new AliTHn("fHistReconstTrack", "fHistReconstTrack", nCFSteps, nTrackVars_fmdfmd,iTrackBin_fmdfmd); fHistReconstTrack->SetBinLimits(0,-3.275,3.225); if(fAnaMode=="SECA") fHistReconstTrack->SetBinLimits(1,1.7,4.9); else if (fAnaMode=="SECC") fHistReconstTrack->SetBinLimits(1,-3.4,-1.7); fHistReconstTrack->SetBinLimits(2,binning_cent_fmdfmd); fHistReconstTrack->SetBinLimits(3,-0.55*TMath::Pi(),1.45*TMath::Pi()); fHistReconstTrack->SetBinLimits(4,binning_zvx); fHistReconstTrack->SetVarTitle(0,"#Delta#eta"); fHistReconstTrack->SetVarTitle(1,"FMD(Trigger) Eta"); fHistReconstTrack->SetVarTitle(2,"centrality"); fHistReconstTrack->SetVarTitle(3,"#Delta#phi"); fHistReconstTrack->SetVarTitle(4,"z vertex"); fHistReconstTrackMix= new AliTHn("fHistReconstTrackMix", "fHistReconstTrackMix", nCFSteps, nTrackVars_fmdfmd,iTrackBin_fmdfmd); fHistReconstTrackMix->SetBinLimits(0,-3.275,3.225); if(fAnaMode=="SECA") fHistReconstTrackMix->SetBinLimits(1,1.7,4.9); else if(fAnaMode=="SECC") fHistReconstTrackMix->SetBinLimits(1,-3.4,-1.7); fHistReconstTrackMix->SetBinLimits(2,binning_cent_fmdfmd); fHistReconstTrackMix->SetBinLimits(3,-0.55*TMath::Pi(),1.45*TMath::Pi()); fHistReconstTrackMix->SetBinLimits(4,binning_zvx); fHistReconstTrackMix->SetVarTitle(0,"#Delta#eta"); fHistReconstTrackMix->SetVarTitle(1,"FMD(Trigger) Eta"); fHistReconstTrackMix->SetVarTitle(2,"centrality"); fHistReconstTrackMix->SetVarTitle(3,"#Delta#phi"); fHistReconstTrackMix->SetVarTitle(4,"z vertex"); }else if(fAnaMode=="V0AV0C"){ const Int_t nTrackVars_v0av0c = 4; const Int_t iTrackBin_VZEROAVZEROC[4]={10,10,11,8}; fHistReconstTrack= new AliTHn("fHistReconstTrack", "fHistReconstTrack", nCFSteps, nTrackVars_v0av0c,iTrackBin_VZEROAVZEROC); fHistReconstTrack->SetBinLimits(0,binning_eta_vzero); fHistReconstTrack->SetBinLimits(1,binning_eta_vzero); fHistReconstTrack->SetBinLimits(2,binning_cent); fHistReconstTrack->SetBinLimits(3,binning_dphi_vzero); fHistReconstTrack->SetVarTitle(0,"Vzero(Asso) Eta"); fHistReconstTrack->SetVarTitle(1,"Vzero(Trigger) Eta"); fHistReconstTrack->SetVarTitle(2,"centrality"); fHistReconstTrack->SetVarTitle(3,"#Delta#phi"); fHistReconstTrackMix= new AliTHn("fHistReconstTrackMix", "fHistReconstTrackMix", nCFSteps, nTrackVars_v0av0c,iTrackBin_VZEROAVZEROC); fHistReconstTrackMix->SetBinLimits(0,binning_eta_vzero); fHistReconstTrackMix->SetBinLimits(1,binning_eta_vzero); fHistReconstTrackMix->SetBinLimits(2,binning_cent); fHistReconstTrackMix->SetBinLimits(3,binning_dphi_vzero); fHistReconstTrackMix->SetVarTitle(0,"Vzero(Asso) Eta"); fHistReconstTrackMix->SetVarTitle(1,"Vzero(Trigger) Eta"); fHistReconstTrackMix->SetVarTitle(2,"centrality"); fHistReconstTrackMix->SetVarTitle(3,"#Delta#phi"); }else if(fAnaMode=="ITSFMD" || fAnaMode=="ITSFMDC"){ Double_t binning_detaFMDITS[66]={ -6.6,-6.5,-6.4,-6.3,-6.2,-6.1,-6.0, -5.9,-5.8,-5.7,-5.6,-5.5,-5.4,-5.3,-5.2,-5.1,-5.0, -4.9,-4.8,-4.7,-4.6,-4.5,-4.4,-4.3,-4.2,-4.1,-4., -3.9,-3.8,-3.7,-3.6,-3.5,-3.4,-3.3,-3.2,-3.1,-3., -2.9,-2.8,-2.7,-2.6,-2.5,-2.4,-2.3,-2.2,-2.1,-2., -1.9,-1.8,-1.7,-1.6,-1.5,-1.4,-1.3,-1.2,-1.1,-1., -0.9,-0.8,-0.7,-0.6,-0.5,-0.4,-0.3,-0.2,-0.1}; Double_t binning_detaFMDCITS[50]={ 0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9, 1.0,1.1,1.2,1.3,1.4,1.5,1.6,1.7,1.8,1.9, 2.0,2.1,2.2,2.3,2.4,2.5,2.6,2.7,2.8,2.9, 3.0,3.1,3.2,3.3,3.4,3.5,3.6,3.7,3.8,3.9, 4.0,4.1,4.2,4.3,4.4,4.5,4.6,4.7,4.8,4.9, 5.0}; Double_t binning_dphi_itsfmd[37] = { -1.570796, -1.396263, -1.221730, -1.047198, -0.872665, -0.698132, -0.523599, -0.349066, -0.174533, 0.0, 0.174533, 0.349066, 0.523599, 0.698132, 0.872665, 1.047198, 1.221730, 1.396263, 1.570796, 1.745329, 1.919862, 2.094395, 2.268928, 2.443461, 2.617994, 2.792527, 2.967060, 3.141593, 3.316126, 3.490659, 3.665191, 3.839724, 4.014257, 4.188790, 4.363323, 4.537856, 4.712389}; Double_t binning_cent_its[8]={0.,5.,10.,20.,40.,60.,80.,100.}; Int_t nbinitsfmddeltaeta; Int_t nbinetafmd; if(fAnaMode=="ITSFMD"){ nbinitsfmddeltaeta=65; nbinetafmd=32; }else{// if(fAnaMode=="ITSFMDC"){ nbinitsfmddeltaeta=49; nbinetafmd=17; } const Int_t iTrackBin_tpcfmd[6]={nbinitsfmddeltaeta,7,nbinetafmd,36,20,6}; Double_t binning_zvx_fmdits[2]={-10,10}; // Double_t binning_itseta[19]={-1.7, -1.6, -1.4, -1.2, -1.0, -0.8, -0.6, -0.4, -0.2, 0.,0.2, 0.4, 0.6, 0.8, 1.0, 1.2, 1.4, 1.6, 1.7}; Double_t binning_itseta[7]={-1.7,-1.2,-0.6,0.,0.6,1.2,1.7}; fHistReconstTrack = new AliTHn("fHistReconstTrack", "fHistReconstTrack", nCFSteps, 6, iTrackBin_tpcfmd); if(fAnaMode=="ITSFMD") { fHistReconstTrack->SetBinLimits(0,binning_detaFMDITS); fHistReconstTrack->SetBinLimits(2,binning_etafmd); }else if(fAnaMode=="ITSFMDC") { fHistReconstTrack->SetBinLimits(0,binning_detaFMDCITS); fHistReconstTrack->SetBinLimits(2,binning_etafmdc); } fHistReconstTrack->SetBinLimits(1,binning_cent_its); fHistReconstTrack->SetBinLimits(3,binning_dphi_itsfmd); fHistReconstTrack->SetBinLimits(4,-10.,10.); fHistReconstTrack->SetBinLimits(5,binning_itseta); fHistReconstTrack->SetVarTitle(0,"#Delta#eta"); fHistReconstTrack->SetVarTitle(2,"FMD Eta"); fHistReconstTrack->SetVarTitle(1,"centrality"); fHistReconstTrack->SetVarTitle(3,"#Delta#phi"); fHistReconstTrack->SetVarTitle(4,"z vertex"); fHistReconstTrack->SetVarTitle(5,"ITS Eta"); fHistReconstTrackMix= new AliTHn("fHistReconstTrackMix", "fHistReconstTrackMix", nCFSteps, 6,iTrackBin_tpcfmd); if(fAnaMode=="ITSFMD") { fHistReconstTrackMix->SetBinLimits(0,binning_detaFMDITS); fHistReconstTrackMix->SetBinLimits(2,binning_etafmd); }else if(fAnaMode=="ITSFMDC") { fHistReconstTrackMix->SetBinLimits(0,binning_detaFMDCITS); fHistReconstTrackMix->SetBinLimits(2,binning_etafmdc); } fHistReconstTrackMix->SetBinLimits(1,binning_cent_its); fHistReconstTrackMix->SetBinLimits(3,binning_dphi_itsfmd); fHistReconstTrackMix->SetBinLimits(4,-10.,10.); fHistReconstTrackMix->SetBinLimits(5,binning_itseta); fHistReconstTrackMix->SetVarTitle(0,"#Delta#eta"); fHistReconstTrackMix->SetVarTitle(1,"centrality"); fHistReconstTrackMix->SetVarTitle(2,"FMD Eta"); fHistReconstTrackMix->SetVarTitle(3,"#Delta#phi"); fHistReconstTrackMix->SetVarTitle(4,"z vertex"); fHistReconstTrackMix->SetVarTitle(5,"ITS Eta"); } fOutputList1->Add(fHistReconstTrack); fOutputList1->Add(fHistReconstTrackMix); if(fAnaMode=="SP"){ fHistQna=new TH2D("fHistQna","fHistQna",200,0.,10.,10,0,100); fOutputList1->Add(fHistQna); fHistQnc=new TH2D("fHistQnc","fHistQnc",200,0.,10.,10,0,100); fOutputList1->Add(fHistQnc); fHistQn=new TH2D("fHistQn","fHistQn",200,0.,10.,10,0,100); fOutputList1->Add(fHistQn); fHistQna_VZERO=new TH2D("fHistQna_VZERO","fHistQna_VZERO",200,0.,10.,10,0,100); fOutputList1->Add(fHistQna_VZERO); fHistQnc_VZERO=new TH2D("fHistQnc_VZERO","fHistQnc_VZERO",200,0.,10.,10,0,100); fOutputList1->Add(fHistQnc_VZERO); fHistQn_VZERO=new TH2D("fHistQn_VZERO","fHistQn_VZERO",200,0.,10.,10,0,100); fOutputList1->Add(fHistQn_VZERO); fHistVn=new TH1D("fHistVn","fHistVn",200,-1.,1.); fOutputList1->Add(fHistVn); for(Int_t i=0;i<4;i++){ fHistQAQB[i]=new TH1D(Form("fHistQAQB_%d",i),Form("fHistQAQB_%d",i),400,-2.,2.); fOutputList1->Add(fHistQAQB[i]); fHistQAQB_VZERO[i]=new TH1D(Form("fHistQAQB_VZERO_%d",i),Form("fHistQAQB_VZERO_%d",i),400,-2.,2.); fOutputList1->Add(fHistQAQB_VZERO[i]); fHistCorrQna[i]=new TH2D(Form("fHistCorrQna_%d",i),"fHistCorrQna",200,0.,10.,200,0,10); fOutputList1->Add(fHistCorrQna[i]); fHistCorrQnc[i]=new TH2D(Form("fHistCorrQnc_%d",i),"fHistCorrQnc",200,0.,10.,200,0,10); fOutputList1->Add(fHistCorrQnc[i]); } Double_t binning_cent_QAQC[5]={0.,20.,40.,60.,100.}; SP_TPCATPCC = new TProfile("SP_TPCATPCC","QAQC",4,binning_cent_QAQC,-3,+3,"s"); fOutputList1->Add(SP_TPCATPCC); SP_TPCATPCC_default = new TProfile("SP_TPCATPCC_default","QAQC",4,binning_cent_QAQC,-3,+3); fOutputList1->Add(SP_TPCATPCC_default); SP_V0AV0C_default = new TProfile("SP_V0AV0C_default","QAQC",4,binning_cent_QAQC,-3,+3); fOutputList1->Add(SP_V0AV0C_default); SP_V0ATPC_default = new TProfile("SP_V0ATPC_default","QAQC",4,binning_cent_QAQC,-3,+3); fOutputList1->Add(SP_V0ATPC_default); SP_V0CTPC_default = new TProfile("SP_V0CTPC_default","QAQC",4,binning_cent_QAQC,-3,+3); fOutputList1->Add(SP_V0CTPC_default); fHist_V0AV0C = new TH1F("fHist_V0AV0C","QAQC",200,-1,1); fOutputList1->Add(fHist_V0AV0C); fHist_V0ATPC= new TH1F("fHist_V0ATPC","QAQC",200,-1,1); fOutputList1->Add(fHist_V0ATPC); fHist_V0CTPC = new TH1F("fHist_V0CTPC","QAQC",200,-1,1); fOutputList1->Add(fHist_V0CTPC); SP_uTPCA = new TProfile("SP_uTPCA","u x Q_{TPCA}",11,binning_pt_assoc,-3,+3); fOutputList1->Add(SP_uTPCA); SP_uTPCC = new TProfile("SP_uTPCC","u x Q_{TPCC}",11,binning_pt_assoc,-3,+3); fOutputList1->Add(SP_uTPCC); Int_t nbin_uTPC=11; Double_t binning_pt_assoc_uTPC[12] = {0.3, 0.5, 0.75, 1.0, 1.25, 1.5,2.0, 2.5, 3.0, 3.5, 4.0, 8.0}; Int_t nbin_uTPCPhi=4; Double_t binning_pt_assoc_uTPCPhi[5] = {0., 0.5, 2.0, 4.0, 8.0}; Int_t nbin_uTPCCas=3; Double_t binning_pt_assoc_uTPCCas[4] = {0., 1., 4., 8.}; for(Int_t i=0;i<8;i++){ SP_uVZEROA_PP[i] = new TProfile(Form("SP_uVZEROA_PP_%d",i),"u x Q_{TPC}",nbin_uTPC,binning_pt_assoc_uTPC,-3,+3); fOutputList1->Add(SP_uVZEROA_PP[i]); SP_uVZEROA[i] = new TProfile(Form("SP_uVZEROA_%d",i),"u x Q_{TPC}",nbin_uTPC,binning_pt_assoc_uTPC,-3,+3); fOutputList1->Add(SP_uVZEROA[i]); SP_uVZEROA1[i] = new TProfile(Form("SP_uVZEROA1_%d",i),"u x Q_{TPC}",nbin_uTPC,binning_pt_assoc_uTPC,-3,+3); fOutputList1->Add(SP_uVZEROA1[i]); SP_uVZEROA2[i] = new TProfile(Form("SP_uVZEROA2_%d",i),"u x Q_{TPC}",nbin_uTPC,binning_pt_assoc_uTPC,-3,+3); fOutputList1->Add(SP_uVZEROA2[i]); SP_uVZEROA3[i] = new TProfile(Form("SP_uVZEROA3_%d",i),"u x Q_{TPC}",nbin_uTPC,binning_pt_assoc_uTPC,-3,+3); fOutputList1->Add(SP_uVZEROA3[i]); SP_uVZEROC_PP[i] = new TProfile(Form("SP_uVZEROC_PP_%d",i),"u x Q_{TPC}",nbin_uTPC,binning_pt_assoc_uTPC,-3,+3); fOutputList1->Add(SP_uVZEROC_PP[i]); SP_uVZEROC[i] = new TProfile(Form("SP_uVZEROC_%d",i),"u x Q_{TPC}",nbin_uTPC,binning_pt_assoc_uTPC,-3,+3); fOutputList1->Add(SP_uVZEROC[i]); SP_uVZEROC1[i] = new TProfile(Form("SP_uVZEROC1_%d",i),"u x Q_{TPC}",nbin_uTPC,binning_pt_assoc_uTPC,-3,+3); fOutputList1->Add(SP_uVZEROC1[i]); SP_uVZEROC2[i] = new TProfile(Form("SP_uVZEROC2_%d",i),"u x Q_{TPC}",nbin_uTPC,binning_pt_assoc_uTPC,-3,+3); fOutputList1->Add(SP_uVZEROC2[i]); SP_uVZEROC3[i] = new TProfile(Form("SP_uVZEROC3_%d",i),"u x Q_{TPC}",nbin_uTPC,binning_pt_assoc_uTPC,-3,+3); fOutputList1->Add(SP_uVZEROC3[i]); } if(fasso=="PID" || fasso=="hadron" || fasso=="V0"){ for(Int_t i=0;i<8;i++){ SP_uTPC_PP[i] = new TProfile(Form("SP_uTPC_PP_%d",i),"u x Q_{TPC}",nbin_uTPC,binning_pt_assoc_uTPC,-3,+3); fOutputList1->Add(SP_uTPC_PP[i]); SP_uTPC[i] = new TProfile(Form("SP_uTPC_%d",i),"u x Q_{TPC}",nbin_uTPC,binning_pt_assoc_uTPC,-3,+3); fOutputList1->Add(SP_uTPC[i]); SP_uTPC1[i] = new TProfile(Form("SP_uTPC1_%d",i),"u x Q_{TPC}",nbin_uTPC,binning_pt_assoc_uTPC,-3,+3); fOutputList1->Add(SP_uTPC1[i]); SP_uTPC2[i] = new TProfile(Form("SP_uTPC2_%d",i),"u x Q_{TPC}",nbin_uTPC,binning_pt_assoc_uTPC,-3,+3); fOutputList1->Add(SP_uTPC2[i]); SP_uTPC3[i] = new TProfile(Form("SP_uTPC3_%d",i),"u x Q_{TPC}",nbin_uTPC,binning_pt_assoc_uTPC,-3,+3); fOutputList1->Add(SP_uTPC3[i]); } }else if(fasso=="Phi"){ for(Int_t i=0;i<8;i++){ SP_uTPC_PP[i] = new TProfile(Form("SP_uTPC_PP_%d",i),"u x Q_{TPC}",nbin_uTPC,binning_pt_assoc_uTPCPhi,-3,+3); fOutputList1->Add(SP_uTPC_PP[i]); SP_uTPC[i] = new TProfile(Form("SP_uTPC_%d",i),"u x Q_{TPC}",nbin_uTPCPhi,binning_pt_assoc_uTPCPhi,-3,+3); fOutputList1->Add(SP_uTPC[i]); SP_uTPC1[i] = new TProfile(Form("SP_uTPC1_%d",i),"u x Q_{TPC}",nbin_uTPCPhi,binning_pt_assoc_uTPCPhi,-3,+3); fOutputList1->Add(SP_uTPC1[i]); SP_uTPC2[i] = new TProfile(Form("SP_uTPC2_%d",i),"u x Q_{TPC}",nbin_uTPCPhi,binning_pt_assoc_uTPCPhi,-3,+3); fOutputList1->Add(SP_uTPC2[i]); SP_uTPC3[i] = new TProfile(Form("SP_uTPC3_%d",i),"u x Q_{TPC}",nbin_uTPCPhi,binning_pt_assoc_uTPCPhi,-3,+3); fOutputList1->Add(SP_uTPC3[i]); } }else if(fasso=="Cascade"){ for(Int_t i=0;i<8;i++){ SP_uTPC_PP[i] = new TProfile(Form("SP_uTPC_PP_%d",i),"u x Q_{TPC}",nbin_uTPC,binning_pt_assoc_uTPCCas,-3,+3); fOutputList1->Add(SP_uTPC_PP[i]); SP_uTPC[i] = new TProfile(Form("SP_uTPC_%d",i),"u x Q_{TPC}",nbin_uTPCCas,binning_pt_assoc_uTPCCas,-3,+3); fOutputList1->Add(SP_uTPC[i]); SP_uTPC1[i] = new TProfile(Form("SP_uTPC1_%d",i),"u x Q_{TPC}",nbin_uTPCCas,binning_pt_assoc_uTPCCas,-3,+3); fOutputList1->Add(SP_uTPC1[i]); SP_uTPC2[i] = new TProfile(Form("SP_uTPC2_%d",i),"u x Q_{TPC}",nbin_uTPCCas,binning_pt_assoc_uTPCCas,-3,+3); fOutputList1->Add(SP_uTPC2[i]); SP_uTPC3[i] = new TProfile(Form("SP_uTPC3_%d",i),"u x Q_{TPC}",nbin_uTPCCas,binning_pt_assoc_uTPCCas,-3,+3); fOutputList1->Add(SP_uTPC3[i]); } } } } void AliAnalysisTaskSEpPbCorrelationsYS::UserExec(Option_t *) { DumpTObjTable("Start analysis"); AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); AliInputEventHandler *inEvMain = (AliInputEventHandler *)(mgr->GetInputEventHandler()); if (!inEvMain) return; if(fasso!="hadron"){ fPIDResponse = inEvMain->GetPIDResponse(); if (!fPIDResponse) return; } if(!fDataType){ AliMCEventHandler* mctruth = (AliMCEventHandler*)(mgr->GetMCtruthEventHandler()); if(!mctruth) return; mcEvent=mctruth->MCEvent();//AliMCEvent } fEvent = dynamic_cast<AliAODEvent *>(inEvMain->GetEvent()); if (!fEvent) { AliWarning("ERROR: fEvent not available \n"); return; } fHist_Stat->Fill(0); if(fcollisiontype=="pPb" || fcollisiontype=="PP"|| fcollisiontype=="PbPb"){ if (!fEventCuts.AcceptEvent(fEvent)) { PostData(1, fOutputList); PostData(2, fOutputList1); PostData(3, fOutputList2); return; } }else if(fcollisiontype=="HMPPV0"){ UInt_t maskIsSelected = inEvMain->IsEventSelected(); Bool_t isSelected = kFALSE; isSelected = ((maskIsSelected & AliVEvent::kHighMultV0)== AliVEvent::kHighMultV0); if (!isSelected) { PostData(1, fOutputList); PostData(2, fOutputList1); PostData(3, fOutputList2); return; } }else if(fcollisiontype=="HMPPSPD"){ UInt_t maskIsSelected = inEvMain->IsEventSelected(); Bool_t isSelected = kFALSE; isSelected = ((maskIsSelected & AliVEvent::kHighMultSPD)== AliVEvent::kHighMultSPD); if (!isSelected) { PostData(1, fOutputList); PostData(2, fOutputList1); PostData(3, fOutputList2); return; } }else if (fcollisiontype.Contains("MBPP")){ UInt_t maskIsSelected = inEvMain->IsEventSelected(); Bool_t isSelected = kFALSE; isSelected = ((maskIsSelected & AliVEvent::kINT7)== AliVEvent::kINT7);//Both for data and if (!isSelected) { PostData(1, fOutputList); PostData(2, fOutputList1); PostData(3, fOutputList2); return; } } /*else if(fcollisiontype=="PbPb"){ //same way as Freja // Get the event validation object AliForwardTaskValidation* ev_val = dynamic_cast<AliForwardTaskValidation*>(this->GetInputData(1)); if (!ev_val->IsValidEvent()){ PostData(1, fOutputList); PostData(2, fOutputList1); PostData(3, fOutputList2); return; } } */ /* //Vertex Bool_t IsGoodVtx=kFALSE; Bool_t IsValidVtx=kFALSE; const AliVVertex* spdVtx = fEvent->GetPrimaryVertexSPD() ; if( spdVtx ){ if( spdVtx->GetNContributors() > 0.5 ) IsValidVtx = kTRUE; auto fZ = spdVtx->GetZ(); auto zbin = binZ.FindBin(fZ) -1; if( fabs(fZ) < 10 && !(zbin < 0 )) IsGoodVtx = kTRUE; } if(!IsGoodVtx || !IsValidVtx){ PostData(1, fOutputList); PostData(2, fOutputList1); PostData(3, fOutputList2); return; } */ //Pile up if(fcollisiontype.Contains("MBPP") || fcollisiontype.Contains("HMPP")){ Bool_t IsNotPileup = kFALSE; if( !fEvent->IsPileupFromSPDInMultBins() ) IsNotPileup = kTRUE; if(!IsNotPileup){ PostData(1, fOutputList); PostData(2, fOutputList1); PostData(3, fOutputList2); return; } fHist_Stat->Fill(8); } fHist_Stat->Fill(1); AliMultSelection *multSelection = (AliMultSelection *)fEvent->FindListObject("MultSelection"); if(!multSelection) return; fHist_Stat->Fill(2); //Pileu rejection by MultSelection if(fcollisiontype.Contains("HMPP") || fcollisiontype.Contains("MBPP")){ Bool_t IsSelectedFromAliMultSelection=kFALSE; if( multSelection->GetThisEventIsNotPileup() && multSelection->GetThisEventIsNotPileupInMultBins() && multSelection->GetThisEventHasNoInconsistentVertices() && multSelection->GetThisEventPassesTrackletVsCluster() ){ IsSelectedFromAliMultSelection = kTRUE; } if(!IsSelectedFromAliMultSelection) { PostData(1, fOutputList); PostData(2, fOutputList1); PostData(3, fOutputList2); return; } fHist_Stat->Fill(9); } // if(fcollisiontype.Contains("HMPP")AliMultSelectionTask::SetHighMultQABinning(kTRUE); lPrimaryBestVtx = fEvent->GetPrimaryVertex(); if(fcollisiontype.Contains("HMPP") || fcollisiontype.Contains("MBPP")){ Int_t nTracksPrim = lPrimaryBestVtx->GetNContributors(); if (nTracksPrim < 0.5) { PostData(1, fOutputList); PostData(2, fOutputList1); PostData(3, fOutputList2); return; } fHist_Stat->Fill(10); } if ((TMath::Abs(lPrimaryBestVtx->GetZ())) >= fZVertex) { PostData(1, fOutputList); PostData(2, fOutputList1); PostData(3, fOutputList2); return; } tPrimaryVtxPosition[0] = lPrimaryBestVtx->GetX(); tPrimaryVtxPosition[1] = lPrimaryBestVtx->GetY(); tPrimaryVtxPosition[2] = lPrimaryBestVtx->GetZ(); fPrimaryZVtx = lPrimaryBestVtx->GetZ(); fHist_Stat->Fill(3); bSign = 0.; bSign = (InputEvent()->GetMagneticField() > 0) ? 1 : -1; /* AliVMultiplicity *tracklets = ((AliAODEvent*)fEvent)->GetTracklets(); if (!tracklets) return; Int_t nTracklets = tracklets->GetNumberOfTracklets(); */ // Multiplicity Object if(fcollisiontype=="HMPPSPD" && fcuthighmult>0){ AliVMultiplicity *tracklets = ((AliAODEvent*)fEvent)->GetTracklets(); // if (!tracklets) return; Int_t nTracklets = tracklets->GetNumberOfTracklets(); Int_t nITScluster= tracklets->GetNumberOfITSClusters(0)+tracklets->GetNumberOfITSClusters(1); Int_t nTracks = fEvent->GetNumberOfTracks(); fh2_SPD_multcorr->Fill(nTracklets,nITScluster); fh2_SPDtrack_multcorr->Fill(nTracklets,nTracks); if(nTracklets<fcuthighmult){ PostData(1, fOutputList); PostData(2, fOutputList1); PostData(3, fOutputList2); return; } } if(fcollisiontype=="HMPPV0" && fcuthighmult>0){ Double_t fCentrality = multSelection->GetMultiplicityPercentile("V0M"); if(fCentrality>fcuthighmult){ PostData(1, fOutputList); PostData(2, fOutputList1); PostData(3, fOutputList2); return; } } if(fCentType=="Manual"){ TObjArray *selectedTracksLeading = new TObjArray; selectedTracksLeading->SetOwner(kTRUE); selectedTracksLeading=GetAcceptedTracksLeading(fEvent,kFALSE,selectedTracksLeading); Int_t nTracks=selectedTracksLeading->GetEntriesFast(); lCentrality=nTracks; selectedTracksLeading->Clear(); delete selectedTracksLeading; }else{ lCentrality = multSelection->GetMultiplicityPercentile(fCentType); Int_t qual = multSelection->GetEvSelCode(); if (qual == 199) lCentrality = -999; if (lCentrality < 0. || lCentrality > 100. - 0.0000001) return; } Double_t *CentBins = fCentBins; poolmin = CentBins[0]; poolmax = CentBins[fNCentBins]; fHist_Stat->Fill(4); // fHistCentV0vsTrackletsbefore->Fill(lCentrality,nTracklets); /* fUtils=new AliAnalysisUtils; //if(fcollisiontype=="pp") if(fUtils->IsPileUpSPD(fEvent)) return; if(fUtils->IsPileUpMV(fEvent)) return; //if(fUtils->IsPileUpSPD(fEvent)) return; // if(fEvent->IsPileupFromSPD(5,0.8,3.,2.,5.)) return; // SPD vertex selection const AliAODVertex* vtxSPD = dynamic_cast<const AliAODVertex*>(fEvent->GetPrimaryVertexSPD()); Double_t cov[6] = {0}; vtxSPD->GetCovarianceMatrix(cov); Double_t zRes = TMath::Sqrt(cov[5]); if ( vtxSPD->IsFromVertexerZ() && (zRes > dMaxResol)) return; fHist_Stat->Fill(6); */ /* if(fcollisiontype=="PbPb"){ if(!NotSPDClusterVsTrackletBG()) { PostData(1, fOutputList); PostData(2, fOutputList1); PostData(3, fOutputList2); return; } fHist_Stat->Fill(12); } */ fHistCentrality_beforecut->Fill(lCentrality); // fHist_Stat->Fill(5); DumpTObjTable("After event selection"); MakeAna(); PostData(1, fOutputList); PostData(2, fOutputList1); PostData(3, fOutputList2); } void AliAnalysisTaskSEpPbCorrelationsYS::Terminate(Option_t *) { // AliInfo(Form("Number of Correlation DumpTObjTable("End of the analysis"); Printf("Entries======================%d",fNEntries); if (fPoolMgr) delete fPoolMgr; // PoolMgr->ClearPools(); if (fPoolMgr1) delete fPoolMgr1; // fPoolMgr1->ClearPools(); } void AliAnalysisTaskSEpPbCorrelationsYS::MakeAna() { DumpTObjTable("start correlation analysis"); fvzero = fEvent->GetVZEROData(); if(!fvzero){ PostData(1, fOutputList); PostData(2, fOutputList1); PostData(3, fOutputList2); return; } Double_t eta_min; Double_t eta_max; Double_t eta_ave; Double_t phi_vzero; Double_t mult_vzero; Double_t mult_vzero_eq; Float_t nV0A_hits_fmdacc=0; Float_t nV0C_hits_fmdacc=0; for (Int_t imod = 0; imod < 64; imod++) { eta_min = fvzero->GetVZEROEtaMin(imod); eta_max = fvzero->GetVZEROEtaMax(imod); phi_vzero = fvzero->GetVZEROAvgPhi(imod); mult_vzero = fvzero->GetMultiplicity(imod); mult_vzero_eq = fEvent->GetVZEROEqMultiplicity(imod); eta_ave = (eta_min + eta_max) / 2.; if(eta_ave>2.8 && eta_ave<5.03) nV0A_hits_fmdacc+=mult_vzero_eq; else if(eta_ave>-3.4 && eta_ave<-2.01) nV0C_hits_fmdacc+=mult_vzero_eq; fHist_vzeromult->Fill(imod, mult_vzero); fHist_vzeromultEqweighted->Fill(imod, mult_vzero_eq); fHist2dmult->Fill(imod, mult_vzero_eq, mult_vzero); } Float_t nFMD_fwd_hits=0; Float_t nFMD_bwd_hits=0; Float_t nFMD_fwdV0acc_hits=0; Float_t nFMD_bwdV0acc_hits=0; AliAODForwardMult*aodForward=static_cast<AliAODForwardMult*>(fEvent->FindListObject("Forward")); if(!aodForward) {//HasFMD PostData(1, fOutputList); PostData(2, fOutputList1); PostData(3, fOutputList2); return; } fHist_Stat->Fill(5); // Shape of d2Ndetadphi: 200, -4, 6, 20, 0, 2pi TH2D& d2Ndetadphi = aodForward->GetHistogram(); TH1*hphiacceptance=aodForward->GetPhiAcceptance(); Int_t nEta = d2Ndetadphi.GetXaxis()->GetNbins(); Int_t nPhi = d2Ndetadphi.GetYaxis()->GetNbins(); Double_t pt = 0; for (Int_t iEta = 1; iEta <= nEta; iEta++) { Int_t valid = Int_t(d2Ndetadphi.GetBinContent(iEta, 0)); if (!valid) { continue; } Float_t eta = d2Ndetadphi.GetXaxis()->GetBinCenter(iEta); Float_t phiacc=hphiacceptance->GetBinContent(iEta); fhistfmdphiacc->Fill(eta,lCentrality,phiacc); for (Int_t iPhi = 1; iPhi <= nPhi; iPhi++) { // Bin content is most likely number of particles! Float_t phi = d2Ndetadphi.GetYaxis()->GetBinCenter(iPhi); Float_t mostProbableN = d2Ndetadphi.GetBinContent(iEta, iPhi); fh2_FMD_acceptance->Fill(eta,tPrimaryVtxPosition[2],mostProbableN); if (mostProbableN > 0) { if(eta>0){ nFMD_fwd_hits+=mostProbableN; if(2.8<eta && eta<5.03) nFMD_fwdV0acc_hits+=mostProbableN; }else{ nFMD_bwd_hits+=mostProbableN; if(-3.4<eta && eta<-2.01) nFMD_bwdV0acc_hits+=mostProbableN; } fh2_FMD_eta_phi->Fill(eta,phi,mostProbableN); } } } Float_t nV0A_hits = fvzero->GetMTotV0A(); Float_t nV0C_hits = fvzero->GetMTotV0C(); if(nFMD_fwd_hits==0 || nFMD_bwd_hits==0){ delete hphiacceptance; PostData(1, fOutputList); PostData(2, fOutputList1); PostData(3, fOutputList2); return; } fHist_Stat->Fill(6); fFMDV0->Fill(nFMD_bwd_hits + nFMD_fwd_hits, nV0C_hits + nV0A_hits); fFMDV0A->Fill(nFMD_fwd_hits, nV0A_hits); fFMDV0C->Fill(nFMD_bwd_hits, nV0C_hits); fFMDV0same->Fill(nFMD_bwdV0acc_hits + nFMD_fwdV0acc_hits, nV0C_hits_fmdacc + nV0A_hits_fmdacc); fFMDV0Asame->Fill(nFMD_fwdV0acc_hits, nV0A_hits_fmdacc); fFMDV0Csame->Fill(nFMD_bwdV0acc_hits, nV0C_hits_fmdacc); if(fFMDaddcut && (fcollisiontype.Contains("HMPP")||fcollisiontype=="MBPP")){ if(!HasValidFMDYS(d2Ndetadphi)){ delete hphiacceptance; PostData(1, fOutputList); PostData(2, fOutputList1); PostData(3, fOutputList2); return; } fHist_Stat->Fill(11); } if(fCentType=="Manual")fh2_SPDV0_multcorr->Fill(lCentrality,nV0C_hits+nV0A_hits); /* fHist_NeventRun->Fill(ConvertRunNumber(fEvent->GetRunNumber())); fHist_V0AMultRun->Fill(ConvertRunNumber(fEvent->GetRunNumber()),nV0A_hits); fHist_V0CMultRun->Fill(ConvertRunNumber(fEvent->GetRunNumber()),nV0C_hits); fHist_FMDAMultRun->Fill(ConvertRunNumber(fEvent->GetRunNumber()),nFMD_fwd_hits); fHist_FMDCMultRun->Fill(ConvertRunNumber(fEvent->GetRunNumber()),nFMD_bwd_hits); */ if(fFMDcut){ Double_t FMDcutapar0=0.; Double_t FMDcutapar1=0.; Double_t FMDcutcpar0=0.; Double_t FMDcutcpar1=0.; switch(fFMDcutmode){ case 1: FMDcutapar0=1.3; FMDcutapar1=200; FMDcutcpar0=2.; FMDcutcpar1=200; break; case 2: FMDcutapar0=1.3; FMDcutapar1=600; FMDcutcpar0=2.; FMDcutcpar1=600; break; case 3: FMDcutapar0=1.5; FMDcutapar1=100; FMDcutcpar0=2.3; FMDcutcpar1=100; break; case 4: FMDcutapar0=1.5; FMDcutapar1=300; FMDcutcpar0=2.3; FMDcutcpar1=300; break; case 5: FMDcutapar0=1.3; FMDcutapar1=400; FMDcutcpar0=2.; FMDcutcpar1=400; break; case 6: FMDcutapar0=1.75; FMDcutapar1=150; FMDcutcpar0=1.4; FMDcutcpar1=120; break; case 7: FMDcutapar0=1.64755; FMDcutapar1=119.602; FMDcutcpar0=2.73426; FMDcutcpar1=150.31; break; case 8: FMDcutapar0=1.64755; FMDcutapar1=159.47; FMDcutcpar0=2.73426; FMDcutcpar1=200.413; break; case 9: FMDcutapar0=1.2031; FMDcutapar1=73.123; FMDcutcpar0=2.25453; FMDcutcpar1=104.941; break; case 10: FMDcutapar0=1.2031; FMDcutapar1=97.4973; FMDcutcpar0=2.25453; FMDcutcpar1=139.921; break; case 11://pp 2 sigma cut FMDcutapar0=1.2031; FMDcutapar1=48.7486; FMDcutcpar0=2.25453; FMDcutcpar1=69.9606; break; case 12://Pbp 2 sigma cut old FMDcutapar0=1.64755; FMDcutapar1=79.7346; FMDcutcpar0=2.73426; FMDcutcpar1=100.20667; break; case 13://pPb 1 sigma cut FMDcutapar0=1.64755; FMDcutapar1=40.907; FMDcutcpar0=2.73426; FMDcutcpar1=36.5323; break; case 14://pPb 2 sigma cut FMDcutapar0=1.64755; FMDcutapar1=80.7744; FMDcutcpar0=2.73426; FMDcutcpar1=86.6355; break; case 15://pPb 2 sigma cut FMDcutapar0=1.64755; FMDcutapar1=80.7744; FMDcutcpar0=2.73426; FMDcutcpar1=86.6355; break; case 16://PbPb 3sigma cut FMDcutapar0=1.26713; FMDcutapar1=211.719; FMDcutcpar0=2.47928; FMDcutcpar1=250.645; break; case 17://PbPb 4sigma cut FMDcutapar0=1.26713; FMDcutapar1=274.066; FMDcutcpar0=2.47928; FMDcutcpar1=338.14; break; default: break; } if(fcollisiontype=="PbPb" && fFMDcutmode<16) { if ((nV0A_hits_fmdacc + nV0C_hits_fmdacc) < 1.5*(nFMD_fwdV0acc_hits + nFMD_bwdV0acc_hits) - 20) { // if ((nV0A_hits_fmdacc < FMDcutapar0*nFMD_fwdV0acc_hits-FMDcutapar1)||(nV0C_hits_fmdacc<FMDcutcpar0*nFMD_bwdV0acc_hits-FMDcutcpar1) ){ delete hphiacceptance; PostData(1, fOutputList); PostData(2, fOutputList1); PostData(3, fOutputList2); return; } } else{ if((nV0A_hits<(FMDcutapar0*nFMD_fwd_hits-FMDcutapar1)) || (nV0C_hits<(FMDcutcpar0*nFMD_bwd_hits-FMDcutcpar1)) ){ delete hphiacceptance; PostData(1, fOutputList); PostData(2, fOutputList1); PostData(3, fOutputList2); return; } } } fHist_Stat->Fill(7); DumpTObjTable("End of FMD vs V0 cuts"); fFMDV0_post->Fill(nFMD_bwd_hits + nFMD_fwd_hits, nV0C_hits + nV0A_hits); fFMDV0A_post->Fill(nFMD_fwd_hits, nV0A_hits); fFMDV0C_post->Fill(nFMD_bwd_hits, nV0C_hits); fFMDV0same_post->Fill(nFMD_bwdV0acc_hits + nFMD_fwdV0acc_hits, nV0C_hits_fmdacc + nV0A_hits_fmdacc); fFMDV0Asame_post->Fill(nFMD_fwdV0acc_hits, nV0A_hits_fmdacc); fFMDV0Csame_post->Fill(nFMD_bwdV0acc_hits, nV0C_hits_fmdacc); TObjArray *selectedTracksLeading = new TObjArray; selectedTracksLeading->SetOwner(kTRUE); TObjArray *selectedTracksAssociated = new TObjArray; selectedTracksAssociated->SetOwner(kTRUE); for (Int_t iEta = 1; iEta <= nEta; iEta++) { Int_t valid = Int_t(d2Ndetadphi.GetBinContent(iEta, 0)); if (!valid) { continue; } Float_t eta = d2Ndetadphi.GetXaxis()->GetBinCenter(iEta); Float_t phiacc=hphiacceptance->GetBinContent(iEta); fhistfmdphiacc->Fill(eta,lCentrality,phiacc); for (Int_t iPhi = 1; iPhi <= nPhi; iPhi++) { // Bin content is most likely number of particles! Float_t phi = d2Ndetadphi.GetYaxis()->GetBinCenter(iPhi); Float_t mostProbableN = d2Ndetadphi.GetBinContent(iEta, iPhi); if(fmakehole){ if((eta>-2.9 && eta<-2.7) && (5*2*TMath::Pi()/20.<phi && 7*2*TMath::Pi()/20.>phi)) continue; if((eta>-2.7 && eta<-2.5) && (1*2*TMath::Pi()/20.<phi && 2*2*TMath::Pi()/20.>phi)) continue; if((eta>-2.1 && eta<-1.9) && (17*2*TMath::Pi()/20.<phi && 20*2*TMath::Pi()/20.>phi)) continue; } if (mostProbableN > 0) { if(eta>0){ Int_t nfmdetabin1=frefetaa->FindBin(eta); if(fAnaMode=="TPCFMD" || fAnaMode=="ITSFMD") selectedTracksAssociated->Add(new AliAssociatedTrackYS(-999,eta,phi,-999,-999,-999,-999,-999,mostProbableN)); else if(fAnaMode=="FMDFMD") selectedTracksLeading->Add(new AliAssociatedTrackYS(-999,eta,phi,-999,-999,-999,-999,-999,mostProbableN)); else if(fAnaMode=="FMDFMD_Ctrig") selectedTracksAssociated->Add(new AliAssociatedTrackYS(-999,eta,phi,-999,-999,-999,-999,-999,mostProbableN)); }else if(eta<0){ Int_t nfmdetabin=frefetac->FindBin(eta); if(fAnaMode=="TPCFMDC" || fAnaMode=="ITSFMDC" ||fAnaMode=="FMDFMD") selectedTracksAssociated->Add(new AliAssociatedTrackYS(-999,eta,phi,-999,-999,-999,-999,-999,mostProbableN)); else if(fAnaMode=="FMDFMD_Ctrig") selectedTracksLeading->Add(new AliAssociatedTrackYS(-999,eta,phi,-999,-999,-999,-999,-999,mostProbableN)); } fhFMDmultchannel->Fill(eta,mostProbableN); Double_t cont[4]={eta,phi,lCentrality,fPrimaryZVtx}; fhistfmd->Fill(cont,0,mostProbableN); fh2_FMD_eta_phi_aftercut->Fill(eta,phi,mostProbableN); } } } if(hphiacceptance) delete hphiacceptance; Double_t vzeroqa[3]; for (Int_t imod = 0; imod < 64; imod++) { eta_min = fvzero->GetVZEROEtaMin(imod); eta_max = fvzero->GetVZEROEtaMax(imod); phi_vzero = fvzero->GetVZEROAvgPhi(imod); mult_vzero = fvzero->GetMultiplicity(imod); mult_vzero_eq = fEvent->GetVZEROEqMultiplicity(imod); eta_ave = (eta_min + eta_max) / 2.; vzeroqa[0] = eta_ave; vzeroqa[1] = phi_vzero; vzeroqa[2] = lCentrality; fHistVZERO->Fill(vzeroqa, 0, (Double_t)mult_vzero_eq); } DumpTObjTable("End of fill fmd tracks"); fHistCentrality->Fill(lCentrality); fHistzvertex->Fill(tPrimaryVtxPosition[2]); fHistCentzvertex->Fill(lCentrality, tPrimaryVtxPosition[2]); fHistCentvsNv0mult->Fill(lCentrality,nV0A_hits+nV0C_hits); if(fAnaMode=="TPCTPC"){ if(fasso=="hadron") selectedTracksAssociated=GetAcceptedTracksLeading(fEvent,kFALSE,selectedTracksAssociated); else if (fasso == "Phi") selectedTracksAssociated = GetAcceptedTracksAssociated(fEvent); else if (fasso == "V0") selectedTracksAssociated = GetAcceptedV0Tracks(fEvent); else if (fasso == "PID") selectedTracksAssociated = GetAcceptedTracksPID(fEvent); else if (fasso == "Cascade") selectedTracksAssociated = GetAcceptedCascadeTracks(fEvent); } // Leading Particle if(fAnaMode=="TPCFMD" || fAnaMode=="TPCTPC" || fAnaMode=="TPCFMDC"){ selectedTracksLeading=GetAcceptedTracksLeading(fEvent,kTRUE,selectedTracksLeading); }else if(fAnaMode=="ITSFMD" || fAnaMode=="ITSFMDC"){ // AliVMultiplicity *tracklets = ((AliAODEvent*)fEvent)->GetTracklets(); // if (!tracklets) return; // Int_t nTracklets = tracklets->GetNumberOfTracklets(); AliVMultiplicity *tracklets = ((AliAODEvent*)fEvent)->GetTracklets(); if (!tracklets) return; Int_t nTracklets = tracklets->GetNumberOfTracklets(); Int_t nITScluster= tracklets->GetNumberOfITSClusters(0)+tracklets->GetNumberOfITSClusters(1); Int_t nTracks = fEvent->GetNumberOfTracks(); // fh2_SPD_multcorr->Fill(nTracklets,nITScluster); // fh2_SPDV0_multcorr->Fill(nTracklets,fvzero->GetMTotV0A()+fvzero->GetMTotV0C()); fh2_SPDtrack_multcorr->Fill(nTracklets,nTracks); for (Int_t i = 0; i < nTracklets; i++) { Double_t dphi = tracklets->GetDeltaPhi(i); fhtrackletsdphi->Fill(1000*dphi); if (TMath::Abs(dphi) * 1000 > 5.) { continue; } Double_t theta = tracklets->GetTheta(i); Double_t etaits = -TMath::Log(TMath::Tan(theta/2)); Double_t etalow=log(7.6)-log(sqrt((-13.8-fPrimaryZVtx)*(-13.8-fPrimaryZVtx)+7.6*7.6)-(-13.8-fPrimaryZVtx)); Double_t etahigh=log(7.6)-log(sqrt((14.4-fPrimaryZVtx)*(14.4-fPrimaryZVtx)+7.6*7.6)-(14.4-fPrimaryZVtx)); if(etaits<etalow || etaits>etahigh) continue; if (etaits < -1.7 || etaits > 1.7) { continue; } Double_t phiits = tracklets->GetPhi(i); phiits+=dphi*39./34.;//same value as Cvetan's analysis if (phiits<0) phiits+=TMath::TwoPi(); if (phiits>TMath::TwoPi()) phiits-=TMath::TwoPi(); fh2_ITS_acceptance->Fill(tPrimaryVtxPosition[2],etaits); Double_t itsqa[4]={etaits,phiits,lCentrality,tPrimaryVtxPosition[2]}; // fhistits->Fill(itsqa); selectedTracksLeading->Add(new AliAssociatedTrackYS(-999, etaits, phiits, -999, 0, -999,-999, 0, 1)); } } Int_t nTracks; if(fAnaMode!="FMDFMD") { nTracks=selectedTracksLeading->GetEntriesFast(); // else nTracks= fEvent->GetNumberOfTracks(); fHistCentV0vsTracklets->Fill(lCentrality,nTracks); fHistV0vsTracks->Fill(nV0C_hits+nV0A_hits,nTracks); fHistTraksvsVz->Fill(fPrimaryZVtx,nTracks); fHistV0multvsVz->Fill(fPrimaryZVtx,nV0C_hits+nV0A_hits); } DumpTObjTable("End of TPC/ITS track fill"); if(ffillcorrelation){ FillCorrelationTracks(lCentrality,selectedTracksLeading,selectedTracksAssociated,fHistTriggerTrack,fHistReconstTrack,kFALSE,0.02,0.8,bSign,0); FillCorrelationTracksMixing(lCentrality,lPrimaryBestVtx->GetZ(),poolmax,poolmin,selectedTracksLeading,selectedTracksAssociated,fHistTriggerTrackMix,fHistReconstTrackMix,kFALSE,0.02,0.8,bSign,0); } DumpTObjTable("End of fill Correlation"); selectedTracksLeading->Clear(); delete selectedTracksLeading; selectedTracksAssociated->Clear(); delete selectedTracksAssociated; DumpTObjTable("after delete TObjects"); fNEntries++; } TObjArray* AliAnalysisTaskSEpPbCorrelationsYS::GetFMDhitsYS(Bool_t Aside){ TObjArray *tracks1 = new TObjArray; tracks1->SetOwner(kTRUE); AliAODForwardMult* aodForward =static_cast<AliAODForwardMult*>(fEvent->FindListObject("Forward")); // Shape of d2Ndetadphi: 200, -4, 6, q20, 0, 2pi const TH2D& d2Ndetadphi = aodForward->GetHistogram(); Int_t nEta = d2Ndetadphi.GetXaxis()->GetNbins(); Int_t nPhi = d2Ndetadphi.GetYaxis()->GetNbins(); //AliAnalysisTaskValidation::Tracks ret_vector; // FMD has no pt resolution! Float_t pt = 0; for (Int_t iEta = 1; iEta <= nEta; iEta++) { Int_t valid = Int_t(d2Ndetadphi.GetBinContent(iEta, 0)); if (!valid) { // No data expected for this eta continue; } Float_t eta = d2Ndetadphi.GetXaxis()->GetBinCenter(iEta); for (Int_t iPhi = 1; iPhi <= nPhi; iPhi++) { // Bin content is most likely number of particles! Float_t mostProbableN = d2Ndetadphi.GetBinContent(iEta, iPhi); if (mostProbableN > 0) { Float_t phi = d2Ndetadphi.GetYaxis()->GetBinCenter(iPhi); if(Aside){ if(eta<0) continue; } else{ if(eta>0) continue; } tracks1->Add(new AliAssociatedVZEROYS(mostProbableN,eta,phi,0,0,0)); Double_t cont[3]={eta,phi,lCentrality}; fhistfmd->Fill(cont,0,mostProbableN); fh2_FMD_acceptance->Fill(eta,tPrimaryVtxPosition[2]); fh2_FMD_eta_phi->Fill(eta,phi,mostProbableN); } } } /* TObjArray *tracks1 = new TObjArray; tracks1->SetOwner(kTRUE); Int_t i=0; for (auto const &track: ret_vector) { //cout<<i<<" "<<track.eta<<" "<<track.phi<<" "<<track.weight<<endl; if(Aside==kTRUE){ if(track.eta>0) tracks1->Add(new AliAssociatedVZEROYS(track.eta,track.phi,track.weight,0,0,0)); } else{ if(track.eta<0) tracks1->Add(new AliAssociatedVZEROYS(track.eta,track.phi,track.weight,0,0,0)); } i++; } */ return tracks1; // std::random_device rd; // std::default_random_engine engine{rd()}; // std::shuffle(std::begin(ret_vector), std::end(ret_vector), engine); // return ret_vector; } void AliAnalysisTaskSEpPbCorrelationsYS::CalculateSP(){ /* //Scalar Product Int_t fHarmonic=2; Double_t fQTPCCCos,fQTPCCSin,fQTPCC; Double_t fQTPCACos,fQTPCASin,fQTPCA; Double_t fQTPCCos,fQTPCSin,fQTPC; Double_t fQTPCCCosArray[3],fQTPCCSinArray[3]; Double_t fQTPCACosArray[3],fQTPCASinArray[3]; fQTPCCCos=0; fQTPCCSin=0; fQTPCC=0; fQTPCACos=0; fQTPCASin=0; fQTPCA=0; fQTPCCos=0; fQTPCSin=0; fQTPC=0; for(Int_t i=0;i<selectedTracksLeading->GetEntriesFast();i++){ AliAssociatedTrackYS* trackRP=(AliAssociatedTrackYS*)selectedTracksLeading->At(i); if(!trackRP) continue; Double_t phiRP=trackRP->Phi(); Double_t ptRP=trackRP->Pt(); Double_t etaRP=trackRP->Eta(); Double_t w=1.; fQTPCCos+=w*TMath::Cos(fHarmonic*phiRP); fQTPCSin+=w*TMath::Sin(fHarmonic*phiRP); fQTPC+=w; if(etaRP<0.4 && etaRP>-0.4) continue; if(etaRP<0){ fQTPCCCos+=w*TMath::Cos(fHarmonic*phiRP); fQTPCCSin+=w*TMath::Sin(fHarmonic*phiRP); fQTPCC+=w; }else{ fQTPCACos+=w*TMath::Cos(fHarmonic*phiRP); fQTPCASin+=w*TMath::Sin(fHarmonic*phiRP); fQTPCA+=w; } if(etaRP<0) { fQTPCCCosArray[0]=fQTPCCCos; fQTPCCSinArray[0]=fQTPCCSin; } if(etaRP>0) { fQTPCACosArray[0]=fQTPCACos; fQTPCASinArray[0]=fQTPCASin; } if(etaRP<-0.4) { fQTPCCCosArray[1]=fQTPCCCos; fQTPCCSinArray[1]=fQTPCCSin; } if(etaRP>0.4) { fQTPCACosArray[1]=fQTPCACos; fQTPCASinArray[1]=fQTPCASin; } } Double_t tpc_qmcos=fQTPCCos/fQTPC; Double_t tpc_qmsin=fQTPCSin/fQTPC; Double_t tpcc_qmcos=fQTPCCCos/fQTPCC; Double_t tpcc_qmsin=fQTPCCSin/fQTPCC; Double_t tpca_qmcos=fQTPCACos/fQTPCA; Double_t tpca_qmsin=fQTPCASin/fQTPCA; Double_t qna=TMath::Sqrt((fQTPCACos*fQTPCACos+fQTPCASin*fQTPCASin)/fQTPCA); if(fQTPCA>1)fHistQna->Fill(qna,lCentrality); Double_t qnc=TMath::Sqrt((fQTPCCCos*fQTPCCCos+fQTPCCSin*fQTPCCSin)/fQTPCC); if(fQTPCC>1)fHistQnc->Fill(qnc,lCentrality); Double_t qn=TMath::Sqrt((fQTPCCos*fQTPCCos+fQTPCSin*fQTPCSin)/fQTPC); if(fQTPC>1)fHistQn->Fill(qn,lCentrality); // cout<<fQTPCCos<<" "<<fQTPCSin<<" "<<fQTPC<<" "<<qn<<endl; Double_t qaqc=tpca_qmcos*tpcc_qmcos+tpca_qmsin*tpcc_qmsin;//Q_a*Q_b/(M_a*M_b) //Double_t qaqcsqrt=TMath::Sqrt(tpca_qmcos*tpcc_qmcos+tpca_qmsin*tpcc_qmsin);//Q_a*Q_b/(M_a*M_b) if(fQTPCC>0 && fQTPCA>0) { fHistVn->Fill(qaqc); if(lCentrality>=0. && lCentrality<20.) fHistQAQB[0]->Fill(qaqc); if(lCentrality>=20. && lCentrality<40.) fHistQAQB[1]->Fill(qaqc); if(lCentrality>=40. && lCentrality<60.) fHistQAQB[2]->Fill(qaqc); if(lCentrality>=60. && lCentrality<100.) fHistQAQB[3]->Fill(qaqc); SP_TPCATPCC->Fill(lCentrality,qaqc); SP_TPCATPCC_default->Fill(lCentrality,qaqc); } //VZERO fvzero = fEvent->GetVZEROData(); Double_t eta_min; Double_t eta_max; Double_t eta_ave; Double_t phi_vzero; Double_t mult_vzero; Double_t vzeroqa[3]; Double_t mult_vzero_eq; Double_t fQVZEROCCos,fQVZEROCSin,fQVZEROC; Double_t fQVZEROACos,fQVZEROASin,fQVZEROA; Double_t fQVZEROCos,fQVZEROSin,fQVZERO; fQVZEROCCos=0; fQVZEROCSin=0; fQVZEROC=0; fQVZEROACos=0; fQVZEROASin=0; fQVZEROA=0; fQVZEROCos=0; fQVZEROSin=0; fQVZERO=0; for (Int_t imod = 0; imod < 64; imod++) { eta_min = fvzero->GetVZEROEtaMin(imod); eta_max = fvzero->GetVZEROEtaMax(imod); phi_vzero = fvzero->GetVZEROAvgPhi(imod); mult_vzero = fvzero->GetMultiplicity(imod); mult_vzero_eq = fEvent->GetVZEROEqMultiplicity(imod); eta_ave = (eta_min + eta_max) / 2.; fHist_vzeromult->Fill(imod, mult_vzero); fHist_vzeromultEqweighted->Fill(imod, mult_vzero_eq); fHist2dmult->Fill(imod, mult_vzero_eq, mult_vzero); vzeroqa[0] = eta_ave; vzeroqa[1] = phi_vzero; vzeroqa[2] = lCentrality; if (fQA) fHistVZERO->Fill(vzeroqa, 0, (Double_t)mult_vzero_eq); Double_t phiRPVZERO=phi_vzero; Double_t etaRPVZERO=eta_ave; Double_t w=mult_vzero; fQVZEROCos+=w*TMath::Cos(fHarmonic*phiRPVZERO); fQVZEROSin+=w*TMath::Sin(fHarmonic*phiRPVZERO); fQVZERO+=w; if(etaRPVZERO<0){ fQVZEROCCos+=w*TMath::Cos(fHarmonic*phiRPVZERO); fQVZEROCSin+=w*TMath::Sin(fHarmonic*phiRPVZERO); fQVZEROC+=w; }else{ fQVZEROACos+=w*TMath::Cos(fHarmonic*phiRPVZERO); fQVZEROASin+=w*TMath::Sin(fHarmonic*phiRPVZERO); fQVZEROA+=w; } if(imod>31) selectedTrackV0A->Add(new AliAssociatedVZEROYS(mult_vzero_eq,eta_ave,phi_vzero,0.0,0,0)); if(imod<32) selectedTrackV0C->Add(new AliAssociatedVZEROYS(mult_vzero_eq,eta_ave,phi_vzero,0.0,0,0)); } Double_t vzeroc_qmcos=fQVZEROCCos/fQVZEROC; Double_t vzeroc_qmsin=fQVZEROCSin/fQVZEROC; Double_t vzeroa_qmcos=fQVZEROACos/fQVZEROA; Double_t vzeroa_qmsin=fQVZEROASin/fQVZEROA; Double_t qna_vzero=TMath::Sqrt((fQVZEROACos*fQVZEROACos+fQVZEROASin*fQVZEROASin)/fQVZEROA); if(fQVZEROA>1) fHistQna_VZERO->Fill(qna_vzero,lCentrality); Double_t qnc_vzero=TMath::Sqrt((fQVZEROCCos*fQVZEROCCos+fQVZEROCSin*fQVZEROCSin)/fQVZEROC); if(fQVZEROC>1) fHistQnc_VZERO->Fill(qnc_vzero,lCentrality); Double_t qn_vzero=TMath::Sqrt((fQVZEROCos*fQVZEROCos+fQVZEROSin*fQVZEROSin)/fQVZERO); if(fQVZERO>1) fHistQn_VZERO->Fill(qn_vzero,lCentrality); Double_t qaqc_vzero=vzeroa_qmcos*vzeroc_qmcos+vzeroa_qmsin*vzeroc_qmsin;//Q_a*Q_b/(M_a*M_b) Double_t qaqc_vzeroatpc=vzeroa_qmcos*tpc_qmcos+vzeroa_qmsin*tpc_qmsin;//Q_a*Q_b/(M_a*M_b) Double_t qaqc_vzeroctpc=vzeroc_qmcos*tpc_qmcos+vzeroc_qmsin*tpc_qmsin;//Q_a*Q_b/(M_a*M_b) if(fQVZEROC>1 && fQTPCC>1) { if(lCentrality>=0. && lCentrality<20.) fHistCorrQnc[0]->Fill(qnc,qnc_vzero); if(lCentrality>=20. && lCentrality<40.) fHistCorrQnc[1]->Fill(qnc,qnc_vzero); if(lCentrality>=40. && lCentrality<60. ) fHistCorrQnc[2]->Fill(qnc,qnc_vzero); if(lCentrality>=60. && lCentrality<100. ) fHistCorrQnc[3]->Fill(qnc,qnc_vzero); } if(fQVZEROA>1 && fQTPCA>1) { if(lCentrality>=0. && lCentrality<20.) fHistCorrQna[0]->Fill(qna,qna_vzero); if(lCentrality>=20. && lCentrality<40.) fHistCorrQna[1]->Fill(qna,qna_vzero); if(lCentrality>=40. && lCentrality<60. ) fHistCorrQna[2]->Fill(qna,qna_vzero); if(lCentrality>=60. && lCentrality<100. ) fHistCorrQna[3]->Fill(qna,qna_vzero); } if(fQVZEROC>0 && fQVZEROA>0) { if(lCentrality>=0. && lCentrality<20.) fHistQAQB_VZERO[0]->Fill(qaqc_vzero); if(lCentrality>=20. && lCentrality<40.) fHistQAQB_VZERO[1]->Fill(qaqc_vzero); if(lCentrality>=40. && lCentrality<60.) fHistQAQB_VZERO[2]->Fill(qaqc_vzero); if(lCentrality>=60. && lCentrality<100.) fHistQAQB_VZERO[3]->Fill(qaqc_vzero); fHist_V0AV0C->Fill(qaqc_vzero); SP_V0AV0C_default->Fill(lCentrality,qaqc_vzero,1); } if(fQVZEROC>0 && fQTPC>0){ fHist_V0CTPC->Fill(qaqc_vzeroctpc); SP_V0CTPC_default->Fill(lCentrality,qaqc_vzeroctpc,1); } if(fQVZEROA>0 && fQTPC>0){ fHist_V0ATPC->Fill(qaqc_vzeroatpc); SP_V0ATPC_default->Fill(lCentrality,qaqc_vzeroatpc,1); } //Calculate uQ Double_t uQ=0; Double_t uQ_vzeroa=0; Double_t uQ_vzeroc=0; for(Int_t i=0;i<selectedTracksAssociated->GetEntriesFast();i++){ AliAssociatedTrackYS* trackPOI=(AliAssociatedTrackYS*)selectedTracksAssociated->At(i); Double_t phi=trackPOI->Phi(); Double_t eta=trackPOI->Eta(); Double_t pt=trackPOI->Pt(); Int_t SpAssoc=trackPOI->WhichCandidate(); Double_t cosn = TMath::Cos(fHarmonic*phi); Double_t sinn = TMath::Sin(fHarmonic*phi); //VZERO-TPC-VZERO uQ_vzeroa=cosn*vzeroa_qmcos+sinn*vzeroa_qmsin; uQ_vzeroc=cosn*vzeroc_qmcos+sinn*vzeroc_qmsin; Double_t w=1; if(fQVZEROA>0){ SP_uVZEROA_PP[SpAssoc]->Fill(pt,uQ_vzeroa,1); if(lCentrality>=0. && lCentrality<20.) SP_uVZEROA[SpAssoc]->Fill(pt,uQ_vzeroa,w); if(lCentrality>=20. && lCentrality<40.) SP_uVZEROA1[SpAssoc]->Fill(pt,uQ_vzeroa,w); if(lCentrality>=40. && lCentrality<60.) SP_uVZEROA2[SpAssoc]->Fill(pt,uQ_vzeroa,w); if(lCentrality>=60. && lCentrality<100.) SP_uVZEROA3[SpAssoc]->Fill(pt,uQ_vzeroa,w); } if(fQVZEROC>0){ SP_uVZEROC_PP[SpAssoc]->Fill(pt,uQ_vzeroa,1); if(lCentrality>=0. && lCentrality<20.) SP_uVZEROC[SpAssoc]->Fill(pt,uQ_vzeroc,w); if(lCentrality>=20. && lCentrality<40.) SP_uVZEROC1[SpAssoc]->Fill(pt,uQ_vzeroc,w); if(lCentrality>=40. && lCentrality<60.) SP_uVZEROC2[SpAssoc]->Fill(pt,uQ_vzeroc,w); if(lCentrality>=60. && lCentrality<100.) SP_uVZEROC3[SpAssoc]->Fill(pt,uQ_vzeroc,w); } //TPC-TPC if(fQTPCC<1 || fQTPCA<1) continue; if( eta<0.4 && eta>-0.4 ) continue; if(eta<0){ uQ=(cosn*tpca_qmcos+sinn*tpca_qmsin); //u x Q/M_a SP_uTPCA->Fill(pt,uQ,1); }else{ uQ=(cosn*tpcc_qmcos+sinn*tpcc_qmsin); SP_uTPCC->Fill(pt,uQ,1); } SP_uTPC_PP[SpAssoc]->Fill(pt,uQ,1); if(lCentrality>=0. && lCentrality<20.) SP_uTPC[SpAssoc]->Fill(pt,uQ,1); if(lCentrality>=20. && lCentrality<40.) SP_uTPC1[SpAssoc]->Fill(pt,uQ,1); if(lCentrality>=40. && lCentrality<60.) SP_uTPC2[SpAssoc]->Fill(pt,uQ,1); if(lCentrality>=60. && lCentrality<100.) SP_uTPC3[SpAssoc]->Fill(pt,uQ,1); } */ } TObjArray *AliAnalysisTaskSEpPbCorrelationsYS::GetAcceptedTracksLeading(AliAODEvent *fAOD,Bool_t leading,TObjArray*tracks) { //TObjArray *tracks = new TObjArray; //tracks->SetOwner(kTRUE); Int_t nTracks = fAOD->GetNumberOfTracks(); Double_t pidqa[5]; for (Int_t i = 0; i < nTracks; i++) { AliAODTrack *aodTrack = dynamic_cast<AliAODTrack *>(fAOD->GetTrack(i)); if (!aodTrack) continue; if (!IsAcceptedTrack(aodTrack)) continue; // if (aodTrack->Eta()<fEtaMinExtra || aodTrack->Eta()>fEtaMaxExtra) continue; if (aodTrack->Charge() == 0) continue; Float_t trackpt=aodTrack->Pt(); Float_t tracketa=aodTrack->Eta(); Float_t trackphi=aodTrack->Phi(); Float_t efficiency=1.; Float_t efficiencyerr=-1; Int_t ivzbin=frefvz->GetXaxis()->FindBin(fPrimaryZVtx); if(fefficalib){ Int_t iPt=fhcorr[ivzbin-1]->GetXaxis()->FindBin(trackpt); Int_t iEta=fhcorr[ivzbin-1]->GetYaxis()->FindBin(tracketa); // Int_t iPhi=fhcorr[ivzbin-1]->GetZaxis()->FindBin(trackphi); // efficiency=fhcorr[ivzbin-1]->GetBinContent(iPt,iEta,iPhi); efficiency=fhcorr[ivzbin-1]->GetBinContent(iPt,iEta); efficiencyerr=fhcorr[ivzbin-1]->GetBinError(iPt,iEta); if(efficiency==0.) { return 0; } }else{ efficiency=1.; } if(leading){ pidqa[0]=trackpt; pidqa[1]=tracketa; pidqa[2]=RangePhi(trackphi); pidqa[3]=lCentrality; pidqa[4]=fPrimaryZVtx; fHistLeadQA->Fill(pidqa,0,1./efficiency); } Int_t SpAsso=0; tracks->Add(new AliAssociatedTrackYS(aodTrack->Charge(), tracketa, trackphi, trackpt, aodTrack->GetID(), -999, -999, SpAsso, 1./efficiency)); } return tracks; } TObjArray *AliAnalysisTaskSEpPbCorrelationsYS::GetAcceptedTracksPID(AliAODEvent *fAOD) { TObjArray *tracks = new TObjArray; tracks->SetOwner(kTRUE); Int_t nTracks = fAOD->GetNumberOfTracks(); Double_t pidqa[4]; for (Int_t i = 0; i < nTracks; i++) { AliAODTrack *aodTrack = dynamic_cast<AliAODTrack *>(fAOD->GetTrack(i)); Int_t SpPID=-999; if (!aodTrack) continue; if (!IsAcceptedTrack(aodTrack)) continue; if (aodTrack->Charge() == 0) continue; Double_t nSigmaKaonTPC = fPIDResponse->NumberOfSigmasTPC(aodTrack, AliPID::kKaon); Double_t nSigmaPionTPC = fPIDResponse->NumberOfSigmasTPC(aodTrack, AliPID::kPion); Double_t nSigmaProtonTPC = fPIDResponse->NumberOfSigmasTPC(aodTrack, AliPID::kProton); Double_t nSigmaKaonTOF = fPIDResponse->NumberOfSigmasTOF(aodTrack, AliPID::kKaon); Double_t nSigmaPionTOF = fPIDResponse->NumberOfSigmasTOF(aodTrack, AliPID::kPion); Double_t nSigmaProtonTOF = fPIDResponse->NumberOfSigmasTOF(aodTrack, AliPID::kProton); fHistNsig[0]->Fill(aodTrack->Pt(),nSigmaPionTPC); fHistNsig[1]->Fill(aodTrack->Pt(),nSigmaKaonTPC); fHistNsig[2]->Fill(aodTrack->Pt(),nSigmaProtonTPC); fHistNsig[3]->Fill(aodTrack->Pt(),nSigmaPionTOF); fHistNsig[4]->Fill(aodTrack->Pt(),nSigmaKaonTOF); fHistNsig[5]->Fill(aodTrack->Pt(),nSigmaProtonTOF); fHistNsigcorr[3]->Fill(nSigmaPionTPC,nSigmaPionTOF); fHistNsigcorr[4]->Fill(nSigmaKaonTPC,nSigmaKaonTOF); fHistNsigcorr[5]->Fill(nSigmaProtonTPC,nSigmaProtonTOF); Double_t d2nsigmakaon = nSigmaKaonTPC * nSigmaKaonTPC + nSigmaKaonTOF * nSigmaKaonTOF; Double_t d2nsigmapion = nSigmaPionTPC * nSigmaPionTPC + nSigmaPionTOF * nSigmaPionTOF; Double_t d2nsigmaproton = nSigmaProtonTPC * nSigmaProtonTPC + nSigmaProtonTOF * nSigmaProtonTOF; Bool_t fPIDTOF = kTRUE; if (fPIDResponse->CheckPIDStatus(AliPIDResponse::kTOF, fAOD->GetTrack(i)) == 0) fPIDTOF = kFALSE; else fPIDTOF = kTRUE; Double_t nSigmaKaonTOFTPC; Double_t nSigmaPionTOFTPC; Double_t nSigmaProtonTOFTPC; if (fPIDTOF && aodTrack->Pt() > 0.5) { nSigmaKaonTOFTPC = TMath::Sqrt(d2nsigmakaon); nSigmaPionTOFTPC = TMath::Sqrt(d2nsigmapion); nSigmaProtonTOFTPC = TMath::Sqrt(d2nsigmaproton); } else { nSigmaKaonTOFTPC = TMath::Abs(nSigmaKaonTPC); nSigmaPionTOFTPC = TMath::Abs(nSigmaPionTPC); nSigmaProtonTOFTPC = TMath::Abs(nSigmaProtonTPC); } if ((nSigmaKaonTOFTPC < fMaxnSigmaTPCTOF) && (nSigmaKaonTOFTPC < nSigmaPionTOFTPC) && (nSigmaKaonTOFTPC < nSigmaProtonTOFTPC)) SpPID = 0; if ((nSigmaPionTOFTPC < fMaxnSigmaTPCTOF) && (nSigmaPionTOFTPC < nSigmaKaonTOFTPC) && (nSigmaPionTOFTPC < nSigmaProtonTOFTPC)) SpPID = 1; if ((nSigmaProtonTOFTPC < fMaxnSigmaTPCTOF) && (nSigmaProtonTOFTPC < nSigmaKaonTOFTPC) && (nSigmaProtonTOFTPC < nSigmaPionTOFTPC)) SpPID = 2; pidqa[0]=aodTrack->Pt(); pidqa[1]=aodTrack->Eta(); pidqa[2]=RangePhi(aodTrack->Phi()); pidqa[3]=lCentrality; if(SpPID<0) continue; if(fQA) fHistPIDQA->Fill(pidqa, SpPID); if(SpPID==1) fHistNsigcorr[0]->Fill(nSigmaPionTPC,nSigmaPionTOF); if(SpPID==0) fHistNsigcorr[1]->Fill(nSigmaKaonTPC,nSigmaKaonTOF); if(SpPID==2) fHistNsigcorr[2]->Fill(nSigmaProtonTPC,nSigmaProtonTOF); tracks->Add(new AliAssociatedTrackYS(aodTrack->Charge(), aodTrack->Eta(), aodTrack->Phi(), aodTrack->Pt(), aodTrack->GetID(), -999, -999, SpPID, 1)); } return tracks; } TObjArray *AliAnalysisTaskSEpPbCorrelationsYS::GetAcceptedTracksAssociated(AliAODEvent *fAODEvent) { TObjArray *tracks = new TObjArray; tracks->SetOwner(kTRUE); TObjArray *dtrack = new TObjArray; dtrack->SetOwner(kTRUE); Int_t nTracks = fAODEvent->GetNumberOfTracks(); for (Int_t i = 0; i < nTracks - 1; i++) { AliAODTrack *aodTrack1 = dynamic_cast<AliAODTrack *>(fAODEvent->GetTrack(i)); if (!aodTrack1) continue; Double_t nSigmaKaonTPC_phi1 = fPIDResponse->NumberOfSigmasTPC(aodTrack1, AliPID::kKaon); Double_t nSigmaKaonTOF_phi1 = fPIDResponse->NumberOfSigmasTOF(aodTrack1, AliPID::kKaon); Double_t nSigmaPionTPC_phi1 = fPIDResponse->NumberOfSigmasTPC(aodTrack1, AliPID::kPion); Double_t nSigmaPionTOF_phi1 = fPIDResponse->NumberOfSigmasTOF(aodTrack1, AliPID::kPion); Double_t nSigmaProtonTPC_phi1 = fPIDResponse->NumberOfSigmasTPC(aodTrack1, AliPID::kProton); Double_t nSigmaProtonTOF_phi1 = fPIDResponse->NumberOfSigmasTOF(aodTrack1, AliPID::kProton); Double_t d2sigmaphi1kaontpctof = nSigmaKaonTPC_phi1 * nSigmaKaonTPC_phi1 + nSigmaKaonTOF_phi1 * nSigmaKaonTOF_phi1; Double_t d2sigmaphi1piontpctof = nSigmaPionTPC_phi1 * nSigmaPionTPC_phi1 + nSigmaPionTOF_phi1 * nSigmaPionTOF_phi1; Double_t d2sigmaphi1protontpctof = nSigmaProtonTPC_phi1 * nSigmaProtonTPC_phi1 + nSigmaProtonTOF_phi1 * nSigmaProtonTOF_phi1; Bool_t fPIDTOF_phi1; if (fPIDResponse->CheckPIDStatus(AliPIDResponse::kTOF, aodTrack1) == 0) fPIDTOF_phi1 = kFALSE; else fPIDTOF_phi1 = kTRUE; Double_t nSigmaKaonTOFTPC_phi1; Double_t nSigmaPionTOFTPC_phi1; Double_t nSigmaProtonTOFTPC_phi1; if (fPIDTOF_phi1 && aodTrack1->Pt() > 0.5) { nSigmaKaonTOFTPC_phi1 = TMath::Sqrt(d2sigmaphi1kaontpctof); nSigmaPionTOFTPC_phi1 = TMath::Sqrt(d2sigmaphi1piontpctof); nSigmaProtonTOFTPC_phi1 = TMath::Sqrt(d2sigmaphi1protontpctof); } else { nSigmaKaonTOFTPC_phi1 = TMath::Abs(nSigmaKaonTPC_phi1); nSigmaPionTOFTPC_phi1 = TMath::Abs(nSigmaPionTPC_phi1); nSigmaProtonTOFTPC_phi1 = TMath::Abs(nSigmaProtonTPC_phi1); } if (!IsAcceptedPhiDaughterTrack(aodTrack1)) continue; fHistPhiDTPCNSig->Fill(aodTrack1->Pt(), nSigmaKaonTPC_phi1); fHistPhiDTOFNSig->Fill(aodTrack1->Pt(), nSigmaKaonTOF_phi1); fHistPhiDTPCTOFNSig->Fill(aodTrack1->Pt(), TMath::Sqrt(d2sigmaphi1kaontpctof)); Bool_t isKaon1 = kFALSE; // if(nSigmaKaonTOFTPC_phi1<5.0 && // nSigmaKaonTOFTPC_phi1<nSigmaPionTOFTPC_phi1 && // nSigmaKaonTOFTPC_phi1<nSigmaProtonTOFTPC_phi1) isKaon1=kTRUE; if (TMath::Abs(nSigmaKaonTPC_phi1) < 5.0 && TMath::Abs(nSigmaKaonTPC_phi1) < TMath::Abs(nSigmaPionTPC_phi1) && TMath::Abs(nSigmaKaonTPC_phi1) < TMath::Abs(nSigmaProtonTPC_phi1)) isKaon1 = kTRUE; if (!isKaon1) continue; dtrack->Add(new AliMixTrackYS( aodTrack1->Charge(), aodTrack1->Eta(), aodTrack1->Phi(), aodTrack1->Pt(), aodTrack1->Px(), aodTrack1->Py(), aodTrack1->Pz())); for (Int_t j = i + 1; j < nTracks; j++) { AliAODTrack *aodTrack2 = dynamic_cast<AliAODTrack *>(fAODEvent->GetTrack(j)); if (!aodTrack2) continue; Double_t nSigmaKaonTPC_phi2 = fPIDResponse->NumberOfSigmasTPC(aodTrack2, AliPID::kKaon); Double_t nSigmaKaonTOF_phi2 = fPIDResponse->NumberOfSigmasTOF(aodTrack2, AliPID::kKaon); Double_t nSigmaPionTPC_phi2 = fPIDResponse->NumberOfSigmasTPC(aodTrack2, AliPID::kPion); Double_t nSigmaPionTOF_phi2 = fPIDResponse->NumberOfSigmasTOF(aodTrack2, AliPID::kPion); Double_t nSigmaProtonTPC_phi2 = fPIDResponse->NumberOfSigmasTPC(aodTrack2, AliPID::kProton); Double_t nSigmaProtonTOF_phi2 = fPIDResponse->NumberOfSigmasTOF(aodTrack2, AliPID::kProton); Double_t d2sigmaphi2kaontpctof = nSigmaKaonTPC_phi2 * nSigmaKaonTPC_phi2 + nSigmaKaonTOF_phi2 * nSigmaKaonTOF_phi2; Double_t d2sigmaphi2piontpctof = nSigmaPionTPC_phi2 * nSigmaPionTPC_phi2 + nSigmaPionTOF_phi2 * nSigmaPionTOF_phi2; Double_t d2sigmaphi2protontpctof = nSigmaProtonTPC_phi2 * nSigmaProtonTPC_phi2 + nSigmaProtonTOF_phi2 * nSigmaProtonTOF_phi2; Bool_t fPIDTOF_phi2; if (fPIDResponse->CheckPIDStatus(AliPIDResponse::kTOF, aodTrack2) == 0) fPIDTOF_phi2 = kFALSE; else fPIDTOF_phi2 = kTRUE; Double_t nSigmaKaonTOFTPC_phi2; Double_t nSigmaPionTOFTPC_phi2; Double_t nSigmaProtonTOFTPC_phi2; if (fPIDTOF_phi2 && aodTrack2->Pt() > 0.5) { nSigmaKaonTOFTPC_phi2 = TMath::Sqrt(d2sigmaphi2kaontpctof); nSigmaPionTOFTPC_phi2 = TMath::Sqrt(d2sigmaphi2piontpctof); nSigmaProtonTOFTPC_phi2 = TMath::Sqrt(d2sigmaphi2protontpctof); } else { nSigmaKaonTOFTPC_phi2 = TMath::Abs(nSigmaKaonTPC_phi2); nSigmaPionTOFTPC_phi2 = TMath::Abs(nSigmaPionTPC_phi2); nSigmaProtonTOFTPC_phi2 = TMath::Abs(nSigmaProtonTPC_phi2); } Bool_t isKaon2 = kFALSE; // if(nSigmaKaonTOFTPC_phi2<5.0 && // nSigmaKaonTOFTPC_phi2<nSigmaPionTOFTPC_phi2 && // nSigmaKaonTOFTPC_phi2<nSigmaProtonTOFTPC_phi2) isKaon2=kTRUE; if (TMath::Abs(nSigmaKaonTPC_phi2) < 5.0 && TMath::Abs(nSigmaKaonTPC_phi2) < TMath::Abs(nSigmaPionTPC_phi2) && TMath::Abs(nSigmaKaonTPC_phi2) < TMath::Abs(nSigmaProtonTPC_phi2)) isKaon2 = kTRUE; if (!isKaon2) continue; if (!IsAcceptedPhiDaughterTrack(aodTrack2)) continue; if (aodTrack1->GetID() == aodTrack2->GetID()) continue; if (aodTrack1->Charge() == aodTrack2->Charge()) continue; Double_t mass_phi; Double_t px_phi = aodTrack1->Px() + aodTrack2->Px(); Double_t py_phi = aodTrack1->Py() + aodTrack2->Py(); Double_t pz_phi = aodTrack1->Pz() + aodTrack2->Pz(); Double_t p_phi = TMath::Sqrt(px_phi * px_phi + py_phi * py_phi + pz_phi * pz_phi); Double_t phi_phi = atan2(py_phi, px_phi); if (phi_phi < 0.) phi_phi += 2 * TMath::Pi(); Double_t px1 = aodTrack1->Px(); Double_t py1 = aodTrack1->Py(); Double_t pz1 = aodTrack1->Pz(); Double_t E1 = TMath::Sqrt(px1 * px1 + py1 * py1 + pz1 * pz1 + 0.493677 * 0.493677); Double_t px2 = aodTrack2->Px(); Double_t py2 = aodTrack2->Py(); Double_t pz2 = aodTrack2->Pz(); Double_t E2 = TMath::Sqrt(px2 * px2 + py2 * py2 + pz2 * pz2 + 0.493677 * 0.493677); mass_phi = TMath::Sqrt((E1 + E2) * (E1 + E2) - (px1 + px2) * (px1 + px2) - (py1 + py2) * (py1 + py2) - (pz1 + pz2) * (pz1 + pz2)); Double_t pt_phi = TMath::Sqrt((px1 + px2) * (px1 + px2) + (py1 + py2) * (py1 + py2)); // if(pt_phi<0.5) continue; Double_t eta_phi = 0.5 * log((p_phi + pz_phi) / (p_phi - pz_phi)); Double_t PhiQA[3] = {mass_phi, pt_phi, lCentrality}; fHistMass_PhiMeson->Fill(PhiQA); if (TMath::Abs(eta_phi) > 0.8) continue; Int_t SpPhi = -999.; const Double_t fPhiMass = TDatabasePDG::Instance()->GetParticle(333)->Mass(); if (TMath::Abs(mass_phi - fPhiMass) < 0.006) SpPhi = 0; // same for step if (mass_phi > 0.99 && mass_phi < fPhiMass - 0.006) SpPhi = 1; // same as step if (mass_phi > fPhiMass + 0.006 && mass_phi < fPhiMass + 0.018) SpPhi = 2; // same as step if (mass_phi > fPhiMass + 0.018 && mass_phi < fPhiMass + 0.030) SpPhi = 3; // same as step if (mass_phi > fPhiMass + 0.030 && mass_phi < fPhiMass + 0.042) SpPhi = 4; // same as step if (mass_phi > fPhiMass + 0.042 && mass_phi < fPhiMass + 0.054) SpPhi = 5; // same as step if (mass_phi > fPhiMass + 0.054 && mass_phi < fPhiMass + 0.066) SpPhi = 6; // same as step if(SpPhi<0) continue; tracks->Add(new AliAssociatedTrackYS(0, eta_phi, phi_phi, pt_phi, -999, aodTrack1->GetID(), aodTrack2->GetID(), SpPhi, 1)); Double_t spPhiQA[4] = {eta_phi, phi_phi, (Float_t)SpPhi, lCentrality}; fHist_PhiQA->Fill(spPhiQA); } } // Mixed Event Double_t pvxMix = fPrimaryZVtx; Double_t counterMix = 0; AliEventPool *pool = fPoolMgr1->GetEventPool(lCentrality, pvxMix); if (!pool) AliFatal(Form("No pool found for centrality = %f, zVtx = %f", lCentrality,pvxMix)); if (pool->IsReady() || pool->NTracksInPool() > fPoolMinNTracks || pool->GetCurrentNEvents() > fMinEventsToMix) { Int_t nMix = pool->GetCurrentNEvents(); for (Int_t jMix = 0; jMix < nMix; jMix++) { TObjArray *mixEvents = pool->GetEvent(jMix); for (Int_t i = 0; i < dtrack->GetEntriesFast(); i++) { AliMixTrackYS *dtrack1 = (AliMixTrackYS *)dtrack->At(i); if (!dtrack1) continue; Double_t pdx1 = dtrack1->Px(); Double_t pdy1 = dtrack1->Py(); Double_t pdz1 = dtrack1->Pz(); Double_t Ed1 = TMath::Sqrt(pdx1 * pdx1 + pdy1 * pdy1 + pdz1 * pdz1 + 0.493677 * 0.493677); counterMix++; for (Int_t j = 0; j < mixEvents->GetEntriesFast(); j++) { AliMixTrackYS *dtrack2 = (AliMixTrackYS *)mixEvents->At(j); if (!dtrack2) continue; if (dtrack1->Charge() == dtrack2->Charge()) continue; Double_t pdx2 = dtrack2->Px(); Double_t pdy2 = dtrack2->Py(); Double_t pdz2 = dtrack2->Pz(); Double_t Ed2 = TMath::Sqrt(pdx2 * pdx2 + pdy2 * pdy2 + pdz2 * pdz2 + 0.493677 * 0.493677); Double_t mass_phi_mix = TMath::Sqrt( (Ed1 + Ed2) * (Ed1 + Ed2) - (pdx1 + pdx2) * (pdx1 + pdx2) - (pdy1 + pdy2) * (pdy1 + pdy2) - (pdz1 + pdz2) * (pdz1 + pdz2)); Double_t pt_phi_mix = TMath::Sqrt((pdx1 + pdx2) * (pdx1 + pdx2) + (pdy1 + pdy2) * (pdy1 + pdy2)); // if(pt_phi_mix<0.5) continue; Double_t px_phi_mix = pdx1 + pdx2; Double_t py_phi_mix = pdy1 + pdy2; Double_t pz_phi_mix = pdz1 + pdz2; Double_t p_phi_mix = TMath::Sqrt(px_phi_mix * px_phi_mix + py_phi_mix * py_phi_mix + pz_phi_mix * pz_phi_mix); Double_t phi_phi_mix = atan2(py_phi_mix, px_phi_mix); if (phi_phi_mix < 0.) phi_phi_mix += 2 * TMath::Pi(); Double_t eta_phi_mix = 0.5 * log((p_phi_mix + pz_phi_mix) / (p_phi_mix - pz_phi_mix)); if (TMath::Abs(eta_phi_mix) > 0.8) continue; Double_t PhiQAMix[3] = {mass_phi_mix, pt_phi_mix, lCentrality}; fHistMass_PhiMeson_MIX->Fill(PhiQAMix, 1. / (Double_t)nMix); } } } } TObjArray *tracksClone = new TObjArray; tracksClone->SetOwner(kTRUE); for (Int_t i = 0; i < dtrack->GetEntriesFast(); i++) { AliMixTrackYS *particle = (AliMixTrackYS *)dtrack->At(i); tracksClone->Add(new AliMixTrackYS( particle->Charge(), particle->Eta(), particle->Phi(), particle->Pt(), particle->Px(), particle->Py(), particle->Pz())); } pool->UpdatePool(tracksClone); return tracks; } TObjArray *AliAnalysisTaskSEpPbCorrelationsYS::GetAcceptedV0Tracks(const AliAODEvent *fAODEvent) { TObjArray *tracks = new TObjArray; tracks->SetOwner(kTRUE); // V0Particles Int_t nv0s = fAODEvent->GetNumberOfV0s(); for (Int_t iv0 = 0; iv0 < nv0s; iv0++) { AliAODv0 *aodv0 = dynamic_cast<AliAODv0 *>(fAODEvent->GetV0(iv0)); if (!aodv0) { AliError(Form("ERROR: Could not retrieve aodv0 %d", iv0)); continue; } fHist_V0Stat->Fill(0); if(!IsAcceptedV0(aodv0)) continue; fHist_V0Stat->Fill(7); // c*taup;ppp; const Double_t kLambdaMass = TDatabasePDG::Instance()->GetParticle(3122)->Mass(); const Double_t kK0Mass = TDatabasePDG::Instance()->GetParticle(311)->Mass(); // Double_t cutcTauLam = fcutctau*7.89;//c*mean life time=2.632*2.9979 cm // Double_t cutcTauK0 = fcutctau*2.68; //c*mean life time=0.8954*2.9979 cm // life time < 20(K0s), 30(lambda) fcutcTauLam=3.8*7.89; fcutcTauK0=5*2.68; Bool_t cutK0ctau = IsAcceptedDecayLength(aodv0,kK0Mass,fcutcTauK0); Bool_t cutLambdactau =IsAcceptedDecayLength(aodv0,kLambdaMass,fcutcTauLam); Bool_t cutAntiLambdactau = IsAcceptedDecayLength(aodv0,kLambdaMass,fcutcTauLam); // cpa Double_t cpa = aodv0->CosPointingAngle(fAODEvent->GetPrimaryVertex()); fcosMinK0s=0.97; fcosMinLambda=0.99; Bool_t cpaK0s = cpa > fcosMinK0s; Bool_t cpaLambda = cpa > fcosMinLambda; const AliAODTrack* myTrackPos=0; const AliAODTrack* myTrackNeg=0; AliAODTrack *myTrackPosTest = dynamic_cast<AliAODTrack *>(aodv0->GetDaughter(0)); // The first dauther track, which should be positive AliAODTrack *myTrackNegTest = dynamic_cast<AliAODTrack *>(aodv0->GetDaughter(1)); // The second dauther track, which should be negative if (!myTrackPosTest || !myTrackNegTest) { Printf("strange analysis::UserExec:: Error:Could not retreive one of the daughter track\n"); continue; } if (!IsAcceptedDaughterTrack(myTrackPosTest) || !IsAcceptedDaughterTrack(myTrackNegTest)) continue; Double_t alpha=aodv0->AlphaV0(); Double_t qt = aodv0->PtArmV0(); fHist_V0Stat->Fill(8); if ((myTrackPosTest->Charge() == 1) && (myTrackNegTest->Charge() == -1)) { hv0dcharge->Fill(0); myTrackPos = myTrackPosTest; myTrackNeg = myTrackNegTest; } if ((myTrackPosTest->Charge() == -1) && (myTrackNegTest->Charge() == 1)) { hv0dcharge->Fill(1); myTrackPos = myTrackNegTest; myTrackNeg = myTrackPosTest; } if (myTrackPosTest->Charge() == myTrackNegTest->Charge()) { hv0dcharge->Fill(2); continue; } fHist_AP[0]->Fill(alpha,qt); fHist_V0Stat->Fill(9); // PID Cut // Positive tracks Double_t nSigmaPosPionTPC = fPIDResponse->NumberOfSigmasTPC(myTrackPos, AliPID::kPion); Double_t nSigmaPosPionTOF = fPIDResponse->NumberOfSigmasTOF(myTrackPos, AliPID::kPion); Double_t nSigmaPosKaonTPC = fPIDResponse->NumberOfSigmasTPC(myTrackPos, AliPID::kKaon); Double_t nSigmaPosKaonTOF = fPIDResponse->NumberOfSigmasTOF(myTrackPos, AliPID::kKaon); Double_t nSigmaPosProtonTPC = fPIDResponse->NumberOfSigmasTPC(myTrackPos, AliPID::kProton); Double_t nSigmaPosProtonTOF = fPIDResponse->NumberOfSigmasTOF(myTrackPos, AliPID::kProton); // negative tracks Double_t nSigmaNegPionTPC = fPIDResponse->NumberOfSigmasTPC(myTrackNeg, AliPID::kPion); Double_t nSigmaNegPionTOF = fPIDResponse->NumberOfSigmasTOF(myTrackNeg, AliPID::kPion); Double_t nSigmaNegKaonTPC = fPIDResponse->NumberOfSigmasTPC(myTrackNeg, AliPID::kKaon); Double_t nSigmaNegKaonTOF = fPIDResponse->NumberOfSigmasTOF(myTrackNeg, AliPID::kKaon); Double_t nSigmaNegProtonTPC = fPIDResponse->NumberOfSigmasTPC(myTrackNeg, AliPID::kProton); Double_t nSigmaNegProtonTOF = fPIDResponse->NumberOfSigmasTOF(myTrackNeg, AliPID::kProton); Bool_t bpPion = TMath::Abs(nSigmaPosPionTPC) <= fMaxnSigmaTPCV0; Bool_t bpProton = TMath::Abs(nSigmaPosProtonTPC) <= fMaxnSigmaTPCV0; Bool_t bnPion = TMath::Abs(nSigmaNegPionTPC) <= fMaxnSigmaTPCV0; Bool_t bnProton = TMath::Abs(nSigmaNegProtonTPC) <= fMaxnSigmaTPCV0; Bool_t bpPion_tof = TMath::Abs(nSigmaPosPionTPC) <= 4.; Bool_t bpProton_tof = TMath::Abs(nSigmaPosProtonTPC) <=4; Bool_t bnPion_tof = TMath::Abs(nSigmaNegPionTOF) <= 4; Bool_t bnProton_tof = TMath::Abs(nSigmaNegProtonTOF) <=4; Bool_t fTOFV0=kTRUE; if(fTOFV0 && myTrackPos->Pt()>0.3 && fPIDResponse->CheckPIDStatus(AliPIDResponse::kTOF, myTrackPos) != 0){ bpPion=bpPion && bpPion_tof; bpProton=bpProton && bpProton_tof; } if(fTOFV0 && myTrackNeg->Pt()>0.3 && fPIDResponse->CheckPIDStatus(AliPIDResponse::kTOF, myTrackNeg) != 0){ bnPion=bnPion && bnPion_tof; bnProton=bnProton && bnProton_tof; } // Arme ntros podoranski cutOD Bool_t k0APcut = (aodv0->PtArmV0() > (TMath::Abs(0.2 * aodv0->AlphaV0()))); Bool_t kGammaconvcut = !(TMath::Power(aodv0->AlphaV0() / 0.95, 2) + TMath::Power(aodv0->PtArmV0() / 0.05, 2) < 1); if (k0APcut) fHist_AP[4]->Fill(aodv0->AlphaV0(), aodv0->PtArmV0()); if (kGammaconvcut) fHist_AP[5]->Fill(aodv0->AlphaV0(), aodv0->PtArmV0()); Bool_t fPIDV0=kFALSE; //if(fPIDV0 && fTOFV0) if ((myTrackPos->Pt()>0.3 && fPIDResponse->CheckPIDStatus(AliPIDResponse::kTOF, myTrackPos) == 0) || (myTrackNeg->Pt()>0.3 && fPIDResponse->CheckPIDStatus(AliPIDResponse::kTOF, myTrackNeg) == 0)) continue; fHistPosNsig[0]->Fill(myTrackPos->Pt(), nSigmaPosPionTPC); fHistPosNsig[1]->Fill(myTrackPos->Pt(), nSigmaPosProtonTPC); fHistPosNsig[2]->Fill(myTrackPos->Pt(), nSigmaPosKaonTPC); fHistPosNsig[3]->Fill(myTrackPos->Pt(), nSigmaPosPionTOF); fHistPosNsig[4]->Fill(myTrackPos->Pt(), nSigmaPosProtonTOF); fHistPosNsig[5]->Fill(myTrackPos->Pt(), nSigmaPosKaonTOF); fHistNegNsig[0]->Fill(myTrackNeg->Pt(), nSigmaNegPionTPC); fHistNegNsig[1]->Fill(myTrackNeg->Pt(), nSigmaNegProtonTPC); fHistNegNsig[2]->Fill(myTrackNeg->Pt(), nSigmaNegKaonTPC); fHistNegNsig[3]->Fill(myTrackNeg->Pt(), nSigmaNegPionTOF); fHistNegNsig[4]->Fill(myTrackNeg->Pt(), nSigmaNegProtonTOF); fHistNegNsig[5]->Fill(myTrackNeg->Pt(), nSigmaNegKaonTOF); /* if (fQA) { if (!kGammaconvcut) fHistPosNsigQA[0]->Fill(myTrackPos->Pt(),nSigmaPosPionTPC); // Nsigma of Pion if the AP diagram indicate gamma conversion } */ Bool_t cutK0Pid = (bpPion && bnPion); Bool_t cutLambdaPid = (bpProton && bnPion); Bool_t cutAntiLambdaPid = (bpPion && bnProton); // Mass cut Double_t lInvMassLambda = aodv0->MassLambda(); Double_t lInvMassK0 = aodv0->MassK0Short(); Double_t lInvMassAntiLambda = aodv0->MassAntiLambda(); const Double_t kProtonMass = TDatabasePDG::Instance()->GetParticle(2212)->Mass(); const Double_t kPionMass = TDatabasePDG::Instance()->GetParticle(211)->Mass(); Double_t mispidmass= -999.; if (fQA) { // QA to evaluate bump Double_t px1 = myTrackPos->Px(); Double_t py1 = myTrackPos->Py(); Double_t pz1 = myTrackPos->Pz(); Double_t px2 = myTrackNeg->Px(); Double_t py2 = myTrackNeg->Py(); Double_t pz2 = myTrackNeg->Pz(); Double_t px_v0 = px1 + px2; Double_t py_v0 = py1 + py2; Double_t pz_v0 = pz1 + pz2; Double_t p2_v0 = px_v0 * px_v0 + py_v0 * py_v0 + pz_v0 * pz_v0; Double_t E_pos_proton = TMath::Sqrt(px1 * px1 + py1 * py1 + pz1 * pz1 + kProtonMass * kProtonMass); Double_t E_neg_proton = TMath::Sqrt(px2 * px2 + py2 * py2 + pz2 * pz2 + kProtonMass * kProtonMass); Double_t E_neg_pion = TMath::Sqrt(px2 * px2 + py2 * py2 + pz2 * pz2 + kPionMass * kPionMass); Double_t E_pos_pion = TMath::Sqrt(px1 * px1 + py1 * py1 + pz1 * pz1 + kPionMass * kPionMass); mispidmass = TMath::Sqrt((E_pos_pion + E_neg_pion) * (E_pos_pion + E_neg_pion) - p2_v0); } Bool_t mispid=TMath::Abs(mispidmass-kK0Mass)<0.01; Bool_t cutMassLambda = ((lInvMassLambda > 1.05) && (lInvMassLambda < 1.25)); Bool_t cutMassAntiLambda = ((lInvMassAntiLambda > 1.05) && (lInvMassAntiLambda < 1.25)); Bool_t cutMassK0 = (lInvMassK0 > 0.4) && (lInvMassK0 < 0.6); if(cutK0Pid){ fHist_V0Stat->Fill(10); if(cutK0ctau){ fHist_V0Stat->Fill(11); if(k0APcut&&kGammaconvcut) fHist_V0Stat->Fill(12); } } if(cutLambdaPid){ fHist_V0Stat->Fill(13); if(cutLambdactau){ fHist_V0Stat->Fill(14); if(!k0APcut&&kGammaconvcut) fHist_V0Stat->Fill(15); } } /* Bool_t IDK0s = cutK0ctau && cpaK0s && k0APcut && (!cutMassLambda) && (!cutMassAntiLambda);//&& kGammaconvcut; Bool_t IDLa = cutLambdactau && cpaLambda && !k0APcut && (!cutMassK0); //&& kGammaconvcut; Bool_t IDALa = cutAntiLambdactau && cpaLambda && !k0APcut && (!cutMassK0);// && kGammaconvcut; */ /* if(fPIDV0){ IDK0s=IDK0s && cutK0Pid ; IDLa= IDLa && cutLambdaPid && !mispid; IDALa= IDALa && cutAntiLambdaPid && !mispid; } */ Bool_t IDK0s = cutK0ctau && cpaK0s && k0APcut; Bool_t IDLa = cutLambdactau && cpaLambda && !k0APcut; Bool_t IDALa = cutAntiLambdactau && cpaLambda && !k0APcut; if (IDK0s) fHist_AP[1]->Fill(aodv0->AlphaV0(), aodv0->PtArmV0()); if (IDLa || IDALa) fHist_AP[2]->Fill(aodv0->AlphaV0(), aodv0->PtArmV0()); Double_t K0sMassQA[4] = {lInvMassK0, aodv0->Pt(), lCentrality,aodv0->Eta()}; if (IDK0s) fHistMass_K0s->Fill(K0sMassQA); Double_t LambdaMassQA[4] = {lInvMassLambda, aodv0->Pt(), lCentrality,aodv0->Eta()}; if (IDLa) fHistMass_Lambda->Fill(LambdaMassQA); Double_t ALambdaMassQA[4] = {lInvMassAntiLambda, aodv0->Pt(), lCentrality,aodv0->Eta()}; if (IDALa) fHistMass_ALambda->Fill(ALambdaMassQA); if (cutLambdaPid && cutLambdactau && cpaLambda && !k0APcut && kGammaconvcut && mispidmass > 0) fHistMass_bumpcorr->Fill(lInvMassLambda, mispidmass); Int_t SpV0 = -999; if ((IDK0s && (TMath::Abs(lInvMassK0 - kK0Mass) < 0.01))) SpV0 = 0; // same for step if (IDK0s && (lInvMassK0 > 0.40) && (lInvMassK0 < 0.44)) SpV0 = 1; // same as step if (IDK0s && (lInvMassK0 > 0.44) && (lInvMassK0 < kK0Mass - 0.01)) SpV0 = 2; // same as step if (IDK0s && (lInvMassK0 > kK0Mass + 0.01) && (lInvMassK0 < 0.56)) SpV0 = 3; // same as step if (IDK0s && (lInvMassK0 > 0.56) && (lInvMassK0 < 0.60)) SpV0 = 4; // same as step if ((IDLa && TMath::Abs(lInvMassLambda - kLambdaMass) < 0.005) || (IDALa && TMath::Abs(lInvMassAntiLambda - kLambdaMass) < 0.005)) SpV0 = 5; // same as step if ((IDLa && (lInvMassLambda > kLambdaMass + 0.005) && (lInvMassLambda < 1.25)) || (IDALa && (lInvMassAntiLambda > kLambdaMass + 0.005) && (lInvMassAntiLambda < 1.25))) SpV0 = 6; // same as step if (SpV0 < 0) continue; Double_t spV0QA[4] = {aodv0->Eta(), aodv0->Phi(), (Float_t)SpV0, lCentrality}; fHist_V0QA->Fill(spV0QA); if (fQA) { if (IDK0s){ fHistPosNsigQA[0]->Fill(myTrackPos->Pt(), nSigmaPosPionTPC); fHistPosNsigQA[1]->Fill(myTrackNeg->Pt(), nSigmaNegPionTPC); fh3NegNsig[0]->Fill(myTrackNeg->Pt(),nSigmaNegPionTPC,nSigmaNegPionTOF); fh3PosNsig[0]->Fill(myTrackPos->Pt(),nSigmaPosPionTPC,nSigmaPosPionTOF); } if (IDLa){ fHistPosNsigQA[2]->Fill(myTrackPos->Pt(), nSigmaPosProtonTPC); fHistPosNsigQA[3]->Fill(myTrackNeg->Pt(), nSigmaNegPionTPC); fh3NegNsig[1]->Fill(myTrackNeg->Pt(),nSigmaNegPionTPC,nSigmaNegPionTOF); fh3PosNsig[1]->Fill(myTrackPos->Pt(),nSigmaPosProtonTPC,nSigmaPosProtonTOF); } if (IDALa){ fHistPosNsigQA[4]->Fill(myTrackPos->Pt(), nSigmaPosPionTPC); fHistPosNsigQA[5]->Fill(myTrackNeg->Pt(), nSigmaNegProtonTPC); fh3NegNsig[2]->Fill(myTrackNeg->Pt(),nSigmaNegProtonTPC,nSigmaNegProtonTOF); fh3PosNsig[2]->Fill(myTrackPos->Pt(),nSigmaPosPionTPC,nSigmaPosPionTOF); } } tracks->Add(new AliAssociatedTrackYS(aodv0->Charge(), aodv0->Eta(), aodv0->Phi(), aodv0->Pt(),aodv0->GetID(), myTrackPos->GetID(), myTrackNeg->GetID(), SpV0, 1)); if(!fDataType){ TClonesArray *mcArray1 = (TClonesArray*)fAODEvent->FindListObject(AliAODMCParticle::StdBranchName()); if(!mcArray1){ Printf("No MC particle branch found"); continue; } Int_t MotherOfMotherPdg =0; Int_t myTrackPosLabel = TMath::Abs(myTrackPos->GetLabel()); Int_t myTrackNegLabel = TMath::Abs(myTrackNeg->GetLabel()); AliAODMCParticle *mcPosTrack = (AliAODMCParticle*)mcArray1->At(myTrackPosLabel); if (!mcPosTrack) continue; //check if positive daughter track is MC particle AliAODMCParticle *mcNegTrack = (AliAODMCParticle*)mcArray1->At(myTrackNegLabel); if (!mcNegTrack) continue; //check if negative daughter track is MC particle Int_t PosTrackPdg = mcPosTrack->GetPdgCode(); Int_t NegTrackPdg = mcNegTrack->GetPdgCode(); Int_t myTrackPosMotherLabel = mcPosTrack->GetMother(); Int_t myTrackNegMotherLabel = mcNegTrack->GetMother(); if ((myTrackPosMotherLabel<0)||(myTrackNegMotherLabel<0)) continue; // check if dauter tracks have mother track if (myTrackPosMotherLabel!=myTrackNegMotherLabel) continue; // require the same mother particle for positive and negative daughter tracks AliAODMCParticle *mcPosMother = (AliAODMCParticle*)mcArray1->At(myTrackPosMotherLabel); if (!mcPosMother) continue; Int_t MotherPdg = mcPosMother->GetPdgCode(); Int_t MotherOfMother = mcPosMother->GetMother(); Bool_t IsK0FromMC = (mcPosMother->IsPhysicalPrimary())&&(MotherPdg==310)&&(PosTrackPdg==211)&&(NegTrackPdg==-211); //Moter track is K0 short, Pos is Pion, Neg is Pion Bool_t IsLambdaFromMC = (mcPosMother->IsPhysicalPrimary())&&(MotherPdg==3122)&&(PosTrackPdg==2212)&&(NegTrackPdg==-211); //Moter track is Lambda, Pos is Proton, Neg is Pion Bool_t IsAntiLambdaFromMC = (mcPosMother->IsPhysicalPrimary())&&(MotherPdg==-3122)&&(PosTrackPdg==211)&&(NegTrackPdg==-2212); //Moter track is Anti-Lambda, Pos is pion, Neg is Proton if(IsK0FromMC) fHistMass_K0s_MC->Fill(K0sMassQA); if(IsLambdaFromMC) fHistMass_Lambda_MC->Fill(LambdaMassQA); if(IsAntiLambdaFromMC) fHistMass_ALambda_MC->Fill(ALambdaMassQA); } } return tracks; } TObjArray *AliAnalysisTaskSEpPbCorrelationsYS::GetAcceptedCascadeTracks(AliAODEvent *fAODEvent) { // To select Cascade Particle TObjArray *tracks = new TObjArray; tracks->SetOwner(kTRUE); Int_t nCascades = fAODEvent->GetNumberOfCascades(); Double_t lInvMassXiMinus=-999.; Double_t lInvMassXiPlus=-999.; Double_t lInvMassOmegaMinus=-999.; Double_t lInvMassOmegaPlus=-999.; for (Int_t icasc = 0; icasc < nCascades; icasc++) { AliAODcascade *casc = fAODEvent->GetCascade(icasc); if (!casc) continue; const AliAODTrack *myTrackCascPos=0; const AliAODTrack *myTrackCascNeg=0; // const AliAODTrack*myTrackCascBach; AliAODTrack *myTrackCascPosTest = dynamic_cast<AliAODTrack *>(casc->GetDaughter(0)); AliAODTrack *myTrackCascNegTest = dynamic_cast<AliAODTrack *>(casc->GetDaughter(1)); const AliAODTrack *myTrackCascBach = dynamic_cast<AliAODTrack *>(casc->GetDecayVertexXi()->GetDaughter(0)); // myTrackCascBach=myTrackCascBachTest; if ((myTrackCascPosTest->Charge() == 1) && (myTrackCascNegTest->Charge() == -1)) { myTrackCascPos = myTrackCascPosTest; myTrackCascNeg = myTrackCascNegTest; } if ((myTrackCascPosTest->Charge() == -1) && (myTrackCascNegTest->Charge() == 1)) { myTrackCascPos = myTrackCascNegTest; myTrackCascNeg = myTrackCascPosTest; } if (!myTrackCascPos || !myTrackCascNeg || !myTrackCascBach) { AliWarning("ERROR: Could not retrieve one of the 3 AOD daughter tracks of the cascade ..."); continue; } UInt_t lIdxPosCasc = (UInt_t)TMath::Abs(myTrackCascPos->GetID()); UInt_t lIdxNegCasc = (UInt_t)TMath::Abs(myTrackCascNeg->GetID()); UInt_t lCascBachIdx = (UInt_t)TMath::Abs(myTrackCascBach->GetID()); if (lCascBachIdx == lIdxNegCasc) { AliWarning("Pb / Idx(Bach. track) = Idx(Neg. track) ... continue!"); continue; } if (lCascBachIdx == lIdxPosCasc) { AliWarning("Pb / Idx(Bach. track) = Idx(Pos. track) ... continue!"); continue; } // if (!IsAcceptedCascade(casc)) continue; Double_t lInvMassxi = casc->MassXi(); Double_t lInvMassomega = casc->MassOmega(); Short_t lChargeXi = casc->ChargeXi(); if (!IsAcceptedDaughterTrack(myTrackCascPos) || !IsAcceptedDaughterTrack(myTrackCascNeg) || !IsAcceptedDaughterTrack(myTrackCascBach)) continue; Double_t lCasx = casc->DecayVertexXiX(); Double_t lCasy = casc->DecayVertexXiY(); Double_t lCasz = casc->DecayVertexXiZ(); const Double_t kximass = TDatabasePDG::Instance()->GetParticle(3312)->Mass(); const Double_t komegamass = TDatabasePDG::Instance()->GetParticle(3334)->Mass(); Bool_t topoXi=IsAcceptedCascade(casc); Bool_t topoOmega=IsAcceptedCascadeOmega(casc); if(!topoXi && !topoOmega) continue; Double_t cutctauxi = 6 * 4.91; Double_t cutctauomega = 6 * 2.461; Double_t lCasDecayLength = TMath::Sqrt(TMath::Power(lCasx - tPrimaryVtxPosition[0], 2) + TMath::Power(lCasy - tPrimaryVtxPosition[1], 2) + TMath::Power(lCasz - tPrimaryVtxPosition[2], 2)); Double_t lPCas = TMath::Sqrt((casc->MomXiX()) * (casc->MomXiX()) +(casc->MomXiY()) * (casc->MomXiY()) +(casc->MomXiZ()) * (casc->MomXiZ())); Double_t lctauXi = (lCasDecayLength * kximass) / lPCas; Double_t lctauOmega = (lCasDecayLength * komegamass) / lPCas; // Bool_t cutXictau=(lctauXi < cutctauxi); // Bool_t cutOmegactau=(lctauOmega<cutctauomega); Bool_t cutXictau = kTRUE; Bool_t cutOmegactau = kTRUE; if (lChargeXi < 0) lInvMassXiMinus = lInvMassxi; if (lChargeXi > 0) lInvMassXiPlus = lInvMassxi; if (lChargeXi < 0) lInvMassOmegaMinus = lInvMassomega; if (lChargeXi > 0) lInvMassOmegaPlus = lInvMassomega; Float_t nSigmaCascBachKaonTPC = fPIDResponse->NumberOfSigmasTPC(myTrackCascBach, AliPID::kKaon); Float_t nSigmaCascBachPionTPC = fPIDResponse->NumberOfSigmasTPC(myTrackCascBach, AliPID::kPion); Float_t nSigmaCascBachProtonTPC = fPIDResponse->NumberOfSigmasTPC(myTrackCascBach, AliPID::kProton); Float_t nSigmaCascBachKaonTOF = fPIDResponse->NumberOfSigmasTOF(myTrackCascBach, AliPID::kKaon); Float_t nSigmaCascBachPionTOF = fPIDResponse->NumberOfSigmasTOF(myTrackCascBach, AliPID::kPion); Float_t nSigmaCascBachProtonTOF = fPIDResponse->NumberOfSigmasTOF(myTrackCascBach, AliPID::kProton); Float_t nSigmaCascPosKaonTPC = fPIDResponse->NumberOfSigmasTPC(myTrackCascPos, AliPID::kKaon); Float_t nSigmaCascPosPionTPC = fPIDResponse->NumberOfSigmasTPC(myTrackCascPos, AliPID::kPion); Float_t nSigmaCascPosProtonTPC = fPIDResponse->NumberOfSigmasTPC(myTrackCascPos, AliPID::kProton); Float_t nSigmaCascPosKaonTOF = fPIDResponse->NumberOfSigmasTOF(myTrackCascPos, AliPID::kKaon); Float_t nSigmaCascPosPionTOF = fPIDResponse->NumberOfSigmasTOF(myTrackCascPos, AliPID::kPion); Float_t nSigmaCascPosProtonTOF = fPIDResponse->NumberOfSigmasTOF(myTrackCascPos, AliPID::kProton); Float_t nSigmaCascNegKaonTPC = fPIDResponse->NumberOfSigmasTPC(myTrackCascNeg, AliPID::kKaon); Float_t nSigmaCascNegPionTPC = fPIDResponse->NumberOfSigmasTPC(myTrackCascNeg, AliPID::kPion); Float_t nSigmaCascNegProtonTPC = fPIDResponse->NumberOfSigmasTPC(myTrackCascNeg, AliPID::kProton); Float_t nSigmaCascNegKaonTOF = fPIDResponse->NumberOfSigmasTOF(myTrackCascNeg, AliPID::kKaon); Float_t nSigmaCascNegPionTOF = fPIDResponse->NumberOfSigmasTOF(myTrackCascNeg, AliPID::kPion); Float_t nSigmaCascNegProtonTOF = fPIDResponse->NumberOfSigmasTOF(myTrackCascNeg, AliPID::kProton); Float_t d2sigmacascbachkaontpctof = nSigmaCascBachKaonTPC * nSigmaCascBachKaonTPC + nSigmaCascBachKaonTOF * nSigmaCascBachKaonTOF; Float_t d2sigmacascbachpiontpctof = nSigmaCascBachPionTPC * nSigmaCascBachPionTPC + nSigmaCascBachPionTOF * nSigmaCascBachPionTOF; Float_t d2sigmacascbachprotontpctof = nSigmaCascBachProtonTPC * nSigmaCascBachProtonTPC + nSigmaCascBachProtonTOF * nSigmaCascBachProtonTOF; Float_t d2sigmacascposkaontpctof = nSigmaCascPosKaonTPC * nSigmaCascPosKaonTPC + nSigmaCascPosKaonTOF * nSigmaCascPosKaonTOF; Float_t d2sigmacascpospiontpctof = nSigmaCascPosPionTPC * nSigmaCascPosPionTPC + nSigmaCascPosPionTOF * nSigmaCascPosPionTOF; Float_t d2sigmacascposprotontpctof = nSigmaCascPosProtonTPC * nSigmaCascPosProtonTPC + nSigmaCascPosProtonTOF * nSigmaCascPosProtonTOF; Float_t d2sigmacascnegkaontpctof = nSigmaCascNegKaonTPC * nSigmaCascNegKaonTPC + nSigmaCascNegKaonTOF * nSigmaCascNegKaonTPC; Float_t d2sigmacascnegpiontpdtof = nSigmaCascNegPionTPC * nSigmaCascNegPionTPC + nSigmaCascNegPionTOF * nSigmaCascNegPionTOF; Float_t d2sigmacascnegprotontpctof = nSigmaCascNegProtonTPC * nSigmaCascNegProtonTPC + nSigmaCascNegProtonTOF * nSigmaCascNegProtonTOF; Bool_t fPIDTOF_cascbach; Bool_t fPIDTOF_cascpos; Bool_t fPIDTOF_cascneg; if (fPIDResponse->CheckPIDStatus(AliPIDResponse::kTOF, myTrackCascBach) == 0) fPIDTOF_cascbach = kFALSE; else fPIDTOF_cascbach = kTRUE; if (fPIDResponse->CheckPIDStatus(AliPIDResponse::kTOF, myTrackCascPos) == 0) fPIDTOF_cascpos = kFALSE; else fPIDTOF_cascpos = kTRUE; if (fPIDResponse->CheckPIDStatus(AliPIDResponse::kTOF, myTrackCascNeg) == 0) fPIDTOF_cascneg = kFALSE; else fPIDTOF_cascneg = kTRUE; Float_t nSigmaCascBachKaonTOFTPC; Float_t nSigmaCascBachPionTOFTPC; Float_t nSigmaCascBachProtonTOFTPC; Float_t nSigmaCascPosKaonTOFTPC; Float_t nSigmaCascPosPionTOFTPC; Float_t nSigmaCascPosProtonTOFTPC; Float_t nSigmaCascNegKaonTOFTPC; Float_t nSigmaCascNegPionTOFTPC; Float_t nSigmaCascNegProtonTOFTPC; if (fPIDTOF_cascbach && myTrackCascBach->Pt() > 0.5) { nSigmaCascBachKaonTOFTPC = TMath::Sqrt(d2sigmacascbachkaontpctof); nSigmaCascBachPionTOFTPC = TMath::Sqrt(d2sigmacascbachpiontpctof); nSigmaCascBachProtonTOFTPC = TMath::Sqrt(d2sigmacascbachprotontpctof); } else { nSigmaCascBachKaonTOFTPC = TMath::Abs(nSigmaCascBachKaonTPC); nSigmaCascBachPionTOFTPC = TMath::Abs(nSigmaCascBachPionTPC); nSigmaCascBachProtonTOFTPC = TMath::Abs(nSigmaCascBachProtonTPC); } if (fPIDTOF_cascpos && myTrackCascPos->Pt() > 0.5) { nSigmaCascPosKaonTOFTPC = TMath::Sqrt(d2sigmacascbachkaontpctof); nSigmaCascPosPionTOFTPC = TMath::Sqrt(d2sigmacascbachpiontpctof); nSigmaCascPosProtonTOFTPC = TMath::Sqrt(d2sigmacascbachprotontpctof); } else { nSigmaCascPosKaonTOFTPC = TMath::Abs(nSigmaCascPosKaonTPC); nSigmaCascPosPionTOFTPC = TMath::Abs(nSigmaCascPosPionTPC); nSigmaCascPosProtonTOFTPC = TMath::Abs(nSigmaCascPosProtonTPC); } if (fPIDTOF_cascpos && myTrackCascNeg->Pt() > 0.5) { nSigmaCascNegKaonTOFTPC = TMath::Sqrt(d2sigmacascbachkaontpctof); nSigmaCascNegPionTOFTPC = TMath::Sqrt(d2sigmacascbachpiontpctof); nSigmaCascNegProtonTOFTPC = TMath::Sqrt(d2sigmacascbachprotontpctof); } else { nSigmaCascNegKaonTOFTPC = TMath::Abs(nSigmaCascNegKaonTPC); nSigmaCascNegPionTOFTPC = TMath::Abs(nSigmaCascNegPionTPC); nSigmaCascNegProtonTOFTPC = TMath::Abs(nSigmaCascNegProtonTPC); } Int_t SpPID_cascbach = 999; // 1:kaon 2:pion 3:proton Int_t SpPID_cascpos = 999; Int_t SpPID_cascneg = 999; /* if( (nSigmaCascBachKaonTOFTPC<5.0) && (nSigmaCascBachKaonTOFTPC<nSigmaCascBachPionTOFTPC) && (nSigmaCascBachKaonTOFTPC<nSigmaCascBachProtonTOFTPC) ) SpPID_cascbach=1; if( (nSigmaCascBachPionTOFTPC<5.0) && (nSigmaCascBachPionTOFTPC<nSigmaCascBachKaonTOFTPC) && (nSigmaCascBachPionTOFTPC<nSigmaCascBachProtonTOFTPC) ) SpPID_cascbach=2; if( (nSigmaCascPosPionTOFTPC<5.0) && (nSigmaCascPosPionTOFTPC<nSigmaCascPosKaonTOFTPC) && (nSigmaCascPosPionTOFTPC<nSigmaCascPosProtonTOFTPC) ) SpPID_cascpos=2; if( (nSigmaCascPosProtonTOFTPC<5.0) && (nSigmaCascPosPionTOFTPC<nSigmaCascPosKaonTOFTPC) && (nSigmaCascPosProtonTOFTPC<nSigmaCascPosPionTOFTPC) ) SpPID_cascpos=3; if( (nSigmaCascNegPionTOFTPC<5.0) && (nSigmaCascNegPionTOFTPC<nSigmaCascNegKaonTOFTPC) && (nSigmaCascNegPionTOFTPC<nSigmaCascNegProtonTOFTPC) ) SpPID_cascneg=2; if( (nSigmaCascNegProtonTOFTPC<5.0) && (nSigmaCascNegPionTOFTPC<nSigmaCascNegKaonTOFTPC) && (nSigmaCascNegProtonTOFTPC<nSigmaCascNegPionTOFTPC) ) SpPID_cascneg=3; */ if (TMath::Abs(nSigmaCascBachKaonTPC) < 5.0) SpPID_cascbach = 1; if (TMath::Abs(nSigmaCascBachPionTPC) < 5.0) SpPID_cascbach = 2; if (TMath::Abs(nSigmaCascPosPionTPC) < 5.0) SpPID_cascpos = 2; if (TMath::Abs(nSigmaCascPosProtonTPC) < 5.0) SpPID_cascpos = 3; if (TMath::Abs(nSigmaCascNegPionTPC) < 5.0) SpPID_cascneg = 2; if (TMath::Abs(nSigmaCascNegProtonTPC) < 5.0) SpPID_cascneg = 3; Bool_t cutXiMinusPID = (SpPID_cascbach == 2 && SpPID_cascneg == 2 && SpPID_cascpos == 3); Bool_t cutXiPlusPID = (SpPID_cascbach == 2 && SpPID_cascneg == 3 && SpPID_cascpos == 2); Bool_t cutOmegaMinusPID = (SpPID_cascbach == 1 && SpPID_cascneg == 2 && SpPID_cascpos == 3); Bool_t cutOmegaPlusPID = (SpPID_cascbach == 1 && SpPID_cascneg == 3 && SpPID_cascpos == 2); Bool_t cutMassXi = ((lInvMassxi > 1.2) && (lInvMassxi < 1.4)); Bool_t cutMassOmega = ((lInvMassomega > 1.55) && (lInvMassomega < 1.75)); Bool_t cutXiMinussc = cutXictau && cutXiMinusPID && topoXi && (!cutMassOmega); Bool_t cutXiPlussc = cutXictau && cutXiPlusPID && topoXi && (!cutMassOmega); Bool_t cutOmegaMinussc = cutOmegactau && cutOmegaMinusPID && topoOmega && (!cutMassXi); Bool_t cutOmegaPlussc = cutOmegactau && cutOmegaPlusPID && topoOmega && (!cutMassXi); Double_t lPtCas = TMath::Sqrt((casc->MomXiX()) * (casc->MomXiX()) + (casc->MomXiY()) * (casc->MomXiY())); Double_t spXiMinus[3] = {lInvMassXiMinus, lPtCas, lCentrality}; Double_t spXiPlus[3] = {lInvMassXiPlus, lPtCas, lCentrality}; Double_t spOmegaMinus[3] = {lInvMassOmegaMinus, lPtCas, lCentrality}; Double_t spOmegaPlus[3] = {lInvMassOmegaPlus, lPtCas, lCentrality}; if (cutXiMinussc && cutMassXi) fHistMassXiMinus->Fill(spXiMinus); if (cutXiPlussc && cutMassXi) fHistMassXiPlus->Fill(spXiPlus); if (cutOmegaMinussc && cutMassOmega) fHistMassOmegaMinus->Fill(spOmegaMinus); if (cutOmegaPlussc && cutMassOmega) fHistMassOmegaPlus->Fill(spOmegaPlus); // if (cutOmegaMinussc) cout << lInvMassOmegaMinus << endl; Double_t etaCas = 0.5 * TMath::Log((lPCas + casc->MomXiZ()) / (lPCas - casc->MomXiZ())); if (TMath::Abs(etaCas) > 0.8) continue; Double_t phiCas = TMath::ATan2(casc->MomXiY(), casc->MomXiX()); if (phiCas < 0.) phiCas += 2 * TMath::Pi(); Int_t SpCas = -999; Bool_t IDXi = (cutXiMinussc || cutXiPlussc) && cutMassXi; Bool_t IDOmega = (cutOmegaMinussc || cutOmegaPlussc) && cutMassOmega; Bool_t XiSignal = ((lInvMassxi > 1.314) && (lInvMassxi < 1.33)); Bool_t XiSignalBg1 = ((lInvMassxi < 1.314) && (lInvMassxi > 1.2)); Bool_t XiSignalBg2 = ((lInvMassxi > 1.33) && (lInvMassxi < 1.4)); Bool_t OmegaSignal = ((lInvMassomega > 1.667) && (lInvMassomega < 1.678)); Bool_t OmegaSignalBg1 = ((lInvMassomega < 1.667) && (lInvMassomega > 1.55)); Bool_t OmegaSignalBg2 = ((lInvMassomega > 1.678) && (lInvMassomega < 1.75)); if (IDXi && XiSignal) SpCas = 0; if (IDXi && XiSignalBg1) SpCas = 1; if (IDXi && XiSignalBg2) SpCas = 2; if (IDOmega && OmegaSignal) SpCas = 3; if (IDOmega && OmegaSignalBg1) SpCas = 4; if (IDOmega && OmegaSignalBg2) SpCas = 5; if(SpCas<0) continue; Double_t spCascadeQA[5] = {casc->Pt(),casc->Eta(), casc->Phi(), (Float_t)SpCas, lCentrality}; fHist_CascadeQA->Fill(spCascadeQA); tracks->Add(new AliAssociatedTrackYS(1., etaCas, phiCas, lPtCas, myTrackCascPos->GetID(),myTrackCascNeg->GetID(), myTrackCascBach->GetID(), SpCas, 1)); } return tracks; } Bool_t AliAnalysisTaskSEpPbCorrelationsYS::IsAcceptedCascade( const AliAODcascade *casc) { if (!casc) return kFALSE; /* AliAODTrack *ptrack = (AliAODTrack*) (casc->GetDaughter(0)); AliAODTrack *ntrack = (AliAODTrack*) (casc->GetDaughter(1)); AliAODTrack *btrack = (AliAODTrack*) (casc->GetDecayVertexXi()->GetDaughter(0)); if(!ptrack||!ntrack||!btrack) return kFALSE; */ const Double_t mLPDG = TDatabasePDG::Instance()->GetParticle(3122)->Mass(); const Double_t mxiPDG = TDatabasePDG::Instance()->GetParticle(3312)->Mass(); const Double_t momegaPDG = TDatabasePDG::Instance()->GetParticle(3334)->Mass(); Double_t massLambda=-1.; Double_t massAntiLambda=-1.; if(casc->ChargeXi()<0){ massLambda = casc->MassLambda(); if(TMath::Abs(massLambda-mLPDG)>0.00775) return kFALSE; }else{ massAntiLambda = casc->MassAntiLambda(); if(TMath::Abs(massAntiLambda-mLPDG)>0.00775) return kFALSE; } Double_t lPosXi[3]; lPosXi[0] = casc->DecayVertexXiX(); lPosXi[1] = casc->DecayVertexXiY(); lPosXi[2] = casc->DecayVertexXiZ(); Double_t decayvertXi = TMath::Sqrt(lPosXi[0] * lPosXi[0] + lPosXi[1] * lPosXi[1]); Double_t lPosV0[3]; lPosV0[0] = casc->DecayVertexV0X(); lPosV0[1] = casc->DecayVertexV0Y(); lPosV0[2] = casc->DecayVertexV0Z(); Double_t decayvertV0 = TMath::Sqrt(lPosV0[0] * lPosV0[0] + lPosV0[1] * lPosV0[1]); if (decayvertV0 < 1.55) return kFALSE; // Decay vertex V0 if (decayvertXi < 0.29) return kFALSE; // Decay Vertex Xi Double_t lDcaXiDaughters = casc->DcaXiDaughters(); Double_t lDcaV0Daughters = casc->DcaV0Daughters(); if (lDcaXiDaughters > 1.83) return kFALSE; // DCA between Xi Daughters if (lDcaV0Daughters > 1.33) return kFALSE; // DCA between V0 Daughters Double_t lDcaBachToPrimVertex = casc->DcaBachToPrimVertex(); Double_t lDcaV0ToPrimVertex = casc->DcaV0ToPrimVertex(); Double_t lDcaPosToPrimVertex = casc->DcaPosToPrimVertex(); Double_t lDcaNegToPrimVertex = casc->DcaNegToPrimVertex(); if (lDcaBachToPrimVertex < 0.0146) return kFALSE; // DCA between Bach track and Primary vertex if (lDcaV0ToPrimVertex < 0.02) return kFALSE; // DCA between V0 deday vertex and primary vertex if (lDcaPosToPrimVertex < 0.061) return kFALSE; // DCA between Pos track and Primary vertex if (lDcaNegToPrimVertex < 0.061) return kFALSE; // DCA between Neg track and Primary vertex Double_t lXiCosineOfPointingAngle = casc->CosPointingAngleXi(tPrimaryVtxPosition[0], tPrimaryVtxPosition[1], tPrimaryVtxPosition[2]); Double_t lV0CosineOfPointingAngleXi = casc->CosPointingAngle(lPosXi); if (lXiCosineOfPointingAngle < 0.9813) return kFALSE; // Pointing angle of Xi if (lV0CosineOfPointingAngleXi < 0.97) return kFALSE; /// Pointing angle of V0 return kTRUE; } Bool_t AliAnalysisTaskSEpPbCorrelationsYS::IsAcceptedCascadeOmega(const AliAODcascade *casc) { if (!casc) return kFALSE; const Double_t mLPDG = TDatabasePDG::Instance()->GetParticle(3122)->Mass(); const Double_t mxiPDG = TDatabasePDG::Instance()->GetParticle(3312)->Mass(); const Double_t momegaPDG = TDatabasePDG::Instance()->GetParticle(3334)->Mass(); Double_t massLambda=-1.; Double_t massAntiLambda=-1.; if(casc->ChargeXi()<0){ massLambda = casc->MassLambda(); if(TMath::Abs(massLambda-mLPDG)>0.00775) return kFALSE; }else{ massAntiLambda = casc->MassAntiLambda(); if(TMath::Abs(massAntiLambda-mLPDG)>0.00775) return kFALSE; } Double_t lPosXi[3]; lPosXi[0] = casc->DecayVertexXiX(); lPosXi[1] = casc->DecayVertexXiY(); lPosXi[2] = casc->DecayVertexXiZ(); Double_t decayvertXi = TMath::Sqrt(lPosXi[0] * lPosXi[0] + lPosXi[1] * lPosXi[1]); Double_t lPosV0[3]; lPosV0[0] = casc->DecayVertexV0X(); lPosV0[1] = casc->DecayVertexV0Y(); lPosV0[2] = casc->DecayVertexV0Z(); Double_t decayvertV0 = TMath::Sqrt(lPosV0[0] * lPosV0[0] + lPosV0[1] * lPosV0[1]); if (decayvertV0 < 1.918) return kFALSE; // Decay vertex V0 if (decayvertXi < 0.59) return kFALSE; // Decay Vertex Xi Double_t lDcaXiDaughters = casc->DcaXiDaughters(); Double_t lDcaV0Daughters = casc->DcaV0Daughters(); if (lDcaXiDaughters > 1.091) return kFALSE; // DCA between Xi Daughters if (lDcaV0Daughters > 1.206) return kFALSE; // DCA between V0 Daughters Double_t lDcaBachToPrimVertex = casc->DcaBachToPrimVertex(); Double_t lDcaV0ToPrimVertex = casc->DcaV0ToPrimVertex(); Double_t lDcaPosToPrimVertex = casc->DcaPosToPrimVertex(); Double_t lDcaNegToPrimVertex = casc->DcaNegToPrimVertex(); if (lDcaBachToPrimVertex < 0.041) return kFALSE; // DCA between Bach track and Primary vertex if (lDcaV0ToPrimVertex < 0.068) return kFALSE; // DCA between V0 deday vertex and primary vertex if (lDcaPosToPrimVertex < 0.061) return kFALSE; // DCA between Pos track and Primary vertex if (lDcaNegToPrimVertex < 0.061) return kFALSE; // DCA between Neg track and Primary vertex Double_t lXiCosineOfPointingAngle = casc->CosPointingAngleXi(tPrimaryVtxPosition[0], tPrimaryVtxPosition[1], tPrimaryVtxPosition[2]); Double_t lV0CosineOfPointingAngleXi = casc->CosPointingAngle(lPosXi); if (lXiCosineOfPointingAngle < 0.9811) return kFALSE; // Pointing angle of Xi if (lV0CosineOfPointingAngleXi < 0.933) return kFALSE; /// Pointing angle of V0 return kTRUE; } Bool_t AliAnalysisTaskSEpPbCorrelationsYS::IsAcceptedPhiDaughterTrack(const AliAODTrack *aodTrack) { if (!aodTrack->TestFilterMask(BIT(ffilterbit))) return kFALSE; if (aodTrack->Pt() < 0.15) return kFALSE; if (TMath::Abs(aodTrack->Eta()) > 0.8) return kFALSE; if (aodTrack->Charge() == 0) return kFALSE; return kTRUE; } Bool_t AliAnalysisTaskSEpPbCorrelationsYS::IsAcceptedDaughterTrack(const AliAODTrack *itrack) {//apply for V0s and Cascade if (TMath::Abs(itrack->Eta()) > 0.8) return kFALSE; // if(itrack->Eta()>fEtaMaxDaughter || itrack->Eta()<fEtaMinDaughter) return kFALSE; if (!itrack->IsOn(AliAODTrack::kTPCrefit)) return kFALSE; Float_t nCrossedRowsTPC = itrack->GetTPCClusterInfo(2, 1); if (nCrossedRowsTPC < fclustermin) return kFALSE; Int_t findable = itrack->GetTPCNclsF(); if (findable <= 0) return kFALSE; if (nCrossedRowsTPC / findable < fratiocluster) return kFALSE; if (itrack->GetKinkIndex(0) > 0) return kFALSE; // if(itrack->Pt()<0.15) return kFALSE; if(itrack->Pt()<0.1) return kFALSE; return kTRUE; } Bool_t AliAnalysisTaskSEpPbCorrelationsYS::IsAcceptedTrack(const AliAODTrack *aodTrack) { if (!aodTrack) return kFALSE; // if(!aodTrack->TestFilterMask(BIT(5))) return kFALSE; // standard cut with // tight DCA cut if(fcollisiontype=="PbPb"){ if (!aodTrack->TestFilterBit(ffilterbit)) return kFALSE; Float_t nCrossedRowsTPC =aodTrack->GetTPCClusterInfo(2,1); if (nCrossedRowsTPC < fnoClusters) return kFALSE; if(fCutChargedDCAzMax > 0. ||fCutChargedDCAxyMax > 0.){ Double_t dTrackXYZ[3] = {0.,0.,0.}; Double_t dVertexXYZ[3] = {0.,0.,0.}; Double_t dDCAXYZ[3] = {0.,0.,0.}; aodTrack->GetXYZ(dTrackXYZ); lPrimaryBestVtx->GetXYZ(dVertexXYZ); for(Short_t i(0); i < 3; i++) { dDCAXYZ[i] = dTrackXYZ[i] - dVertexXYZ[i]; } if(fCutChargedDCAzMax > 0. && TMath::Abs(dDCAXYZ[2]) >fCutChargedDCAzMax) return kFALSE; if(fCutChargedDCAxyMax > 0. && TMath::Sqrt(dDCAXYZ[0]*dDCAXYZ[0] + dDCAXYZ[1]*dDCAXYZ[1]) > fCutChargedDCAxyMax) return kFALSE; } }else{ // if(aodTrack->TestFilterMask(BIT(5))!=aodTrack->TestFilterBit(32)) cout<<"bad!!!!!!!!!!!!!!!!!!!!!!!!!!!!"<<endl; // if (!aodTrack->TestFilterMask(BIT(ffilterbit))) return kFALSE; if (!aodTrack->TestFilterBit(ffilterbit)) return kFALSE; } /* if (!aodTrack->IsOn(AliAODTrack::kTPCrefit)) return kFALSE; Float_t nCrossedRowsTPC =aodTrack->GetTPCClusterInfo(2,1); if (nCrossedRowsTPC < 70) return kFALSE; Int_t findable=aodTrack->GetTPCNclsF(); if (findable <= 0)return kFALSE; if (nCrossedRowsTPC/findable < 0.8) return kFALSE; */ if (aodTrack->Pt() < fPtMin) return kFALSE; if(aodTrack->Pt()>8.) return kFALSE; if(!fptdiff) {if (aodTrack->Pt() > fPtMax) return kFALSE;} if (TMath::Abs(aodTrack->Eta()) > fEtaMax) return kFALSE; return kTRUE; } Bool_t AliAnalysisTaskSEpPbCorrelationsYS::IsAcceptedV0(const AliAODv0 *aodV0) { /* Pseudo rapidity V0 < 0.8 daughter tracks DCA to P >0.06cm DCA between daughters <1 sigma V0 2D decay radius from 0.5cm to 200cm */ if (!aodV0) return kFALSE; if(aodV0->GetOnFlyStatus()) fHist_V0Stat->Fill(1); //Onfly else fHist_V0Stat->Fill(2); //Onfly if (fOnfly) { if (!aodV0->GetOnFlyStatus()) return kFALSE; // onfly reconstraction only } else { if (aodV0->GetOnFlyStatus()) return kFALSE; // ofline reconstraction only } Double_t leta_v0 = aodV0->PseudoRapV0(); if (TMath::Abs(leta_v0) > 0.8) return kFALSE; // default 0.8 // if (leta_v0 < fEtaMinV0 || fEtaMaxV0<leta_v0) return kFALSE; // default 0.8 else fHist_V0Stat->Fill(3); // DCA to primary vertex Float_t xyn = aodV0->DcaNegToPrimVertex(); Float_t xyp = aodV0->DcaPosToPrimVertex(); if ((TMath::Abs(xyn) > fdcaDaughtersToPrimVtx) || (TMath::Abs(xyp) > fdcaDaughtersToPrimVtx)) fHist_V0Stat->Fill(4); if (TMath::Abs(xyn) < fdcaDaughtersToPrimVtx) return kFALSE; // default 0.06 if (TMath::Abs(xyp) < fdcaDaughtersToPrimVtx) return kFALSE; // default 0.06 // DCA between dauther tracks Double_t dca = aodV0->DcaV0Daughters(); if (dca > fdcaBetweenDaughters) return kFALSE; // default 1.0 else fHist_V0Stat->Fill(5); // Fiducial volume Double_t xyz[3]; aodV0->GetSecondaryVtx(xyz); Double_t r2 = xyz[0] * xyz[0] + xyz[1] * xyz[1]; if (r2 > fRadiMin * fRadiMin && r2 < fRadiMax * fRadiMax) fHist_V0Stat->Fill(6); if (r2 < fRadiMin * fRadiMin) return kFALSE; // default 0.5 cm if (r2 > fRadiMax * fRadiMax) return kFALSE; // default 100cm return kTRUE; } Bool_t AliAnalysisTaskSEpPbCorrelationsYS::IsAcceptedDecayLength(const AliAODv0*aodv0,Double_t mass,Double_t maxctau){ Double_t lDVx = aodv0->GetSecVtxX(); Double_t lDVy = aodv0->GetSecVtxY(); Double_t lDVz = aodv0->GetSecVtxZ(); Double_t lV0DecayLength =TMath::Sqrt(TMath::Power(lDVx - tPrimaryVtxPosition[0], 2) + TMath::Power(lDVy - tPrimaryVtxPosition[1], 2) + TMath::Power(lDVz - tPrimaryVtxPosition[2], 2)); Double_t lPV0 = TMath::Sqrt((aodv0->Pt()) * (aodv0->Pt()) +(aodv0->Pz()) * (aodv0->Pz())); Double_t lcTau = (lV0DecayLength * mass) / lPV0; if(lcTau>maxctau) return kFALSE; return kTRUE; } void AliAnalysisTaskSEpPbCorrelationsYS::FillCorrelationTracks( Double_t centrality, TObjArray *triggerArray, TObjArray *selectedTrackArray,AliTHn *triggerHist, AliTHn *associateHist, Bool_t twoTrackEfficiencyCut, Float_t twoTrackEfficiencyCutValue, Float_t fTwoTrackCutMinRadius,Float_t bSign, Int_t step) { twoTrackEfficiencyCut=kFALSE; twoTrackEfficiencyCutValue=0; fTwoTrackCutMinRadius=0; bSign=0; step=1;//default if (!triggerHist || !associateHist) return; if(fAnaMode=="TPCTPC"){ Double_t binscontTrig[3]; Double_t binscont[6]; for (Int_t i = 0; i < triggerArray->GetEntriesFast(); i++) { AliAssociatedTrackYS *trigger = (AliAssociatedTrackYS *)triggerArray->At(i); if (!trigger) continue; Float_t triggerPt = trigger->Pt(); Float_t triggerEta = trigger->Eta(); Float_t triggerPhi = trigger->Phi(); Int_t trigFirstID = trigger->GetIDFirstDaughter(); Int_t trigSecondID = trigger->GetIDSecondDaughter(); Int_t trigID = trigger->GetID(); binscontTrig[0] = triggerPt; binscontTrig[1] = centrality; binscontTrig[2] = fPrimaryZVtx; Float_t triggermultiplicity=trigger->Multiplicity(); /* Float_t efficiency=999; Int_t ivzbin=frefvz->GetXaxis()->FindBin(fPrimaryZVtx); if(fefficalib){ Int_t iPt=fhcorr[ivzbin-1]->GetXaxis()->FindBin(triggerPt); Int_t iEta=fhcorr[ivzbin-1]->GetYaxis()->FindBin(triggerEta); Int_t iPhi=fhcorr[ivzbin-1]->GetZaxis()->FindBin(triggerPhi); efficiency=fhcorr[ivzbin-1]->GetBinContent(iPt,iEta,iPhi); }else efficiency=1.; if(efficiency==0.) continue; */ // triggerHist->Fill(binscontTrig,0,1./efficiency); triggerHist->Fill(binscontTrig,0,triggermultiplicity); for (Int_t j = 0; j < selectedTrackArray->GetEntriesFast(); j++) { AliAssociatedTrackYS *associate = (AliAssociatedTrackYS*)selectedTrackArray->At(j); if (!associate) continue; Int_t AssoFirstID = associate->GetIDFirstDaughter(); Int_t AssoSecondID = associate->GetIDSecondDaughter(); if (fasso == "V0" || fasso == "Phi"){ if (trigID == AssoFirstID || trigID == AssoSecondID){ continue; } } if (fasso == "hadron" || fasso=="PID") { if (triggerPt < associate->Pt()) continue; if (trigID == associate->GetID()) continue; } if (fasso == "Cascade") if (trigID == associate->GetID() || trigID == AssoFirstID || trigID == AssoSecondID) continue; binscont[0] = triggerEta - associate->Eta(); binscont[1] = associate->Pt(); binscont[2] = triggerPt; binscont[3] = centrality; binscont[4] = RangePhi(triggerPhi - associate->Phi()); binscont[5] = fPrimaryZVtx; Float_t assomultiplicity=associate->Multiplicity(); /* Float_t efficiency1=999.; if(fefficalib){ Int_t iPt1=fhcorr[ivzbin-1]->GetXaxis()->FindBin(associate->Pt()); Int_t iEta1=fhcorr[ivzbin-1]->GetYaxis()->FindBin(associate->Eta()); Int_t iPhi1=fhcorr[ivzbin-1]->GetZaxis()->FindBin(associate->Phi()); efficiency1=fhcorr[ivzbin-1]->GetBinContent(iPt1,iEta1,iPhi1); }else efficiency1=1.; if(efficiency1==0.) continue; */ Int_t SpAsso = associate->WhichCandidate(); if (fasso == "V0" || fasso == "Phi" || fasso == "Cascade" || (fasso == "PID")) { if (SpAsso < 0) continue; associateHist->Fill(binscont, SpAsso); }else if(fasso=="hadron"){ // associateHist->Fill(binscont, 0,1./(efficiency*efficiency1)); associateHist->Fill(binscont, 0,triggermultiplicity*assomultiplicity); } } } }else if (fAnaMode=="TPCV0A" || fAnaMode=="TPCV0C" || fAnaMode=="TPCFMD" || fAnaMode=="TPCFMDC"){ Double_t binscontTrig[4]; Double_t binscont[7]; for(Int_t i=0;i<triggerArray->GetEntriesFast();i++){ AliAssociatedTrackYS* trigger = (AliAssociatedTrackYS*) triggerArray->At(i); if(!trigger)continue; Float_t triggerEta = trigger->Eta(); Float_t triggerPhi = trigger->Phi(); Float_t triggerPt = trigger->Pt(); binscontTrig[0]=triggerPt; binscontTrig[1]=centrality; binscontTrig[2]=fPrimaryZVtx; binscontTrig[3]=triggerEta; Float_t triggermultiplicity=trigger->Multiplicity(); Int_t SpAsso= trigger->WhichCandidate(); // triggerHist->Fill(binscontTrig,0,1./efficiency); triggerHist->Fill(binscontTrig,0,triggermultiplicity); for (Int_t j=0; j<selectedTrackArray->GetEntriesFast(); j++){ AliAssociatedTrackYS* associate = (AliAssociatedTrackYS*) selectedTrackArray->At(j); if(!associate)continue; Float_t associatemultiplicity=associate->Multiplicity(); Float_t assophi=associate->Phi(); Float_t assoeta=associate->Eta(); binscont[0]=triggerEta-associate->Eta(); binscont[1]=triggerPt; binscont[2]=associate->Eta(); binscont[3]=centrality; binscont[4]=RangePhi(triggerPhi-associate->Phi()); binscont[5]=fPrimaryZVtx; binscont[6]=triggerEta; // associateHist->Fill(binscont, 0, (Double_t)associate->Multiplicity()/efficienc); associateHist->Fill(binscont, 0, (Double_t)associate->Multiplicity()*triggermultiplicity); } } }else if (fAnaMode=="ITSFMD" || fAnaMode=="ITSFMDC"){ Double_t binscontTrig[4]; Double_t binscont[6]; for(Int_t i=0;i<triggerArray->GetEntriesFast();i++){ AliAssociatedTrackYS* trigger = (AliAssociatedTrackYS*) triggerArray->At(i); if(!trigger)continue; Float_t triggerEta = trigger->Eta(); Float_t triggerPhi = trigger->Phi(); Float_t triggerPt = 0.5; binscontTrig[0]=triggerPt; binscontTrig[1]=centrality; binscontTrig[2]=fPrimaryZVtx; binscontTrig[3]=triggerEta; Int_t SpAsso= trigger->WhichCandidate(); triggerHist->Fill(binscontTrig,SpAsso); for (Int_t j=0; j<selectedTrackArray->GetEntriesFast(); j++){ AliAssociatedTrackYS* associate = (AliAssociatedTrackYS*) selectedTrackArray->At(j); if(!associate)continue; Float_t associatemultiplicity=associate->Multiplicity(); Float_t assophi=associate->Phi(); Float_t assoeta=associate->Eta(); binscont[0]=triggerEta-associate->Eta(); binscont[1]=centrality; binscont[2]=associate->Eta(); binscont[3]=RangePhi(triggerPhi-associate->Phi()); binscont[4]=fPrimaryZVtx; binscont[5]=triggerEta; associateHist->Fill(binscont, 0, (Double_t)associate->Multiplicity()); } } } else if(fAnaMode=="FMDFMD"|| fAnaMode=="FMDFMD_Ctrig"){ Double_t binscontTrig[3]; Double_t binscont[6]; for(Int_t i=0;i<triggerArray->GetEntriesFast();i++){ AliAssociatedTrackYS* trigger = (AliAssociatedTrackYS*) triggerArray->At(i); if(!trigger)continue; Float_t triggerMultiplicity= trigger->Multiplicity(); Float_t triggerEta = trigger->Eta(); Float_t triggerPhi = trigger->Phi(); binscontTrig[0]=centrality; binscontTrig[1]=triggerEta; binscontTrig[2]=fPrimaryZVtx; triggerHist->Fill(binscontTrig,0,(Double_t)triggerMultiplicity); for (Int_t j=0; j<selectedTrackArray->GetEntriesFast(); j++){ AliAssociatedTrackYS* associate = (AliAssociatedTrackYS*) selectedTrackArray->At(j); if(!associate)continue; Float_t assophi=associate->Phi(); Float_t assoeta=associate->Eta(); Float_t mult=associate->Multiplicity()*triggerMultiplicity; binscont[0]=triggerEta-associate->Eta(); binscont[1]=associate->Eta(); binscont[2]=triggerEta; binscont[3]=centrality; binscont[4]=RangePhi_FMD(triggerPhi-associate->Phi()); binscont[5]=fPrimaryZVtx; Float_t dphivzero=triggerPhi-associate->Phi(); if(triggerPhi==assophi && triggerEta==assoeta) continue; associateHist->Fill(binscont,0,(Double_t)mult); } } }else if(fAnaMode=="SECA"||fAnaMode=="SECC"){ Double_t binscontTrig[3]; Double_t binscont[5]; for(Int_t i=0;i<triggerArray->GetEntriesFast();i++){ AliAssociatedTrackYS* trigger = (AliAssociatedTrackYS*) triggerArray->At(i); if(!trigger)continue; Float_t triggerMultiplicity= trigger->Multiplicity(); Float_t triggerEta = trigger->Eta(); Float_t triggerPhi = trigger->Phi(); binscontTrig[0]=centrality; binscontTrig[1]=triggerEta; binscontTrig[2]=fPrimaryZVtx; triggerHist->Fill(binscontTrig,0,(Double_t)triggerMultiplicity); for (Int_t j=0; j<selectedTrackArray->GetEntriesFast(); j++){ AliAssociatedTrackYS* associate = (AliAssociatedTrackYS*) selectedTrackArray->At(j); if(!associate)continue; Float_t assophi=associate->Phi(); Float_t assoeta=associate->Eta(); Float_t mult=associate->Multiplicity()*triggerMultiplicity; binscont[0]=triggerEta-associate->Eta(); binscont[1]=triggerEta; binscont[2]=centrality; binscont[3]=RangePhi_FMD(triggerPhi-associate->Phi()); binscont[4]=fPrimaryZVtx; // if(triggerEta>2.7 && triggerEta<2.8)cout<<triggerEta<<" "<<associate->Eta()<<" "<<binscont[0]<<endl; Float_t dphivzero=triggerPhi-associate->Phi(); if(triggerPhi==assophi && triggerEta==assoeta) continue; associateHist->Fill(binscont,0,(Double_t)mult); } } }else if(fAnaMode=="V0AV0C"){ Double_t binscont1[4]; Double_t binscontTrig1[3]; for(Int_t i=0;i<triggerArray->GetEntriesFast();i++){ AliAssociatedTrackYS* trigger = (AliAssociatedTrackYS*) triggerArray->At(i); if(!trigger)continue; Double_t triggerMultiplicity= trigger->Multiplicity(); Double_t triggerEta = trigger->Eta(); Double_t triggerPhi = trigger->Phi(); binscontTrig1[0]=centrality; binscontTrig1[1]=triggerEta; binscontTrig1[2]=triggerPhi; triggerHist->Fill(binscontTrig1,0,(Double_t)triggerMultiplicity); for (Int_t j=0; j<selectedTrackArray->GetEntriesFast(); j++){ AliAssociatedTrackYS* associate = (AliAssociatedTrackYS*) selectedTrackArray->At(j); if(!associate)continue; Double_t associatemultiplicity=associate->Multiplicity(); Double_t assophi=associate->Phi(); Double_t assoeta=associate->Eta(); binscont1[0]=associate->Eta(); binscont1[1]=triggerEta; binscont1[2]=centrality; binscont1[3]=RangePhi2(triggerPhi-associate->Phi()); if(triggerPhi==assophi && triggerEta==assoeta) continue; Double_t dphivzero=triggerPhi-associate->Phi(); associateHist->Fill(binscont1,0,(Double_t)triggerMultiplicity*associatemultiplicity); } } } } void AliAnalysisTaskSEpPbCorrelationsYS::FillCorrelationTracksMixing(Double_t centrality, Double_t pvxMix, Double_t poolmax, Double_t poolmin, TObjArray *triggerArray, TObjArray *selectedTrackArray, AliTHn *triggerHist, AliTHn *associateHist, Bool_t twoTrackEfficiencyCut, Float_t twoTrackEfficiencyCutValue, Float_t fTwoTrackCutMinRadius, Float_t bSign, Int_t step) { Bool_t twoTrackEfficiencyCut_1= twoTrackEfficiencyCut; Double_t twoTrackEfficiencyCutValue_1= twoTrackEfficiencyCutValue; Double_t fTwoTrackCutMinRadius1=fTwoTrackCutMinRadius; Float_t bSign1=bSign; Int_t step1=step; Double_t poolmax1=poolmax; Double_t poolmin1=poolmin; /* if (!triggerHist || !associateHist){ return; } */ Double_t counterMix = 0; AliEventPool *pool = fPoolMgr->GetEventPool(centrality, pvxMix); if (!pool){ AliFatal(Form("No pool found for centrality = %f, zVtx = %f", centrality, pvxMix)); } if (pool->IsReady() || pool->NTracksInPool() > fPoolMinNTracks || pool->GetCurrentNEvents() > fMinEventsToMix) { mixedDist ->Fill(centrality, pool->NTracksInPool()); mixedDist2->Fill(centrality, pool->GetCurrentNEvents()); Int_t nMix = pool->GetCurrentNEvents(); for (Int_t jMix = 0; jMix < nMix; jMix++) { TObjArray *mixEvents = pool->GetEvent(jMix); if(fAnaMode=="TPCTPC"){ Double_t binscontTrig[2]; Double_t binscont[6]; for (Int_t i = 0; i < triggerArray->GetEntriesFast(); i++) { AliAssociatedTrackYS *trig = (AliAssociatedTrackYS *)triggerArray->At(i); if (!trig) continue; Double_t triggerPhi = trig->Phi(); Double_t triggerEta = trig->Eta(); Double_t triggerPt = trig->Pt(); counterMix++; binscontTrig[0] = triggerPt; binscontTrig[1] = centrality; Double_t triggermultiplicity=trig->Multiplicity(); /* Float_t efficiency; Int_t ivzbin=frefvz->GetXaxis()->FindBin(fPrimaryZVtx); if(fefficalib){ Int_t iPt=fhcorr[ivzbin-1]->GetXaxis()->FindBin(triggerPt); Int_t iEta=fhcorr[ivzbin-1]->GetYaxis()->FindBin(triggerEta); Int_t iPhi=fhcorr[ivzbin-1]->GetZaxis()->FindBin(triggerPhi); efficiency=fhcorr[ivzbin-1]->GetBinContent(iPt,iEta,iPhi); }else efficiency=1.; if(efficiency==0.) continue; */ triggerHist->Fill(binscontTrig, 0,triggermultiplicity); for (Int_t j = 0; j < mixEvents->GetEntriesFast(); j++) { AliAssociatedTrackYS *associate = (AliAssociatedTrackYS *)mixEvents->At(j); if (!associate) continue; //if (triggerPt < associate->Pt()) continue; //if (trigID == associate->GetID()) continue; binscont[0] = triggerEta - associate->Eta(); binscont[1] = associate->Pt(); binscont[2] = triggerPt; binscont[3] = centrality; binscont[4] = RangePhi(triggerPhi - associate->Phi()); binscont[5] = pvxMix; Double_t assomultiplicity=associate->Multiplicity(); /* Float_t efficiency1; if(fefficalib){ Int_t iPt1=fhcorr[ivzbin-1]->GetXaxis()->FindBin(associate->Pt()); Int_t iEta1=fhcorr[ivzbin-1]->GetYaxis()->FindBin(associate->Eta()); Int_t iPhi1=fhcorr[ivzbin-1]->GetZaxis()->FindBin(associate->Phi()); efficiency1=fhcorr[ivzbin-1]->GetBinContent(iPt1,iEta1,iPhi1); }else efficiency1=1.; if(efficiency1==0.) continue; */ Int_t SpAsso = associate->WhichCandidate(); if (fasso == "V0" || fasso == "Phi" || fasso == "Cascade" || (fasso == "PID")) { if (SpAsso < 0) continue; associateHist->Fill(binscont, SpAsso, 1. / (Double_t)nMix); }else if(fasso=="hadron"){ associateHist->Fill(binscont, 0,triggermultiplicity*assomultiplicity/(Double_t)nMix); } } } }else if(fAnaMode=="TPCV0A" || fAnaMode=="TPCV0C" || fAnaMode=="TPCFMD" || fAnaMode=="TPCFMDC"){ Double_t binscontTrig[2]; Double_t binscont[7]; //Double_t binscont[6]; for(Int_t i=0;i<triggerArray->GetEntriesFast();i++){ AliAssociatedTrackYS* trigger =(AliAssociatedTrackYS*) triggerArray->At(i); if(!trigger)continue; Double_t triggerPt = trigger->Pt(); Double_t triggerEta = trigger->Eta(); Double_t triggerPhi = trigger->Phi(); Int_t SpAsso=trigger->WhichCandidate(); counterMix++; binscontTrig[0]=triggerPt; binscontTrig[1]=centrality; Int_t ivzbin=frefvz->GetXaxis()->FindBin(fPrimaryZVtx); Double_t triggermultiplicity=trigger->Multiplicity(); /* Float_t efficiency=999.; if(fefficalib){ Int_t iPt=fhcorr[ivzbin-1]->GetXaxis()->FindBin(triggerPt); Int_t iEta=fhcorr[ivzbin-1]->GetYaxis()->FindBin(triggerEta); Int_t iPhi=fhcorr[ivzbin-1]->GetZaxis()->FindBin(triggerPhi); efficiency=fhcorr[ivzbin-1]->GetBinContent(iPt,iEta,iPhi); }else efficiency=1.; if(efficiency==0.) continue; */ triggerHist->Fill(binscontTrig,SpAsso,triggermultiplicity); for (Int_t j=0; j<mixEvents->GetEntriesFast(); j++){ AliAssociatedTrackYS* associate=(AliAssociatedTrackYS*) mixEvents->At(j); if(!associate)continue; binscont[0]=triggerEta-associate->Eta(); binscont[1]=triggerPt; binscont[2]=associate->Eta(); binscont[3]=centrality; binscont[4]=RangePhi(triggerPhi-associate->Phi()); binscont[5]=pvxMix; binscont[6]=triggerEta; /* Int_t nstep=999; if(triggerEta<-0.4) nstep=0; else if(triggerEta>-0.4 && triggerEta<0) nstep=1; else if(triggerEta>0 && triggerEta<0.4) nstep=2; else if(triggerEta>0.4 && triggerEta<0.8) nstep=3; */ associateHist->Fill(binscont, 0,(Double_t)associate->Multiplicity()*triggermultiplicity/(Double_t)nMix); } } }else if(fAnaMode=="ITSFMD" || fAnaMode=="ITSFMDC"){ Double_t binscontTrig[2]; Double_t binscont[6]; for(Int_t i=0;i<triggerArray->GetEntriesFast();i++){ AliAssociatedTrackYS* trigger =(AliAssociatedTrackYS*) triggerArray->At(i); if(!trigger)continue; Double_t triggerPt = 0.5; Double_t triggerEta = trigger->Eta(); Double_t triggerPhi = trigger->Phi(); Int_t SpAsso=trigger->WhichCandidate(); counterMix++; binscontTrig[0]=triggerPt; binscontTrig[1]=centrality; triggerHist->Fill(binscontTrig,SpAsso); for (Int_t j=0; j<mixEvents->GetEntriesFast(); j++){ AliAssociatedTrackYS* associate=(AliAssociatedTrackYS*) mixEvents->At(j); if(!associate)continue; binscont[0]=triggerEta-associate->Eta(); binscont[1]=centrality; binscont[2]=associate->Eta(); binscont[3]=RangePhi(triggerPhi-associate->Phi()); binscont[4]=pvxMix; binscont[5]=triggerEta; associateHist->Fill(binscont, 0,(Double_t)associate->Multiplicity()/(Double_t)nMix); } } }else if(fAnaMode=="FMDFMD"||fAnaMode=="FMDFMD_Ctrig"){ Double_t binscontTrig[2]; Double_t binscont[6]; for(Int_t i=0;i<triggerArray->GetEntriesFast();i++){ AliAssociatedTrackYS* trigger = (AliAssociatedTrackYS*) triggerArray->At(i); if(!trigger)continue; Float_t triggerMultiplicity= trigger->Multiplicity(); Float_t triggerEta = trigger->Eta(); Float_t triggerPhi = trigger->Phi(); counterMix++; binscontTrig[0]=centrality; binscontTrig[1]=triggerEta; triggerHist->Fill(binscontTrig,step,(Double_t)triggerMultiplicity); for (Int_t j=0; j<mixEvents->GetEntriesFast(); j++){ AliAssociatedTrackYS* associate = (AliAssociatedTrackYS*) mixEvents->At(j); if(!associate)continue; // Double_t associatemultiplicity=associate->Multiplicity(); Float_t assophi=associate->Phi(); Float_t assoeta=associate->Eta(); Float_t mult=triggerMultiplicity*associate->Multiplicity(); binscont[0]=triggerEta-associate->Eta(); binscont[1]=associate->Eta(); binscont[2]=triggerEta; binscont[3]=centrality; binscont[4]=RangePhi_FMD(triggerPhi-associate->Phi()); binscont[5]=pvxMix; // if(triggerPhi==assophi && triggerEta==assoeta) continue; // associateHist->Fill(binscont,0,(Double_t)triggerMultiplicity*associatemultiplicity/(Double_t)nMix); associateHist->Fill(binscont,0,mult/(Double_t)nMix); } } }else if(fAnaMode=="SECA"||fAnaMode=="SECC"){ Double_t binscontTrig[2]; Double_t binscont[5]; for(Int_t i=0;i<triggerArray->GetEntriesFast();i++){ AliAssociatedTrackYS* trigger = (AliAssociatedTrackYS*) triggerArray->At(i); if(!trigger)continue; Float_t triggerMultiplicity= trigger->Multiplicity(); Float_t triggerEta = trigger->Eta(); Float_t triggerPhi = trigger->Phi(); counterMix++; binscontTrig[0]=centrality; binscontTrig[1]=triggerEta; triggerHist->Fill(binscontTrig,step,(Double_t)triggerMultiplicity); for (Int_t j=0; j<mixEvents->GetEntriesFast(); j++){ AliAssociatedTrackYS* associate = (AliAssociatedTrackYS*) mixEvents->At(j); if(!associate)continue; // Double_t associatemultiplicity=associate->Multiplicity(); Float_t assophi=associate->Phi(); Float_t assoeta=associate->Eta(); Float_t mult=triggerMultiplicity*associate->Multiplicity(); binscont[0]=triggerEta-associate->Eta(); binscont[1]=triggerEta; binscont[2]=centrality; binscont[3]=RangePhi_FMD(triggerPhi-associate->Phi()); binscont[4]=pvxMix; // if(triggerPhi==assophi && triggerEta==assoeta) continue; // associateHist->Fill(binscont,0,(Double_t)triggerMultiplicity*associatemultiplicity/(Double_t)nMix); associateHist->Fill(binscont,0,mult/(Double_t)nMix); } } }else if (fAnaMode=="V0AV0C"){ Double_t binscont1[4]; Double_t binscontTrig1[3]; for(Int_t i=0;i<triggerArray->GetEntriesFast();i++){ AliAssociatedTrackYS* trigger = (AliAssociatedTrackYS*) triggerArray->At(i); if(!trigger)continue; Double_t triggerMultiplicity= trigger->Multiplicity(); Double_t triggerEta = trigger->Eta(); Double_t triggerPhi = trigger->Phi(); counterMix++; binscontTrig1[0]=centrality; binscontTrig1[1]=triggerEta; binscontTrig1[2]=triggerPhi; triggerHist->Fill(binscontTrig1,step,(Double_t)triggerMultiplicity); for (Int_t j=0; j<mixEvents->GetEntriesFast(); j++){ AliAssociatedTrackYS* associate = (AliAssociatedTrackYS*) mixEvents->At(j); if(!associate)continue; Double_t associatemultiplicity=associate->Multiplicity(); Double_t assophi=associate->Phi(); Double_t assoeta=associate->Eta(); binscont1[0]=associate->Eta(); binscont1[1]=triggerEta; binscont1[2]=centrality; binscont1[3]=RangePhi2(triggerPhi-associate->Phi()); if(triggerPhi==assophi && triggerEta==assoeta) continue; associateHist->Fill(binscont1,0,(Double_t)triggerMultiplicity*associatemultiplicity/(Double_t)nMix); } } } } } TObjArray* tracksClone=CloneTrack(selectedTrackArray); pool->UpdatePool(tracksClone); } TObjArray* AliAnalysisTaskSEpPbCorrelationsYS::CloneTrack(TObjArray*selectedTrackArray){ TObjArray *tracksClone = new TObjArray; tracksClone->SetOwner(kTRUE); for (Int_t i = 0; i < selectedTrackArray->GetEntriesFast(); i++) { AliAssociatedTrackYS *particle = (AliAssociatedTrackYS *)selectedTrackArray->At(i); tracksClone->Add(new AliAssociatedTrackYS(particle->Charge(), particle->Eta(), particle->Phi(), particle->Pt(), particle->GetID(), particle->GetIDFirstDaughter(), particle->GetIDSecondDaughter(), particle->WhichCandidate(), particle->Multiplicity())); } return tracksClone; } Double_t AliAnalysisTaskSEpPbCorrelationsYS::RangePhi(Double_t DPhi) { if (DPhi < -TMath::Pi() / 2) DPhi += 2 * TMath::Pi(); if (DPhi > 3 * TMath::Pi() / 2) DPhi -= 2*TMath::Pi(); return DPhi; } Double_t AliAnalysisTaskSEpPbCorrelationsYS::RangePhi_FMD(Double_t DPhi) { //if (DPhi < (-TMath::Pi() / 2 -0.0001)) DPhi += 2 * TMath::Pi(); //if (DPhi > (3 * TMath::Pi() / 2-0.0001)) DPhi -= 2*TMath::Pi(); DPhi = TMath::ATan2(TMath::Sin(DPhi), TMath::Cos(DPhi)); if (DPhi < (-0.5*TMath::Pi()-0.0001)) DPhi += 2 * TMath::Pi(); return DPhi; } Double_t AliAnalysisTaskSEpPbCorrelationsYS::RangePhi2(Double_t DPhi) { DPhi = TMath::ATan2(TMath::Sin(DPhi), TMath::Cos(DPhi)); if (DPhi < -1.178097) DPhi += 2 * TMath::Pi(); return DPhi; } void AliAnalysisTaskSEpPbCorrelationsYS::DumpTObjTable(const char* note) { /* if(note) { printf("TObjectTable::%s",note); } gObjectTable->Print(); */ } Int_t AliAnalysisTaskSEpPbCorrelationsYS::ConvertRunNumber(Int_t run){ if( (265308<run && run< 265526) || (267160<run && run<267167)){ switch(run){ case 265309 : return 0; case 265332 : return 1; case 265334 : return 2; case 265336 : return 3; case 265338 : return 4; case 265339 : return 5; case 265342 : return 6; case 265343 : return 7; case 265344 : return 8; case 265377 : return 9; case 265378 : return 10; case 265381 : return 11; case 265383 : return 12; case 265384 : return 13; case 265385 : return 14; case 265387 : return 15; case 265388 : return 16; case 265419 : return 17; case 265420 : return 18; case 265421 : return 19; case 265422 : return 20; case 265424 : return 21; case 265425 : return 22; case 265426 : return 23; case 265427 : return 24; case 265435 : return 25; case 265499 : return 26; case 265500 : return 27; case 265501 : return 28; case 265521 : return 29; case 265525 : return 30; case 267166 : return 31; //16t case 267165 : return 32; //16t case 267164 : return 33; //16t case 267163 : return 34; //16t case 267161 : return 35; //16t default : return 199; } } else if(run> 280281 && run<281962){ switch(run){ case 281961 : return 0; // case 281959 : return 1; case 281956 : return 1; case 281953:return 2; case 281940:return 3; case 281939:return 4; case 281932:return 5; case 281931:return 6; case 281928:return 7; case 281920:return 8; case 281918:return 9; case 281915:return 10;// case 281895:return 11;// case 281894:return 12;// case 281892:return 13;// case 281633:return 14;// case 281583:return 15; // case 281581:return 12; // case 281580:return 13; case 281574:return 16; case 281569:return 17; case 281568:return 18; case 281562:return 19; case 281557:return 20; case 281511:return 21; case 281509:return 22; case 281477:return 23; case 281475:return 24; case 281450:return 25; case 281449:return 26; case 281444:return 27; case 281443:return 28; case 281441:return 29; case 281415:return 30; case 281321:return 31; case 281301:return 32; case 281277:return 33; case 281275:return 34; case 281273:return 35; case 281271:return 36; case 281243:return 37; case 281242:return 38; case 281241:return 39; case 281240:return 40; case 281213:return 41; case 281212:return 42; case 281191:return 43; case 281190:return 44; case 281189:return 45; case 281181:return 46; case 281180:return 47;// case 281179:return 48; case 281081:return 49; case 281080:return 50; case 281062:return 51; case 281061:return 52; case 281060:return 53; case 280999:return 54; case 280998:return 55; case 280997:return 56; case 280994:return 57; case 280990:return 58; case 280947:return 59; case 280940:return 60; case 280936:return 61; case 280897:return 62; case 280890:return 63;// case 280881:return 64;// case 280880:return 65; case 280856:return 66; case 280849:return 67; case 280848:return 68; case 280847:return 69; case 280845:return 70;// case 280844:return 71; case 280842:return 72; case 280793:return 73; case 280792:return 74; case 280787:return 75; case 280786:return 76; case 280768:return 77; case 280767:return 78; case 280766:return 79; case 280765:return 80; case 280764:return 81; case 280763:return 82; case 280762:return 83; case 280761:return 84; case 280757:return 85; case 280756:return 86; case 280755:return 87; case 280754:return 88; case 280753:return 89; case 280729:return 90; case 280706:return 91; case 280705:return 92; case 280681:return 93; case 280679:return 94; // case 280676:return 88; // case 280673:return 89; case 280671:return 95; // case 280650:return 91; // case 280648:return 92; case 280647:return 96; case 280645:return 97; case 280639:return 98; case 280637:return 99; case 280636:return 100; case 280634:return 101; case 280613:return 102; case 280583:return 103; case 280581:return 104; case 280576:return 105;// case 280575:return 106;// case 280574:return 107; case 280551:return 108; case 280550:return 109; case 280547:return 110; case 280546:return 111; case 280519:return 112; case 280518:return 113; case 280499:return 114; case 280448:return 115; case 280447:return 116; case 280446:return 117; case 280445:return 118; case 280443:return 119; case 280419:return 120; case 280415:return 121; case 280413:return 122;// case 280406:return 123; case 280405:return 124; case 280403:return 125; case 280375:return 126; case 280374:return 127; // case 280352:return 122; case 280351:return 128; case 280350:return 129; case 280349:return 130; case 280348:return 131; case 280312:return 132; case 280310:return 133; case 280290:return 134; case 280286:return 135; case 280285:return 136; case 280284:return 137; case 280283:return 138; case 280282:return 139; default : return 199; } } else if (run>274689 && run<286509){ switch(run){ //LHC17k case 276508:return 0; case 276507:return 1; case 276506:return 2; case 276462:return 3; case 276439:return 4; case 276438:return 5; case 276437:return 6; case 276435:return 7; case 276351:return 8; case 276348:return 9; case 276312:return 10; case 276307:return 11; case 276302:return 12; case 276297:return 13; case 276294:return 14; case 276292:return 15; case 276291:return 16; case 276290:return 17; case 276259:return 18; case 276257:return 19; case 276230:return 20; case 276205:return 21; case 276178:return 22; case 276170:return 23; case 276104:return 24; case 276102:return 25; case 276099:return 26; case 276098:return 27; case 276097:return 28; case 276045:return 29; case 276041:return 30; case 276040:return 31; case 276020:return 32; case 276019:return 33; case 276017:return 34; case 276013:return 35; case 276012:return 36; case 275925:return 37; case 275924:return 38; case 275847:return 39; case 275664:return 40; case 275661:return 41; case 275657:return 42; case 275650:return 43; case 275648:return 44; case 275647:return 45; case 275624:return 46; case 275623:return 47; case 275622:return 48; case 275621:return 49; case 275617:return 50; case 275612:return 51; case 275559:return 52; case 275558:return 53; case 275515:return 54; case 275472:return 55; case 275471:return 56; case 275467:return 57; case 275459:return 58; case 275457:return 59; case 275456:return 60; case 275453:return 61; case 275452:return 62; case 275448:return 63; case 275443:return 64; case 275406:return 65; case 275404:return 66; case 275401:return 67; case 275395:return 68; case 275394:return 69; case 275372:return 70; case 275369:return 71; case 275361:return 72; case 275360:return 73; case 275333:return 74; case 275332:return 75; case 275328:return 76; case 275326:return 77; case 275324:return 78; case 275322:return 79; case 275314:return 80; case 275283:return 81; case 275247:return 82; case 275246:return 83; case 275245:return 84; case 275239:return 85; case 275188:return 86; case 275184:return 87; case 275180:return 88; case 275177:return 89; case 275174:return 90; case 275173:return 91; case 275151:return 92; case 275150:return 93; case 275149:return 94; case 275076:return 95; case 275075:return 96; case 275073:return 97; case 275068:return 98; case 275067:return 99; case 274979:return 100; case 274978:return 101; case 274886:return 102; case 274882:return 103; case 274878:return 104; case 274877:return 105; case 274822:return 106; case 274821:return 107; case 274817:return 108; case 274815:return 109; case 274811:return 110; case 274807:return 111; case 274806:return 112; case 274803:return 113; case 274802:return 114; case 274801:return 115; case 274708:return 116; case 274690:return 117; default:return 199; } } else if (run> 271867 && run<273104){ switch(run){ //LHC17h case 273103:return 0; case 273100:return 1; case 273099:return 2; case 272949:return 3; case 272947:return 4; case 272939:return 5; case 272935:return 6; case 272934:return 7; case 272933:return 8; case 272932:return 9; case 272905:return 10; case 272903:return 11; case 272871:return 12; case 272870:return 13; case 272836:return 14; case 272833:return 15; case 272829:return 16; case 272828:return 17; case 272784:return 18; case 272782:return 19; case 272764:return 20; case 272763:return 21; case 272760:return 22; case 272749:return 23; case 272747:return 24; case 272746:return 25; case 272712:return 26; case 272692:return 27; case 272610:return 28; case 272608:return 29; case 272607:return 30; case 272585:return 31; case 272577:return 32; case 272575:return 33; case 272574:return 34; case 272521:return 35; case 272468:return 36; case 272463:return 37; case 272462:return 38; case 272461:return 39; case 272413:return 40; case 272411:return 41; case 272400:return 42; case 272399:return 43; case 272395:return 44; case 272394:return 45; case 272389:return 46; case 272388:return 47; case 272360:return 48; case 272359:return 49; case 272335:return 50; case 272194:return 51; case 272156:return 52; case 272155:return 53; case 272154:return 54; case 272153:return 55; case 272152:return 56; case 272123:return 57; case 272101:return 58; case 272100:return 59; case 272041:return 60; case 272040:return 61; case 272039:return 62; case 272038:return 63; case 272036:return 64; case 271886:return 65; case 271881:return 66; case 271880:return 67; case 271874:return 68; case 271873:return 69; case 271871:return 70; case 271870:return 71; case 271868:return 72; default:return 199; } } else if (run>273590 && run<27443){ switch(run){ //LHC17k case 274442:return 0; case 274390:return 1; case 274389:return 2; case 274388:return 3; case 274387:return 4; case 274386:return 5; case 274385:return 6; case 274364:return 7; case 274363:return 8; case 274360:return 9; case 274352:return 10; case 274351:return 11; case 274329:return 12; case 274283:return 13; case 274281:return 14; case 274280:return 15; case 274278:return 16; case 274276:return 17; case 274271:return 18; case 274270:return 19; case 274269:return 20; case 274268:return 21; case 274266:return 22; case 274264:return 23; case 274263:return 24; case 274259:return 25; case 274258:return 26; case 274232:return 27; case 274212:return 28; case 274174:return 29; case 274148:return 30; case 274147:return 31; case 274125:return 32; case 274094:return 33; case 274092:return 34; case 274064:return 35; case 274058:return 36; case 273986:return 37; case 273985:return 38; case 273946:return 39; case 273943:return 40; case 273942:return 41; case 273918:return 42; case 273889:return 43; case 273887:return 44; case 273886:return 45; case 273885:return 46; case 273825:return 47; case 273824:return 48; case 273719:return 49; case 273711:return 50; case 273709:return 51; case 273695:return 52; case 273690:return 53; case 273689:return 54; case 273687:return 55; case 273654:return 56; case 273653:return 57; case 273593:return 58; case 273592:return 59; case 273591:return 60; default :return 199; } } else if (run>274652 && run<274672){ switch(run){ //LHC17j case 274671:return 0; case 274669:return 1; case 274667:return 2; case 274657:return 3; case 274653:return 4; default:return 199; } } else{ return 199; } } Bool_t AliAnalysisTaskSEpPbCorrelationsYS::HasValidFMDYS(TH2D h){ // AliMultSelection *MultSelection = dynamic_cast< AliMultSelection* >(InputEvent()->FindListObject("MultSelection")); //AliMultSelection *MultSelection = (AliMultSelection*)fInputEvent->FindListObject("MultSelection"); // Double_t cent = MultSelection->GetMultiplicityPercentile("V0M"); //if (useEvent) return useEvent; Int_t nBadBins = 0; Int_t phibins = h.GetNbinsY(); Double_t totalFMDpar = 0; // Outlier cut calculations Double_t fSigmaCut = 4.0; for (Int_t etaBin = 1; etaBin <= h.GetNbinsX(); etaBin++) { Double_t eta = h.GetXaxis()->GetBinCenter(etaBin); Double_t runAvg = 0; Double_t avgSqr = 0; Double_t max = 0; Int_t nInAvg = 0; for (Int_t phiBin = 0; phiBin <= phibins; phiBin++) { if ( fabs(eta) > 1.7) { if (phiBin == 0 && h.GetBinContent(etaBin, 0) == 0) break; } Double_t weight = h.GetBinContent(etaBin, phiBin); if (!weight){ weight = 0; } totalFMDpar += weight; // We calculate the average Nch per. bin avgSqr += weight*weight; runAvg += weight; nInAvg++; if (weight == 0) continue; if (weight > max) { max = weight; } } // End of phi loop if (nInAvg > 0) { runAvg /= nInAvg; avgSqr /= nInAvg; Double_t stdev = (nInAvg > 1 ? TMath::Sqrt(nInAvg/(nInAvg-1))*TMath::Sqrt(avgSqr - runAvg*runAvg) : 0); Double_t nSigma = (stdev == 0 ? 0 : (max-runAvg)/stdev); fOutliers->Fill(lCentrality,nSigma); //std::cout << "sigma = " << nSigma << std::endl; // if (fSigmaCut > 0. && nSigma >= fSigmaCut) nBadBins++; else nBadBins = 0; // We still finish the loop, for fOutliers to make sense, // but we do no keep the event for analysis if (nBadBins > 3) return kFALSE; //if (nBadBins > 3) std::cout << "NUMBER OF BAD BINS > 3" << std::endl; } } // End of eta bin // if (totalFMDpar < 10) return kFALSE; return kTRUE; }
/** Authors: Dr. Claas Nendel <claas.nendel@zalf.de> Xenia Specka <xenia.specka@zalf.de> Michael Berg <michael.berg@zalf.de> Maintainers: Currently maintained by the authors. This file is part of the MONICA model. Copyright (C) 2007-2013, Leibniz Centre for Agricultural Landscape Research (ZALF) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <map> #include <sstream> #include <iostream> #include <fstream> #include <cmath> #include <utility> #include "boost/foreach.hpp" #include "db/abstract-db-connections.h" #include "climate/climate-common.h" #include "tools/use-stl-algo-boost-lambda.h" #include "tools/helper.h" #include "tools/algorithms.h" #include "monica-parameters.h" #include "monica.h" #include "eva_methods.h" #include "debug.h" #include "conversion.h" #define LOKI_OBJECT_LEVEL_THREADING #include "loki/Threads.h" using namespace Db; using namespace std; using namespace Monica; using namespace Tools; using namespace Climate; // Some profile definitions for eva2 namespace { /** * @brief Lockable object */ struct L: public Loki::ObjectLevelLockable<L> {}; //---------------------------------------------------------------------------- /** * @brief * * @param humus_st * * @return */ // double humus_st2corg(int humus_st) // { // switch (humus_st) // { // case 0: // return 0.0; // case 1: // return 0.5 / 1.72; // case 2: // return 1.5 / 1.72; // case 3: // return 3.0 / 1.72; // case 4: // return 6.0 / 1.72; // case 5: // return 11.5 / 2.0; // case 6: // return 17.5 / 2.0; // case 7: // return 30.0 / 2.0; // } // return 0.0; // } //---------------------------------------------------------------------------- /** * @brief * * @param ldEff * @param clayPercent * * @return */ // double ld_eff2trd(int ldEff, double clay) // { // double x = 0.0; // switch (ldEff) // { // case 1: // x = 1.3; // break; // case 2: // x = 1.5; // break; // case 3: // x = 1.7; // break; // case 4: // x = 1.9; // break; // case 5: // x = 2.1; // break; // } // return x - (0.9 * clay); // } //---------------------------------------------------------------------------- /** * @brief Returns lambda from soil texture * * @param lambda * * @return */ // double texture2lambda(double sand, double clay) // { // double lambda = (2.0 * (sand * sand * 0.575)) + // (clay * 0.1) + ((1.0 - sand - clay) * 0.35); // // lambda = 1.0; /** @todo <b>Claas:</b> Temporary override until we have solved the problem with low water percolation loam soils **/ // return lambda; // } //---------------------------------------------------------------------------- /** * @brief Returns KA5 texture class from soil texture * * @param Soil texture * * @return */ // std::string texture2KA5(double sand, double clay) // { // double silt = 1.0 - sand - clay; // std::string soilTexture; // if ((silt < 0.1) && (clay < 0.05)){ // soilTexture = "Ss"; // } else if ((silt < 0.25) && (clay < 0.05)){ // soilTexture = "Su2"; // } else if ((silt < 0.25) && (clay < 0.08)){ // soilTexture = "Sl2"; // } else if ((silt < 0.40) && (clay < 0.08)){ // soilTexture = "Su3"; // } else if ((silt < 0.50) && (clay < 0.08)){ // soilTexture = "Su4"; // } else if ((silt < 0.8) && (clay < 0.08)){ // soilTexture = "Us"; // } else if ((silt >= 0.8) && (clay < 0.08)){ // soilTexture = "Uu"; // } else if ((silt < 0.1) && (clay < 0.17)){ // soilTexture = "St2"; // } else if ((silt < 0.4) && (clay < 0.12)){ // soilTexture = "Sl3"; // } else if ((silt < 0.4) && (clay < 0.17)){ // soilTexture = "Sl4"; // } else if ((silt < 0.5) && (clay < 0.17)){ // soilTexture = "Slu"; // } else if ((silt < 0.65) && (clay < 0.17)){ // soilTexture = "Uls"; // } else if ((silt >= 0.65) && (clay < 0.12)){ // soilTexture = "Ut2"; // } else if ((silt >= 0.65) && (clay < 0.17)){ // soilTexture = "Ut3"; // } else if ((silt < 0.15) && (clay < 0.25)){ // soilTexture = "St3"; // } else if ((silt < 0.30) && (clay < 0.25)){ // soilTexture = "Ls4"; // } else if ((silt < 0.40) && (clay < 0.25)){ // soilTexture = "Ls3"; // } else if ((silt < 0.50) && (clay < 0.25)){ // soilTexture = "Ls2"; // } else if ((silt < 0.65) && (clay < 0.30)){ // soilTexture = "Lu"; // } else if ((silt >= 0.65) && (clay < 0.25)){ // soilTexture = "Ut4"; // } else if ((silt < 0.15) && (clay < 0.35)){ // soilTexture = "Ts4"; // } else if ((silt < 0.30) && (clay < 0.45)){ // soilTexture = "Lts"; // } else if ((silt < 0.50) && (clay < 0.35)){ // soilTexture = "Lt2"; // } else if ((silt < 0.65) && (clay < 0.45)){ // soilTexture = "Tu3"; // } else if ((silt >= 0.65) && (clay >= 0.25)){ // soilTexture = "Tu4"; // } else if ((silt < 0.15) && (clay < 0.45)){ // soilTexture = "Ts3"; // } else if ((silt < 0.50) && (clay < 0.45)){ // soilTexture = "Lt3"; // } else if ((silt < 0.15) && (clay < 0.65)){ // soilTexture = "Ts2"; // } else if ((silt < 0.30) && (clay < 0.65)){ // soilTexture = "Tl"; // } else if ((silt >= 0.30) && (clay < 0.65)){ // soilTexture = "Tu2"; // } else if (clay >= 0.65){ // soilTexture = "Tt"; // } else soilTexture = ""; // return soilTexture; // } //---------------------------------------------------------------------------- CropPtr hermesCropId2Crop(const string& hermesCropId) { if(hermesCropId == "WW") return CropPtr(new Crop(1, hermesCropId)); // Winter wheat if(hermesCropId == "SW") return CropPtr(new Crop(1, hermesCropId)); // Spring wheat if(hermesCropId == "WG") return CropPtr(new Crop(2, hermesCropId)); // Winter barley if(hermesCropId == "SG") return CropPtr(new Crop(4, hermesCropId)); // Spring barley if(hermesCropId == "WR") return CropPtr(new Crop(3, hermesCropId)); // Winter rye if(hermesCropId == "SR") return CropPtr(new Crop(20, hermesCropId)); // Spring rye if(hermesCropId == "OAT") return CropPtr(new Crop(22, hermesCropId)); // Oats if(hermesCropId == "ZR") return CropPtr(new Crop(10, hermesCropId)); // Sugar beet if(hermesCropId == "SM") return CropPtr(new Crop(7, hermesCropId)); // Silage maize if(hermesCropId == "GM") return CropPtr(new Crop(5, hermesCropId)); // Grain maize if(hermesCropId == "GMB") return CropPtr(new Crop(6, hermesCropId)); // Grain maize Brazil (Pioneer) if(hermesCropId == "MEP") return CropPtr(new Crop(8, hermesCropId)); // Late potato if(hermesCropId == "MLP") return CropPtr(new Crop(8, hermesCropId)); // Early potato if(hermesCropId == "WC") return CropPtr(new Crop(9, hermesCropId)); // Winter canola if(hermesCropId == "SC") return CropPtr(new Crop(9, hermesCropId)); // Spring canola if(hermesCropId == "MU") return CropPtr(new Crop(11, hermesCropId)); // Mustard if(hermesCropId == "PH") return CropPtr(new Crop(12, hermesCropId)); // Phacelia if(hermesCropId == "CLV") return CropPtr(new Crop(13, hermesCropId)); // Kleegras if(hermesCropId == "LZG") return CropPtr(new Crop(14, hermesCropId)); // Luzerne-Gras if(hermesCropId == "WDG") return CropPtr(new Crop(16, hermesCropId)); // Weidelgras if(hermesCropId == "FP") return CropPtr(new Crop(24, hermesCropId)); // Field pea if(hermesCropId == "OR") return CropPtr(new Crop(17, hermesCropId)); // Oil raddish if(hermesCropId == "SDG") return CropPtr(new Crop(18, hermesCropId)); // Sudan grass if(hermesCropId == "WTR") return CropPtr(new Crop(19, hermesCropId)); // Winter triticale if(hermesCropId == "STR") return CropPtr(new Crop(23, hermesCropId)); // Spring triticale if(hermesCropId == "SOR") return CropPtr(new Crop(21, hermesCropId)); // Sorghum if(hermesCropId == "SX0") return CropPtr(new Crop(28, hermesCropId)); // Soy bean maturity group 000 if(hermesCropId == "S00") return CropPtr(new Crop(29, hermesCropId)); // Soy bean maturity group 00 if(hermesCropId == "S0X") return CropPtr(new Crop(30, hermesCropId)); // Soy bean maturity group 0 if(hermesCropId == "S01") return CropPtr(new Crop(31, hermesCropId)); // Soy bean maturity group I if(hermesCropId == "S02") return CropPtr(new Crop(32, hermesCropId)); // Soy bean maturity group II if(hermesCropId == "S03") return CropPtr(new Crop(33, hermesCropId)); // Soy bean maturity group III if(hermesCropId == "S04") return CropPtr(new Crop(34, hermesCropId)); // Soy bean maturity group IV if(hermesCropId == "S05") return CropPtr(new Crop(35, hermesCropId)); // Soy bean maturity group V if(hermesCropId == "S06") return CropPtr(new Crop(36, hermesCropId)); // Soy bean maturity group VI if(hermesCropId == "S07") return CropPtr(new Crop(37, hermesCropId)); // Soy bean maturity group VII if(hermesCropId == "S08") return CropPtr(new Crop(38, hermesCropId)); // Soy bean maturity group VIII if(hermesCropId == "S09") return CropPtr(new Crop(39, hermesCropId)); // Soy bean maturity group IX if(hermesCropId == "S10") return CropPtr(new Crop(40, hermesCropId)); // Soy bean maturity group X if(hermesCropId == "S11") return CropPtr(new Crop(41, hermesCropId)); // Soy bean maturity group XI if(hermesCropId == "S12") return CropPtr(new Crop(42, hermesCropId)); // Soy bean maturity group XII if(hermesCropId == "COS") return CropPtr(new Crop(43, hermesCropId)); // Cotton short if(hermesCropId == "COM") return CropPtr(new Crop(44, hermesCropId)); // Cotton medium if(hermesCropId == "COL") return CropPtr(new Crop(45, hermesCropId)); // Cotton long if(hermesCropId == "BR") return CropPtr(new Crop(hermesCropId)); return CropPtr(); } //---------------------------------------------------------------------------- /*! * @todo Claas bitte ausfüllen * @param name * @return */ pair<FertiliserType, int> hermesFertiliserName2monicaFertiliserId(const string& name) { if (name == "KN") return make_pair(mineral, 7); //0.00 1.00 0.00 01.00 M Kaliumnitrat (Einh : kg N / ha) if (name == "KAS") return make_pair(mineral, 1); //1.00 0.00 0.00 01.00 M Kalkammonsalpeter (Einh : kg N / ha) if (name == "UR") return make_pair(mineral, 8); //1.00 0.00 0.00 01.00 M Harnstoff if (name == "AHL") return make_pair(mineral, 10); //1.00 0.00 0.00 01.00 M Ammoniumharnstoffloesung if (name == "UAN") return make_pair(mineral, 9); //1.00 0.00 0.00 01.00 M Urea ammonium nitrate solution if (name == "AS") return make_pair(mineral, 3); //1.00 0.00 0.00 01.00 M Ammoniumsulfat (Einh: kg N/ha) if (name == "DAP") return make_pair(mineral, 2); //1.00 0.00 0.00 01.00 M Diammoniumphosphat (Einh: kg N/ha) if (name == "SG") return make_pair(organic, 3); //0.67 0.00 1.00 06.70 O Schweineguelle (Einh: z. B. m3/ha) if (name == "RG1") return make_pair(organic, 3); //0.43 0.00 1.00 02.40 O Rinderguelle (Einh: z. B. m3/ha) if (name == "RG2") return make_pair(organic, 3); //0.43 0.00 1.00 01.80 O Rinderguelle (Einh: z. B. m3/ha) if (name == "RG3") return make_pair(organic, 3); //0.43 0.00 1.00 03.40 O Rinderguelle (Einh: z. B. m3/ha) if (name == "RG4") return make_pair(organic, 3); //0.43 0.00 1.00 03.70 O Rinderguelle (Einh: z. B. m3/ha) if (name == "RG5") return make_pair(organic, 3); //0.43 0.00 1.00 03.30 O Rinderguelle (Einh: z. B. m3/ha) if (name == "SM") return make_pair(organic, 1); //0.15 0.20 0.80 00.60 O Stallmist (Einh: z. B. dt/ha) if (name == "ST1") return make_pair(organic, 1); //0.07 0.10 0.90 00.48 O Stallmist (Einh: z. B. dt/ha) if (name == "ST2") return make_pair(organic, 1); //0.07 0.10 0.90 00.63 O Stallmist (Einh: z. B. dt/ha) if (name == "ST3") return make_pair(organic, 1); //0.07 0.10 0.90 00.82 O Stallmist (Einh: z. B. dt/ha) if (name == "RM1") return make_pair(organic, 2); //0.15 0.20 0.80 00.60 O Stallmist (Einh: z. B. dt/ha) if (name == "FM") return make_pair(organic, 1); //0.65 0.80 0.20 01.00 O Stallmist (Einh: z. B. kg N/ha) if (name == "LM") return make_pair(organic, 3); //0.85 0.80 0.20 01.00 O Jauche (Einh: z. B. kg N/ha) if (name == "H") return make_pair(mineral, 8); //01.00 1.00 0.00 0.00 1.00 0.15 kg N/ha M Harnstoff if (name == "NPK") return make_pair(mineral, 5); //01.00 1.00 0.00 0.00 0.00 0.10 kg N/ha M NPK Mineraldünger if (name == "ALZ") return make_pair(mineral, 8); //01.00 1.00 0.00 0.00 1.00 0.12 kg N/ha M Alzon if (name == "AZU") return make_pair(mineral, 1); //01.00 1.00 0.00 0.00 1.00 0.12 kg N/ha M Ansul if (name == "NIT") return make_pair(mineral, 5); //01.00 1.00 0.00 0.00 0.00 0.10 kg N/ha M Nitrophoska if (name == "SSA") return make_pair(mineral, 3); //01.00 1.00 0.00 0.00 1.00 0.10 kg N/ha M schwefelsaures Ammoniak if (name == "RG") return make_pair(organic, 3); //04.70 0.43 0.00 1.00 1.00 0.40 m3 / ha O Rindergülle if (name == "RM") return make_pair(organic, 1); //00.60 0.15 0.20 0.80 1.00 0.40 dt / ha O Rindermist if (name == "RSG") return make_pair(organic, 3); //05.70 0.55 0.00 1.00 1.00 0.40 m3 / ha O Rinder/Schweinegülle if (name == "SSM") return make_pair(organic, 5); //00.76 0.15 0.20 0.80 1.00 0.40 dt / ha O Schweinemist if (name == "HG") return make_pair(organic, 12); //10.70 0.68 0.00 1.00 1.00 0.40 m3 / ha O Hühnergülle if (name == "HFM") return make_pair(organic, 11); //02.30 0.15 0.20 0.80 1.00 0.40 dt / ha O Hähnchentrockenmist if (name == "HM") return make_pair(organic, 11); //02.80 0.15 0.20 0.80 1.00 0.40 dt / ha O Hühnermist if (name == "CK") return make_pair(mineral, 1); //00.30 0.00 1.00 0.00 0.00 0.00 dt / ha M Carbokalk if (name == "KSL") return make_pair(organic, 16); //01.00 0.25 0.20 0.80 0.00 0.10 dt / ha O Klärschlamm if (name == "BAK") return make_pair(organic, 15); //01.63 0.00 0.05 0.60 0.00 0.00 dt / ha O Bioabfallkompst if (name == "MST") return make_pair(organic, 21); // Maize straw if (name == "WST") return make_pair(organic, 19); // Wheat straw if (name == "SST") return make_pair(organic, 23); // Soybean straw if (name == "WEE") return make_pair(organic, 22); // Weeds if (name == "YP3") return make_pair(mineral, 13); //01.00 0.43 0.57 0.00 1.00 1.00 kg N/ha M Yara Pellon Y3 cout << "Error: Cannot find fertiliser " << name << " in hermes fertiliser map. Aborting..." << endl; exit(-1); return make_pair(mineral, -1); } } // namespace //------------------------------------------------------------------------------ /** * Returns the result vector of a special output. Python swig is * not able to wrap stl-maps correctly. Stl-vectors are working * properly so this function has been implemented to use the results * in wrapped python code. * * @param id ResultId of output * @return Vector of result values */ std::vector<double> Result::getResultsById(int id) { // test if crop results are requested if (id == primaryYield || id == secondaryYield || id == sumIrrigation || id == sumFertiliser || id == biomassNContent || id == sumTotalNUptake || id == cropHeight || id == cropname || id == sumETaPerCrop || id == primaryYieldTM || id == secondaryYieldTM || id == daysWithCrop || id == aboveBiomassNContent || id == NStress || id == WaterStress || id == HeatStress || id == OxygenStress ) { vector<double> result_vector; int size = pvrs.size(); for (int i=0; i<size; i++) { PVResult crop_result = pvrs.at(i); result_vector.push_back(crop_result.pvResults[(ResultId)id]); } return result_vector; } return generalResults[(ResultId)id]; } const vector<ResultId>& Monica::cropResultIds() { static ResultId ids[] = { primaryYield, secondaryYield, sumFertiliser, sumIrrigation, sumMineralisation }; static vector<ResultId> v(ids, ids + 5); return v; } //------------------------------------------------------------------------------ const vector<ResultId>& Monica::monthlyResultIds() { static ResultId ids[] = { avg10cmMonthlyAvgCorg, avg30cmMonthlyAvgCorg, mean90cmMonthlyAvgWaterContent, monthlySumGroundWaterRecharge, monthlySumNLeaching }; static vector<ResultId> v(ids, ids + 5); return v; } //------------------------------------------------------------------------------ const vector<int>& Monica::sensitivityAnalysisResultIds() { static ResultId ids[] = { // primaryYield, // done // secondaryYield, // done // cropHeight, // done // mean90cmMonthlyAvgWaterContent, // done // sum90cmYearlyNatDay, // done // sum90cmYearlyNO3AtDay, // done // maxSnowDepth, // done // sumSnowDepth, // done // sumFrostDepth, // done // avg30cmSoilTemperature, // done // sum30cmSoilTemperature, // done // avg0_30cmSoilMoisture, // done // avg30_60cmSoilMoisture, // done // avg60_90cmSoilMoisture, // done // monthlySumGroundWaterRecharge, // done // waterFluxAtLowerBoundary, // done // avg0_30cmCapillaryRise, // done // avg30_60cmCapillaryRise, // done // avg60_90cmCapillaryRise, // done // avg0_30cmPercolationRate, // done // avg30_60cmPercolationRate, // done // avg60_90cmPercolationRate, // done // sumSurfaceRunOff, // done // evapotranspiration, // done // transpiration, // done // evaporation, // done // biomassNContent, // done // sumTotalNUptake, // done // sum30cmSMB_CO2EvolutionRate, // done // NH3Volatilised, // done // sumNH3Volatilised, // done // sum30cmActDenitrificationRate, // done // leachingNAtBoundary, // done // yearlySumGroundWaterRecharge, // yearlySumNLeaching, dev_stage }; //static vector<int> v(ids, ids+2); static vector<int> v(ids, ids+1); return v; } //------------------------------------------------------------------------------ const vector<int>& Monica::CCGermanyResultIds() { static ResultId ids[] = { primaryYield, // done yearlySumGroundWaterRecharge, yearlySumNLeaching }; static vector<int> v(ids, ids+3); return v; } //------------------------------------------------------------------------------ const vector<int>& Monica::eva2CropResultIds() { static ResultId ids[] = { cropname, primaryYieldTM, secondaryYieldTM, sumFertiliser, sumETaPerCrop, biomassNContent, daysWithCrop, aboveBiomassNContent, NStress, WaterStress, HeatStress, OxygenStress }; static vector<int> v(ids, ids + 12); return v; } //------------------------------------------------------------------------------ const vector<int>& Monica::eva2MonthlyResultIds() { static ResultId ids[] = { avg10cmMonthlyAvgCorg, avg30cmMonthlyAvgCorg, mean90cmMonthlyAvgWaterContent, monthlySumGroundWaterRecharge, monthlySumNLeaching, monthlySurfaceRunoff, monthlyPrecip, monthlyETa, monthlySoilMoistureL0, monthlySoilMoistureL1, monthlySoilMoistureL2, monthlySoilMoistureL3, monthlySoilMoistureL4, monthlySoilMoistureL5, monthlySoilMoistureL6, monthlySoilMoistureL7, monthlySoilMoistureL8, monthlySoilMoistureL9, monthlySoilMoistureL10, monthlySoilMoistureL11, monthlySoilMoistureL12, monthlySoilMoistureL13, monthlySoilMoistureL14, monthlySoilMoistureL15, monthlySoilMoistureL16, monthlySoilMoistureL17, monthlySoilMoistureL18 }; static vector<int> v(ids, ids + 27); return v; } //------------------------------------------------------------------------------ /** * Returns some information about a result id. * @param rid ResultID of interest * @return ResultIdInfo Information object of result ids */ ResultIdInfo Monica::resultIdInfo(ResultId rid) { switch(rid) { case primaryYield: return ResultIdInfo("Hauptertrag", "dt/ha", "primYield"); case secondaryYield: return ResultIdInfo("Nebenertrag", "dt/ha", "secYield"); case sumFertiliser: return ResultIdInfo("N", "kg/ha", "sumFert"); case sumIrrigation: return ResultIdInfo("Beregnungswassermenge", "mm/ha", "sumIrrig"); case sumMineralisation: return ResultIdInfo("Mineralisation", "????", "sumMin"); case avg10cmMonthlyAvgCorg: return ResultIdInfo("Kohlenstoffgehalt 0-10cm", "% kg C/kg Boden", "Corg10cm"); case avg30cmMonthlyAvgCorg: return ResultIdInfo("Kohlenstoffgehalt 0-30cm", "% kg C/kg Boden", "Corg30cm"); case mean90cmMonthlyAvgWaterContent: return ResultIdInfo("Bodenwassergehalt 0-90cm", "%nFK", "Moist90cm"); case sum90cmYearlyNatDay: return ResultIdInfo("Boden-Nmin-Gehalt 0-90cm am 31.03.", "kg N/ha", "Nmin3103"); case monthlySumGroundWaterRecharge: return ResultIdInfo("Grundwasserneubildung", "mm", "GWRech"); case monthlySumNLeaching: return ResultIdInfo("N-Auswaschung", "kg N/ha", "monthLeachN"); case cropHeight: return ResultIdInfo("Pflanzenhöhe zum Erntezeitpunkt", "m","cropHeight"); case sum90cmYearlyNO3AtDay: return ResultIdInfo("Summe Nitratkonzentration in 0-90cm Boden am 31.03.", "kg N/ha","NO3_90cm"); case sum90cmYearlyNH4AtDay: return ResultIdInfo("Ammoniumkonzentratio in 0-90cm Boden am 31.03.", "kg N/ha", "NH4_90cm"); case maxSnowDepth: return ResultIdInfo("Maximale Schneetiefe während der Simulation","m","maxSnowDepth"); case sumSnowDepth: return ResultIdInfo("Akkumulierte Schneetiefe der gesamten Simulation", "m","sumSnowDepth"); case sumFrostDepth: return ResultIdInfo("Akkumulierte Frosttiefe der gesamten Simulation","m","sumFrostDepth"); case avg30cmSoilTemperature: return ResultIdInfo("Durchschnittliche Bodentemperatur in 0-30cm Boden am 31.03.", "°C","STemp30cm"); case sum30cmSoilTemperature: return ResultIdInfo("Akkumulierte Bodentemperature der ersten 30cm des Bodens am 31.03", "°C","sumSTemp30cm"); case avg0_30cmSoilMoisture: return ResultIdInfo("Durchschnittlicher Wassergehalt in 0-30cm Boden am 31.03.", "%","Moist0_30"); case avg30_60cmSoilMoisture: return ResultIdInfo("Durchschnittlicher Wassergehalt in 30-60cm Boden am 31.03.", "%","Moist30_60"); case avg60_90cmSoilMoisture: return ResultIdInfo("Durchschnittlicher Wassergehalt in 60-90cm Boden am 31.03.", "%","Moist60_90"); case waterFluxAtLowerBoundary: return ResultIdInfo("Sickerwasser der unteren Bodengrenze am 31.03.", "mm/d", "waterFlux"); case avg0_30cmCapillaryRise: return ResultIdInfo("Durchschnittlicher kapillarer Aufstieg in 0-30cm Boden am 31.03.", "mm/d", "capRise0_30"); case avg30_60cmCapillaryRise: return ResultIdInfo("Durchschnittlicher kapillarer Aufstieg in 30-60cm Boden am 31.03.", "mm/d", "capRise30_60"); case avg60_90cmCapillaryRise: return ResultIdInfo("Durchschnittlicher kapillarer Aufstieg in 60-90cm Boden am 31.03.", "mm/d", "capRise60_90"); case avg0_30cmPercolationRate: return ResultIdInfo("Durchschnittliche Durchflussrate in 0-30cm Boden am 31.03.", "mm/d", "percRate0_30"); case avg30_60cmPercolationRate: return ResultIdInfo("Durchschnittliche Durchflussrate in 30-60cm Boden am 31.03.", "mm/d", "percRate30_60"); case avg60_90cmPercolationRate: return ResultIdInfo("Durchschnittliche Durchflussrate in 60-90cm Boden am 31.03.", "mm/d", "percRate60_90"); case sumSurfaceRunOff: return ResultIdInfo("Summe des Oberflächenabflusses der gesamten Simulation", "mm", "sumSurfRunOff"); case evapotranspiration: return ResultIdInfo("Evaporatranspiration am 31.03.", "mm", "ET"); case transpiration: return ResultIdInfo("Transpiration am 31.03.", "mm", "transp"); case evaporation: return ResultIdInfo("Evaporation am 31.03.", "mm", "evapo"); case biomassNContent: return ResultIdInfo("Stickstoffanteil im Erntegut", "kg N/ha", "biomNContent"); case aboveBiomassNContent: return ResultIdInfo("Stickstoffanteil in der gesamten oberirdischen Biomasse", "kg N/ha", "aboveBiomassNContent"); case sumTotalNUptake: return ResultIdInfo("Summe des aufgenommenen Stickstoffs", "kg/ha", "sumNUptake"); case sum30cmSMB_CO2EvolutionRate: return ResultIdInfo("SMB-CO2 Evolutionsrate in 0-30cm Boden am 31.03.", "kg/ha", "sumSMB_CO2_EvRate"); case NH3Volatilised: return ResultIdInfo("Menge des verdunstenen Stickstoffs (NH3) am 31.03.", "kg N / m2 d", "NH3Volat"); case sumNH3Volatilised: return ResultIdInfo("Summe des verdunstenen Stickstoffs (NH3) des gesamten Simulationszeitraums", "kg N / m2", "sumNH3Volat"); case sum30cmActDenitrificationRate: return ResultIdInfo("Summe der Denitrifikationsrate in 0-30cm Boden am 31.03.", "kg N / m3 d", "denitRate"); case leachingNAtBoundary: return ResultIdInfo("Menge des ausgewaschenen Stickstoffs im Boden am 31.03.", "kg / ha", "leachN"); case yearlySumGroundWaterRecharge: return ResultIdInfo("Gesamt-akkumulierte Grundwasserneubildung im Jahr", "mm", "Yearly_GWRech"); case yearlySumNLeaching: return ResultIdInfo("Gesamt-akkumulierte N-Auswaschung im Jahr", "kg N/ha", "Yearly_monthLeachN"); case sumETaPerCrop: return ResultIdInfo("Evapotranspiration pro Vegetationszeit der Pflanze", "mm", "ETa_crop"); case cropname: return ResultIdInfo("Pflanzenname", "", "cropname"); case primaryYieldTM: return ResultIdInfo("Hauptertrag in TM", "dt TM/ha", "primYield"); case secondaryYieldTM: return ResultIdInfo("Nebenertrag in TM", "dt TM/ha", "secYield"); case monthlySurfaceRunoff: return ResultIdInfo("Monatlich akkumulierte Oberflächenabfluss", "mm", "monthlySurfaceRunoff"); case monthlyPrecip: return ResultIdInfo("Akkumulierte korrigierte Niederschläge pro Monat", "mm", "monthlyPrecip"); case monthlyETa: return ResultIdInfo("Akkumulierte korrigierte Evapotranspiration pro Monat", "mm", "monthlyETa"); case monthlySoilMoistureL0: return ResultIdInfo("Monatlicher mittlerer Wassergehalt für Schicht 1", "Vol-%", "monthlySoilMoisL1"); case monthlySoilMoistureL1: return ResultIdInfo("Monatlicher mittlerer Wassergehalt für Schicht 2", "Vol-%", "monthlySoilMoisL2"); case monthlySoilMoistureL2: return ResultIdInfo("Monatlicher mittlerer Wassergehalt für Schicht 3", "Vol-%", "monthlySoilMoisL3"); case monthlySoilMoistureL3: return ResultIdInfo("Monatlicher mittlerer Wassergehalt für Schicht 4", "Vol-%", "monthlySoilMoisL4"); case monthlySoilMoistureL4: return ResultIdInfo("Monatlicher mittlerer Wassergehalt für Schicht 5", "Vol-%", "monthlySoilMoisL5"); case monthlySoilMoistureL5: return ResultIdInfo("Monatlicher mittlerer Wassergehalt für Schicht 6", "Vol-%", "monthlySoilMoisL6"); case monthlySoilMoistureL6: return ResultIdInfo("Monatlicher mittlerer Wassergehalt für Schicht 7", "Vol-%", "monthlySoilMoisL7"); case monthlySoilMoistureL7: return ResultIdInfo("Monatlicher mittlerer Wassergehalt für Schicht 8", "Vol-%", "monthlySoilMoisL8"); case monthlySoilMoistureL8: return ResultIdInfo("Monatlicher mittlerer Wassergehalt für Schicht 9", "Vol-%", "monthlySoilMoisL9"); case monthlySoilMoistureL9: return ResultIdInfo("Monatlicher mittlerer Wassergehalt für Schicht 10", "Vol-%", "monthlySoilMoisL10"); case monthlySoilMoistureL10: return ResultIdInfo("Monatlicher mittlerer Wassergehalt für Schicht 11", "Vol-%", "monthlySoilMoisL11"); case monthlySoilMoistureL11: return ResultIdInfo("Monatlicher mittlerer Wassergehalt für Schicht 12", "Vol-%", "monthlySoilMoisL12"); case monthlySoilMoistureL12: return ResultIdInfo("Monatlicher mittlerer Wassergehalt für Schicht 13", "Vol-%", "monthlySoilMoisL13"); case monthlySoilMoistureL13: return ResultIdInfo("Monatlicher mittlerer Wassergehalt für Schicht 14", "Vol-%", "monthlySoilMoisL14"); case monthlySoilMoistureL14: return ResultIdInfo("Monatlicher mittlerer Wassergehalt für Schicht 15", "Vol-%", "monthlySoilMoisL15"); case monthlySoilMoistureL15: return ResultIdInfo("Monatlicher mittlerer Wassergehalt für Schicht 16", "Vol-%", "monthlySoilMoisL16"); case monthlySoilMoistureL16: return ResultIdInfo("Monatlicher mittlerer Wassergehalt für Schicht 17", "Vol-%", "monthlySoilMoisL17"); case monthlySoilMoistureL17: return ResultIdInfo("Monatlicher mittlerer Wassergehalt für Schicht 18", "Vol-%", "monthlySoilMoisL18"); case monthlySoilMoistureL18: return ResultIdInfo("Monatlicher mittlerer Wassergehalt für Schicht 19", "Vol-%", "monthlySoilMoisL19"); case daysWithCrop: return ResultIdInfo("Anzahl der Tage mit Pflanzenbewuchs", "d", "daysWithCrop"); case NStress: return ResultIdInfo("Akkumulierte Werte für N-Stress", "", "NStress"); case WaterStress: return ResultIdInfo("Akkumulierte Werte für N-Stress", "", "waterStress"); case HeatStress: return ResultIdInfo("Akkumulierte Werte für N-Stress", "", "heatStress"); case OxygenStress: return ResultIdInfo("Akkumulierte Werte für N-Stress", "", "oxygenStress"); case dev_stage: return ResultIdInfo("Liste mit täglichen Werten für das Entwicklungsstadium", "[]", "devStage"); default: ; } return ResultIdInfo("", ""); } //------------------------------------------------------------------------------ string WorkStep::toString() const { ostringstream s; s << "date: " << date().toString(); return s.str(); } //------------------------------------------------------------------------------ void Seed::apply(MonicaModel* model) { debug() << "seeding crop: " << _crop->toString() << " at: " << date().toString() << endl; model->seedCrop(_crop); } string Seed::toString() const { ostringstream s; s << "seeding at: " << date().toString() << " crop: " << _crop->toString(); return s.str(); } //------------------------------------------------------------------------------ void Harvest::apply(MonicaModel* model) { if (model->cropGrowth()) { debug() << "harvesting crop: " << _crop->toString() << " at: " << date().toString() << endl; if (model->currentCrop() == _crop) { if (model->cropGrowth()) { _crop->setHarvestYields (model->cropGrowth()->get_FreshPrimaryCropYield() / 100.0, model->cropGrowth()->get_FreshSecondaryCropYield() / 100.0); _crop->setHarvestYieldsTM (model->cropGrowth()->get_PrimaryCropYield() / 100.0, model->cropGrowth()->get_SecondaryCropYield() / 100.0); _crop->setYieldNContent(model->cropGrowth()->get_PrimaryYieldNContent(), model->cropGrowth()->get_SecondaryYieldNContent()); _crop->setSumTotalNUptake(model->cropGrowth()->get_SumTotalNUptake()); _crop->setCropHeight(model->cropGrowth()->get_CropHeight()); _crop->setAccumulatedETa(model->cropGrowth()->get_AccumulatedETa()); } //store results for this crop _cropResult->pvResults[primaryYield] = _crop->primaryYield(); _cropResult->pvResults[secondaryYield] = _crop->secondaryYield(); _cropResult->pvResults[primaryYieldTM] = _crop->primaryYieldTM(); _cropResult->pvResults[secondaryYieldTM] = _crop->secondaryYieldTM(); _cropResult->pvResults[sumIrrigation] = _crop->appliedIrrigationWater(); _cropResult->pvResults[biomassNContent] = _crop->primaryYieldN(); _cropResult->pvResults[aboveBiomassNContent] = _crop->aboveGroundBiomasseN(); _cropResult->pvResults[daysWithCrop] = model->daysWithCrop(); _cropResult->pvResults[sumTotalNUptake] = _crop->sumTotalNUptake(); _cropResult->pvResults[cropHeight] = _crop->cropHeight(); _cropResult->pvResults[sumETaPerCrop] = _crop->get_AccumulatedETa(); _cropResult->pvResults[cropname] = _crop->id(); _cropResult->pvResults[NStress] = model->getAccumulatedNStress(); _cropResult->pvResults[WaterStress] = model->getAccumulatedWaterStress(); _cropResult->pvResults[HeatStress] = model->getAccumulatedHeatStress(); _cropResult->pvResults[OxygenStress] = model->getAccumulatedOxygenStress(); model->harvestCurrentCrop(); } else { debug() << "Crop: " << model->currentCrop()->toString() << " to be harvested isn't actual crop of this Harvesting action: " << _crop->toString() << endl; } } } string Harvest::toString() const { ostringstream s; s << "harvesting at: " << date().toString() << " crop: " << _crop->toString(); return s.str(); } //------------------------------------------------------------------------------ void Cutting::apply(MonicaModel* model) { debug() << "Cutting crop: " << _crop->toString() << " at: " << date().toString() << endl; if (model->currentCrop() == _crop) { if (model->cropGrowth()) { _crop->setHarvestYields (model->cropGrowth()->get_FreshPrimaryCropYield() / 100.0, model->cropGrowth()->get_FreshSecondaryCropYield() / 100.0); _crop->setHarvestYieldsTM (model->cropGrowth()->get_PrimaryCropYield() / 100.0, model->cropGrowth()->get_SecondaryCropYield() / 100.0); } _crop->setYieldNContent(model->cropGrowth()->get_PrimaryYieldNContent(), model->cropGrowth()->get_SecondaryYieldNContent()); _crop->setSumTotalNUptake(model->cropGrowth()->get_SumTotalNUptake()); _crop->setCropHeight(model->cropGrowth()->get_CropHeight()); if (model->cropGrowth()) { model->cropGrowth()->applyCutting(); } } } string Cutting::toString() const { ostringstream s; s << "Cutting at: " << date().toString() << " crop: " << _crop->toString(); return s.str(); } //------------------------------------------------------------------------------ string NMinCropParameters::toString() const { ostringstream s; s << "samplingDepth: " << samplingDepth << " nTarget: " << nTarget << " nTarget40: " << nTarget30; return s.str(); } //------------------------------------------------------------------------------ string NMinUserParameters::toString() const { ostringstream s; s << "min: " << min << " max: " << max << " delay: " << delayInDays << " days"; return s.str(); } //------------------------------------------------------------------------------ void MineralFertiliserApplication::apply(MonicaModel* model) { debug() << toString() << endl; model->applyMineralFertiliser(partition(), amount()); } string MineralFertiliserApplication::toString() const { ostringstream s; s << "applying mineral fertiliser at: " << date().toString() << " amount: " << amount() << " partition: " << partition().toString(); return s.str(); } //------------------------------------------------------------------------------ void OrganicFertiliserApplication::apply(MonicaModel* model) { debug() << toString() << endl; model->applyOrganicFertiliser(_params, _amount, _incorporation); } string OrganicFertiliserApplication::toString() const { ostringstream s; s << "applying organic fertiliser at: " << date().toString() << " amount: " << amount() << "\tN percentage: " << _params->vo_NConcentration << "\tN amount: " << amount() * _params->vo_NConcentration; // << "parameters: " << endl; return s.str(); } //------------------------------------------------------------------------------ void TillageApplication::apply(MonicaModel* model) { debug() << toString() << endl; model->applyTillage(_depth); } string TillageApplication::toString() const { ostringstream s; s << "applying tillage at: " << date().toString() << " depth: " << depth(); return s.str(); } //------------------------------------------------------------------------------ string IrrigationParameters::toString() const { ostringstream s; s << "nitrateConcentration: " << nitrateConcentration << " sulfateConcentration: " << sulfateConcentration; return s.str(); } string AutomaticIrrigationParameters::toString() const { ostringstream s; s << "amount: " << amount << " treshold: " << treshold << " " << IrrigationParameters::toString(); return s.str(); } void IrrigationApplication::apply(MonicaModel* model) { //cout << toString() << endl; model->applyIrrigation(amount(), nitrateConcentration()); } string IrrigationApplication::toString() const { ostringstream s; s << "applying irrigation at: " << date().toString() << " amount: " << amount() << " nitrateConcentration: " << nitrateConcentration() << " sulfateConcentration: " << sulfateConcentration(); return s.str(); } //------------------------------------------------------------------------------ ProductionProcess::ProductionProcess(const std::string& name, CropPtr crop) : _name(name), _crop(crop), _cropResult(new PVResult()) { debug() << "ProductionProcess: " << name.c_str() << endl; _cropResult->id = _crop->id(); if ((crop->seedDate() != Date(1,1,1951)) && (crop->seedDate() != Date(0,0,0))) { addApplication(Seed(crop->seedDate(), crop)); } if ((crop->harvestDate() != Date(1,1,1951)) && (crop->harvestDate() != Date(0,0,0))) { debug() << "crop->harvestDate(): " << crop->harvestDate().toString().c_str() << endl; addApplication(Harvest(crop->harvestDate(), crop, _cropResult)); } std::vector<Date> cuttingDates = crop->getCuttingDates(); unsigned int size = cuttingDates.size(); for (unsigned int i=0; i<size; i++) { debug() << "Add cutting date: " << Tools::Date(cuttingDates.at(i)).toString().c_str() << endl; // if (i<size-1) { addApplication(Cutting(Tools::Date(cuttingDates.at(i)), crop)); // } else { // addApplication(Harvest(crop->harvestDate(), crop, _cropResult)); // } } } /** * @brief Copy constructor * @param new_pp */ /* ProductionProcess::ProductionProcess(const ProductionProcess& other) { _name = other._name; _crop = CropPtr(new Crop(*(other._crop.get()))); _cropResult = PVResultPtr(new PVResult(*(other._cropResult.get()))); _worksteps = other._worksteps; } */ ProductionProcess ProductionProcess::deepCloneAndClearWorksteps() const { ProductionProcess clone(name(), CropPtr(new Crop(*(crop().get())))); clone._cropResult = PVResultPtr(new PVResult(*(_cropResult.get()))); return clone; } void ProductionProcess::apply(const Date& date, MonicaModel* model) const { typedef multimap<Date, WSPtr>::const_iterator CI; pair<CI, CI> p = _worksteps.equal_range(date); if (p.first != p.second) { while (p.first != p.second) { p.first->second->apply(model); p.first++; } } } Date ProductionProcess::nextDate(const Date& date) const { typedef multimap<Date, WSPtr>::const_iterator CI; CI ci = _worksteps.upper_bound(date); return ci != _worksteps.end() ? ci->first : Date(); } Date ProductionProcess::start() const { if (_worksteps.empty()) return Date(); return _worksteps.begin()->first; } Date ProductionProcess::end() const { if (_worksteps.empty()) return Date(); return _worksteps.rbegin()->first; } std::string ProductionProcess::toString() const { ostringstream s; s << "name: " << name() << " start: " << start().toString() << " end: " << end().toString() << endl; s << "worksteps:" << endl; typedef multimap<Date, WSPtr>::const_iterator CI; for (CI ci = _worksteps.begin(); ci != _worksteps.end(); ci++) { s << "at: " << ci->first.toString() << " what: " << ci->second->toString() << endl; } return s.str(); } //------------------------------------------------------------------------------ //helper for parsing dates struct DMY { int d, m, y; Date toDate(bool useLeapYears = true) const { return Date(d, m, y, useLeapYears); } }; // to read HERMES two digit date format in management files struct ParseDate { DMY operator()(const string & d) { DMY r; r.d = atoi(d.substr(0, 2).c_str()); r.m = atoi(d.substr(2, 2).c_str()); r.y = atoi(d.substr(4, 2).c_str()); r.y = r.y <= 76 ? 2000 + r.y : 1900 + r.y; return r; } } parseDate; //---------------------------------------------------------------------------- vector<ProductionProcess> Monica::cropRotationFromHermesFile(const string& pathToFile) { vector<ProductionProcess> ff; ifstream ifs(pathToFile.c_str(), ios::binary); if (! ifs.good()) { cerr << "Could not open file " << pathToFile.c_str() << " . Aborting now!" << endl; exit(1); } string s; //skip first line getline(ifs, s); while (getline(ifs, s)) { if (trim(s) == "end") break; istringstream ss(s); string crp; string sowingDate, harvestDate, tillageDate; double exp, tillage_depth; int t; ss >> t >> crp >> sowingDate >> harvestDate >> tillageDate >> exp >> tillage_depth; Date sd = parseDate(sowingDate).toDate(true); Date hd = parseDate(harvestDate).toDate(true); Date td = parseDate(tillageDate).toDate(true); // tst if dates are valid if (!sd.isValid() || !hd.isValid() || !td.isValid()) { debug() << "Error - Invalid date in \"" << pathToFile.c_str() << "\"" << endl; debug() << "Line: " << s.c_str() << endl; debug() << "Aborting simulation now!" << endl; exit(-1); } //create crop CropPtr crop = hermesCropId2Crop(crp); crop->setSeedAndHarvestDate(sd, hd); crop->setCropParameters(getCropParametersFromMonicaDB(crop->id())); crop->setResidueParameters(getResidueParametersFromMonicaDB(crop->id())); ProductionProcess pp(crp, crop); pp.addApplication(TillageApplication(td, (tillage_depth/100.0) )); //cout << "production-process: " << pp.toString() << endl; ff.push_back(pp); } return ff; } /** * @todo Micha/Xenia: Überprüfen, ob YearIndex rauskommen kann. */ DataAccessor Monica::climateDataFromHermesFiles(const std::string& pathToFile, int fromYear, int toYear, const CentralParameterProvider& cpp, bool useLeapYears, double latitude) { DataAccessor da(Date(1, 1, fromYear, useLeapYears), Date(31, 12, toYear, useLeapYears)); vector<double> _tmin; vector<double> _tavg; vector<double> _tmax; vector<double> _globrad; vector<double> _relhumid; vector<double> _wind; vector<double> _precip; vector<double> _sunhours; Date date = Date(1, 1, fromYear, useLeapYears); for (int y = fromYear; y <= toYear; y++) { ostringstream yss; yss << y; string ys = yss.str(); ostringstream oss; oss << pathToFile << ys.substr(1, 3); debug() << "File: " << oss.str().c_str() << endl; ifstream ifs(oss.str().c_str(), ios::binary); if (! ifs.good()) { cerr << "Could not open file " << oss.str().c_str() << " . Aborting now!" << endl; exit(1); } string s; //skip first line(s) getline(ifs, s); getline(ifs, s); getline(ifs, s); int daysCount = 0; int allowedDays = Date(31, 12, y, useLeapYears).dayOfYear(); // cout << "tavg\t" << "tmin\t" << "tmax\t" << "wind\t" debug() << "allowedDays: " << allowedDays << " " << y<< "\t" << useLeapYears << "\tlatitude:\t" << latitude << endl; //<< "sunhours\t" << "globrad\t" << "precip\t" << "ti\t" << "relhumid\n"; while (getline(ifs, s)) { //if(trim(s) == "end") break; //Tp_av Tpmin Tpmax T_s10 T_s20 vappd wind sundu radia prec jday RF double td; int ti; double tmin, tmax, tavg, wind, sunhours, globrad, precip, relhumid; istringstream ss(s); ss >> tavg >> tmin >> tmax >> td >> td >> td >> wind >> sunhours >> globrad >> precip >> ti >> relhumid; // test if globrad or sunhours should be used if(globrad >=0.0) { // use globrad // HERMES weather files deliver global radiation as [J cm-2] // Here, we push back [MJ m-2 d-1] double globradMJpm2pd = globrad * 100.0 * 100.0 / 1000000.0; _globrad.push_back(globradMJpm2pd); } else if(sunhours >= 0.0) { // invalid globrad use sunhours // convert sunhours into globrad // debug() << "Invalid globrad - use sunhours instead" << endl; _globrad.push_back(sunshine2globalRadiation(date.dayOfYear(), sunhours, latitude, true)); _sunhours.push_back(sunhours); } else { // error case debug() << "Error: No global radiation or sunhours specified for day " << date.toString().c_str() << endl; debug() << "Aborting now ..." << endl; exit(-1); } if (relhumid>0) { _relhumid.push_back(relhumid); } // precipitation correction by Richter values precip*=cpp.getPrecipCorrectionValue(date.month()-1); // cout << tavg << "\t"<< tmin << "\t" << tmax << "\t" << wind //<< "\t" << sunhours <<"\t" << globrad <<"\t" << precip <<"\t" << ti <<"\t" << relhumid << endl; _tavg.push_back(tavg); _tmin.push_back(tmin); _tmax.push_back(tmax); _wind.push_back(wind); _precip.push_back(precip); daysCount++; date++; } if (daysCount != allowedDays) { debug() << "Wrong number of days in " << oss.str().c_str() << " ." << " Found " << daysCount << " days but should have been " << allowedDays << " days. Aborting." << endl; exit(1); } } //int days = (toYearIndex - fromYearIndex + 1) * 365; //assert(int(_tmin.size()) == days); da.addClimateData(tmin, _tmin); da.addClimateData(tmax, _tmax); da.addClimateData(tavg, _tavg); da.addClimateData(globrad, _globrad); da.addClimateData(wind, _wind); da.addClimateData(precip, _precip); if(!_sunhours.empty()) da.addClimateData(sunhours, _sunhours); if (!_relhumid.empty()) { da.addClimateData(relhumid, _relhumid); } return da; } //---------------------------------------------------------------------------- /** * @brief Constructor * * Parameter initiliazation */ CropParameters::CropParameters() : pc_NumberOfDevelopmentalStages(0), pc_NumberOfOrgans(0), pc_CarboxylationPathway(0), pc_DefaultRadiationUseEfficiency(0), pc_FixingN(0), pc_InitialKcFactor(0), pc_LuxuryNCoeff(0), pc_MaxAssimilationRate(0), pc_MaxCropHeight(0), pc_CropHeightP1(0), pc_CropHeightP2(0), pc_MinimumNConcentration(0), pc_MinimumTemperatureForAssimilation(0), pc_NConcentrationAbovegroundBiomass(0), pc_NConcentrationB0(0), pc_NConcentrationPN(0), pc_NConcentrationRoot(0), pc_ResidueNRatio(0), pc_DevelopmentAccelerationByNitrogenStress(0), pc_CuttingDelayDays(0) {} /** * @brief */ void CropParameters::resizeStageOrganVectors() { pc_AssimilatePartitioningCoeff.resize(pc_NumberOfDevelopmentalStages, std::vector<double>(pc_NumberOfOrgans)); pc_OrganSenescenceRate.resize(pc_NumberOfDevelopmentalStages, std::vector<double>(pc_NumberOfOrgans)); } /** * @brief Returns a string of information about crop parameters. * * Generates a string that contains all relevant crop parameter information. * * @return String of crop information. */ string CropParameters::toString() const { ostringstream s; s << "pc_CropName:\t" << pc_CropName << endl; s << "------------------------------------------------" << endl; s << "pc_NumberOfDevelopmentalStages:\t" << pc_NumberOfDevelopmentalStages << endl; s << "pc_NumberOfOrgans:\t\t\t\t" << pc_NumberOfOrgans << endl; s << "------------------------------------------------" << endl; // assimilate partitioning coefficient matrix s << "pc_AssimilatePartitioningCoeff:\t" << endl; for (unsigned int i = 0; i < pc_AssimilatePartitioningCoeff.size(); i++) { for (unsigned int j = 0; j < pc_AssimilatePartitioningCoeff[i].size(); j++) { s << pc_AssimilatePartitioningCoeff[i][j] << " "; } s << endl; } s << "------------------------------------------------" << endl; s << "pc_CarboxylationPathway:\t\t\t\t" << pc_CarboxylationPathway << endl; s << "pc_MaxAssimilationRate:\t\t\t\t\t" << pc_MaxAssimilationRate << endl; s << "pc_MinimumTemperatureForAssimilation:\t" << pc_MinimumTemperatureForAssimilation << endl; s << "pc_CropSpecificMaxRootingDepth:\t\t\t" << pc_CropSpecificMaxRootingDepth << endl; s << "pc_InitialKcFactor:\t\t\t\t\t\t" << pc_InitialKcFactor << endl; s << "pc_MaxCropDiameter:\t\t\t\t\t\t" << pc_MaxCropDiameter << endl; s << "pc_StageAtMaxDiameter:\t\t\t\t\t" << pc_StageAtMaxDiameter << endl; s << "pc_PlantDensity:\t\t\t\t\t\t" << pc_PlantDensity << endl; s << "pc_DefaultRadiationUseEfficiency:\t\t" << pc_DefaultRadiationUseEfficiency << endl; s << "pc_StageAfterCut:\t\t\t\t\t\t" << pc_StageAfterCut << endl; s << "pc_CuttingDelayDays:\t\t\t\t\t" << pc_CuttingDelayDays << endl; s << "------------------------------------------------" << endl; s << "pc_RootDistributionParam:\t\t\t" << pc_RootDistributionParam << endl; s << "pc_RootGrowthLag:\t\t\t\t\t" << pc_RootGrowthLag << endl; s << "pc_MinimumTemperatureRootGrowth:\t" << pc_MinimumTemperatureRootGrowth << endl; s << "pc_InitialRootingDepth:\t\t\t\t" << pc_InitialRootingDepth << endl; s << "pc_RootPenetrationRate:\t\t\t\t" << pc_RootPenetrationRate << endl; s << "pc_RootFormFactor:\t\t\t\t\t" << pc_RootFormFactor << endl; s << "pc_SpecificRootLength:\t\t\t\t" << pc_SpecificRootLength << endl; s << "------------------------------------------------" << endl; s << "pc_MaxCropHeight:\t\t" << pc_MaxCropHeight << endl; s << "pc_CropHeightP1:\t\t" << pc_CropHeightP1 << endl; s << "pc_CropHeightP2:\t\t" << pc_CropHeightP2 << endl; s << "pc_StageAtMaxHeight:\t" << pc_StageAtMaxHeight << endl; s << "------------------------------------------------" << endl; s << "pc_FixingN:\t\t\t\t\t" << pc_FixingN << endl; s << "pc_MinimumNConcentration:\t" << pc_MinimumNConcentration << endl; s << "pc_LuxuryNCoeff:\t\t\t" << pc_LuxuryNCoeff << endl; s << "pc_NConcentrationB0:\t\t" << pc_NConcentrationB0 << endl; s << "pc_NConcentrationPN:\t\t" << pc_NConcentrationPN << endl; s << "pc_NConcentrationRoot:\t\t" << pc_NConcentrationRoot << endl; s << "pc_ResidueNRatio:\t\t\t" << pc_ResidueNRatio << endl; s << "pc_MaxNUptakeParam:\t\t\t" << pc_MaxNUptakeParam << endl; s << "------------------------------------------------" << endl; s << "pc_DevelopmentAccelerationByNitrogenStress:\t" << pc_DevelopmentAccelerationByNitrogenStress << endl; s << "pc_NConcentrationAbovegroundBiomass:\t\t" << pc_NConcentrationAbovegroundBiomass << endl; s << "pc_DroughtImpactOnFertilityFactor:\t\t\t" << pc_DroughtImpactOnFertilityFactor << endl; s << "------------------------------------------------" << endl; s << "pc_SamplingDepth:\t\t\t\t\t" << pc_SamplingDepth << endl; s << "pc_TargetNSamplingDepth:\t\t\t" << pc_TargetNSamplingDepth << endl; s << "pc_TargetN30:\t\t\t\t\t\t" << pc_TargetN30 << endl; s << "pc_HeatSumIrrigationStart:\t\t\t" << pc_HeatSumIrrigationStart << endl; s << "pc_HeatSumIrrigationEnd:\t\t\t" << pc_HeatSumIrrigationEnd << endl; s << "pc_CriticalTemperatureHeatStress:\t" << pc_CriticalTemperatureHeatStress << endl; s << "pc_LimitingTemperatureHeatStress:\t" << pc_LimitingTemperatureHeatStress << endl; s << "pc_BeginSensitivePhaseHeatStress:\t" << pc_BeginSensitivePhaseHeatStress << endl; s << "pc_EndSensitivePhaseHeatStress:\t\t" << pc_EndSensitivePhaseHeatStress << endl; //s << endl; s << "------------------------------------------------" << endl; // above-ground organ s << "pc_AbovegroundOrgan:" << endl; for (unsigned i = 0; i < pc_AbovegroundOrgan.size(); i++) s << (pc_AbovegroundOrgan[i] == 1) << " "; s << endl; s << endl; // initial organic biomass s << "pc_InitialOrganBiomass:" << endl; for (unsigned int i = 0; i < pc_InitialOrganBiomass.size(); i++) s << pc_InitialOrganBiomass[i] << " "; s << endl; s << endl; // organ maintenance respiration rate s << "pc_OrganMaintenanceRespiration:" << endl; for (unsigned int i = 0; i < pc_OrganMaintenanceRespiration.size(); i++) s << pc_OrganMaintenanceRespiration[i] << " "; s << endl; s << endl; // organ growth respiration rate s << "pc_OrganGrowthRespiration:" << endl; for (unsigned int i = 0; i < pc_OrganGrowthRespiration.size(); i++) s << pc_OrganGrowthRespiration[i] << " "; s << endl; s << endl; // organ senescence rate s << "pc_OrganSenescenceRate:" << endl; for (unsigned int i = 0; i < pc_OrganSenescenceRate.size(); i++) { for (unsigned int j = 0; j < pc_OrganSenescenceRate[i].size(); j++) { s << pc_OrganSenescenceRate[i][j] << " "; } s << endl; } s << "------------------------------------------------" << endl; //s << endl; //s << endl; // stage temperature sum s << "pc_StageTemperatureSum:" << endl; for (unsigned int i = 0; i < pc_StageTemperatureSum.size(); i++) s << pc_StageTemperatureSum[i] << " "; s << endl; s << endl; // Base day length s << "pc_BaseDaylength: " << endl; for (unsigned int i = 0; i < pc_BaseDaylength.size(); i++) s << pc_BaseDaylength[i] << " "; s << endl; s << endl; // base temperature s << "pc_BaseTemperature: " << endl; for (unsigned int i = 0; i < pc_BaseTemperature.size(); i++) s << pc_BaseTemperature[i] << " "; s << endl; s << endl; // optimum temperature s << "pc_OptimumTemperature: " << endl; for (unsigned int i = 0; i < pc_OptimumTemperature.size(); i++) s << pc_OptimumTemperature[i] << " "; s << endl; s << endl; // day length requirement s << "pc_DaylengthRequirement: " << endl; for (unsigned int i = 0; i < pc_DaylengthRequirement.size(); i++) s << pc_DaylengthRequirement[i] << " "; s << endl; s << endl; // specific leaf area s << "pc_SpecificLeafArea:" << endl; for (unsigned int i = 0; i < pc_SpecificLeafArea.size(); i++) s << pc_SpecificLeafArea[i] << " "; s << endl; s << endl; // stage max root n content s << "pc_StageMaxRootNConcentration:" << endl; for (unsigned int i = 0; i < pc_StageMaxRootNConcentration.size(); i++) s << pc_StageMaxRootNConcentration[i] << " "; s << endl; s << endl; // stage kc factor s << "pc_StageKcFactor:" << endl; for (unsigned int i = 0; i < pc_StageKcFactor.size(); i++) s << pc_StageKcFactor[i] << " "; s << endl; s << endl; // drought stress treshold s << "pc_DroughtStressThreshold:" << endl; for (unsigned int i = 0; i < pc_DroughtStressThreshold.size(); i++) s << pc_DroughtStressThreshold[i] << " "; s << endl; s << endl; // vernalisation requirement s << "pc_VernalisationRequirement:" << endl; for (unsigned int i = 0; i < pc_VernalisationRequirement.size(); i++) s << pc_VernalisationRequirement[i] << " "; s << endl; s << endl; // critical oxygen content s << "pc_CriticalOxygenContent:" << endl; for (unsigned int i = 0; i < pc_CriticalOxygenContent.size(); i++) s << pc_CriticalOxygenContent[i] << " "; s << endl; return s.str(); } //------------------------------------------------------------------------------ /** * @brief Returns data structure for crop parameters with values from DB * * A datastructure for crop parameters is created, initialized with * database values and returned. This structure will be initialized only * once. Similar to a singleton pattern. * * @param cropId * * @return Reference to crop parameters */ const CropParameters* Monica::getCropParametersFromMonicaDB(int cropId) { static L lockable; static bool initialized = false; typedef boost::shared_ptr<CropParameters> CPPtr; typedef map<int, CPPtr> CPS; static CPS cpss; // only initialize once if (!initialized) { L::Lock lock(lockable); //test if after waiting for the lock the other thread //already initialized the whole thing if (!initialized) { DB *con = newConnection("monica"); DBRow row; std::string text_request = "select id, name, max_assimilation_rate, " "carboxylation_pathway, minimum_temperature_for_assimilation, " "crop_specific_max_rooting_depth, min_n_content, " "n_content_pn, n_content_b0, " "n_content_above_ground_biomass, n_content_root, initial_kc_factor, " "development_acceleration_by_nitrogen_stress, fixing_n, " "luxury_n_coeff, max_crop_height, residue_n_ratio, " "sampling_depth, target_n_sampling_depth, target_n30, " "default_radiation_use_efficiency, crop_height_P1, crop_height_P2, " "stage_at_max_height, max_stem_diameter, stage_at_max_diameter, " "heat_sum_irrigation_start, heat_sum_irrigation_end, " "max_N_uptake_p, root_distribution_p, plant_density, " "root_growth_lag, min_temperature_root_growth, initial_rooting_depth, " "root_penetration_rate, root_form_factor, specific_root_length, " "stage_after_cut, crit_temperature_heat_stress, " "lim_temperature_heat_stress, begin_sensitive_phase_heat_stress, " "end_sensitive_phase_heat_stress, drought_impact_on_fertility_factor, " "cutting_delay_days from crop"; con->select(text_request.c_str()); debug () << text_request.c_str() << endl; while (!(row = con->getRow()).empty()) { int i = 0; int id = satoi(row[i++]); debug() << "Reading in crop Parameters for: " << id << endl; CPS::iterator cpsi = cpss.find(id); CPPtr cps; if (cpsi == cpss.end()) { cpss.insert(make_pair(id, cps = boost::shared_ptr<CropParameters>(new CropParameters))); } else { cps = cpsi->second; } cps->pc_CropName = row[i++].c_str(); cps->pc_MaxAssimilationRate = satof(row[i++]); cps->pc_CarboxylationPathway = satoi(row[i++]); cps->pc_MinimumTemperatureForAssimilation = satof(row[i++]); cps->pc_CropSpecificMaxRootingDepth = satof(row[i++]); cps->pc_MinimumNConcentration = satof(row[i++]); cps->pc_NConcentrationPN = satof(row[i++]); cps->pc_NConcentrationB0 = satof(row[i++]); cps->pc_NConcentrationAbovegroundBiomass = satof(row[i++]); cps->pc_NConcentrationRoot = satof(row[i++]); cps->pc_InitialKcFactor = satof(row[i++]); cps->pc_DevelopmentAccelerationByNitrogenStress = satoi(row[i++]); cps->pc_FixingN = satoi(row[i++]); cps->pc_LuxuryNCoeff = satof(row[i++]); cps->pc_MaxCropHeight = satof(row[i++]); cps->pc_ResidueNRatio = satof(row[i++]); cps->pc_SamplingDepth = satof(row[i++]); cps->pc_TargetNSamplingDepth = satof(row[i++]); cps->pc_TargetN30 = satof(row[i++]); cps->pc_DefaultRadiationUseEfficiency = satof(row[i++]); cps->pc_CropHeightP1 = satof(row[i++]); cps->pc_CropHeightP2 = satof(row[i++]); cps->pc_StageAtMaxHeight = satof(row[i++]); cps->pc_MaxCropDiameter = satof(row[i++]); cps->pc_StageAtMaxDiameter = satof(row[i++]); cps->pc_HeatSumIrrigationStart = satof(row[i++]); cps->pc_HeatSumIrrigationEnd = satof(row[i++]); cps->pc_MaxNUptakeParam = satof(row[i++]); cps->pc_RootDistributionParam = satof(row[i++]); cps->pc_PlantDensity = satof(row[i++]); cps->pc_RootGrowthLag = satof(row[i++]); cps->pc_MinimumTemperatureRootGrowth = satof(row[i++]); cps->pc_InitialRootingDepth = satof(row[i++]); cps->pc_RootPenetrationRate = satof(row[i++]); cps->pc_RootFormFactor = satof(row[i++]); cps->pc_SpecificRootLength = satof(row[i++]); cps->pc_StageAfterCut = satoi(row[i++]); cps->pc_CriticalTemperatureHeatStress = satof(row[i++]); cps->pc_LimitingTemperatureHeatStress = satof(row[i++]); cps->pc_BeginSensitivePhaseHeatStress = satof(row[i++]); cps->pc_EndSensitivePhaseHeatStress = satof(row[i++]); cps->pc_DroughtImpactOnFertilityFactor = satof(row[i++]); cps->pc_CuttingDelayDays = satoi(row[i++]); } std::string req2 ="select o.crop_id, o.id, o.initial_organ_biomass, " "o.organ_maintainance_respiration, o.is_above_ground, " "o.organ_growth_respiration, o.is_storage_organ " "from organ as o inner join crop as c on c.id = o.crop_id " "order by o.crop_id, c.id"; con->select(req2.c_str()); debug() << req2.c_str() << endl; while (!(row = con->getRow()).empty()) { int cropId = satoi(row[0]); // debug() << "Organ for crop: " << cropId << endl; auto cps = cpss[cropId]; cps->pc_NumberOfOrgans++; cps->pc_InitialOrganBiomass.push_back(satof(row[2])); cps->pc_OrganMaintenanceRespiration.push_back(satof(row[3])); cps->pc_AbovegroundOrgan.push_back(satoi(row[4]) == 1); cps->pc_OrganGrowthRespiration.push_back(satof(row[5])); cps->pc_StorageOrgan.push_back(satoi(row[6])); } std::string req4 = "select crop_id, id, stage_temperature_sum, " "base_temperature, opt_temperature, vernalisation_requirement, " "day_length_requirement, base_day_length, " "drought_stress_threshold, critical_oxygen_content, " "specific_leaf_area, stage_max_root_n_content, " "stage_kc_factor " "from dev_stage " "order by crop_id, id"; con->select(req4.c_str()); debug() << req4.c_str() << endl; while (!(row = con->getRow()).empty()) { int cropId = satoi(row[0]); auto cps = cpss[cropId]; cps->pc_NumberOfDevelopmentalStages++; cps->pc_StageTemperatureSum.push_back(satof(row[2])); cps->pc_BaseTemperature.push_back(satof(row[3])); cps->pc_OptimumTemperature.push_back(satof(row[4])); cps->pc_VernalisationRequirement.push_back(satof(row[5])); cps->pc_DaylengthRequirement.push_back(satof(row[6])); cps->pc_BaseDaylength.push_back(satof(row[7])); cps->pc_DroughtStressThreshold.push_back(satof(row[8])); cps->pc_CriticalOxygenContent.push_back(satof(row[9])); cps->pc_SpecificLeafArea.push_back(satof(row[10])); cps->pc_StageMaxRootNConcentration.push_back(satof(row[11])); cps->pc_StageKcFactor.push_back(satof(row[12])); } BOOST_FOREACH(CPS::value_type vt, cpss) { vt.second->resizeStageOrganVectors(); } //for (CPS::iterator it = cpss.begin(); it != cpss.end(); it++) // it->second->resizeStageOrganVectors(); std::string req3 = "select crop_id, organ_id, dev_stage_id, " "ods_dependent_param_id, value " "from crop2ods_dependent_param " "order by crop_id, ods_dependent_param_id, dev_stage_id, organ_id"; con->select(req3.c_str()); debug() << req3.c_str() << endl; while (!(row = con->getRow()).empty()) { int cropId = satoi(row[0]); // debug() << "ods_dependent_param " << cropId << "\t" << satoi(row[3]) <<"\t" << satoi(row[2]) <<"\t" << satoi(row[1])<< endl; auto cps = cpss[cropId]; vector<vector<double> >& sov = satoi(row[3]) == 1 ? cps->pc_AssimilatePartitioningCoeff : cps->pc_OrganSenescenceRate; sov[satoi(row[2]) - 1][satoi(row[1]) - 1] = satof(row[4]); } con->select("SELECT crop_id, organ_id, is_primary, percentage, dry_matter FROM yield_parts"); debug() << "SELECT crop_id, organ_id, is_primary, percentage, dry_matter FROM yield_parts" << endl; while (!(row = con->getRow()).empty()) { int cropId = satoi(row[0]); int organId = satoi(row[1]); bool isPrimary = satoi(row[2]) == 1; double percentage = satof(row[3]) / 100.0; double yieldDryMatter = satof(row[4]); auto cps = cpss[cropId]; // normal case, uses yield partitioning from crop database if (isPrimary) { // cout << cropId<< " Add primary organ: " << organId << endl; cps->organIdsForPrimaryYield.push_back(Monica::YieldComponent(organId, percentage, yieldDryMatter)); } else { // cout << cropId << " Add secondary organ: " << organId << endl; cps->organIdsForSecondaryYield.push_back(Monica::YieldComponent(organId, percentage, yieldDryMatter)); } } // get cutting parts if there are some data available con->select("SELECT crop_id, organ_id, is_primary, percentage, dry_matter FROM cutting_parts"); while (!(row = con->getRow()).empty()) { int cropId = satoi(row[0]); int organId = satoi(row[1]); //bool isPrimary = satoi(row[2]) == 1; double percentage = satof(row[3]) / 100.0; double yieldDryMatter = satof(row[4]); auto cps = cpss[cropId]; cps->organIdsForCutting.push_back(Monica::YieldComponent(organId, percentage, yieldDryMatter)); if (cropId!=18) { // do not add cutting part organ id for sudan gras because they are already added cps->organIdsForPrimaryYield.push_back(Monica::YieldComponent(organId, percentage, yieldDryMatter)); } } delete con; initialized = true; /* for(CPS::const_iterator it = cpss.begin(); it != cpss.end(); it++) cout << it->second->toString(); //*/ } } static CropParameters nothing; CPS::const_iterator ci = cpss.find(cropId); debug() << "Find crop parameter: " << cropId << endl; return ci != cpss.end() ? ci->second.get() : &nothing; } //------------------------------------------------------------------------------ /** * @brief Constructor * @param ps_LayerThickness * @param ps_ProfileDepth * @param ps_MaxMineralisationDepth * @param ps_NitrogenResponseOn * @param ps_WaterDeficitResponseOn */ GeneralParameters::GeneralParameters(double ps_LayerThickness, double ps_ProfileDepth, double ps_MaximumMineralisationDepth, bool pc_NitrogenResponseOn, bool pc_WaterDeficitResponseOn) : ps_LayerThickness(int(ps_ProfileDepth / ps_LayerThickness), ps_LayerThickness), ps_ProfileDepth(ps_ProfileDepth), ps_MaxMineralisationDepth(ps_MaximumMineralisationDepth), pc_NitrogenResponseOn(pc_NitrogenResponseOn), pc_WaterDeficitResponseOn(pc_WaterDeficitResponseOn) {} //------------------------------------------------------------------------------ /** * @brief Definition of organic constants */ double const OrganicConstants::po_UreaMolecularWeight = 0.06006;//[kg mol-1] double const OrganicConstants::po_Urea_to_N = 0.46667; //Converts 1 kg urea to 1 kg N double const OrganicConstants::po_NH3MolecularWeight = 0.01401; //[kg mol-1] double const OrganicConstants::po_NH4MolecularWeight = 0.01401; //[kg mol-1] double const OrganicConstants::po_H2OIonConcentration = 1.0; double const OrganicConstants::po_pKaHNO2 = 3.29; // [] pKa value for nitrous acid double const OrganicConstants::po_pKaNH3 = 6.5; // [] pKa value for ammonium double const OrganicConstants::po_SOM_to_C = 0.57; // = 0.58; // [] converts soil organic matter to carbon double const OrganicConstants::po_AOM_to_C = 0.45; // [] converts added organic matter to carbon //------------------------------------------------------------------------------ /** * @brief Constructor */ SiteParameters::SiteParameters() : vs_Latitude(60.0), vs_Slope(0.01), vs_HeightNN(50.0), vs_GroundwaterDepth(70.0), vs_Soil_CN_Ratio(10.0), vq_NDeposition(30.0) {} /** * @brief Serializes site parameters into a string. * @return String containing size parameters */ string SiteParameters::toString() const { ostringstream s; s << "vs_Latitude: " << vs_Latitude << " vs_Slope: " << vs_Slope << " vs_HeightNN: " << vs_HeightNN << " vs_DepthGroundwaterTable: " << vs_GroundwaterDepth << " vs_Soil_CN_Ratio: " << vs_Soil_CN_Ratio << " vq_NDeposition: " << vq_NDeposition << endl; return s.str(); } //------------------------------------------------------------------------------ /** * @brief Constructor * * Parameter initialization */ SoilParameters::SoilParameters() : vs_SoilSandContent(0.4), vs_SoilClayContent(0.05), vs_SoilpH(6.9), _vs_SoilRawDensity(0), _vs_SoilOrganicCarbon(-1), _vs_SoilOrganicMatter(-1) {} bool SoilParameters::isValid() { bool is_valid = true; if (vs_FieldCapacity <= 0) { cout << "SoilParameters::Error: No field capacity defined in database for " << vs_SoilTexture.c_str() << " , RawDensity: "<< _vs_SoilRawDensity << endl; is_valid = false; } if (vs_Saturation <= 0) { cout << "SoilParameters::Error: No saturation defined in database for " << vs_SoilTexture.c_str() << " , RawDensity: " << _vs_SoilRawDensity << endl; is_valid = false; } if (vs_PermanentWiltingPoint <= 0) { cout << "SoilParameters::Error: No saturation defined in database for " << vs_SoilTexture.c_str() << " , RawDensity: " << _vs_SoilRawDensity << endl; is_valid = false; } if (vs_SoilSandContent<0) { cout << "SoilParameters::Error: Invalid soil sand content: "<< vs_SoilSandContent << endl; is_valid = false; } if (vs_SoilClayContent<0) { cout << "SoilParameters::Error: Invalid soil clay content: "<< vs_SoilClayContent << endl; is_valid = false; } if (vs_SoilpH<0) { cout << "SoilParameters::Error: Invalid soil ph value: "<< vs_SoilpH << endl; is_valid = false; } if (vs_SoilStoneContent<0) { cout << "SoilParameters::Error: Invalid soil stone content: "<< vs_SoilStoneContent << endl; is_valid = false; } if (vs_Saturation<0) { cout << "SoilParameters::Error: Invalid value for saturation: "<< vs_Saturation << endl; is_valid = false; } if (vs_PermanentWiltingPoint<0) { cout << "SoilParameters::Error: Invalid value for permanent wilting point: "<< vs_PermanentWiltingPoint << endl; is_valid = false; } if (_vs_SoilRawDensity<0) { cout << "SoilParameters::Error: Invalid soil raw density: "<< _vs_SoilRawDensity << endl; is_valid = false; } return is_valid; } /** * @brief Returns raw density of soil * @return raw density of soil */ double SoilParameters::vs_SoilRawDensity() const { // conversion from g cm-3 in kg m-3 return _vs_SoilRawDensity * 1000; } /** * @brief Sets soil raw density * @param srd New soil rad density */ void SoilParameters::set_vs_SoilRawDensity(double srd) { _vs_SoilRawDensity = srd; } /** * @brief Returns soil organic carbon. * @return soil organic carbon */ double SoilParameters::vs_SoilOrganicCarbon() const { if (_vs_SoilOrganicMatter < 0) return _vs_SoilOrganicCarbon; return _vs_SoilOrganicMatter * OrganicConstants::po_SOM_to_C; } /** * @brief Setter of soil organic carbon. * @param soc New soil organic carbon */ void SoilParameters::set_vs_SoilOrganicCarbon(double soc) { _vs_SoilOrganicCarbon = soc; } /** * @brief Getter for soil organic matter. * @return Soil organic matter */ double SoilParameters::vs_SoilOrganicMatter() const { if (_vs_SoilOrganicCarbon < 0) return _vs_SoilOrganicMatter; return _vs_SoilOrganicCarbon / OrganicConstants::po_SOM_to_C; } /** * @brief Setter for soil organic matter. * @param som New soil organic matter */ void SoilParameters::set_vs_SoilOrganicMatter(double som) { _vs_SoilOrganicMatter = som; } /** * @brief Getter for silt content * @return silt content */ double SoilParameters::vs_SoilSiltContent() const { if ((vs_SoilSandContent - 0.001) < 0 && (vs_SoilClayContent - 0.001) < 0) return 0; return 1 - vs_SoilSandContent - vs_SoilClayContent; } /** * @brief Getter for soil bulk density. * @return bulk density */ double SoilParameters::vs_SoilBulkDensity() const { return (_vs_SoilRawDensity + (0.009 * 100 * vs_SoilClayContent)) * 1000; } /** * @brief Serializes soil parameters into a string. * @return String of soil parameters */ string SoilParameters::toString() const { ostringstream s; s << "vs_Soilph: " << vs_SoilpH << endl << "vs_SoilOrganicCarbon: " << vs_SoilOrganicCarbon() << endl << "vs_SoilOrganicMatter: " << vs_SoilOrganicMatter() << endl << "vs_SoilRawDensity: " << vs_SoilRawDensity() << endl << "vs_SoilBulkDensity: " << vs_SoilBulkDensity() << endl << "vs_SoilSandContent: " << vs_SoilSandContent << endl << "vs_SoilClayContent: " << vs_SoilClayContent << endl << "vs_SoilSiltContent: " << vs_SoilSiltContent() << endl << "vs_SoilStoneContent: " << vs_SoilStoneContent << endl; return s.str(); } /** * @brief Returns lambda from soil texture * * @param lambda * * @return */ double SoilParameters::texture2lambda(double sand, double clay) { return Tools::texture2lambda(sand, clay); } //------------------------------------------------------------------------------ /** * @brief Overloaded function that returns soil parameter for ucker. * * Parameters are read from database. * * @param str * @param gps General parameters * @return Soil parameters */ const SoilPMs* Monica::ueckerSoilParameters(const std::string& str, const GeneralParameters& gps, bool loadSingleParameter) { //cout << "getting soilparameters for STR: " << str << endl; int lt = int(gps.ps_LayerThickness.front() * 100); //cm int maxDepth = int(gps.ps_ProfileDepth) * 100; //cm int maxNoOfLayers = int(double(maxDepth) / double(lt)); static L lockable; typedef map<string, SoilPMsPtr> Map; static bool initialized = false; static Map spss; if (!initialized) { L::Lock lock(lockable); if (!initialized) { DBPtr con(newConnection("landcare-dss")); DBRow row; ostringstream s; s << "select str, anzhor, hor, ho, hu, ph, corg, trd, s, t " "from mmk_profile " "where ho <= 201 "; if(loadSingleParameter) s << "and str = '" << str << "' "; s << "order by str, hor"; con->select(s.str().c_str()); while (!(row = con->getRow()).empty()) { string id = row[0]; Map::iterator spsi = spss.find(id); SoilPMsPtr sps; if (spsi == spss.end()) spss.insert(make_pair(id, sps = SoilPMsPtr(new SoilPMs))); else sps = spsi->second; int hcount = satoi(row[1]); int currenth = satoi(row[2]); int ho = sps->size() * lt; int hu = satoi(row[4]) ? satoi(row[4]) : maxDepth; int hsize = hu - ho; int subhcount = int(Tools::round(double(hsize) / double(lt)));//std::floor(double(hsize) / double(lt)); if (currenth == hcount && (int(sps->size()) + subhcount) < maxNoOfLayers) subhcount += maxNoOfLayers - sps->size() - subhcount; SoilParameters p; if (satof(row[5])) p.vs_SoilpH = satof(row[5]); p.set_vs_SoilOrganicCarbon(satof(row[6]) ? (satof(row[6]) / 100.0) : 0); p.set_vs_SoilRawDensity(satof(row[7])); p.vs_SoilSandContent = satof(row[8]) / 100.0; p.vs_SoilClayContent = satof(row[9]) / 100.0; p.vs_SoilTexture = texture2KA5(p.vs_SoilSandContent, p.vs_SoilClayContent); p.vs_SoilStoneContent = 0.0; p.vs_Lambda = texture2lambda(p.vs_SoilSandContent, p.vs_SoilClayContent); // initialization of saturation, field capacity and perm. wilting point soilCharacteristicsKA5(p); bool valid_soil_params = p.isValid(); if (!valid_soil_params) { cout << "Error in soil parameters. Aborting now simulation"; exit(-1); } for (int i = 0; i < subhcount; i++) sps->push_back(p); } initialized = true; // BOOST_FOREACH(Map::value_type p, spss) // { // cout << "code: " << p.first << endl; // BOOST_FOREACH(SoilParameters sp, *p.second) // { // cout << sp.toString(); // cout << "---------------------------------" << endl; // } // } } } static SoilPMs nothing; Map::const_iterator ci = spss.find(str); /* if(ci != spss.end()) { cout << "code: " << str << endl; BOOST_FOREACH(SoilParameters sp, *ci->second) { cout << sp.toString(); cout << "---------------------------------" << endl; } } */ return ci != spss.end() ? ci->second.get() : &nothing; } /** * @brief Overloaded function that returns soil parameter for ucker. * @param mmkGridId * @param gps General parameters * @return Soil parameters */ const SoilPMs* Monica::ueckerSoilParameters(int mmkGridId, const GeneralParameters& gps, bool loadSingleParameter) { //cout << "mmkGridId: " << mmkGridId << " -> str: " << ueckerGridId2STR(mmkGridId) << endl; string str = ueckerGridId2STR(mmkGridId); return str.empty() ? NULL : ueckerSoilParameters(str, gps, loadSingleParameter); } string Monica::ueckerGridId2STR(int ugid) { static L lockable; static bool initialized = false; typedef map<int, string> Map; static Map m; if (!initialized) { L::Lock lock(lockable); if (!initialized) { DBPtr con(newConnection("landcare-dss")); DBRow row; con->select("SELECT grid_id, str FROM uecker_grid_id_2_str"); while (!(row = con->getRow()).empty()) m.insert(make_pair(satoi(row[0]), row[1])); initialized = true; } } Map::const_iterator ci = m.find(ugid); return ci != m.end() ? ci->second : ""; } //---------------------------------------------------------------------------- /** * @brief Returns soil parameter of weisseritz * @param bk50GridId * @param gps General parameters * @return Soil parameters */ const SoilPMs* Monica::weisseritzSoilParameters(int bk50GridId, const GeneralParameters& gps, bool loadSingleParameter) { static SoilPMs nothing; int lt = int(gps.ps_LayerThickness.front() * 100); //cm int maxDepth = int(gps.ps_ProfileDepth) * 100; //cm int maxNoOfLayers = int(double(maxDepth) / double(lt)); static L lockable; typedef map<int, SoilPMsPtr> Map; static bool initialized = false; static Map spss; if(!initialized) { L::Lock lock(lockable); if (!initialized) { DBPtr con(newConnection("landcare-dss")); DBRow row; ostringstream s; s << "select b2.grid_id, bk.anzahl_horizonte, bk.horizont_id, " "bk.otief, bk.utief, bk.humus_st, bk.ld_eff, w.s, w.t " "from bk50_profile as bk inner join bk50_grid_id_2_aggnr as b2 on " "bk.aggnr = b2.aggnr inner join ka4wind as w on " "bk.boart = w.bodart "; if(loadSingleParameter) s << "where b2.grid_id = " << bk50GridId << " "; s << "order by b2.grid_id, bk.horizont_id"; set<int> skip; con->select(s.str().c_str()); while (!(row = con->getRow()).empty()) { int id = satoi(row[0]); //skip elements which are incomplete if(skip.find(id) != skip.end()) continue; SoilPMsPtr sps = spss[id]; if(!sps) { sps = SoilPMsPtr(new SoilPMs); spss[id] = sps; } int hcount = satoi(row[1]); int currenth = satoi(row[2]); int ho = sps->size() * lt; int hu = satof(row[4]) ? int(satof(row[4])*100) : maxDepth; int hsize = hu - ho; int subhcount = int(Tools::round(double(hsize) / double(lt)));//std::floor(double(hsize) / double(lt)); if (currenth == hcount && (int(sps->size()) + subhcount) < maxNoOfLayers) subhcount += maxNoOfLayers - sps->size() - subhcount; SoilParameters p; p.set_vs_SoilOrganicCarbon(humus_st2corg(satoi(row[5])) / 100.0); double clayPercent = satof(row[8]); p.set_vs_SoilRawDensity(ld_eff2trd(satoi(row[6]), clayPercent / 100.0)); p.vs_SoilSandContent = satof(row[7]) / 100.0; p.vs_SoilClayContent = clayPercent / 100.0; p.vs_SoilTexture = texture2KA5(p.vs_SoilSandContent, p.vs_SoilClayContent); p.vs_SoilStoneContent = 0.0; p.vs_Lambda = texture2lambda(p.vs_SoilSandContent, p.vs_SoilClayContent); // initialization of saturation, field capacity and perm. wilting point soilCharacteristicsKA5(p); if(!p.isValid()) { skip.insert(id); cout << "Error in soil parameters. Skipping bk50Id: " << id << endl; spss.erase(id); continue; } for (int i = 0; i < subhcount; i++) sps->push_back(p); } initialized = true; // BOOST_FOREACH(Map::value_type p, spss) // { // cout << "bk50Id: " << p.first << endl; // BOOST_FOREACH(const SoilParameters& sps, *(p.second.get())) // { // cout << sps.toString() << endl; // } // cout << "---------------------------------" << endl; // } } } Map::const_iterator ci = spss.find(bk50GridId); return ci != spss.end() ? ci->second.get() : &nothing; } /** * @brief Returns soil parameter of weisseritz * @param bk50GridId * @param gps General parameters * @return Soil parameters */ const SoilPMs* Monica::bk50SoilParameters(int bk50GridId, const GeneralParameters& gps, bool loadSingleParameter) { static SoilPMs nothing; int lt = int(gps.ps_LayerThickness.front() * 100); //cm int maxDepth = int(gps.ps_ProfileDepth) * 100; //cm int maxNoOfLayers = int(double(maxDepth) / double(lt)); static L lockable; typedef map<int, SoilPMsPtr> Map; static bool initialized = false; static Map spss; if(!initialized) { L::Lock lock(lockable); if (!initialized) { DBPtr con(newConnection("landcare-dss")); DBRow row; ostringstream s; s << "select bk.grid_id, bk.lower_depth_m, " "bk.humus_class, bk.ld_eff_class, w.s, w.t " "from bk50_sachsen_juli_2012 as bk inner join ka4wind as w on " "bk.ka4_soil_type = w.bodart "; if(loadSingleParameter) s << "where bk.grid_id = " << bk50GridId << " "; s << "order by bk.grid_id, bk.lower_depth_m"; ostringstream s2; s2 << "select grid_id, count(grid_id) " "from bk50_sachsen_juli_2012 " "group by grid_id"; con->select(s2.str().c_str()); map<int, int> id2layerCount; while (!(row = con->getRow()).empty()) id2layerCount[satoi(row[0])] = satoi(row[1]); con->freeResultSet(); set<int> skip; con->select(s.str().c_str()); int currenth = 0; while (!(row = con->getRow()).empty()) { int id = satoi(row[0]); //skip elements which are incomplete if(skip.find(id) != skip.end()) continue; SoilPMsPtr sps = spss[id]; if(!sps) { sps = SoilPMsPtr(new SoilPMs); spss[id] = sps; currenth = 0; } int hcount = id2layerCount[id]; currenth++; int ho = sps->size() * lt; int hu = int(satof(row[1])*100); int hsize = hu - ho; int subhcount = int(Tools::round(double(hsize) / double(lt)));//std::floor(double(hsize) / double(lt)); if (currenth == hcount && (int(sps->size()) + subhcount) < maxNoOfLayers) subhcount += maxNoOfLayers - sps->size() - subhcount; SoilParameters p; p.set_vs_SoilOrganicCarbon(humus_st2corg(satoi(row[2])) / 100.0); double clayPercent = satof(row[5]); p.set_vs_SoilRawDensity(ld_eff2trd(satoi(row[3]), clayPercent / 100.0)); p.vs_SoilSandContent = satof(row[4]) / 100.0; p.vs_SoilClayContent = clayPercent / 100.0; p.vs_SoilTexture = texture2KA5(p.vs_SoilSandContent, p.vs_SoilClayContent); p.vs_SoilStoneContent = 0.0; p.vs_Lambda = texture2lambda(p.vs_SoilSandContent, p.vs_SoilClayContent); // initialization of saturation, field capacity and perm. wilting point soilCharacteristicsKA5(p); if(!p.isValid()) { skip.insert(id); cout << "Error in soil parameters. Skipping bk50Id: " << id << endl; spss.erase(id); continue; } for (int i = 0; i < subhcount; i++) sps->push_back(p); } initialized = true; // BOOST_FOREACH(Map::value_type p, spss) // { // cout << "bk50Id: " << p.first << endl; // BOOST_FOREACH(const SoilParameters& sps, *(p.second.get())) // { // cout << sps.toString() << endl; // } // cout << "---------------------------------" << endl; // } } } Map::const_iterator ci = spss.find(bk50GridId); return ci != spss.end() ? ci->second.get() : &nothing; } string Monica::bk50GridId2ST(int bk50GridId) { static L lockable; typedef map<int, string> Map; static Map m; static bool initialized = false; if (!initialized) { L::Lock lock(lockable); if (!initialized) { DBPtr con(newConnection("landcare-dss")); con->setCharacterSet("utf8"); DBRow row; con->select("SELECT grid_id, st from bk50 where st is not null"); while (!(row = con->getRow()).empty()) m[satoi(row[0])] = row[1]; initialized = true; } } Map::const_iterator ci = m.find(bk50GridId); return ci != m.end() ? ci->second : "ST unbekannt"; } string Monica::bk50GridId2KA4Layers(int bk50GridId) { static L lockable; typedef map<int, string> Map; static Map m; static bool initialized = false; if (!initialized) { L::Lock lock(lockable); if (!initialized) { DBPtr con(newConnection("landcare-dss")); con->setCharacterSet("utf8"); DBRow row; con->select("SELECT grid_id, ka4_soil_type " "from bk50_sachsen_juli_2012 " "order by grid_id, lower_depth_m"); while (!(row = con->getRow()).empty()) { string pre = m[satoi(row[0])].empty() ? "" : "|"; m[satoi(row[0])].append(pre).append(row[1]); } initialized = true; } } Map::const_iterator ci = m.find(bk50GridId); return ci != m.end() ? ci->second : "Kein Bodenprofil vorhanden!"; } const SoilPMs* Monica::soilParametersFromHermesFile(int soilId, const string& pathToFile, const GeneralParameters& gps, double soil_ph) { debug() << pathToFile.c_str() << endl; int lt = int(gps.ps_LayerThickness.front() * 100); //cm int maxDepth = int(gps.ps_ProfileDepth) * 100; //cm int maxNoOfLayers = int(double(maxDepth) / double(lt)); static L lockable; typedef map<int, SoilPMsPtr> Map; static bool initialized = false; static Map spss; if (!initialized) { L::Lock lock(lockable); if (!initialized) { ifstream ifs(pathToFile.c_str(), ios::binary); string s; //skip first line(s) getline(ifs, s); int currenth = 1; while (getline(ifs, s)) { // cout << "s: " << s << endl; if (trim(s) == "end") break; //BdID Corg Bart UKT LD Stn C/N C/S Hy Wmx AzHo int ti; string ba, ts; int id, hu, ld, stone, cn, hcount; double corg, wmax; istringstream ss(s); ss >> id >> corg >> ba >> hu >> ld >> stone >> cn >> ts >> ti >> wmax >> hcount; //double vs_SoilSpecificMaxRootingDepth = wmax / 10.0; //[dm] --> [m] hu *= 10; //reset horizont count to start new soil definition if (hcount > 0) currenth = 1; Map::iterator spsi = spss.find(soilId); SoilPMsPtr sps; if (spsi == spss.end()) { spss.insert(make_pair(soilId, sps = SoilPMsPtr(new SoilPMs))); } else { sps = spsi->second; } int ho = sps->size() * lt; int hsize = hu - ho; int subhcount = int(Tools::round(double(hsize) / double(lt)));//std::floor(double(hsize) / double(lt)); if (currenth == hcount && (int(sps->size()) + subhcount) < maxNoOfLayers) subhcount += maxNoOfLayers - sps->size() - subhcount; if ((ba != "Ss") && (ba != "Sl2") && (ba != "Sl3") && (ba != "Sl4") && (ba != "Slu") && (ba != "St2") && (ba != "St3") && (ba != "Su2") && (ba != "Su3") && (ba != "Su4") && (ba != "Ls2") && (ba != "Ls3") && (ba != "Ls4") && (ba != "Lt2") && (ba != "Lt3") && (ba != "Lts") && (ba != "Lu") && (ba != "Uu") && (ba != "Uls") && (ba != "Us") && (ba != "Ut2") && (ba != "Ut3") && (ba != "Ut4") && (ba != "Tt") && (ba != "Tl") && (ba != "Tu2") && (ba != "Tu3") && (ba != "Tu4") && (ba != "Ts2") && (ba != "Ts3") && (ba != "Ts4") && (ba != "fS") && (ba != "fS") && (ba != "fSms") && (ba != "fSgs") && (ba != "mS") && (ba != "mSfs") && (ba != "mSgs") && (ba != "gS")){ cerr << "no valid texture class defined" << endl; exit(1); } SoilParameters p; // cout << "Bodenart:\t" << ba << "\tld: " << ld << endl; p.set_vs_SoilOrganicCarbon(corg / 100.0); p.set_vs_SoilRawDensity(ld_eff2trd(ld, KA52clay(ba))); p.vs_SoilSandContent = KA52sand(ba); p.vs_SoilClayContent = KA52clay(ba); p.vs_SoilStoneContent = stone / 100.0; p.vs_Lambda = texture2lambda(p.vs_SoilSandContent, p.vs_SoilClayContent); p.vs_SoilTexture = ba; if (soil_ph != -1.0) { p.vs_SoilpH = soil_ph; } // initialization of saturation, field capacity and perm. wilting point soilCharacteristicsKA5(p); // cout << p.toString() << endl; bool valid_soil_params = p.isValid(); if (!valid_soil_params) { cout << "Error in soil parameters. Aborting now simulation"; exit(-1); } for (int i = 0; i < subhcount; i++) sps->push_back(p); // cout << "sps: " << sps->size() << endl; currenth++; } initialized = true; // // for (Map::const_iterator it = spss.begin(); it != spss.end(); it++) { // cout << "code: " << it->first << endl; // for (vector<SoilParameters>::const_iterator it2 = it->second->begin(); it2 != it->second->end(); it2++) // cout << it2->toString(); // cout << "---------------------------------" << endl; // } } } static SoilPMs nothing; Map::const_iterator ci = spss.find(soilId); return ci != spss.end() ? ci->second.get() : &nothing; } //------------------------------------------------------------------------------ void Monica::soilCharacteristicsKA5(SoilParameters& soilParameter) { debug() << "soilCharacteristicsKA5" << endl; std::string vs_SoilTexture = soilParameter.vs_SoilTexture; double vs_SoilStoneContent = soilParameter.vs_SoilStoneContent; double vs_FieldCapacity; double vs_Saturation; double vs_PermanentWiltingPoint; if (vs_SoilTexture != "") { double vs_SoilRawDensity = soilParameter.vs_SoilRawDensity() / 1000.0; // [kg m-3] -> [g cm-3] double vs_SoilOrganicMatter = soilParameter.vs_SoilOrganicMatter() * 100.0; // [kg kg-1] -> [%] // *************************************************************************** // *** The following boundaries are extracted from: *** // *** Wessolek, G., M. Kaupenjohann, M. Renger (2009) Bodenphysikalische *** // *** Kennwerte und Berechnungsverfahren für die Praxis. Bodenökologie *** // *** und Bodengenese 40, Selbstverlag Technische Universität Berlin *** // *** (Tab. 4). *** // *************************************************************************** double vs_SoilRawDensityLowerBoundary=0.0; double vs_SoilRawDensityUpperBoundary=0.0; if (vs_SoilRawDensity < 1.1) { vs_SoilRawDensityLowerBoundary = 1.1; vs_SoilRawDensityUpperBoundary = 1.1; } else if ((vs_SoilRawDensity >= 1.1) && (vs_SoilRawDensity < 1.3)) { vs_SoilRawDensityLowerBoundary = 1.1; vs_SoilRawDensityUpperBoundary = 1.3; } else if ((vs_SoilRawDensity >= 1.3) && (vs_SoilRawDensity < 1.5)) { vs_SoilRawDensityLowerBoundary = 1.3; vs_SoilRawDensityUpperBoundary = 1.5; } else if ((vs_SoilRawDensity >= 1.5) && (vs_SoilRawDensity < 1.7)) { vs_SoilRawDensityLowerBoundary = 1.5; vs_SoilRawDensityUpperBoundary = 1.7; } else if ((vs_SoilRawDensity >= 1.7) && (vs_SoilRawDensity < 1.9)) { vs_SoilRawDensityLowerBoundary = 1.7; vs_SoilRawDensityUpperBoundary = 1.9; } else if (vs_SoilRawDensity >= 1.9) { vs_SoilRawDensityLowerBoundary = 1.9; vs_SoilRawDensityUpperBoundary = 1.9; } // special treatment for "torf" soils if (vs_SoilTexture=="Hh" || vs_SoilTexture=="Hn") { vs_SoilRawDensityLowerBoundary = -1; vs_SoilRawDensityUpperBoundary = -1; } // Boundaries for linear interpolation double vs_FieldCapacityLowerBoundary = 0.0; double vs_FieldCapacityUpperBoundary = 0.0; double vs_SaturationLowerBoundary = 0.0; double vs_SaturationUpperBoundary = 0.0; double vs_PermanentWiltingPointLowerBoundary = 0.0; double vs_PermanentWiltingPointUpperBoundary = 0.0; readPrincipalSoilCharacteristicData(vs_SoilTexture, vs_SoilRawDensityLowerBoundary, vs_SaturationLowerBoundary, vs_FieldCapacityLowerBoundary, vs_PermanentWiltingPointLowerBoundary); readPrincipalSoilCharacteristicData(vs_SoilTexture, vs_SoilRawDensityUpperBoundary, vs_SaturationUpperBoundary, vs_FieldCapacityUpperBoundary, vs_PermanentWiltingPointUpperBoundary); // cout << "Soil Raw Density:\t" << vs_SoilRawDensity << endl; // cout << "Saturation:\t\t" << vs_SaturationLowerBoundary << "\t" << vs_SaturationUpperBoundary << endl; // cout << "Field Capacity:\t" << vs_FieldCapacityLowerBoundary << "\t" << vs_FieldCapacityUpperBoundary << endl; // cout << "PermanentWP:\t" << vs_PermanentWiltingPointLowerBoundary << "\t" << vs_PermanentWiltingPointUpperBoundary << endl; // cout << "Soil Organic Matter:\t" << vs_SoilOrganicMatter << endl; // *************************************************************************** // *** The following boundaries are extracted from: *** // *** Wessolek, G., M. Kaupenjohann, M. Renger (2009) Bodenphysikalische *** // *** Kennwerte und Berechnungsverfahren für die Praxis. Bodenökologie *** // *** und Bodengenese 40, Selbstverlag Technische Universität Berlin *** // *** (Tab. 5). *** // *************************************************************************** double vs_SoilOrganicMatterLowerBoundary=0.0; double vs_SoilOrganicMatterUpperBoundary=0.0; if ((vs_SoilOrganicMatter >= 0.0) && (vs_SoilOrganicMatter < 1.0)) { vs_SoilOrganicMatterLowerBoundary = 0.0; vs_SoilOrganicMatterUpperBoundary = 0.0; } else if ((vs_SoilOrganicMatter >= 1.0) && (vs_SoilOrganicMatter < 1.5)) { vs_SoilOrganicMatterLowerBoundary = 0.0; vs_SoilOrganicMatterUpperBoundary = 1.5; } else if ((vs_SoilOrganicMatter >= 1.5) && (vs_SoilOrganicMatter < 3.0)) { vs_SoilOrganicMatterLowerBoundary = 1.5; vs_SoilOrganicMatterUpperBoundary = 3.0; } else if ((vs_SoilOrganicMatter >= 3.0) && (vs_SoilOrganicMatter < 6.0)) { vs_SoilOrganicMatterLowerBoundary = 3.0; vs_SoilOrganicMatterUpperBoundary = 6.0; } else if ((vs_SoilOrganicMatter >= 6.0) && (vs_SoilOrganicMatter < 11.5)) { vs_SoilOrganicMatterLowerBoundary = 6.0; vs_SoilOrganicMatterUpperBoundary = 11.5; } else if (vs_SoilOrganicMatter >= 11.5) { vs_SoilOrganicMatterLowerBoundary = 11.5; vs_SoilOrganicMatterUpperBoundary = 11.5; } // special treatment for "torf" soils if (vs_SoilTexture=="Hh" || vs_SoilTexture=="Hn") { vs_SoilOrganicMatterLowerBoundary = 0.0; vs_SoilOrganicMatterUpperBoundary = 0.0; } // Boundaries for linear interpolation double vs_FieldCapacityModifierLowerBoundary = 0.0; double vs_SaturationModifierLowerBoundary = 0.0; double vs_PermanentWiltingPointModifierLowerBoundary = 0.0; double vs_FieldCapacityModifierUpperBoundary = 0.0; double vs_SaturationModifierUpperBoundary = 0.0; double vs_PermanentWiltingPointModifierUpperBoundary = 0.0; // modifier values are given only for organic matter > 1.0% (class h2) if (vs_SoilOrganicMatterLowerBoundary != 0.0) { readSoilCharacteristicModifier(vs_SoilTexture, vs_SoilOrganicMatterLowerBoundary, vs_SaturationModifierLowerBoundary, vs_FieldCapacityModifierLowerBoundary, vs_PermanentWiltingPointModifierLowerBoundary); } else { vs_SaturationModifierLowerBoundary = 0.0; vs_FieldCapacityModifierLowerBoundary = 0.0; vs_PermanentWiltingPointModifierLowerBoundary = 0.0; } if (vs_SoilOrganicMatterUpperBoundary != 0.0) { readSoilCharacteristicModifier(vs_SoilTexture, vs_SoilOrganicMatterUpperBoundary, vs_SaturationModifierUpperBoundary, vs_FieldCapacityModifierUpperBoundary, vs_PermanentWiltingPointModifierUpperBoundary); } else { vs_SaturationModifierUpperBoundary = 0.0; vs_FieldCapacityModifierUpperBoundary = 0.0; vs_PermanentWiltingPointModifierUpperBoundary = 0.0; } // cout << "Saturation-Modifier:\t" << vs_SaturationModifierLowerBoundary << "\t" << vs_SaturationModifierUpperBoundary << endl; // cout << "Field capacity-Modifier:\t" << vs_FieldCapacityModifierLowerBoundary << "\t" << vs_FieldCapacityModifierUpperBoundary << endl; // cout << "PWP-Modifier:\t" << vs_PermanentWiltingPointModifierLowerBoundary << "\t" << vs_PermanentWiltingPointModifierUpperBoundary << endl; // Linear interpolation double vs_FieldCapacityUnmodified; double vs_SaturationUnmodified; double vs_PermanentWiltingPointUnmodified; if ((vs_FieldCapacityUpperBoundary < 0.5) && (vs_FieldCapacityLowerBoundary >= 1.0)) { vs_FieldCapacityUnmodified = vs_FieldCapacityLowerBoundary; } else if ((vs_FieldCapacityLowerBoundary < 0.5) && (vs_FieldCapacityUpperBoundary >= 1.0)) { vs_FieldCapacityUnmodified = vs_FieldCapacityUpperBoundary; } else if (vs_SoilRawDensityUpperBoundary != vs_SoilRawDensityLowerBoundary) { vs_FieldCapacityUnmodified = (vs_SoilRawDensity - vs_SoilRawDensityLowerBoundary) / (vs_SoilRawDensityUpperBoundary - vs_SoilRawDensityLowerBoundary) * (vs_FieldCapacityUpperBoundary - vs_FieldCapacityLowerBoundary) + vs_FieldCapacityLowerBoundary; } else { vs_FieldCapacityUnmodified = vs_FieldCapacityLowerBoundary; } if ((vs_SaturationUpperBoundary < 0.5) && (vs_SaturationLowerBoundary >= 1.0)) { vs_SaturationUnmodified = vs_SaturationLowerBoundary; } else if ((vs_SaturationLowerBoundary < 0.5) && (vs_SaturationUpperBoundary >= 1.0)) { vs_SaturationUnmodified = vs_SaturationUpperBoundary; } else if (vs_SoilRawDensityUpperBoundary != vs_SoilRawDensityLowerBoundary) { vs_SaturationUnmodified = (vs_SoilRawDensity - vs_SoilRawDensityLowerBoundary) / (vs_SoilRawDensityUpperBoundary - vs_SoilRawDensityLowerBoundary) * (vs_SaturationUpperBoundary - vs_SaturationLowerBoundary) + vs_SaturationLowerBoundary; } else { vs_SaturationUnmodified = vs_SaturationLowerBoundary; } if ((vs_PermanentWiltingPointUpperBoundary < 0.5) && (vs_PermanentWiltingPointLowerBoundary >= 1.0)) { vs_PermanentWiltingPointUnmodified = vs_PermanentWiltingPointLowerBoundary; } else if ((vs_PermanentWiltingPointLowerBoundary < 0.5) && (vs_PermanentWiltingPointUpperBoundary >= 1.0)) { vs_PermanentWiltingPointUnmodified = vs_PermanentWiltingPointUpperBoundary; } else if (vs_SoilRawDensityUpperBoundary != vs_SoilRawDensityLowerBoundary) { vs_PermanentWiltingPointUnmodified = (vs_SoilRawDensity - vs_SoilRawDensityLowerBoundary) / (vs_SoilRawDensityUpperBoundary - vs_SoilRawDensityLowerBoundary) * (vs_PermanentWiltingPointUpperBoundary - vs_PermanentWiltingPointLowerBoundary) + vs_PermanentWiltingPointLowerBoundary; } else { vs_PermanentWiltingPointUnmodified = vs_PermanentWiltingPointLowerBoundary; } double vs_FieldCapacityModifier; double vs_SaturationModifier; double vs_PermanentWiltingPointModifier; if (vs_SoilOrganicMatterUpperBoundary != vs_SoilOrganicMatterLowerBoundary) { vs_FieldCapacityModifier = (vs_SoilOrganicMatter - vs_SoilOrganicMatterLowerBoundary) / (vs_SoilOrganicMatterUpperBoundary - vs_SoilOrganicMatterLowerBoundary) * (vs_FieldCapacityModifierUpperBoundary - vs_FieldCapacityModifierLowerBoundary) + vs_FieldCapacityModifierLowerBoundary; vs_SaturationModifier = (vs_SoilOrganicMatter - vs_SoilOrganicMatterLowerBoundary) / (vs_SoilOrganicMatterUpperBoundary - vs_SoilOrganicMatterLowerBoundary) * (vs_SaturationModifierUpperBoundary - vs_SaturationModifierLowerBoundary) + vs_SaturationModifierLowerBoundary; vs_PermanentWiltingPointModifier = (vs_SoilOrganicMatter - vs_SoilOrganicMatterLowerBoundary) / (vs_SoilOrganicMatterUpperBoundary - vs_SoilOrganicMatterLowerBoundary) * (vs_PermanentWiltingPointModifierUpperBoundary - vs_PermanentWiltingPointModifierLowerBoundary) + vs_PermanentWiltingPointModifierLowerBoundary; } else { vs_FieldCapacityModifier = vs_FieldCapacityModifierLowerBoundary; vs_SaturationModifier = vs_SaturationModifierLowerBoundary; vs_PermanentWiltingPointModifier = vs_PermanentWiltingPointModifierLowerBoundary; // in this case upper and lower boundary are equal, so doesn't matter. } // Modifying the principal values by organic matter vs_FieldCapacity = (vs_FieldCapacityUnmodified + vs_FieldCapacityModifier) / 100.0; // [m3 m-3] vs_Saturation = (vs_SaturationUnmodified + vs_SaturationModifier) / 100.0; // [m3 m-3] vs_PermanentWiltingPoint = (vs_PermanentWiltingPointUnmodified + vs_PermanentWiltingPointModifier) / 100.0; // [m3 m-3] // Modifying the principal values by stone content vs_FieldCapacity *= (1.0 - vs_SoilStoneContent); vs_Saturation *= (1.0 - vs_SoilStoneContent); vs_PermanentWiltingPoint *= (1.0 - vs_SoilStoneContent); } else { vs_FieldCapacity = 0.0; vs_Saturation = 0.0; vs_PermanentWiltingPoint = 0.0; } debug() << "vs_SoilTexture:\t\t\t" << vs_SoilTexture << endl; debug() << "vs_Saturation:\t\t\t" << vs_Saturation << endl; debug() << "vs_FieldCapacity:\t\t" << vs_FieldCapacity << endl; debug() << "vs_PermanentWiltingPoint:\t" << vs_PermanentWiltingPoint << endl << endl; soilParameter.vs_FieldCapacity = vs_FieldCapacity; soilParameter.vs_Saturation = vs_Saturation; soilParameter.vs_PermanentWiltingPoint = vs_PermanentWiltingPoint; } //------------------------------------------------------------------------------ string Crop::toString(bool detailed) const { ostringstream s; s << "id: " << id() << " name: " << name() << " seedDate: " << seedDate().toString() << " harvestDate: " << harvestDate().toString(); if (detailed) { s << endl << "CropParameters: " << endl << cropParameters()->toString() << endl << "ResidueParameters: " << endl << residueParameters()->toString() << endl; } return s.str(); } //------------------------------------------------------------------------------ void Crop::writeCropParameters(std::string path) { ofstream parameter_output_file; parameter_output_file.open((path + "crop_parameters-" + _name.c_str() + ".txt").c_str()); if (parameter_output_file.fail()){ debug() << "Could not write file\"" << (path + "crop_parameters-" + _name.c_str() + ".txt").c_str() << "\"" << endl; return; } parameter_output_file << _cropParams->toString().c_str(); parameter_output_file.close(); } //------------------------------------------------------------------------------ /** * Default constructor for mineral fertilisers * @return */ MineralFertiliserParameters::MineralFertiliserParameters() : vo_Carbamid(0), vo_NH4(0), vo_NO3(0) {} /** * Constructor for mineral fertilisers * @param name Name of fertiliser * @param carbamid Carbamid part of fertiliser * @param no3 Nitrat part of fertiliser. * @param nh4 Ammonium part of fertiliser. * @return */ MineralFertiliserParameters:: MineralFertiliserParameters(const std::string& name, double carbamid, double no3, double nh4) : name(name), vo_Carbamid(carbamid), vo_NH4(nh4), vo_NO3(no3) {} /** * @brief Serializes all object information into a string. * @return String with parameter information. */ string MineralFertiliserParameters::toString() const { ostringstream s; s << "name: " << name << " carbamid: " << vo_Carbamid << " NH4: " << vo_NH4 << " NO3: " << vo_NO3; return s.str(); } /** * @brief Reads mineral fertiliser parameters from monica DB * @param id of the fertiliser * @return mineral fertiliser parameters value object with values from database */ MineralFertiliserParameters Monica::getMineralFertiliserParametersFromMonicaDB(int id) { static L lockable; static bool initialized = false; static map<int, MineralFertiliserParameters> m; if (!initialized) { L::Lock lock(lockable); if (!initialized) { DB *con = newConnection("monica"); DBRow row; con->select("select id, name, no3, nh4, carbamid from mineral_fertilisers"); while (!(row = con->getRow()).empty()) { int id = satoi(row[0]); string name = row[1]; double no3 = satof(row[2]); double nh4 = satof(row[3]); double carbamid = satof(row[4]); m.insert(make_pair(id, MineralFertiliserParameters(name, carbamid, no3, nh4))); } delete con; initialized = true; } } map<int, MineralFertiliserParameters>::const_iterator ci = m.find(id); return ci != m.end() ? ci->second : MineralFertiliserParameters(); } std::vector<ProductionProcess> Monica::attachFertiliserSA(std::vector<ProductionProcess> cropRotation, const std::string pathToFertiliserFile) { attachFertiliserApplicationsToCropRotation(cropRotation, pathToFertiliserFile); return cropRotation; } void Monica::attachFertiliserApplicationsToCropRotation(std::vector<ProductionProcess>& cr, const std::string& pathToFile) { ifstream ifs(pathToFile.c_str(), ios::binary); string s; std::vector<ProductionProcess>::iterator it = cr.begin(); if (it == cr.end()) return; //skip first line getline(ifs, s); Date currentEnd = it->end(); while (getline(ifs, s)) { if (trim(s) == "end") break; //Schlag_ID N FRT Date double sid; double n; string frt; string sfdate; bool incorp; istringstream ss(s); ss >> sid >> n >> frt >> sfdate >> incorp; //get data parsed and to use leap years if the crop rotation uses them Date fdate = parseDate(sfdate).toDate(it->crop()->seedDate().useLeapYears()); if (!fdate.isValid()) { debug() << "Error - Invalid date in \"" << pathToFile.c_str() << "\"" << endl; debug() << "Line: " << s.c_str() << endl; debug() << "Aborting simulation now!" << endl; exit(-1); } //cout << "PP start: " << it->start().toString() //<< " PP end: " << it->end().toString() << endl; //cout << "fdate: " << fdate.toString() //<< " currentEnd: " << currentEnd.toString() << endl; //if the currently read fertiliser date is after the current end //of the crop, move as long through the crop rotation as //we find an end date that lies after the currently read fertiliser date while (fdate > currentEnd) { //move to next crop and possibly exit at the end it++; if (it == cr.end()) break; currentEnd = it->end(); //cout << "new PP start: " << it->start().toString() //<< " new PP end: " << it->end().toString() << endl; //cout << "new currentEnd: " << currentEnd.toString() << endl; } //which type and id is the current fertiliser pair<FertiliserType, int> fertTypeAndId = hermesFertiliserName2monicaFertiliserId(frt); switch (fertTypeAndId.first) { case mineral: { //create mineral fertiliser application const MineralFertiliserParameters& mfp = getMineralFertiliserParametersFromMonicaDB(fertTypeAndId.second); it->addApplication(MineralFertiliserApplication(fdate, mfp, n)); break; } case organic: { //create organic fertiliser application OrganicMatterParameters* omp = getOrganicFertiliserParametersFromMonicaDB(fertTypeAndId.second); it->addApplication(OrganicFertiliserApplication(fdate, omp, n, incorp)); break; } case undefined: { break; } } //cout << "----------------------------------" << endl; } } //------------------------------------------------------------------------------ void Monica::attachIrrigationApplicationsToCropRotation(std::vector<ProductionProcess>& cr, const std::string& pathToFile) { ifstream ifs(pathToFile.c_str(), ios::in); if (!ifs.is_open()) { return; } string s; std::vector<ProductionProcess>::iterator it = cr.begin(); if (it == cr.end()) return; //skip first line getline(ifs, s); Date currentEnd = it->end(); while (getline(ifs, s)) { if (trim(s) == "end") break; //Field_ID mm SCc IrrDat NCc double fid; int mm; double scc; //sulfate concentration [mg dm-3] string irrDate; double ncc; //nitrate concentration [mg dm-3] istringstream ss(s); ss >> fid >> mm >> scc >> irrDate >> ncc; //get data parsed and to use leap years if the crop rotation uses them Date idate = parseDate(irrDate).toDate(it->crop()->seedDate().useLeapYears()); if (!idate.isValid()) { debug() << "Error - Invalid date in \"" << pathToFile.c_str() << "\"" << endl; debug() << "Line: " << s.c_str() << endl; debug() << "Aborting simulation now!" << endl; exit(-1); } //cout << "PP start: " << it->start().toString() //<< " PP end: " << it->end().toString() << endl; //cout << "irrigationDate: " << idate.toString() //<< " currentEnd: " << currentEnd.toString() << endl; //if the currently read irrigation date is after the current end //of the crop, move as long through the crop rotation as //we find an end date that lies after the currently read irrigation date while (idate > currentEnd) { //move to next crop and possibly exit at the end it++; if (it == cr.end()) break; currentEnd = it->end(); //cout << "new PP start: " << it->start().toString() //<< " new PP end: " << it->end().toString() << endl; //cout << "new currentEnd: " << currentEnd.toString() << endl; } //finally add the application to the current crops list it->addApplication(IrrigationApplication(idate, mm, IrrigationParameters(ncc, scc))); //cout << "----------------------------------" << endl; } } //------------------------------------------------------------------------------ /** * @brief Default constructor */ OrganicMatterParameters::OrganicMatterParameters() : name(""), vo_AOM_DryMatterContent(0.0), vo_AOM_NH4Content(0.0), vo_AOM_NO3Content(0.0), vo_AOM_CarbamidContent(0.0), vo_AOM_SlowDecCoeffStandard(0.0), vo_AOM_FastDecCoeffStandard(0.0), vo_PartAOM_to_AOM_Slow(0.0), vo_PartAOM_to_AOM_Fast(0.0), vo_CN_Ratio_AOM_Slow(0.0), vo_CN_Ratio_AOM_Fast(0.0), vo_PartAOM_Slow_to_SMB_Slow(0.0), vo_PartAOM_Slow_to_SMB_Fast(0.0), vo_NConcentration(0.0) {} OrganicMatterParameters::OrganicMatterParameters(const OrganicMatterParameters& omp) { this->vo_AOM_DryMatterContent = omp.vo_AOM_DryMatterContent; this->vo_AOM_NH4Content = omp.vo_AOM_NH4Content; this->vo_AOM_NO3Content = omp.vo_AOM_NO3Content; this->vo_AOM_CarbamidContent = omp.vo_AOM_CarbamidContent; this->vo_AOM_SlowDecCoeffStandard = omp.vo_AOM_SlowDecCoeffStandard; this->vo_AOM_FastDecCoeffStandard = omp.vo_AOM_FastDecCoeffStandard; this->vo_PartAOM_to_AOM_Slow = omp.vo_PartAOM_to_AOM_Slow; this->vo_PartAOM_to_AOM_Fast = omp.vo_PartAOM_to_AOM_Fast; this->vo_CN_Ratio_AOM_Slow = omp.vo_CN_Ratio_AOM_Slow; this->vo_CN_Ratio_AOM_Fast = omp.vo_CN_Ratio_AOM_Fast; this->vo_PartAOM_Slow_to_SMB_Slow = omp.vo_PartAOM_Slow_to_SMB_Slow; this->vo_PartAOM_Slow_to_SMB_Fast = omp.vo_PartAOM_Slow_to_SMB_Fast; this->vo_NConcentration = omp.vo_NConcentration; } /** * @brief Serializes all object information into a string. * @return String with parameter information. */ string OrganicMatterParameters::toString() const { ostringstream s; s << "Name: " << name << endl << "vo_NConcentration: " << vo_NConcentration << endl << "vo_DryMatter: " << vo_AOM_DryMatterContent << endl << "vo_NH4: " << vo_AOM_NH4Content << endl << "vo_NO3: " << vo_AOM_NO3Content << endl << "vo_NH2: " << vo_AOM_CarbamidContent << endl << "vo_kSlow: " << vo_AOM_SlowDecCoeffStandard << endl << "vo_kFast: " << vo_AOM_FastDecCoeffStandard << endl << "vo_PartSlow: " << vo_PartAOM_to_AOM_Slow << endl << "vo_PartFast: " << vo_PartAOM_to_AOM_Fast << endl << "vo_CNSlow: " << vo_CN_Ratio_AOM_Slow << endl << "vo_CNFast: " << vo_CN_Ratio_AOM_Fast << endl << "vo_SMBSlow: " << vo_PartAOM_Slow_to_SMB_Slow << endl << "vo_SMBFast: " << vo_PartAOM_Slow_to_SMB_Fast << endl; return s.str(); } /** * @brief Reads organic fertiliser parameters from monica DB * @param organ_fert_id ID of fertiliser * @return organic fertiliser parameters with values from database */ OrganicMatterParameters* Monica::getOrganicFertiliserParametersFromMonicaDB(int id) { static L lockable; static bool initialized = false; typedef map<int, OMPPtr> Map; static Map m; if (!initialized) { L::Lock lock(lockable); if (!initialized) { DB *con = newConnection("monica"); DBRow row; con->select("select om_Type, dm, nh4_n, no3_n, nh2_n, k_slow, k_fast, part_s, " "part_f, cn_s, cn_f, smb_s, smb_f, id " "from organic_fertiliser"); while (!(row = con->getRow()).empty()) { auto omp = OMPPtr(new OMP); omp->name = row[0]; omp->vo_AOM_DryMatterContent = satof(row[1]); omp->vo_AOM_NH4Content = satof(row[2]); omp->vo_AOM_NO3Content = satof(row[3]); omp->vo_AOM_CarbamidContent = satof(row[4]); omp->vo_AOM_SlowDecCoeffStandard = satof(row[5]); omp->vo_AOM_FastDecCoeffStandard = satof(row[6]); omp->vo_PartAOM_to_AOM_Slow = satof(row[7]); omp->vo_PartAOM_to_AOM_Fast = satof(row[8]); omp->vo_CN_Ratio_AOM_Slow = satof(row[9]); omp->vo_CN_Ratio_AOM_Fast = satof(row[10]); omp->vo_PartAOM_Slow_to_SMB_Slow = satof(row[11]); omp->vo_PartAOM_Slow_to_SMB_Fast = satof(row[12]); int id = satoi(row[13]); m.insert(make_pair(id, omp)); } delete con; initialized = true; } } static OrganicMatterParameters nothing; Map::const_iterator ci = m.find(id); return ci != m.end() ? ci->second.get() : &nothing; } /* ResidueParameters::ResidueParameters() : vo_AOM_DryMatterContent(0.289), vo_AOM_NH4Content(0.007), vo_AOM_NO3Content(0.0), vo_AOM_CarbamidContent(0.0), vo_AOM_SlowDecCoeffStandard(2.0e-4), vo_AOM_FastDecCoeffStandard(2.0e-3), vo_PartAOM_to_AOM_Slow(0.72), vo_PartAOM_to_AOM_Fast(0.18), vo_CN_Ratio_AOM_Slow(100.0), vo_CN_Ratio_AOM_Fast(7.3), vo_PartAOM_Slow_to_SMB_Slow(0.0), vo_PartAOM_Slow_to_SMB_Fast(1.0) { } */ /** * @brief Reads residue parameters from monica DB * @param crop_id ID of crop * @return Residues parameters with values from database */ const OrganicMatterParameters* Monica::getResidueParametersFromMonicaDB(int cropId) { static L lockable; static bool initialized = false; typedef map<int, OMPPtr> Map; static Map m; if (!initialized) { L::Lock lock(lockable); if (!initialized) { DB *con = newConnection("monica"); DBRow row; con->select("select residue_type, dm, nh4, no3, nh2, k_slow, k_fast, part_s, " "part_f, cn_s, cn_f, smb_s, smb_f, crop_id " "from residue_table"); while (!(row = con->getRow()).empty()) { auto omp = OMPPtr(new OMP); omp->name = row[0]; omp->vo_AOM_DryMatterContent = satoi(row[1]); omp->vo_AOM_NH4Content = satof(row[2]); omp->vo_AOM_NO3Content = satof(row[3]); omp->vo_AOM_CarbamidContent = satof(row[4]); omp->vo_AOM_SlowDecCoeffStandard = satof(row[5]); omp->vo_AOM_FastDecCoeffStandard = satof(row[6]); omp->vo_PartAOM_to_AOM_Slow = satof(row[7]); omp->vo_PartAOM_to_AOM_Fast = satof(row[8]); omp->vo_CN_Ratio_AOM_Slow = satof(row[9]); omp->vo_CN_Ratio_AOM_Fast = satof(row[10]); omp->vo_PartAOM_Slow_to_SMB_Slow = satof(row[11]); omp->vo_PartAOM_Slow_to_SMB_Fast = satof(row[12]); int id = satoi(row[13]); m.insert(make_pair(id, omp)); } delete con; initialized = true; } } static OrganicMatterParameters nothing; Map::const_iterator ci = m.find(cropId); return ci != m.end() ? ci->second.get() : &nothing; } //------------------------------------------------------------------------------ /** * @brief Constructor */ CentralParameterProvider::CentralParameterProvider() { for (int i=0; i<MONTH; i++) { precipCorrectionValues[i] = 1.0; } writeOutputFiles = false; } /** * Copy constructor * @param * @return */ CentralParameterProvider:: CentralParameterProvider(const CentralParameterProvider& cpp) { userCropParameters = cpp.userCropParameters; userEnvironmentParameters = cpp.userEnvironmentParameters; userSoilMoistureParameters = cpp.userSoilMoistureParameters; userSoilTemperatureParameters = cpp.userSoilTemperatureParameters; userSoilTransportParameters = cpp.userSoilTransportParameters; userSoilOrganicParameters = cpp.userSoilOrganicParameters; sensitivityAnalysisParameters = cpp.sensitivityAnalysisParameters; capillaryRiseRates = cpp.capillaryRiseRates; userInitValues = cpp.userInitValues; for (int i=0; i<12; i++) precipCorrectionValues[i] = cpp.precipCorrectionValues[i]; } /** * @brief Returns a precipitation correction value for a specific month. * @param month Month * @return Correction value that should be applied to precipitation value read from database. */ double CentralParameterProvider::getPrecipCorrectionValue(int month) const { assert(month<12); assert(month>=0); if (month<12) { return precipCorrectionValues[month]; } cerr << "Requested correction value for precipitation for an invalid month.\nMust be in range of 0<=value<12." << endl; return 1.0; } /** * Sets a correction value for a specific month. * @param month Month the value should be used for. * @param value Correction value that should be added. */ void CentralParameterProvider::setPrecipCorrectionValue(int month, double value) { assert(month<12); assert(month>=0); precipCorrectionValues[month]=value; // debug // cout << "Added precip correction value for month " << month << ":\t " << value << endl; } // -------------------------------------------------------------------- CentralParameterProvider Monica::readUserParameterFromDatabase(int type) { static L lockable; static bool initialized = false; static CentralParameterProvider centralParameterProvider; if (!initialized) { L::Lock lock(lockable); if (!initialized) { debug() << "DB Conncection user parameters" << endl; DB *con = newConnection("monica"); DBRow row; switch (type) { case Env::MODE_HERMES: con->select("select name, value_hermes from user_parameter"); break; case Env::MODE_EVA2: con->select("select name, value_eva2 from user_parameter"); break; default: con->select("select name, value_hermes from user_parameter"); break; } UserCropParameters& user_crops = centralParameterProvider.userCropParameters; UserEnvironmentParameters& user_env = centralParameterProvider.userEnvironmentParameters; UserSoilMoistureParameters& user_soil_moisture = centralParameterProvider.userSoilMoistureParameters; UserSoilTemperatureParameters& user_soil_temperature = centralParameterProvider.userSoilTemperatureParameters; UserSoilTransportParameters& user_soil_transport = centralParameterProvider.userSoilTransportParameters; UserSoilOrganicParameters& user_soil_organic = centralParameterProvider.userSoilOrganicParameters; UserInitialValues& user_init_values = centralParameterProvider.userInitValues; while (!(row = con->getRow()).empty()) { std::string name = row[0]; if (name == "tortuosity") user_crops.pc_Tortuosity = satof(row[1]); else if (name == "canopy_reflection_coefficient") user_crops.pc_CanopyReflectionCoefficient = satof(row[1]); else if (name == "reference_max_assimilation_rate") user_crops.pc_ReferenceMaxAssimilationRate = satof(row[1]); else if (name == "reference_leaf_area_index") user_crops.pc_ReferenceLeafAreaIndex = satof(row[1]); else if (name == "maintenance_respiration_parameter_2") user_crops.pc_MaintenanceRespirationParameter2 = satof(row[1]); else if (name == "maintenance_respiration_parameter_1") user_crops.pc_MaintenanceRespirationParameter1 = satof(row[1]); else if (name == "minimum_n_concentration_root") user_crops.pc_MinimumNConcentrationRoot = satof(row[1]); else if (name == "minimum_available_n") user_crops.pc_MinimumAvailableN = satof(row[1]); else if (name == "reference_albedo") user_crops.pc_ReferenceAlbedo = satof(row[1]); else if (name == "stomata_conductance_alpha") user_crops.pc_StomataConductanceAlpha = satof(row[1]); else if (name == "saturation_beta") user_crops.pc_SaturationBeta = satof(row[1]); else if (name == "growth_respiration_redux") user_crops.pc_GrowthRespirationRedux = satof(row[1]); else if (name == "max_crop_n_demand") user_crops.pc_MaxCropNDemand = satof(row[1]); else if (name == "growth_respiration_parameter_2") user_crops.pc_GrowthRespirationParameter2 = satof(row[1]); else if (name == "growth_respiration_parameter_1") user_crops.pc_GrowthRespirationParameter1 = satof(row[1]); else if (name == "use_automatic_irrigation") user_env.p_UseAutomaticIrrigation = satoi(row[1]) == 1; else if (name == "use_nmin_mineral_fertilising_method") user_env.p_UseNMinMineralFertilisingMethod = satoi(row[1]) == 1; else if (name == "layer_thickness") user_env.p_LayerThickness = satof(row[1]); else if (name == "number_of_layers") user_env.p_NumberOfLayers = satoi(row[1]); else if (name == "start_pv_index") user_env.p_StartPVIndex = satoi(row[1]); else if (name == "albedo") user_env.p_Albedo = satof(row[1]); else if (name == "athmospheric_co2") user_env.p_AthmosphericCO2 = satof(row[1]); else if (name == "wind_speed_height") user_env.p_WindSpeedHeight = satof(row[1]); else if (name == "use_secondary_yields") user_env.p_UseSecondaryYields = satoi(row[1]) == 1; else if (name == "julian_day_automatic_fertilising") user_env.p_JulianDayAutomaticFertilising = satoi(row[1]); else if (name == "critical_moisture_depth") user_soil_moisture.pm_CriticalMoistureDepth = satof(row[1]); else if (name == "saturated_hydraulic_conductivity") user_soil_moisture.pm_SaturatedHydraulicConductivity = satof(row[1]); else if (name == "surface_roughness") user_soil_moisture.pm_SurfaceRoughness = satof(row[1]); else if (name == "hydraulic_conductivity_redux") user_soil_moisture.pm_HydraulicConductivityRedux = satof(row[1]); else if (name == "snow_accumulation_treshold_temperature") user_soil_moisture.pm_SnowAccumulationTresholdTemperature = satof(row[1]); else if (name == "kc_factor") user_soil_moisture.pm_KcFactor = satof(row[1]); else if (name == "time_step") user_env.p_timeStep = satof(row[1]); else if (name == "temperature_limit_for_liquid_water") user_soil_moisture.pm_TemperatureLimitForLiquidWater = satof(row[1]); else if (name == "correction_snow") user_soil_moisture.pm_CorrectionSnow = satof(row[1]); else if (name == "correction_rain") user_soil_moisture.pm_CorrectionRain = satof(row[1]); else if (name == "snow_max_additional_density") user_soil_moisture.pm_SnowMaxAdditionalDensity = satof(row[1]); else if (name == "new_snow_density_min") user_soil_moisture.pm_NewSnowDensityMin = satof(row[1]); else if (name == "snow_retention_capacity_min") user_soil_moisture.pm_SnowRetentionCapacityMin = satof(row[1]); else if (name == "refreeze_parameter_2") user_soil_moisture.pm_RefreezeParameter2 = satof(row[1]); else if (name == "refreeze_parameter_1") user_soil_moisture.pm_RefreezeParameter1 = satof(row[1]); else if (name == "refreeze_temperature") user_soil_moisture.pm_RefreezeTemperature = satof(row[1]); else if (name == "snowmelt_temperature") user_soil_moisture.pm_SnowMeltTemperature = satof(row[1]); else if (name == "snow_packing") user_soil_moisture.pm_SnowPacking = satof(row[1]); else if (name == "snow_retention_capacity_max") user_soil_moisture.pm_SnowRetentionCapacityMax = satof(row[1]); else if (name == "evaporation_zeta") user_soil_moisture.pm_EvaporationZeta = satof(row[1]); else if (name == "xsa_critical_soil_moisture") user_soil_moisture.pm_XSACriticalSoilMoisture = satof(row[1]); else if (name == "maximum_evaporation_impact_depth") user_soil_moisture.pm_MaximumEvaporationImpactDepth = satof(row[1]); else if (name == "ntau") user_soil_temperature.pt_NTau = satof(row[1]); else if (name == "initial_surface_temperature") user_soil_temperature.pt_InitialSurfaceTemperature = satof(row[1]); else if (name == "base_temperature") user_soil_temperature.pt_BaseTemperature = satof(row[1]); else if (name == "quartz_raw_density") user_soil_temperature.pt_QuartzRawDensity = satof(row[1]); else if (name == "density_air") user_soil_temperature.pt_DensityAir = satof(row[1]); else if (name == "density_water") user_soil_temperature.pt_DensityWater = satof(row[1]); else if (name == "specific_heat_capacity_air") user_soil_temperature.pt_SpecificHeatCapacityAir = satof(row[1]); else if (name == "specific_heat_capacity_quartz") user_soil_temperature.pt_SpecificHeatCapacityQuartz = satof(row[1]); else if (name == "specific_heat_capacity_water") user_soil_temperature.pt_SpecificHeatCapacityWater = satof(row[1]); else if (name == "soil_albedo") user_soil_temperature.pt_SoilAlbedo = satof(row[1]); else if (name == "dispersion_length") user_soil_transport.pq_DispersionLength = satof(row[1]); else if (name == "AD") user_soil_transport.pq_AD = satof(row[1]); else if (name == "diffusion_coefficient_standard") user_soil_transport.pq_DiffusionCoefficientStandard = satof(row[1]); else if (name == "leaching_depth") user_env.p_LeachingDepth = satof(row[1]); else if (name == "groundwater_discharge") user_soil_moisture.pm_GroundwaterDischarge = satof(row[1]); else if (name == "density_humus") user_soil_temperature.pt_DensityHumus = satof(row[1]); else if (name == "specific_heat_capacity_humus") user_soil_temperature.pt_SpecificHeatCapacityHumus = satof(row[1]); else if (name == "max_percolation_rate") user_soil_moisture.pm_MaxPercolationRate = satof(row[1]); else if (name == "max_groundwater_depth") user_env.p_MaxGroundwaterDepth = satof(row[1]); else if (name == "min_groundwater_depth") user_env.p_MinGroundwaterDepth = satof(row[1]); else if (name == "min_groundwater_depth_month") user_env.p_MinGroundwaterDepthMonth = satoi(row[1]); else if (name == "SOM_SlowDecCoeffStandard") user_soil_organic.po_SOM_SlowDecCoeffStandard = satof(row[1]); else if (name == "SOM_FastDecCoeffStandard") user_soil_organic.po_SOM_FastDecCoeffStandard = satof(row[1]); else if (name == "SMB_SlowMaintRateStandard") user_soil_organic.po_SMB_SlowMaintRateStandard = satof(row[1]); else if (name == "SMB_FastMaintRateStandard") user_soil_organic.po_SMB_FastMaintRateStandard = satof(row[1]); else if (name == "SMB_SlowDeathRateStandard") user_soil_organic.po_SMB_SlowDeathRateStandard = satof(row[1]); else if (name == "SMB_FastDeathRateStandard") user_soil_organic.po_SMB_FastDeathRateStandard = satof(row[1]); else if (name == "SMB_UtilizationEfficiency") user_soil_organic.po_SMB_UtilizationEfficiency = satof(row[1]); else if (name == "SOM_SlowUtilizationEfficiency") user_soil_organic.po_SOM_SlowUtilizationEfficiency = satof(row[1]); else if (name == "SOM_FastUtilizationEfficiency") user_soil_organic.po_SOM_FastUtilizationEfficiency = satof(row[1]); else if (name == "AOM_SlowUtilizationEfficiency") user_soil_organic.po_AOM_SlowUtilizationEfficiency = satof(row[1]); else if (name == "AOM_FastUtilizationEfficiency") user_soil_organic.po_AOM_FastUtilizationEfficiency = satof(row[1]); else if (name == "AOM_FastMaxC_to_N") user_soil_organic.po_AOM_FastMaxC_to_N = satof(row[1]); else if (name == "PartSOM_Fast_to_SOM_Slow") user_soil_organic.po_PartSOM_Fast_to_SOM_Slow = satof(row[1]); else if (name == "PartSMB_Slow_to_SOM_Fast") user_soil_organic.po_PartSMB_Slow_to_SOM_Fast = satof(row[1]); else if (name == "PartSMB_Fast_to_SOM_Fast") user_soil_organic.po_PartSMB_Fast_to_SOM_Fast = satof(row[1]); else if (name == "PartSOM_to_SMB_Slow") user_soil_organic.po_PartSOM_to_SMB_Slow = satof(row[1]); else if (name == "PartSOM_to_SMB_Fast") user_soil_organic.po_PartSOM_to_SMB_Fast = satof(row[1]); else if (name == "CN_Ratio_SMB") user_soil_organic.po_CN_Ratio_SMB = satof(row[1]); else if (name == "LimitClayEffect") user_soil_organic.po_LimitClayEffect = satof(row[1]); else if (name == "AmmoniaOxidationRateCoeffStandard") user_soil_organic.po_AmmoniaOxidationRateCoeffStandard = satof(row[1]); else if (name == "NitriteOxidationRateCoeffStandard") user_soil_organic.po_NitriteOxidationRateCoeffStandard = satof(row[1]); else if (name == "TransportRateCoeff") user_soil_organic.po_TransportRateCoeff = satof(row[1]); else if (name == "SpecAnaerobDenitrification") user_soil_organic.po_SpecAnaerobDenitrification = satof(row[1]); else if (name == "ImmobilisationRateCoeffNO3") user_soil_organic.po_ImmobilisationRateCoeffNO3 = satof(row[1]); else if (name == "ImmobilisationRateCoeffNH4") user_soil_organic.po_ImmobilisationRateCoeffNH4 = satof(row[1]); else if (name == "Denit1") user_soil_organic.po_Denit1 = satof(row[1]); else if (name == "Denit2") user_soil_organic.po_Denit2 = satof(row[1]); else if (name == "Denit3") user_soil_organic.po_Denit3 = satof(row[1]); else if (name == "HydrolysisKM") user_soil_organic.po_HydrolysisKM = satof(row[1]); else if (name == "ActivationEnergy") user_soil_organic.po_ActivationEnergy = satof(row[1]); else if (name == "HydrolysisP1") user_soil_organic.po_HydrolysisP1 = satof(row[1]); else if (name == "HydrolysisP2") user_soil_organic.po_HydrolysisP2 = satof(row[1]); else if (name == "AtmosphericResistance") user_soil_organic.po_AtmosphericResistance = satof(row[1]); else if (name == "N2OProductionRate") user_soil_organic.po_N2OProductionRate = satof(row[1]); else if (name == "Inhibitor_NH3") user_soil_organic.po_Inhibitor_NH3 = satof(row[1]); } delete con; initialized = true; centralParameterProvider.capillaryRiseRates = readCapillaryRiseRates(); } } return centralParameterProvider; } //---------------------------------------------------------------------------- namespace { struct X { double sat, fc, pwp; static int makeInt(double value) { return int(Tools::round(value, 1)*10); } }; void readXSoilCharacteristicY(std::string key1, double key2, double &sat, double &fc, double &pwp, string query) { static L lockable; typedef map<int, X> M1; typedef map<string, M1> M2; typedef map<string, M2> M3; static M3 m; static bool initialized = false; if(!initialized) { L::Lock lock(lockable); if(!initialized) { // read soil characteristic like air-, field- and n-field-capacity from monica database DB *con = newConnection("monica"); con->select(query.c_str()); debug() << endl << query.c_str() << endl; DBRow row; while (!(row = con->getRow()).empty()) { double ac = satof(row[2]); double fc = satof(row[3]); double nfc = satof(row[4]); int r = X::makeInt(satof(row[1])); X& x = m[query][row[0]][r]; x.sat = ac + fc; x.fc = fc; x.pwp = fc - nfc; } delete con; initialized = true; } } M3::const_iterator qci = m.find(query); if(qci != m.end()) { const M2& m2 = qci->second; M2::const_iterator ci = m2.find(key1); // debug () <<"key1 " << key1.c_str() << endl; if(ci != m2.end()) { const M1& m1 = ci->second; M1::const_iterator ci2 = m1.find(X::makeInt(key2)); // debug () <<"key2 " << key2 << endl; if(ci2 != m1.end()) { const X& x = ci2->second; sat = x.sat; fc = x.fc; pwp = x.pwp; return; } } } sat = 0; fc = 0; pwp = 0; } } void Monica::readPrincipalSoilCharacteristicData(std::string soil_type, double raw_density, double &sat, double &fc, double &pwp) { static const string query = "select soil_type, soil_raw_density, air_capacity, " "field_capacity, n_field_capacity " "from soil_characteristic_data"; return readXSoilCharacteristicY(soil_type, raw_density, sat, fc, pwp, query); } void Monica::readSoilCharacteristicModifier(std::string soil_type, double organic_matter, double &sat, double &fc, double &pwp) { static const string query = "select soil_type, organic_matter, air_capacity, " "field_capacity, n_field_capacity " "from soil_aggregation_values"; return readXSoilCharacteristicY(soil_type, organic_matter, sat, fc, pwp, query); } /** * Simple output of climate data stored in given data accessor. * @param climateData Data structure that stores climate data. */ void Monica::testClimateData(Climate::DataAccessor &climateData) { for (int i = 0, size = climateData.noOfStepsPossible(); i < size; i++) { double tmin = climateData.dataForTimestep(Climate::tmin, i); double tavg = climateData.dataForTimestep(Climate::tavg, i); double tmax = climateData.dataForTimestep(Climate::tmax, i); double precip = climateData.dataForTimestep(Climate::precip, i); double wind = climateData.dataForTimestep(Climate::wind, i); double globrad = climateData.dataForTimestep(Climate::globrad, i); double relhumid = climateData.dataForTimestep(Climate::relhumid, i); double sunhours = climateData.dataForTimestep(Climate::sunhours, i); debug() << "day: " << i << " tmin: " << tmin << " tavg: " << tavg << " tmax: " << tmax << " precip: " << precip << " wind: " << wind << " globrad: " << globrad << " relhumid: " << relhumid << " sunhours: " << sunhours << endl; } } /** * Check, if some parameters should be changed according to sensitivity analysis simulation. * Replace old parameters with new values from sensitivity analysis object * @param ff * @param centralParameterProvider * @return New crop rotation vector */ std::vector<ProductionProcess> Monica::applySAChanges(std::vector<ProductionProcess> ff, const CentralParameterProvider &centralParameterProvider) { // cout << "Apply SA values method" << endl; std::vector<ProductionProcess> new_ff; BOOST_FOREACH(ProductionProcess pp, ff) { CropPtr crop = pp.crop(); const SensitivityAnalysisParameters& saps = centralParameterProvider.sensitivityAnalysisParameters; if (saps.sa_crop_id != crop->id() && saps.sa_crop_id>0){ // cout << "Do not apply SA values" << endl; continue; } else { // cout << "CropIds: SA:\t"<< saps.sa_crop_id << "\tMONICA:\t" << crop->id() << endl; } CropParameters* cps = new CropParameters((*crop->cropParameters())); // pc_DaylengthRequirement if (saps.crop_parameters.pc_DaylengthRequirement.size() > 0) { std::vector<double> new_values; for (unsigned int i=0; i<cps->pc_DaylengthRequirement.size(); i++) { double sa_value = saps.crop_parameters.pc_DaylengthRequirement.at(i); double default_value = cps->pc_DaylengthRequirement.at(i); if (sa_value == -9999) { new_values.push_back(default_value); } else { new_values.push_back(sa_value); } } cps->pc_DaylengthRequirement = new_values; } // pc_VernalisationRequirement if (saps.crop_parameters.pc_VernalisationRequirement.size() > 0) { std::vector<double> new_values; for (unsigned int i=0; i<cps->pc_VernalisationRequirement.size(); i++) { double sa_value = saps.crop_parameters.pc_VernalisationRequirement.at(i); double default_value = cps->pc_VernalisationRequirement.at(i); if (sa_value == -9999) { new_values.push_back(default_value); } else { new_values.push_back(sa_value); } } cps->pc_VernalisationRequirement = new_values; } if (saps.crop_parameters.pc_CriticalOxygenContent.size() > 0) { std::vector<double> new_values; for (unsigned int i=0; i<cps->pc_CriticalOxygenContent.size(); i++) { double sa_value = saps.crop_parameters.pc_CriticalOxygenContent.at(i); double default_value = cps->pc_CriticalOxygenContent.at(i); if (sa_value == -9999) { new_values.push_back(default_value); } else { new_values.push_back(sa_value); } } cps->pc_CriticalOxygenContent = new_values; } if (saps.crop_parameters.pc_InitialKcFactor != UNDEFINED) { cps->pc_InitialKcFactor = saps.crop_parameters.pc_InitialKcFactor; } if (saps.crop_parameters.pc_StageKcFactor.size() > 0) { std::vector<double> new_values; for (unsigned int i=0; i<cps->pc_StageKcFactor.size(); i++) { double sa_value = saps.crop_parameters.pc_StageKcFactor.at(i); double default_value = cps->pc_StageKcFactor.at(i); if (sa_value == -9999) { new_values.push_back(default_value); } else { new_values.push_back(sa_value); } } cps->pc_StageKcFactor = new_values; } // pc_StageAtMaxHeight if (saps.crop_parameters.pc_StageAtMaxHeight != UNDEFINED) { cps->pc_StageAtMaxHeight = saps.crop_parameters.pc_StageAtMaxHeight; } if (saps.crop_parameters.pc_CropHeightP1 != UNDEFINED) { cps->pc_CropHeightP1 = saps.crop_parameters.pc_CropHeightP1; } // pc_CropHeightP2 if (saps.crop_parameters.pc_CropHeightP2 != UNDEFINED) { cps->pc_CropHeightP2 = saps.crop_parameters.pc_CropHeightP2; } // pc_SpecificLeafArea if (saps.crop_parameters.pc_SpecificLeafArea.size() > 0) { std::vector<double> new_values; for (unsigned int i=0; i<cps->pc_SpecificLeafArea.size(); i++) { double sa_value = saps.crop_parameters.pc_SpecificLeafArea.at(i); double default_value = cps->pc_SpecificLeafArea.at(i); if (sa_value == -9999) { new_values.push_back(default_value); } else { new_values.push_back(sa_value); } } cps->pc_SpecificLeafArea = new_values; } // pc_StageTemperatureSum if (saps.crop_parameters.pc_StageTemperatureSum.size() > 0) { std::vector<double> new_values; for (unsigned int i=0; i<cps->pc_StageTemperatureSum.size(); i++) { double sa_value = saps.crop_parameters.pc_StageTemperatureSum.at(i); double default_value = cps->pc_StageTemperatureSum.at(i); if (sa_value == -9999) { new_values.push_back(default_value); } else { new_values.push_back(sa_value); } } cps->pc_StageTemperatureSum = new_values; } // pc_BaseTemperature if (saps.crop_parameters.pc_BaseTemperature.size() > 0) { std::vector<double> new_values; for (unsigned int i=0; i<cps->pc_BaseTemperature.size(); i++) { double sa_value = saps.crop_parameters.pc_BaseTemperature.at(i); double default_value = cps->pc_BaseTemperature.at(i); if (sa_value == -9999) { new_values.push_back(default_value); } else { new_values.push_back(sa_value); } } cps->pc_BaseTemperature = new_values; } // pc_LuxuryNCoeff if (saps.crop_parameters.pc_LuxuryNCoeff != UNDEFINED) { cps->pc_LuxuryNCoeff = saps.crop_parameters.pc_LuxuryNCoeff; } // pc_StageMaxRootNConcentration if (saps.crop_parameters.pc_StageMaxRootNConcentration.size() > 0) { std::vector<double> new_values; for (unsigned int i=0; i<cps->pc_StageMaxRootNConcentration.size(); i++) { double sa_value = saps.crop_parameters.pc_StageMaxRootNConcentration.at(i); double default_value = cps->pc_StageMaxRootNConcentration.at(i); if (sa_value == -9999) { new_values.push_back(default_value); } else { new_values.push_back(sa_value); } } cps->pc_StageMaxRootNConcentration = new_values; } // pc_ResidueNRatio if (saps.crop_parameters.pc_ResidueNRatio != UNDEFINED) { cps->pc_ResidueNRatio = saps.crop_parameters.pc_ResidueNRatio; } // pc_CropSpecificMaxRootingDepth if (saps.crop_parameters.pc_CropSpecificMaxRootingDepth != UNDEFINED) { cps->pc_CropSpecificMaxRootingDepth = saps.crop_parameters.pc_CropSpecificMaxRootingDepth; } // pc_RootPenetrationRate if (saps.crop_parameters.pc_RootPenetrationRate != UNDEFINED) { cps->pc_RootPenetrationRate = saps.crop_parameters.pc_RootPenetrationRate; } // pc_RootGrowthLag if (saps.crop_parameters.pc_RootGrowthLag != UNDEFINED) { cps->pc_RootGrowthLag = saps.crop_parameters.pc_RootGrowthLag; } // pc_InitialRootingDepth if (saps.crop_parameters.pc_InitialRootingDepth != UNDEFINED) { cps->pc_InitialRootingDepth = saps.crop_parameters.pc_InitialRootingDepth; } // pc_RootFormFactor if (saps.crop_parameters.pc_RootFormFactor != UNDEFINED) { cps->pc_RootFormFactor = saps.crop_parameters.pc_RootFormFactor; } // pc_MaxNUptakeParam if (saps.crop_parameters.pc_MaxNUptakeParam != UNDEFINED) { cps->pc_MaxNUptakeParam = saps.crop_parameters.pc_MaxNUptakeParam; } // pc_BaseDaylength if (saps.crop_parameters.pc_BaseDaylength.size() > 0) { std::vector<double> new_values; for (unsigned int i=0; i<cps->pc_BaseDaylength.size(); i++) { double sa_value = saps.crop_parameters.pc_BaseDaylength.at(i); double default_value = cps->pc_BaseDaylength.at(i); if (sa_value == -9999) { new_values.push_back(default_value); } else { new_values.push_back(sa_value); } } cps->pc_BaseDaylength = new_values; } // pc_CarboxylationPathway if (saps.crop_parameters.pc_CarboxylationPathway > -9999) { // UNDEFINED cps->pc_CarboxylationPathway = saps.crop_parameters.pc_CarboxylationPathway; } // pc_DefaultRadiationUseEfficiency if (saps.crop_parameters.pc_DefaultRadiationUseEfficiency != UNDEFINED) { cps->pc_DefaultRadiationUseEfficiency = saps.crop_parameters.pc_DefaultRadiationUseEfficiency; } // pc_DroughtStressThreshold { if (saps.crop_parameters.pc_DroughtStressThreshold.size() > 0) { std::vector<double> new_values; for (unsigned int i=0; i<cps->pc_DroughtStressThreshold.size(); i++) { double sa_value = saps.crop_parameters.pc_DroughtStressThreshold.at(i); double default_value = cps->pc_DroughtStressThreshold.at(i); if (sa_value == -9999) { new_values.push_back(default_value); } else { new_values.push_back(sa_value); } } cps->pc_DroughtStressThreshold = new_values; } // pc_MaxAssimilationRate if (saps.crop_parameters.pc_MaxAssimilationRate != UNDEFINED) { cps->pc_MaxAssimilationRate = saps.crop_parameters.pc_MaxAssimilationRate; } // pc_MaxCropDiameter if (saps.crop_parameters.pc_MaxCropDiameter != UNDEFINED) { cps->pc_MaxCropDiameter = saps.crop_parameters.pc_MaxCropDiameter; } // pc_MinimumNConcentration if (saps.crop_parameters.pc_MinimumNConcentration != UNDEFINED) { cps->pc_MinimumNConcentration = saps.crop_parameters.pc_MinimumNConcentration; } // pc_NConcentrationB0 if (saps.crop_parameters.pc_NConcentrationB0 != UNDEFINED) { cps->pc_NConcentrationB0 = saps.crop_parameters.pc_NConcentrationB0; } // pc_NConcentrationPN if (saps.crop_parameters.pc_NConcentrationPN != UNDEFINED) { cps->pc_NConcentrationPN = saps.crop_parameters.pc_NConcentrationPN; } // pc_NConcentrationRoot if (saps.crop_parameters.pc_NConcentrationRoot != UNDEFINED) { cps->pc_NConcentrationRoot = saps.crop_parameters.pc_NConcentrationRoot; } // pc_OrganGrowthRespiration if (saps.crop_parameters.pc_OrganGrowthRespiration.size() > 0) { cps->pc_OrganGrowthRespiration = saps.crop_parameters.pc_OrganGrowthRespiration; } // pc_OrganMaintenanceRespiration if (saps.crop_parameters.pc_OrganMaintenanceRespiration.size() > 0) { cps->pc_OrganMaintenanceRespiration = saps.crop_parameters.pc_OrganMaintenanceRespiration; } // pc_PlantDensity if (saps.crop_parameters.pc_PlantDensity != UNDEFINED) { cps->pc_PlantDensity = saps.crop_parameters.pc_PlantDensity; } // pc_ResidueNRatio if (saps.crop_parameters.pc_ResidueNRatio != UNDEFINED) { cps->pc_ResidueNRatio = saps.crop_parameters.pc_ResidueNRatio; } //cout << cps->toString().c_str() << endl; crop->setCropParameters(cps); new_ff.push_back(pp); } return ff; } CapillaryRiseRates Monica::readCapillaryRiseRates() { static L lockable; // static bool initialized = false; CapillaryRiseRates cap_rates; // if(!initialized) { L::Lock lock(lockable); // if(!initialized) // { static const string query = "select soil_type, distance, capillary_rate " "from capillary_rise_rate"; // read capillary rise rates from database DB *con = newConnection("monica"); con->select(query.c_str()); DBRow row; while (!(row = con->getRow()).empty()) { string soil_type = row[0]; int distance = satoi(row[1]); double rate = satof(row[2]); cap_rates.addRate(soil_type, distance, rate); } delete con; // initialized = true; } // } return cap_rates; } /* void Monica::Crop::applyCutting() { const CropParameters* cps = this->cropParameters(); } */ No changes; this comment is only used to test the github issue tracker; closes #1 /** Authors: Dr. Claas Nendel <claas.nendel@zalf.de> Xenia Specka <xenia.specka@zalf.de> Michael Berg <michael.berg@zalf.de> Maintainers: Currently maintained by the authors. This file is part of the MONICA model. Copyright (C) 2007-2013, Leibniz Centre for Agricultural Landscape Research (ZALF) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <map> #include <sstream> #include <iostream> #include <fstream> #include <cmath> #include <utility> #include "boost/foreach.hpp" #include "db/abstract-db-connections.h" #include "climate/climate-common.h" #include "tools/use-stl-algo-boost-lambda.h" #include "tools/helper.h" #include "tools/algorithms.h" #include "monica-parameters.h" #include "monica.h" #include "eva_methods.h" #include "debug.h" #include "conversion.h" #define LOKI_OBJECT_LEVEL_THREADING #include "loki/Threads.h" using namespace Db; using namespace std; using namespace Monica; using namespace Tools; using namespace Climate; // Some profile definitions for eva2 namespace { /** * @brief Lockable object */ struct L: public Loki::ObjectLevelLockable<L> {}; //---------------------------------------------------------------------------- /** * @brief * * @param humus_st * * @return */ // double humus_st2corg(int humus_st) // { // switch (humus_st) // { // case 0: // return 0.0; // case 1: // return 0.5 / 1.72; // case 2: // return 1.5 / 1.72; // case 3: // return 3.0 / 1.72; // case 4: // return 6.0 / 1.72; // case 5: // return 11.5 / 2.0; // case 6: // return 17.5 / 2.0; // case 7: // return 30.0 / 2.0; // } // return 0.0; // } //---------------------------------------------------------------------------- /** * @brief * * @param ldEff * @param clayPercent * * @return */ // double ld_eff2trd(int ldEff, double clay) // { // double x = 0.0; // switch (ldEff) // { // case 1: // x = 1.3; // break; // case 2: // x = 1.5; // break; // case 3: // x = 1.7; // break; // case 4: // x = 1.9; // break; // case 5: // x = 2.1; // break; // } // return x - (0.9 * clay); // } //---------------------------------------------------------------------------- /** * @brief Returns lambda from soil texture * * @param lambda * * @return */ // double texture2lambda(double sand, double clay) // { // double lambda = (2.0 * (sand * sand * 0.575)) + // (clay * 0.1) + ((1.0 - sand - clay) * 0.35); // // lambda = 1.0; /** @todo <b>Claas:</b> Temporary override until we have solved the problem with low water percolation loam soils **/ // return lambda; // } //---------------------------------------------------------------------------- /** * @brief Returns KA5 texture class from soil texture * * @param Soil texture * * @return */ // std::string texture2KA5(double sand, double clay) // { // double silt = 1.0 - sand - clay; // std::string soilTexture; // if ((silt < 0.1) && (clay < 0.05)){ // soilTexture = "Ss"; // } else if ((silt < 0.25) && (clay < 0.05)){ // soilTexture = "Su2"; // } else if ((silt < 0.25) && (clay < 0.08)){ // soilTexture = "Sl2"; // } else if ((silt < 0.40) && (clay < 0.08)){ // soilTexture = "Su3"; // } else if ((silt < 0.50) && (clay < 0.08)){ // soilTexture = "Su4"; // } else if ((silt < 0.8) && (clay < 0.08)){ // soilTexture = "Us"; // } else if ((silt >= 0.8) && (clay < 0.08)){ // soilTexture = "Uu"; // } else if ((silt < 0.1) && (clay < 0.17)){ // soilTexture = "St2"; // } else if ((silt < 0.4) && (clay < 0.12)){ // soilTexture = "Sl3"; // } else if ((silt < 0.4) && (clay < 0.17)){ // soilTexture = "Sl4"; // } else if ((silt < 0.5) && (clay < 0.17)){ // soilTexture = "Slu"; // } else if ((silt < 0.65) && (clay < 0.17)){ // soilTexture = "Uls"; // } else if ((silt >= 0.65) && (clay < 0.12)){ // soilTexture = "Ut2"; // } else if ((silt >= 0.65) && (clay < 0.17)){ // soilTexture = "Ut3"; // } else if ((silt < 0.15) && (clay < 0.25)){ // soilTexture = "St3"; // } else if ((silt < 0.30) && (clay < 0.25)){ // soilTexture = "Ls4"; // } else if ((silt < 0.40) && (clay < 0.25)){ // soilTexture = "Ls3"; // } else if ((silt < 0.50) && (clay < 0.25)){ // soilTexture = "Ls2"; // } else if ((silt < 0.65) && (clay < 0.30)){ // soilTexture = "Lu"; // } else if ((silt >= 0.65) && (clay < 0.25)){ // soilTexture = "Ut4"; // } else if ((silt < 0.15) && (clay < 0.35)){ // soilTexture = "Ts4"; // } else if ((silt < 0.30) && (clay < 0.45)){ // soilTexture = "Lts"; // } else if ((silt < 0.50) && (clay < 0.35)){ // soilTexture = "Lt2"; // } else if ((silt < 0.65) && (clay < 0.45)){ // soilTexture = "Tu3"; // } else if ((silt >= 0.65) && (clay >= 0.25)){ // soilTexture = "Tu4"; // } else if ((silt < 0.15) && (clay < 0.45)){ // soilTexture = "Ts3"; // } else if ((silt < 0.50) && (clay < 0.45)){ // soilTexture = "Lt3"; // } else if ((silt < 0.15) && (clay < 0.65)){ // soilTexture = "Ts2"; // } else if ((silt < 0.30) && (clay < 0.65)){ // soilTexture = "Tl"; // } else if ((silt >= 0.30) && (clay < 0.65)){ // soilTexture = "Tu2"; // } else if (clay >= 0.65){ // soilTexture = "Tt"; // } else soilTexture = ""; // return soilTexture; // } //---------------------------------------------------------------------------- CropPtr hermesCropId2Crop(const string& hermesCropId) { if(hermesCropId == "WW") return CropPtr(new Crop(1, hermesCropId)); // Winter wheat if(hermesCropId == "SW") return CropPtr(new Crop(1, hermesCropId)); // Spring wheat if(hermesCropId == "WG") return CropPtr(new Crop(2, hermesCropId)); // Winter barley if(hermesCropId == "SG") return CropPtr(new Crop(4, hermesCropId)); // Spring barley if(hermesCropId == "WR") return CropPtr(new Crop(3, hermesCropId)); // Winter rye if(hermesCropId == "SR") return CropPtr(new Crop(20, hermesCropId)); // Spring rye if(hermesCropId == "OAT") return CropPtr(new Crop(22, hermesCropId)); // Oats if(hermesCropId == "ZR") return CropPtr(new Crop(10, hermesCropId)); // Sugar beet if(hermesCropId == "SM") return CropPtr(new Crop(7, hermesCropId)); // Silage maize if(hermesCropId == "GM") return CropPtr(new Crop(5, hermesCropId)); // Grain maize if(hermesCropId == "GMB") return CropPtr(new Crop(6, hermesCropId)); // Grain maize Brazil (Pioneer) if(hermesCropId == "MEP") return CropPtr(new Crop(8, hermesCropId)); // Late potato if(hermesCropId == "MLP") return CropPtr(new Crop(8, hermesCropId)); // Early potato if(hermesCropId == "WC") return CropPtr(new Crop(9, hermesCropId)); // Winter canola if(hermesCropId == "SC") return CropPtr(new Crop(9, hermesCropId)); // Spring canola if(hermesCropId == "MU") return CropPtr(new Crop(11, hermesCropId)); // Mustard if(hermesCropId == "PH") return CropPtr(new Crop(12, hermesCropId)); // Phacelia if(hermesCropId == "CLV") return CropPtr(new Crop(13, hermesCropId)); // Kleegras if(hermesCropId == "LZG") return CropPtr(new Crop(14, hermesCropId)); // Luzerne-Gras if(hermesCropId == "WDG") return CropPtr(new Crop(16, hermesCropId)); // Weidelgras if(hermesCropId == "FP") return CropPtr(new Crop(24, hermesCropId)); // Field pea if(hermesCropId == "OR") return CropPtr(new Crop(17, hermesCropId)); // Oil raddish if(hermesCropId == "SDG") return CropPtr(new Crop(18, hermesCropId)); // Sudan grass if(hermesCropId == "WTR") return CropPtr(new Crop(19, hermesCropId)); // Winter triticale if(hermesCropId == "STR") return CropPtr(new Crop(23, hermesCropId)); // Spring triticale if(hermesCropId == "SOR") return CropPtr(new Crop(21, hermesCropId)); // Sorghum if(hermesCropId == "SX0") return CropPtr(new Crop(28, hermesCropId)); // Soy bean maturity group 000 if(hermesCropId == "S00") return CropPtr(new Crop(29, hermesCropId)); // Soy bean maturity group 00 if(hermesCropId == "S0X") return CropPtr(new Crop(30, hermesCropId)); // Soy bean maturity group 0 if(hermesCropId == "S01") return CropPtr(new Crop(31, hermesCropId)); // Soy bean maturity group I if(hermesCropId == "S02") return CropPtr(new Crop(32, hermesCropId)); // Soy bean maturity group II if(hermesCropId == "S03") return CropPtr(new Crop(33, hermesCropId)); // Soy bean maturity group III if(hermesCropId == "S04") return CropPtr(new Crop(34, hermesCropId)); // Soy bean maturity group IV if(hermesCropId == "S05") return CropPtr(new Crop(35, hermesCropId)); // Soy bean maturity group V if(hermesCropId == "S06") return CropPtr(new Crop(36, hermesCropId)); // Soy bean maturity group VI if(hermesCropId == "S07") return CropPtr(new Crop(37, hermesCropId)); // Soy bean maturity group VII if(hermesCropId == "S08") return CropPtr(new Crop(38, hermesCropId)); // Soy bean maturity group VIII if(hermesCropId == "S09") return CropPtr(new Crop(39, hermesCropId)); // Soy bean maturity group IX if(hermesCropId == "S10") return CropPtr(new Crop(40, hermesCropId)); // Soy bean maturity group X if(hermesCropId == "S11") return CropPtr(new Crop(41, hermesCropId)); // Soy bean maturity group XI if(hermesCropId == "S12") return CropPtr(new Crop(42, hermesCropId)); // Soy bean maturity group XII if(hermesCropId == "COS") return CropPtr(new Crop(43, hermesCropId)); // Cotton short if(hermesCropId == "COM") return CropPtr(new Crop(44, hermesCropId)); // Cotton medium if(hermesCropId == "COL") return CropPtr(new Crop(45, hermesCropId)); // Cotton long if(hermesCropId == "BR") return CropPtr(new Crop(hermesCropId)); return CropPtr(); } //---------------------------------------------------------------------------- /*! * @todo Claas bitte ausfüllen * @param name * @return */ pair<FertiliserType, int> hermesFertiliserName2monicaFertiliserId(const string& name) { if (name == "KN") return make_pair(mineral, 7); //0.00 1.00 0.00 01.00 M Kaliumnitrat (Einh : kg N / ha) if (name == "KAS") return make_pair(mineral, 1); //1.00 0.00 0.00 01.00 M Kalkammonsalpeter (Einh : kg N / ha) if (name == "UR") return make_pair(mineral, 8); //1.00 0.00 0.00 01.00 M Harnstoff if (name == "AHL") return make_pair(mineral, 10); //1.00 0.00 0.00 01.00 M Ammoniumharnstoffloesung if (name == "UAN") return make_pair(mineral, 9); //1.00 0.00 0.00 01.00 M Urea ammonium nitrate solution if (name == "AS") return make_pair(mineral, 3); //1.00 0.00 0.00 01.00 M Ammoniumsulfat (Einh: kg N/ha) if (name == "DAP") return make_pair(mineral, 2); //1.00 0.00 0.00 01.00 M Diammoniumphosphat (Einh: kg N/ha) if (name == "SG") return make_pair(organic, 3); //0.67 0.00 1.00 06.70 O Schweineguelle (Einh: z. B. m3/ha) if (name == "RG1") return make_pair(organic, 3); //0.43 0.00 1.00 02.40 O Rinderguelle (Einh: z. B. m3/ha) if (name == "RG2") return make_pair(organic, 3); //0.43 0.00 1.00 01.80 O Rinderguelle (Einh: z. B. m3/ha) if (name == "RG3") return make_pair(organic, 3); //0.43 0.00 1.00 03.40 O Rinderguelle (Einh: z. B. m3/ha) if (name == "RG4") return make_pair(organic, 3); //0.43 0.00 1.00 03.70 O Rinderguelle (Einh: z. B. m3/ha) if (name == "RG5") return make_pair(organic, 3); //0.43 0.00 1.00 03.30 O Rinderguelle (Einh: z. B. m3/ha) if (name == "SM") return make_pair(organic, 1); //0.15 0.20 0.80 00.60 O Stallmist (Einh: z. B. dt/ha) if (name == "ST1") return make_pair(organic, 1); //0.07 0.10 0.90 00.48 O Stallmist (Einh: z. B. dt/ha) if (name == "ST2") return make_pair(organic, 1); //0.07 0.10 0.90 00.63 O Stallmist (Einh: z. B. dt/ha) if (name == "ST3") return make_pair(organic, 1); //0.07 0.10 0.90 00.82 O Stallmist (Einh: z. B. dt/ha) if (name == "RM1") return make_pair(organic, 2); //0.15 0.20 0.80 00.60 O Stallmist (Einh: z. B. dt/ha) if (name == "FM") return make_pair(organic, 1); //0.65 0.80 0.20 01.00 O Stallmist (Einh: z. B. kg N/ha) if (name == "LM") return make_pair(organic, 3); //0.85 0.80 0.20 01.00 O Jauche (Einh: z. B. kg N/ha) if (name == "H") return make_pair(mineral, 8); //01.00 1.00 0.00 0.00 1.00 0.15 kg N/ha M Harnstoff if (name == "NPK") return make_pair(mineral, 5); //01.00 1.00 0.00 0.00 0.00 0.10 kg N/ha M NPK Mineraldünger if (name == "ALZ") return make_pair(mineral, 8); //01.00 1.00 0.00 0.00 1.00 0.12 kg N/ha M Alzon if (name == "AZU") return make_pair(mineral, 1); //01.00 1.00 0.00 0.00 1.00 0.12 kg N/ha M Ansul if (name == "NIT") return make_pair(mineral, 5); //01.00 1.00 0.00 0.00 0.00 0.10 kg N/ha M Nitrophoska if (name == "SSA") return make_pair(mineral, 3); //01.00 1.00 0.00 0.00 1.00 0.10 kg N/ha M schwefelsaures Ammoniak if (name == "RG") return make_pair(organic, 3); //04.70 0.43 0.00 1.00 1.00 0.40 m3 / ha O Rindergülle if (name == "RM") return make_pair(organic, 1); //00.60 0.15 0.20 0.80 1.00 0.40 dt / ha O Rindermist if (name == "RSG") return make_pair(organic, 3); //05.70 0.55 0.00 1.00 1.00 0.40 m3 / ha O Rinder/Schweinegülle if (name == "SSM") return make_pair(organic, 5); //00.76 0.15 0.20 0.80 1.00 0.40 dt / ha O Schweinemist if (name == "HG") return make_pair(organic, 12); //10.70 0.68 0.00 1.00 1.00 0.40 m3 / ha O Hühnergülle if (name == "HFM") return make_pair(organic, 11); //02.30 0.15 0.20 0.80 1.00 0.40 dt / ha O Hähnchentrockenmist if (name == "HM") return make_pair(organic, 11); //02.80 0.15 0.20 0.80 1.00 0.40 dt / ha O Hühnermist if (name == "CK") return make_pair(mineral, 1); //00.30 0.00 1.00 0.00 0.00 0.00 dt / ha M Carbokalk if (name == "KSL") return make_pair(organic, 16); //01.00 0.25 0.20 0.80 0.00 0.10 dt / ha O Klärschlamm if (name == "BAK") return make_pair(organic, 15); //01.63 0.00 0.05 0.60 0.00 0.00 dt / ha O Bioabfallkompst if (name == "MST") return make_pair(organic, 21); // Maize straw if (name == "WST") return make_pair(organic, 19); // Wheat straw if (name == "SST") return make_pair(organic, 23); // Soybean straw if (name == "WEE") return make_pair(organic, 22); // Weeds if (name == "YP3") return make_pair(mineral, 13); //01.00 0.43 0.57 0.00 1.00 1.00 kg N/ha M Yara Pellon Y3 cout << "Error: Cannot find fertiliser " << name << " in hermes fertiliser map. Aborting..." << endl; exit(-1); return make_pair(mineral, -1); } } // namespace //------------------------------------------------------------------------------ /** * Returns the result vector of a special output. Python swig is * not able to wrap stl-maps correctly. Stl-vectors are working * properly so this function has been implemented to use the results * in wrapped python code. * * @param id ResultId of output * @return Vector of result values */ std::vector<double> Result::getResultsById(int id) { // test if crop results are requested if (id == primaryYield || id == secondaryYield || id == sumIrrigation || id == sumFertiliser || id == biomassNContent || id == sumTotalNUptake || id == cropHeight || id == cropname || id == sumETaPerCrop || id == primaryYieldTM || id == secondaryYieldTM || id == daysWithCrop || id == aboveBiomassNContent || id == NStress || id == WaterStress || id == HeatStress || id == OxygenStress ) { vector<double> result_vector; int size = pvrs.size(); for (int i=0; i<size; i++) { PVResult crop_result = pvrs.at(i); result_vector.push_back(crop_result.pvResults[(ResultId)id]); } return result_vector; } return generalResults[(ResultId)id]; } const vector<ResultId>& Monica::cropResultIds() { static ResultId ids[] = { primaryYield, secondaryYield, sumFertiliser, sumIrrigation, sumMineralisation }; static vector<ResultId> v(ids, ids + 5); return v; } //------------------------------------------------------------------------------ const vector<ResultId>& Monica::monthlyResultIds() { static ResultId ids[] = { avg10cmMonthlyAvgCorg, avg30cmMonthlyAvgCorg, mean90cmMonthlyAvgWaterContent, monthlySumGroundWaterRecharge, monthlySumNLeaching }; static vector<ResultId> v(ids, ids + 5); return v; } //------------------------------------------------------------------------------ const vector<int>& Monica::sensitivityAnalysisResultIds() { static ResultId ids[] = { // primaryYield, // done // secondaryYield, // done // cropHeight, // done // mean90cmMonthlyAvgWaterContent, // done // sum90cmYearlyNatDay, // done // sum90cmYearlyNO3AtDay, // done // maxSnowDepth, // done // sumSnowDepth, // done // sumFrostDepth, // done // avg30cmSoilTemperature, // done // sum30cmSoilTemperature, // done // avg0_30cmSoilMoisture, // done // avg30_60cmSoilMoisture, // done // avg60_90cmSoilMoisture, // done // monthlySumGroundWaterRecharge, // done // waterFluxAtLowerBoundary, // done // avg0_30cmCapillaryRise, // done // avg30_60cmCapillaryRise, // done // avg60_90cmCapillaryRise, // done // avg0_30cmPercolationRate, // done // avg30_60cmPercolationRate, // done // avg60_90cmPercolationRate, // done // sumSurfaceRunOff, // done // evapotranspiration, // done // transpiration, // done // evaporation, // done // biomassNContent, // done // sumTotalNUptake, // done // sum30cmSMB_CO2EvolutionRate, // done // NH3Volatilised, // done // sumNH3Volatilised, // done // sum30cmActDenitrificationRate, // done // leachingNAtBoundary, // done // yearlySumGroundWaterRecharge, // yearlySumNLeaching, dev_stage }; //static vector<int> v(ids, ids+2); static vector<int> v(ids, ids+1); return v; } //------------------------------------------------------------------------------ const vector<int>& Monica::CCGermanyResultIds() { static ResultId ids[] = { primaryYield, // done yearlySumGroundWaterRecharge, yearlySumNLeaching }; static vector<int> v(ids, ids+3); return v; } //------------------------------------------------------------------------------ const vector<int>& Monica::eva2CropResultIds() { static ResultId ids[] = { cropname, primaryYieldTM, secondaryYieldTM, sumFertiliser, sumETaPerCrop, biomassNContent, daysWithCrop, aboveBiomassNContent, NStress, WaterStress, HeatStress, OxygenStress }; static vector<int> v(ids, ids + 12); return v; } //------------------------------------------------------------------------------ const vector<int>& Monica::eva2MonthlyResultIds() { static ResultId ids[] = { avg10cmMonthlyAvgCorg, avg30cmMonthlyAvgCorg, mean90cmMonthlyAvgWaterContent, monthlySumGroundWaterRecharge, monthlySumNLeaching, monthlySurfaceRunoff, monthlyPrecip, monthlyETa, monthlySoilMoistureL0, monthlySoilMoistureL1, monthlySoilMoistureL2, monthlySoilMoistureL3, monthlySoilMoistureL4, monthlySoilMoistureL5, monthlySoilMoistureL6, monthlySoilMoistureL7, monthlySoilMoistureL8, monthlySoilMoistureL9, monthlySoilMoistureL10, monthlySoilMoistureL11, monthlySoilMoistureL12, monthlySoilMoistureL13, monthlySoilMoistureL14, monthlySoilMoistureL15, monthlySoilMoistureL16, monthlySoilMoistureL17, monthlySoilMoistureL18 }; static vector<int> v(ids, ids + 27); return v; } //------------------------------------------------------------------------------ /** * Returns some information about a result id. * @param rid ResultID of interest * @return ResultIdInfo Information object of result ids */ ResultIdInfo Monica::resultIdInfo(ResultId rid) { switch(rid) { case primaryYield: return ResultIdInfo("Hauptertrag", "dt/ha", "primYield"); case secondaryYield: return ResultIdInfo("Nebenertrag", "dt/ha", "secYield"); case sumFertiliser: return ResultIdInfo("N", "kg/ha", "sumFert"); case sumIrrigation: return ResultIdInfo("Beregnungswassermenge", "mm/ha", "sumIrrig"); case sumMineralisation: return ResultIdInfo("Mineralisation", "????", "sumMin"); case avg10cmMonthlyAvgCorg: return ResultIdInfo("Kohlenstoffgehalt 0-10cm", "% kg C/kg Boden", "Corg10cm"); case avg30cmMonthlyAvgCorg: return ResultIdInfo("Kohlenstoffgehalt 0-30cm", "% kg C/kg Boden", "Corg30cm"); case mean90cmMonthlyAvgWaterContent: return ResultIdInfo("Bodenwassergehalt 0-90cm", "%nFK", "Moist90cm"); case sum90cmYearlyNatDay: return ResultIdInfo("Boden-Nmin-Gehalt 0-90cm am 31.03.", "kg N/ha", "Nmin3103"); case monthlySumGroundWaterRecharge: return ResultIdInfo("Grundwasserneubildung", "mm", "GWRech"); case monthlySumNLeaching: return ResultIdInfo("N-Auswaschung", "kg N/ha", "monthLeachN"); case cropHeight: return ResultIdInfo("Pflanzenhöhe zum Erntezeitpunkt", "m","cropHeight"); case sum90cmYearlyNO3AtDay: return ResultIdInfo("Summe Nitratkonzentration in 0-90cm Boden am 31.03.", "kg N/ha","NO3_90cm"); case sum90cmYearlyNH4AtDay: return ResultIdInfo("Ammoniumkonzentratio in 0-90cm Boden am 31.03.", "kg N/ha", "NH4_90cm"); case maxSnowDepth: return ResultIdInfo("Maximale Schneetiefe während der Simulation","m","maxSnowDepth"); case sumSnowDepth: return ResultIdInfo("Akkumulierte Schneetiefe der gesamten Simulation", "m","sumSnowDepth"); case sumFrostDepth: return ResultIdInfo("Akkumulierte Frosttiefe der gesamten Simulation","m","sumFrostDepth"); case avg30cmSoilTemperature: return ResultIdInfo("Durchschnittliche Bodentemperatur in 0-30cm Boden am 31.03.", "°C","STemp30cm"); case sum30cmSoilTemperature: return ResultIdInfo("Akkumulierte Bodentemperature der ersten 30cm des Bodens am 31.03", "°C","sumSTemp30cm"); case avg0_30cmSoilMoisture: return ResultIdInfo("Durchschnittlicher Wassergehalt in 0-30cm Boden am 31.03.", "%","Moist0_30"); case avg30_60cmSoilMoisture: return ResultIdInfo("Durchschnittlicher Wassergehalt in 30-60cm Boden am 31.03.", "%","Moist30_60"); case avg60_90cmSoilMoisture: return ResultIdInfo("Durchschnittlicher Wassergehalt in 60-90cm Boden am 31.03.", "%","Moist60_90"); case waterFluxAtLowerBoundary: return ResultIdInfo("Sickerwasser der unteren Bodengrenze am 31.03.", "mm/d", "waterFlux"); case avg0_30cmCapillaryRise: return ResultIdInfo("Durchschnittlicher kapillarer Aufstieg in 0-30cm Boden am 31.03.", "mm/d", "capRise0_30"); case avg30_60cmCapillaryRise: return ResultIdInfo("Durchschnittlicher kapillarer Aufstieg in 30-60cm Boden am 31.03.", "mm/d", "capRise30_60"); case avg60_90cmCapillaryRise: return ResultIdInfo("Durchschnittlicher kapillarer Aufstieg in 60-90cm Boden am 31.03.", "mm/d", "capRise60_90"); case avg0_30cmPercolationRate: return ResultIdInfo("Durchschnittliche Durchflussrate in 0-30cm Boden am 31.03.", "mm/d", "percRate0_30"); case avg30_60cmPercolationRate: return ResultIdInfo("Durchschnittliche Durchflussrate in 30-60cm Boden am 31.03.", "mm/d", "percRate30_60"); case avg60_90cmPercolationRate: return ResultIdInfo("Durchschnittliche Durchflussrate in 60-90cm Boden am 31.03.", "mm/d", "percRate60_90"); case sumSurfaceRunOff: return ResultIdInfo("Summe des Oberflächenabflusses der gesamten Simulation", "mm", "sumSurfRunOff"); case evapotranspiration: return ResultIdInfo("Evaporatranspiration am 31.03.", "mm", "ET"); case transpiration: return ResultIdInfo("Transpiration am 31.03.", "mm", "transp"); case evaporation: return ResultIdInfo("Evaporation am 31.03.", "mm", "evapo"); case biomassNContent: return ResultIdInfo("Stickstoffanteil im Erntegut", "kg N/ha", "biomNContent"); case aboveBiomassNContent: return ResultIdInfo("Stickstoffanteil in der gesamten oberirdischen Biomasse", "kg N/ha", "aboveBiomassNContent"); case sumTotalNUptake: return ResultIdInfo("Summe des aufgenommenen Stickstoffs", "kg/ha", "sumNUptake"); case sum30cmSMB_CO2EvolutionRate: return ResultIdInfo("SMB-CO2 Evolutionsrate in 0-30cm Boden am 31.03.", "kg/ha", "sumSMB_CO2_EvRate"); case NH3Volatilised: return ResultIdInfo("Menge des verdunstenen Stickstoffs (NH3) am 31.03.", "kg N / m2 d", "NH3Volat"); case sumNH3Volatilised: return ResultIdInfo("Summe des verdunstenen Stickstoffs (NH3) des gesamten Simulationszeitraums", "kg N / m2", "sumNH3Volat"); case sum30cmActDenitrificationRate: return ResultIdInfo("Summe der Denitrifikationsrate in 0-30cm Boden am 31.03.", "kg N / m3 d", "denitRate"); case leachingNAtBoundary: return ResultIdInfo("Menge des ausgewaschenen Stickstoffs im Boden am 31.03.", "kg / ha", "leachN"); case yearlySumGroundWaterRecharge: return ResultIdInfo("Gesamt-akkumulierte Grundwasserneubildung im Jahr", "mm", "Yearly_GWRech"); case yearlySumNLeaching: return ResultIdInfo("Gesamt-akkumulierte N-Auswaschung im Jahr", "kg N/ha", "Yearly_monthLeachN"); case sumETaPerCrop: return ResultIdInfo("Evapotranspiration pro Vegetationszeit der Pflanze", "mm", "ETa_crop"); case cropname: return ResultIdInfo("Pflanzenname", "", "cropname"); case primaryYieldTM: return ResultIdInfo("Hauptertrag in TM", "dt TM/ha", "primYield"); case secondaryYieldTM: return ResultIdInfo("Nebenertrag in TM", "dt TM/ha", "secYield"); case monthlySurfaceRunoff: return ResultIdInfo("Monatlich akkumulierte Oberflächenabfluss", "mm", "monthlySurfaceRunoff"); case monthlyPrecip: return ResultIdInfo("Akkumulierte korrigierte Niederschläge pro Monat", "mm", "monthlyPrecip"); case monthlyETa: return ResultIdInfo("Akkumulierte korrigierte Evapotranspiration pro Monat", "mm", "monthlyETa"); case monthlySoilMoistureL0: return ResultIdInfo("Monatlicher mittlerer Wassergehalt für Schicht 1", "Vol-%", "monthlySoilMoisL1"); case monthlySoilMoistureL1: return ResultIdInfo("Monatlicher mittlerer Wassergehalt für Schicht 2", "Vol-%", "monthlySoilMoisL2"); case monthlySoilMoistureL2: return ResultIdInfo("Monatlicher mittlerer Wassergehalt für Schicht 3", "Vol-%", "monthlySoilMoisL3"); case monthlySoilMoistureL3: return ResultIdInfo("Monatlicher mittlerer Wassergehalt für Schicht 4", "Vol-%", "monthlySoilMoisL4"); case monthlySoilMoistureL4: return ResultIdInfo("Monatlicher mittlerer Wassergehalt für Schicht 5", "Vol-%", "monthlySoilMoisL5"); case monthlySoilMoistureL5: return ResultIdInfo("Monatlicher mittlerer Wassergehalt für Schicht 6", "Vol-%", "monthlySoilMoisL6"); case monthlySoilMoistureL6: return ResultIdInfo("Monatlicher mittlerer Wassergehalt für Schicht 7", "Vol-%", "monthlySoilMoisL7"); case monthlySoilMoistureL7: return ResultIdInfo("Monatlicher mittlerer Wassergehalt für Schicht 8", "Vol-%", "monthlySoilMoisL8"); case monthlySoilMoistureL8: return ResultIdInfo("Monatlicher mittlerer Wassergehalt für Schicht 9", "Vol-%", "monthlySoilMoisL9"); case monthlySoilMoistureL9: return ResultIdInfo("Monatlicher mittlerer Wassergehalt für Schicht 10", "Vol-%", "monthlySoilMoisL10"); case monthlySoilMoistureL10: return ResultIdInfo("Monatlicher mittlerer Wassergehalt für Schicht 11", "Vol-%", "monthlySoilMoisL11"); case monthlySoilMoistureL11: return ResultIdInfo("Monatlicher mittlerer Wassergehalt für Schicht 12", "Vol-%", "monthlySoilMoisL12"); case monthlySoilMoistureL12: return ResultIdInfo("Monatlicher mittlerer Wassergehalt für Schicht 13", "Vol-%", "monthlySoilMoisL13"); case monthlySoilMoistureL13: return ResultIdInfo("Monatlicher mittlerer Wassergehalt für Schicht 14", "Vol-%", "monthlySoilMoisL14"); case monthlySoilMoistureL14: return ResultIdInfo("Monatlicher mittlerer Wassergehalt für Schicht 15", "Vol-%", "monthlySoilMoisL15"); case monthlySoilMoistureL15: return ResultIdInfo("Monatlicher mittlerer Wassergehalt für Schicht 16", "Vol-%", "monthlySoilMoisL16"); case monthlySoilMoistureL16: return ResultIdInfo("Monatlicher mittlerer Wassergehalt für Schicht 17", "Vol-%", "monthlySoilMoisL17"); case monthlySoilMoistureL17: return ResultIdInfo("Monatlicher mittlerer Wassergehalt für Schicht 18", "Vol-%", "monthlySoilMoisL18"); case monthlySoilMoistureL18: return ResultIdInfo("Monatlicher mittlerer Wassergehalt für Schicht 19", "Vol-%", "monthlySoilMoisL19"); case daysWithCrop: return ResultIdInfo("Anzahl der Tage mit Pflanzenbewuchs", "d", "daysWithCrop"); case NStress: return ResultIdInfo("Akkumulierte Werte für N-Stress", "", "NStress"); case WaterStress: return ResultIdInfo("Akkumulierte Werte für N-Stress", "", "waterStress"); case HeatStress: return ResultIdInfo("Akkumulierte Werte für N-Stress", "", "heatStress"); case OxygenStress: return ResultIdInfo("Akkumulierte Werte für N-Stress", "", "oxygenStress"); case dev_stage: return ResultIdInfo("Liste mit täglichen Werten für das Entwicklungsstadium", "[]", "devStage"); default: ; } return ResultIdInfo("", ""); } //------------------------------------------------------------------------------ string WorkStep::toString() const { ostringstream s; s << "date: " << date().toString(); return s.str(); } //------------------------------------------------------------------------------ void Seed::apply(MonicaModel* model) { debug() << "seeding crop: " << _crop->toString() << " at: " << date().toString() << endl; model->seedCrop(_crop); } string Seed::toString() const { ostringstream s; s << "seeding at: " << date().toString() << " crop: " << _crop->toString(); return s.str(); } //------------------------------------------------------------------------------ void Harvest::apply(MonicaModel* model) { if (model->cropGrowth()) { debug() << "harvesting crop: " << _crop->toString() << " at: " << date().toString() << endl; if (model->currentCrop() == _crop) { if (model->cropGrowth()) { _crop->setHarvestYields (model->cropGrowth()->get_FreshPrimaryCropYield() / 100.0, model->cropGrowth()->get_FreshSecondaryCropYield() / 100.0); _crop->setHarvestYieldsTM (model->cropGrowth()->get_PrimaryCropYield() / 100.0, model->cropGrowth()->get_SecondaryCropYield() / 100.0); _crop->setYieldNContent(model->cropGrowth()->get_PrimaryYieldNContent(), model->cropGrowth()->get_SecondaryYieldNContent()); _crop->setSumTotalNUptake(model->cropGrowth()->get_SumTotalNUptake()); _crop->setCropHeight(model->cropGrowth()->get_CropHeight()); _crop->setAccumulatedETa(model->cropGrowth()->get_AccumulatedETa()); } //store results for this crop _cropResult->pvResults[primaryYield] = _crop->primaryYield(); _cropResult->pvResults[secondaryYield] = _crop->secondaryYield(); _cropResult->pvResults[primaryYieldTM] = _crop->primaryYieldTM(); _cropResult->pvResults[secondaryYieldTM] = _crop->secondaryYieldTM(); _cropResult->pvResults[sumIrrigation] = _crop->appliedIrrigationWater(); _cropResult->pvResults[biomassNContent] = _crop->primaryYieldN(); _cropResult->pvResults[aboveBiomassNContent] = _crop->aboveGroundBiomasseN(); _cropResult->pvResults[daysWithCrop] = model->daysWithCrop(); _cropResult->pvResults[sumTotalNUptake] = _crop->sumTotalNUptake(); _cropResult->pvResults[cropHeight] = _crop->cropHeight(); _cropResult->pvResults[sumETaPerCrop] = _crop->get_AccumulatedETa(); _cropResult->pvResults[cropname] = _crop->id(); _cropResult->pvResults[NStress] = model->getAccumulatedNStress(); _cropResult->pvResults[WaterStress] = model->getAccumulatedWaterStress(); _cropResult->pvResults[HeatStress] = model->getAccumulatedHeatStress(); _cropResult->pvResults[OxygenStress] = model->getAccumulatedOxygenStress(); model->harvestCurrentCrop(); } else { debug() << "Crop: " << model->currentCrop()->toString() << " to be harvested isn't actual crop of this Harvesting action: " << _crop->toString() << endl; } } } string Harvest::toString() const { ostringstream s; s << "harvesting at: " << date().toString() << " crop: " << _crop->toString(); return s.str(); } //------------------------------------------------------------------------------ void Cutting::apply(MonicaModel* model) { debug() << "Cutting crop: " << _crop->toString() << " at: " << date().toString() << endl; if (model->currentCrop() == _crop) { if (model->cropGrowth()) { _crop->setHarvestYields (model->cropGrowth()->get_FreshPrimaryCropYield() / 100.0, model->cropGrowth()->get_FreshSecondaryCropYield() / 100.0); _crop->setHarvestYieldsTM (model->cropGrowth()->get_PrimaryCropYield() / 100.0, model->cropGrowth()->get_SecondaryCropYield() / 100.0); } _crop->setYieldNContent(model->cropGrowth()->get_PrimaryYieldNContent(), model->cropGrowth()->get_SecondaryYieldNContent()); _crop->setSumTotalNUptake(model->cropGrowth()->get_SumTotalNUptake()); _crop->setCropHeight(model->cropGrowth()->get_CropHeight()); if (model->cropGrowth()) { model->cropGrowth()->applyCutting(); } } } string Cutting::toString() const { ostringstream s; s << "Cutting at: " << date().toString() << " crop: " << _crop->toString(); return s.str(); } //------------------------------------------------------------------------------ string NMinCropParameters::toString() const { ostringstream s; s << "samplingDepth: " << samplingDepth << " nTarget: " << nTarget << " nTarget40: " << nTarget30; return s.str(); } //------------------------------------------------------------------------------ string NMinUserParameters::toString() const { ostringstream s; s << "min: " << min << " max: " << max << " delay: " << delayInDays << " days"; return s.str(); } //------------------------------------------------------------------------------ void MineralFertiliserApplication::apply(MonicaModel* model) { debug() << toString() << endl; model->applyMineralFertiliser(partition(), amount()); } string MineralFertiliserApplication::toString() const { ostringstream s; s << "applying mineral fertiliser at: " << date().toString() << " amount: " << amount() << " partition: " << partition().toString(); return s.str(); } //------------------------------------------------------------------------------ void OrganicFertiliserApplication::apply(MonicaModel* model) { debug() << toString() << endl; model->applyOrganicFertiliser(_params, _amount, _incorporation); } string OrganicFertiliserApplication::toString() const { ostringstream s; s << "applying organic fertiliser at: " << date().toString() << " amount: " << amount() << "\tN percentage: " << _params->vo_NConcentration << "\tN amount: " << amount() * _params->vo_NConcentration; // << "parameters: " << endl; return s.str(); } //------------------------------------------------------------------------------ void TillageApplication::apply(MonicaModel* model) { debug() << toString() << endl; model->applyTillage(_depth); } string TillageApplication::toString() const { ostringstream s; s << "applying tillage at: " << date().toString() << " depth: " << depth(); return s.str(); } //------------------------------------------------------------------------------ string IrrigationParameters::toString() const { ostringstream s; s << "nitrateConcentration: " << nitrateConcentration << " sulfateConcentration: " << sulfateConcentration; return s.str(); } string AutomaticIrrigationParameters::toString() const { ostringstream s; s << "amount: " << amount << " treshold: " << treshold << " " << IrrigationParameters::toString(); return s.str(); } void IrrigationApplication::apply(MonicaModel* model) { //cout << toString() << endl; model->applyIrrigation(amount(), nitrateConcentration()); } string IrrigationApplication::toString() const { ostringstream s; s << "applying irrigation at: " << date().toString() << " amount: " << amount() << " nitrateConcentration: " << nitrateConcentration() << " sulfateConcentration: " << sulfateConcentration(); return s.str(); } //------------------------------------------------------------------------------ ProductionProcess::ProductionProcess(const std::string& name, CropPtr crop) : _name(name), _crop(crop), _cropResult(new PVResult()) { debug() << "ProductionProcess: " << name.c_str() << endl; _cropResult->id = _crop->id(); if ((crop->seedDate() != Date(1,1,1951)) && (crop->seedDate() != Date(0,0,0))) { addApplication(Seed(crop->seedDate(), crop)); } if ((crop->harvestDate() != Date(1,1,1951)) && (crop->harvestDate() != Date(0,0,0))) { debug() << "crop->harvestDate(): " << crop->harvestDate().toString().c_str() << endl; addApplication(Harvest(crop->harvestDate(), crop, _cropResult)); } std::vector<Date> cuttingDates = crop->getCuttingDates(); unsigned int size = cuttingDates.size(); for (unsigned int i=0; i<size; i++) { debug() << "Add cutting date: " << Tools::Date(cuttingDates.at(i)).toString().c_str() << endl; // if (i<size-1) { addApplication(Cutting(Tools::Date(cuttingDates.at(i)), crop)); // } else { // addApplication(Harvest(crop->harvestDate(), crop, _cropResult)); // } } } /** * @brief Copy constructor * @param new_pp */ /* ProductionProcess::ProductionProcess(const ProductionProcess& other) { _name = other._name; _crop = CropPtr(new Crop(*(other._crop.get()))); _cropResult = PVResultPtr(new PVResult(*(other._cropResult.get()))); _worksteps = other._worksteps; } */ ProductionProcess ProductionProcess::deepCloneAndClearWorksteps() const { ProductionProcess clone(name(), CropPtr(new Crop(*(crop().get())))); clone._cropResult = PVResultPtr(new PVResult(*(_cropResult.get()))); return clone; } void ProductionProcess::apply(const Date& date, MonicaModel* model) const { typedef multimap<Date, WSPtr>::const_iterator CI; pair<CI, CI> p = _worksteps.equal_range(date); if (p.first != p.second) { while (p.first != p.second) { p.first->second->apply(model); p.first++; } } } Date ProductionProcess::nextDate(const Date& date) const { typedef multimap<Date, WSPtr>::const_iterator CI; CI ci = _worksteps.upper_bound(date); return ci != _worksteps.end() ? ci->first : Date(); } Date ProductionProcess::start() const { if (_worksteps.empty()) return Date(); return _worksteps.begin()->first; } Date ProductionProcess::end() const { if (_worksteps.empty()) return Date(); return _worksteps.rbegin()->first; } std::string ProductionProcess::toString() const { ostringstream s; s << "name: " << name() << " start: " << start().toString() << " end: " << end().toString() << endl; s << "worksteps:" << endl; typedef multimap<Date, WSPtr>::const_iterator CI; for (CI ci = _worksteps.begin(); ci != _worksteps.end(); ci++) { s << "at: " << ci->first.toString() << " what: " << ci->second->toString() << endl; } return s.str(); } //------------------------------------------------------------------------------ //helper for parsing dates struct DMY { int d, m, y; Date toDate(bool useLeapYears = true) const { return Date(d, m, y, useLeapYears); } }; // to read HERMES two digit date format in management files struct ParseDate { DMY operator()(const string & d) { DMY r; r.d = atoi(d.substr(0, 2).c_str()); r.m = atoi(d.substr(2, 2).c_str()); r.y = atoi(d.substr(4, 2).c_str()); r.y = r.y <= 76 ? 2000 + r.y : 1900 + r.y; return r; } } parseDate; //---------------------------------------------------------------------------- vector<ProductionProcess> Monica::cropRotationFromHermesFile(const string& pathToFile) { vector<ProductionProcess> ff; ifstream ifs(pathToFile.c_str(), ios::binary); if (! ifs.good()) { cerr << "Could not open file " << pathToFile.c_str() << " . Aborting now!" << endl; exit(1); } string s; //skip first line getline(ifs, s); while (getline(ifs, s)) { if (trim(s) == "end") break; istringstream ss(s); string crp; string sowingDate, harvestDate, tillageDate; double exp, tillage_depth; int t; ss >> t >> crp >> sowingDate >> harvestDate >> tillageDate >> exp >> tillage_depth; Date sd = parseDate(sowingDate).toDate(true); Date hd = parseDate(harvestDate).toDate(true); Date td = parseDate(tillageDate).toDate(true); // tst if dates are valid if (!sd.isValid() || !hd.isValid() || !td.isValid()) { debug() << "Error - Invalid date in \"" << pathToFile.c_str() << "\"" << endl; debug() << "Line: " << s.c_str() << endl; debug() << "Aborting simulation now!" << endl; exit(-1); } //create crop CropPtr crop = hermesCropId2Crop(crp); crop->setSeedAndHarvestDate(sd, hd); crop->setCropParameters(getCropParametersFromMonicaDB(crop->id())); crop->setResidueParameters(getResidueParametersFromMonicaDB(crop->id())); ProductionProcess pp(crp, crop); pp.addApplication(TillageApplication(td, (tillage_depth/100.0) )); //cout << "production-process: " << pp.toString() << endl; ff.push_back(pp); } return ff; } /** * @todo Micha/Xenia: Überprüfen, ob YearIndex rauskommen kann. */ DataAccessor Monica::climateDataFromHermesFiles(const std::string& pathToFile, int fromYear, int toYear, const CentralParameterProvider& cpp, bool useLeapYears, double latitude) { DataAccessor da(Date(1, 1, fromYear, useLeapYears), Date(31, 12, toYear, useLeapYears)); vector<double> _tmin; vector<double> _tavg; vector<double> _tmax; vector<double> _globrad; vector<double> _relhumid; vector<double> _wind; vector<double> _precip; vector<double> _sunhours; Date date = Date(1, 1, fromYear, useLeapYears); for (int y = fromYear; y <= toYear; y++) { ostringstream yss; yss << y; string ys = yss.str(); ostringstream oss; oss << pathToFile << ys.substr(1, 3); debug() << "File: " << oss.str().c_str() << endl; ifstream ifs(oss.str().c_str(), ios::binary); if (! ifs.good()) { cerr << "Could not open file " << oss.str().c_str() << " . Aborting now!" << endl; exit(1); } string s; //skip first line(s) getline(ifs, s); getline(ifs, s); getline(ifs, s); int daysCount = 0; int allowedDays = Date(31, 12, y, useLeapYears).dayOfYear(); // cout << "tavg\t" << "tmin\t" << "tmax\t" << "wind\t" debug() << "allowedDays: " << allowedDays << " " << y<< "\t" << useLeapYears << "\tlatitude:\t" << latitude << endl; //<< "sunhours\t" << "globrad\t" << "precip\t" << "ti\t" << "relhumid\n"; while (getline(ifs, s)) { //if(trim(s) == "end") break; //Tp_av Tpmin Tpmax T_s10 T_s20 vappd wind sundu radia prec jday RF double td; int ti; double tmin, tmax, tavg, wind, sunhours, globrad, precip, relhumid; istringstream ss(s); ss >> tavg >> tmin >> tmax >> td >> td >> td >> wind >> sunhours >> globrad >> precip >> ti >> relhumid; // test if globrad or sunhours should be used if(globrad >=0.0) { // use globrad // HERMES weather files deliver global radiation as [J cm-2] // Here, we push back [MJ m-2 d-1] double globradMJpm2pd = globrad * 100.0 * 100.0 / 1000000.0; _globrad.push_back(globradMJpm2pd); } else if(sunhours >= 0.0) { // invalid globrad use sunhours // convert sunhours into globrad // debug() << "Invalid globrad - use sunhours instead" << endl; _globrad.push_back(sunshine2globalRadiation(date.dayOfYear(), sunhours, latitude, true)); _sunhours.push_back(sunhours); } else { // error case debug() << "Error: No global radiation or sunhours specified for day " << date.toString().c_str() << endl; debug() << "Aborting now ..." << endl; exit(-1); } if (relhumid>0) { _relhumid.push_back(relhumid); } // precipitation correction by Richter values precip*=cpp.getPrecipCorrectionValue(date.month()-1); // cout << tavg << "\t"<< tmin << "\t" << tmax << "\t" << wind //<< "\t" << sunhours <<"\t" << globrad <<"\t" << precip <<"\t" << ti <<"\t" << relhumid << endl; _tavg.push_back(tavg); _tmin.push_back(tmin); _tmax.push_back(tmax); _wind.push_back(wind); _precip.push_back(precip); daysCount++; date++; } if (daysCount != allowedDays) { debug() << "Wrong number of days in " << oss.str().c_str() << " ." << " Found " << daysCount << " days but should have been " << allowedDays << " days. Aborting." << endl; exit(1); } } //int days = (toYearIndex - fromYearIndex + 1) * 365; //assert(int(_tmin.size()) == days); da.addClimateData(tmin, _tmin); da.addClimateData(tmax, _tmax); da.addClimateData(tavg, _tavg); da.addClimateData(globrad, _globrad); da.addClimateData(wind, _wind); da.addClimateData(precip, _precip); if(!_sunhours.empty()) da.addClimateData(sunhours, _sunhours); if (!_relhumid.empty()) { da.addClimateData(relhumid, _relhumid); } return da; } //---------------------------------------------------------------------------- /** * @brief Constructor * * Parameter initiliazation */ CropParameters::CropParameters() : pc_NumberOfDevelopmentalStages(0), pc_NumberOfOrgans(0), pc_CarboxylationPathway(0), pc_DefaultRadiationUseEfficiency(0), pc_FixingN(0), pc_InitialKcFactor(0), pc_LuxuryNCoeff(0), pc_MaxAssimilationRate(0), pc_MaxCropHeight(0), pc_CropHeightP1(0), pc_CropHeightP2(0), pc_MinimumNConcentration(0), pc_MinimumTemperatureForAssimilation(0), pc_NConcentrationAbovegroundBiomass(0), pc_NConcentrationB0(0), pc_NConcentrationPN(0), pc_NConcentrationRoot(0), pc_ResidueNRatio(0), pc_DevelopmentAccelerationByNitrogenStress(0), pc_CuttingDelayDays(0) {} /** * @brief */ void CropParameters::resizeStageOrganVectors() { pc_AssimilatePartitioningCoeff.resize(pc_NumberOfDevelopmentalStages, std::vector<double>(pc_NumberOfOrgans)); pc_OrganSenescenceRate.resize(pc_NumberOfDevelopmentalStages, std::vector<double>(pc_NumberOfOrgans)); } /** * @brief Returns a string of information about crop parameters. * * Generates a string that contains all relevant crop parameter information. * * @return String of crop information. */ string CropParameters::toString() const { ostringstream s; s << "pc_CropName:\t" << pc_CropName << endl; s << "------------------------------------------------" << endl; s << "pc_NumberOfDevelopmentalStages:\t" << pc_NumberOfDevelopmentalStages << endl; s << "pc_NumberOfOrgans:\t\t\t\t" << pc_NumberOfOrgans << endl; s << "------------------------------------------------" << endl; // assimilate partitioning coefficient matrix s << "pc_AssimilatePartitioningCoeff:\t" << endl; for (unsigned int i = 0; i < pc_AssimilatePartitioningCoeff.size(); i++) { for (unsigned int j = 0; j < pc_AssimilatePartitioningCoeff[i].size(); j++) { s << pc_AssimilatePartitioningCoeff[i][j] << " "; } s << endl; } s << "------------------------------------------------" << endl; s << "pc_CarboxylationPathway:\t\t\t\t" << pc_CarboxylationPathway << endl; s << "pc_MaxAssimilationRate:\t\t\t\t\t" << pc_MaxAssimilationRate << endl; s << "pc_MinimumTemperatureForAssimilation:\t" << pc_MinimumTemperatureForAssimilation << endl; s << "pc_CropSpecificMaxRootingDepth:\t\t\t" << pc_CropSpecificMaxRootingDepth << endl; s << "pc_InitialKcFactor:\t\t\t\t\t\t" << pc_InitialKcFactor << endl; s << "pc_MaxCropDiameter:\t\t\t\t\t\t" << pc_MaxCropDiameter << endl; s << "pc_StageAtMaxDiameter:\t\t\t\t\t" << pc_StageAtMaxDiameter << endl; s << "pc_PlantDensity:\t\t\t\t\t\t" << pc_PlantDensity << endl; s << "pc_DefaultRadiationUseEfficiency:\t\t" << pc_DefaultRadiationUseEfficiency << endl; s << "pc_StageAfterCut:\t\t\t\t\t\t" << pc_StageAfterCut << endl; s << "pc_CuttingDelayDays:\t\t\t\t\t" << pc_CuttingDelayDays << endl; s << "------------------------------------------------" << endl; s << "pc_RootDistributionParam:\t\t\t" << pc_RootDistributionParam << endl; s << "pc_RootGrowthLag:\t\t\t\t\t" << pc_RootGrowthLag << endl; s << "pc_MinimumTemperatureRootGrowth:\t" << pc_MinimumTemperatureRootGrowth << endl; s << "pc_InitialRootingDepth:\t\t\t\t" << pc_InitialRootingDepth << endl; s << "pc_RootPenetrationRate:\t\t\t\t" << pc_RootPenetrationRate << endl; s << "pc_RootFormFactor:\t\t\t\t\t" << pc_RootFormFactor << endl; s << "pc_SpecificRootLength:\t\t\t\t" << pc_SpecificRootLength << endl; s << "------------------------------------------------" << endl; s << "pc_MaxCropHeight:\t\t" << pc_MaxCropHeight << endl; s << "pc_CropHeightP1:\t\t" << pc_CropHeightP1 << endl; s << "pc_CropHeightP2:\t\t" << pc_CropHeightP2 << endl; s << "pc_StageAtMaxHeight:\t" << pc_StageAtMaxHeight << endl; s << "------------------------------------------------" << endl; s << "pc_FixingN:\t\t\t\t\t" << pc_FixingN << endl; s << "pc_MinimumNConcentration:\t" << pc_MinimumNConcentration << endl; s << "pc_LuxuryNCoeff:\t\t\t" << pc_LuxuryNCoeff << endl; s << "pc_NConcentrationB0:\t\t" << pc_NConcentrationB0 << endl; s << "pc_NConcentrationPN:\t\t" << pc_NConcentrationPN << endl; s << "pc_NConcentrationRoot:\t\t" << pc_NConcentrationRoot << endl; s << "pc_ResidueNRatio:\t\t\t" << pc_ResidueNRatio << endl; s << "pc_MaxNUptakeParam:\t\t\t" << pc_MaxNUptakeParam << endl; s << "------------------------------------------------" << endl; s << "pc_DevelopmentAccelerationByNitrogenStress:\t" << pc_DevelopmentAccelerationByNitrogenStress << endl; s << "pc_NConcentrationAbovegroundBiomass:\t\t" << pc_NConcentrationAbovegroundBiomass << endl; s << "pc_DroughtImpactOnFertilityFactor:\t\t\t" << pc_DroughtImpactOnFertilityFactor << endl; s << "------------------------------------------------" << endl; s << "pc_SamplingDepth:\t\t\t\t\t" << pc_SamplingDepth << endl; s << "pc_TargetNSamplingDepth:\t\t\t" << pc_TargetNSamplingDepth << endl; s << "pc_TargetN30:\t\t\t\t\t\t" << pc_TargetN30 << endl; s << "pc_HeatSumIrrigationStart:\t\t\t" << pc_HeatSumIrrigationStart << endl; s << "pc_HeatSumIrrigationEnd:\t\t\t" << pc_HeatSumIrrigationEnd << endl; s << "pc_CriticalTemperatureHeatStress:\t" << pc_CriticalTemperatureHeatStress << endl; s << "pc_LimitingTemperatureHeatStress:\t" << pc_LimitingTemperatureHeatStress << endl; s << "pc_BeginSensitivePhaseHeatStress:\t" << pc_BeginSensitivePhaseHeatStress << endl; s << "pc_EndSensitivePhaseHeatStress:\t\t" << pc_EndSensitivePhaseHeatStress << endl; //s << endl; s << "------------------------------------------------" << endl; // above-ground organ s << "pc_AbovegroundOrgan:" << endl; for (unsigned i = 0; i < pc_AbovegroundOrgan.size(); i++) s << (pc_AbovegroundOrgan[i] == 1) << " "; s << endl; s << endl; // initial organic biomass s << "pc_InitialOrganBiomass:" << endl; for (unsigned int i = 0; i < pc_InitialOrganBiomass.size(); i++) s << pc_InitialOrganBiomass[i] << " "; s << endl; s << endl; // organ maintenance respiration rate s << "pc_OrganMaintenanceRespiration:" << endl; for (unsigned int i = 0; i < pc_OrganMaintenanceRespiration.size(); i++) s << pc_OrganMaintenanceRespiration[i] << " "; s << endl; s << endl; // organ growth respiration rate s << "pc_OrganGrowthRespiration:" << endl; for (unsigned int i = 0; i < pc_OrganGrowthRespiration.size(); i++) s << pc_OrganGrowthRespiration[i] << " "; s << endl; s << endl; // organ senescence rate s << "pc_OrganSenescenceRate:" << endl; for (unsigned int i = 0; i < pc_OrganSenescenceRate.size(); i++) { for (unsigned int j = 0; j < pc_OrganSenescenceRate[i].size(); j++) { s << pc_OrganSenescenceRate[i][j] << " "; } s << endl; } s << "------------------------------------------------" << endl; //s << endl; //s << endl; // stage temperature sum s << "pc_StageTemperatureSum:" << endl; for (unsigned int i = 0; i < pc_StageTemperatureSum.size(); i++) s << pc_StageTemperatureSum[i] << " "; s << endl; s << endl; // Base day length s << "pc_BaseDaylength: " << endl; for (unsigned int i = 0; i < pc_BaseDaylength.size(); i++) s << pc_BaseDaylength[i] << " "; s << endl; s << endl; // base temperature s << "pc_BaseTemperature: " << endl; for (unsigned int i = 0; i < pc_BaseTemperature.size(); i++) s << pc_BaseTemperature[i] << " "; s << endl; s << endl; // optimum temperature s << "pc_OptimumTemperature: " << endl; for (unsigned int i = 0; i < pc_OptimumTemperature.size(); i++) s << pc_OptimumTemperature[i] << " "; s << endl; s << endl; // day length requirement s << "pc_DaylengthRequirement: " << endl; for (unsigned int i = 0; i < pc_DaylengthRequirement.size(); i++) s << pc_DaylengthRequirement[i] << " "; s << endl; s << endl; // specific leaf area s << "pc_SpecificLeafArea:" << endl; for (unsigned int i = 0; i < pc_SpecificLeafArea.size(); i++) s << pc_SpecificLeafArea[i] << " "; s << endl; s << endl; // stage max root n content s << "pc_StageMaxRootNConcentration:" << endl; for (unsigned int i = 0; i < pc_StageMaxRootNConcentration.size(); i++) s << pc_StageMaxRootNConcentration[i] << " "; s << endl; s << endl; // stage kc factor s << "pc_StageKcFactor:" << endl; for (unsigned int i = 0; i < pc_StageKcFactor.size(); i++) s << pc_StageKcFactor[i] << " "; s << endl; s << endl; // drought stress treshold s << "pc_DroughtStressThreshold:" << endl; for (unsigned int i = 0; i < pc_DroughtStressThreshold.size(); i++) s << pc_DroughtStressThreshold[i] << " "; s << endl; s << endl; // vernalisation requirement s << "pc_VernalisationRequirement:" << endl; for (unsigned int i = 0; i < pc_VernalisationRequirement.size(); i++) s << pc_VernalisationRequirement[i] << " "; s << endl; s << endl; // critical oxygen content s << "pc_CriticalOxygenContent:" << endl; for (unsigned int i = 0; i < pc_CriticalOxygenContent.size(); i++) s << pc_CriticalOxygenContent[i] << " "; s << endl; return s.str(); } //------------------------------------------------------------------------------ /** * @brief Returns data structure for crop parameters with values from DB * * A datastructure for crop parameters is created, initialized with * database values and returned. This structure will be initialized only * once. Similar to a singleton pattern. * * @param cropId * * @return Reference to crop parameters */ const CropParameters* Monica::getCropParametersFromMonicaDB(int cropId) { static L lockable; static bool initialized = false; typedef boost::shared_ptr<CropParameters> CPPtr; typedef map<int, CPPtr> CPS; static CPS cpss; // only initialize once if (!initialized) { L::Lock lock(lockable); //test if after waiting for the lock the other thread //already initialized the whole thing if (!initialized) { DB *con = newConnection("monica"); DBRow row; std::string text_request = "select id, name, max_assimilation_rate, " "carboxylation_pathway, minimum_temperature_for_assimilation, " "crop_specific_max_rooting_depth, min_n_content, " "n_content_pn, n_content_b0, " "n_content_above_ground_biomass, n_content_root, initial_kc_factor, " "development_acceleration_by_nitrogen_stress, fixing_n, " "luxury_n_coeff, max_crop_height, residue_n_ratio, " "sampling_depth, target_n_sampling_depth, target_n30, " "default_radiation_use_efficiency, crop_height_P1, crop_height_P2, " "stage_at_max_height, max_stem_diameter, stage_at_max_diameter, " "heat_sum_irrigation_start, heat_sum_irrigation_end, " "max_N_uptake_p, root_distribution_p, plant_density, " "root_growth_lag, min_temperature_root_growth, initial_rooting_depth, " "root_penetration_rate, root_form_factor, specific_root_length, " "stage_after_cut, crit_temperature_heat_stress, " "lim_temperature_heat_stress, begin_sensitive_phase_heat_stress, " "end_sensitive_phase_heat_stress, drought_impact_on_fertility_factor, " "cutting_delay_days from crop"; con->select(text_request.c_str()); debug () << text_request.c_str() << endl; while (!(row = con->getRow()).empty()) { int i = 0; int id = satoi(row[i++]); debug() << "Reading in crop Parameters for: " << id << endl; CPS::iterator cpsi = cpss.find(id); CPPtr cps; if (cpsi == cpss.end()) { cpss.insert(make_pair(id, cps = boost::shared_ptr<CropParameters>(new CropParameters))); } else { cps = cpsi->second; } cps->pc_CropName = row[i++].c_str(); cps->pc_MaxAssimilationRate = satof(row[i++]); cps->pc_CarboxylationPathway = satoi(row[i++]); cps->pc_MinimumTemperatureForAssimilation = satof(row[i++]); cps->pc_CropSpecificMaxRootingDepth = satof(row[i++]); cps->pc_MinimumNConcentration = satof(row[i++]); cps->pc_NConcentrationPN = satof(row[i++]); cps->pc_NConcentrationB0 = satof(row[i++]); cps->pc_NConcentrationAbovegroundBiomass = satof(row[i++]); cps->pc_NConcentrationRoot = satof(row[i++]); cps->pc_InitialKcFactor = satof(row[i++]); cps->pc_DevelopmentAccelerationByNitrogenStress = satoi(row[i++]); cps->pc_FixingN = satoi(row[i++]); cps->pc_LuxuryNCoeff = satof(row[i++]); cps->pc_MaxCropHeight = satof(row[i++]); cps->pc_ResidueNRatio = satof(row[i++]); cps->pc_SamplingDepth = satof(row[i++]); cps->pc_TargetNSamplingDepth = satof(row[i++]); cps->pc_TargetN30 = satof(row[i++]); cps->pc_DefaultRadiationUseEfficiency = satof(row[i++]); cps->pc_CropHeightP1 = satof(row[i++]); cps->pc_CropHeightP2 = satof(row[i++]); cps->pc_StageAtMaxHeight = satof(row[i++]); cps->pc_MaxCropDiameter = satof(row[i++]); cps->pc_StageAtMaxDiameter = satof(row[i++]); cps->pc_HeatSumIrrigationStart = satof(row[i++]); cps->pc_HeatSumIrrigationEnd = satof(row[i++]); cps->pc_MaxNUptakeParam = satof(row[i++]); cps->pc_RootDistributionParam = satof(row[i++]); cps->pc_PlantDensity = satof(row[i++]); cps->pc_RootGrowthLag = satof(row[i++]); cps->pc_MinimumTemperatureRootGrowth = satof(row[i++]); cps->pc_InitialRootingDepth = satof(row[i++]); cps->pc_RootPenetrationRate = satof(row[i++]); cps->pc_RootFormFactor = satof(row[i++]); cps->pc_SpecificRootLength = satof(row[i++]); cps->pc_StageAfterCut = satoi(row[i++]); cps->pc_CriticalTemperatureHeatStress = satof(row[i++]); cps->pc_LimitingTemperatureHeatStress = satof(row[i++]); cps->pc_BeginSensitivePhaseHeatStress = satof(row[i++]); cps->pc_EndSensitivePhaseHeatStress = satof(row[i++]); cps->pc_DroughtImpactOnFertilityFactor = satof(row[i++]); cps->pc_CuttingDelayDays = satoi(row[i++]); } std::string req2 ="select o.crop_id, o.id, o.initial_organ_biomass, " "o.organ_maintainance_respiration, o.is_above_ground, " "o.organ_growth_respiration, o.is_storage_organ " "from organ as o inner join crop as c on c.id = o.crop_id " "order by o.crop_id, c.id"; con->select(req2.c_str()); debug() << req2.c_str() << endl; while (!(row = con->getRow()).empty()) { int cropId = satoi(row[0]); // debug() << "Organ for crop: " << cropId << endl; auto cps = cpss[cropId]; cps->pc_NumberOfOrgans++; cps->pc_InitialOrganBiomass.push_back(satof(row[2])); cps->pc_OrganMaintenanceRespiration.push_back(satof(row[3])); cps->pc_AbovegroundOrgan.push_back(satoi(row[4]) == 1); cps->pc_OrganGrowthRespiration.push_back(satof(row[5])); cps->pc_StorageOrgan.push_back(satoi(row[6])); } std::string req4 = "select crop_id, id, stage_temperature_sum, " "base_temperature, opt_temperature, vernalisation_requirement, " "day_length_requirement, base_day_length, " "drought_stress_threshold, critical_oxygen_content, " "specific_leaf_area, stage_max_root_n_content, " "stage_kc_factor " "from dev_stage " "order by crop_id, id"; con->select(req4.c_str()); debug() << req4.c_str() << endl; while (!(row = con->getRow()).empty()) { int cropId = satoi(row[0]); auto cps = cpss[cropId]; cps->pc_NumberOfDevelopmentalStages++; cps->pc_StageTemperatureSum.push_back(satof(row[2])); cps->pc_BaseTemperature.push_back(satof(row[3])); cps->pc_OptimumTemperature.push_back(satof(row[4])); cps->pc_VernalisationRequirement.push_back(satof(row[5])); cps->pc_DaylengthRequirement.push_back(satof(row[6])); cps->pc_BaseDaylength.push_back(satof(row[7])); cps->pc_DroughtStressThreshold.push_back(satof(row[8])); cps->pc_CriticalOxygenContent.push_back(satof(row[9])); cps->pc_SpecificLeafArea.push_back(satof(row[10])); cps->pc_StageMaxRootNConcentration.push_back(satof(row[11])); cps->pc_StageKcFactor.push_back(satof(row[12])); } BOOST_FOREACH(CPS::value_type vt, cpss) { vt.second->resizeStageOrganVectors(); } //for (CPS::iterator it = cpss.begin(); it != cpss.end(); it++) // it->second->resizeStageOrganVectors(); std::string req3 = "select crop_id, organ_id, dev_stage_id, " "ods_dependent_param_id, value " "from crop2ods_dependent_param " "order by crop_id, ods_dependent_param_id, dev_stage_id, organ_id"; con->select(req3.c_str()); debug() << req3.c_str() << endl; while (!(row = con->getRow()).empty()) { int cropId = satoi(row[0]); // debug() << "ods_dependent_param " << cropId << "\t" << satoi(row[3]) <<"\t" << satoi(row[2]) <<"\t" << satoi(row[1])<< endl; auto cps = cpss[cropId]; vector<vector<double> >& sov = satoi(row[3]) == 1 ? cps->pc_AssimilatePartitioningCoeff : cps->pc_OrganSenescenceRate; sov[satoi(row[2]) - 1][satoi(row[1]) - 1] = satof(row[4]); } con->select("SELECT crop_id, organ_id, is_primary, percentage, dry_matter FROM yield_parts"); debug() << "SELECT crop_id, organ_id, is_primary, percentage, dry_matter FROM yield_parts" << endl; while (!(row = con->getRow()).empty()) { int cropId = satoi(row[0]); int organId = satoi(row[1]); bool isPrimary = satoi(row[2]) == 1; double percentage = satof(row[3]) / 100.0; double yieldDryMatter = satof(row[4]); auto cps = cpss[cropId]; // normal case, uses yield partitioning from crop database if (isPrimary) { // cout << cropId<< " Add primary organ: " << organId << endl; cps->organIdsForPrimaryYield.push_back(Monica::YieldComponent(organId, percentage, yieldDryMatter)); } else { // cout << cropId << " Add secondary organ: " << organId << endl; cps->organIdsForSecondaryYield.push_back(Monica::YieldComponent(organId, percentage, yieldDryMatter)); } } // get cutting parts if there are some data available con->select("SELECT crop_id, organ_id, is_primary, percentage, dry_matter FROM cutting_parts"); while (!(row = con->getRow()).empty()) { int cropId = satoi(row[0]); int organId = satoi(row[1]); //bool isPrimary = satoi(row[2]) == 1; double percentage = satof(row[3]) / 100.0; double yieldDryMatter = satof(row[4]); auto cps = cpss[cropId]; cps->organIdsForCutting.push_back(Monica::YieldComponent(organId, percentage, yieldDryMatter)); if (cropId!=18) { // do not add cutting part organ id for sudan gras because they are already added cps->organIdsForPrimaryYield.push_back(Monica::YieldComponent(organId, percentage, yieldDryMatter)); } } delete con; initialized = true; /* for(CPS::const_iterator it = cpss.begin(); it != cpss.end(); it++) cout << it->second->toString(); //*/ } } static CropParameters nothing; CPS::const_iterator ci = cpss.find(cropId); debug() << "Find crop parameter: " << cropId << endl; return ci != cpss.end() ? ci->second.get() : &nothing; } //------------------------------------------------------------------------------ /** * @brief Constructor * @param ps_LayerThickness * @param ps_ProfileDepth * @param ps_MaxMineralisationDepth * @param ps_NitrogenResponseOn * @param ps_WaterDeficitResponseOn */ GeneralParameters::GeneralParameters(double ps_LayerThickness, double ps_ProfileDepth, double ps_MaximumMineralisationDepth, bool pc_NitrogenResponseOn, bool pc_WaterDeficitResponseOn) : ps_LayerThickness(int(ps_ProfileDepth / ps_LayerThickness), ps_LayerThickness), ps_ProfileDepth(ps_ProfileDepth), ps_MaxMineralisationDepth(ps_MaximumMineralisationDepth), pc_NitrogenResponseOn(pc_NitrogenResponseOn), pc_WaterDeficitResponseOn(pc_WaterDeficitResponseOn) {} //------------------------------------------------------------------------------ /** * @brief Definition of organic constants */ double const OrganicConstants::po_UreaMolecularWeight = 0.06006;//[kg mol-1] double const OrganicConstants::po_Urea_to_N = 0.46667; //Converts 1 kg urea to 1 kg N double const OrganicConstants::po_NH3MolecularWeight = 0.01401; //[kg mol-1] double const OrganicConstants::po_NH4MolecularWeight = 0.01401; //[kg mol-1] double const OrganicConstants::po_H2OIonConcentration = 1.0; double const OrganicConstants::po_pKaHNO2 = 3.29; // [] pKa value for nitrous acid double const OrganicConstants::po_pKaNH3 = 6.5; // [] pKa value for ammonium double const OrganicConstants::po_SOM_to_C = 0.57; // = 0.58; // [] converts soil organic matter to carbon double const OrganicConstants::po_AOM_to_C = 0.45; // [] converts added organic matter to carbon //------------------------------------------------------------------------------ /** * @brief Constructor */ SiteParameters::SiteParameters() : vs_Latitude(60.0), vs_Slope(0.01), vs_HeightNN(50.0), vs_GroundwaterDepth(70.0), vs_Soil_CN_Ratio(10.0), vq_NDeposition(30.0) {} /** * @brief Serializes site parameters into a string. * @return String containing size parameters */ string SiteParameters::toString() const { ostringstream s; s << "vs_Latitude: " << vs_Latitude << " vs_Slope: " << vs_Slope << " vs_HeightNN: " << vs_HeightNN << " vs_DepthGroundwaterTable: " << vs_GroundwaterDepth << " vs_Soil_CN_Ratio: " << vs_Soil_CN_Ratio << " vq_NDeposition: " << vq_NDeposition << endl; return s.str(); } //------------------------------------------------------------------------------ /** * @brief Constructor * * Parameter initialization */ SoilParameters::SoilParameters() : vs_SoilSandContent(0.4), vs_SoilClayContent(0.05), vs_SoilpH(6.9), _vs_SoilRawDensity(0), _vs_SoilOrganicCarbon(-1), _vs_SoilOrganicMatter(-1) {} bool SoilParameters::isValid() { bool is_valid = true; if (vs_FieldCapacity <= 0) { cout << "SoilParameters::Error: No field capacity defined in database for " << vs_SoilTexture.c_str() << " , RawDensity: "<< _vs_SoilRawDensity << endl; is_valid = false; } if (vs_Saturation <= 0) { cout << "SoilParameters::Error: No saturation defined in database for " << vs_SoilTexture.c_str() << " , RawDensity: " << _vs_SoilRawDensity << endl; is_valid = false; } if (vs_PermanentWiltingPoint <= 0) { cout << "SoilParameters::Error: No saturation defined in database for " << vs_SoilTexture.c_str() << " , RawDensity: " << _vs_SoilRawDensity << endl; is_valid = false; } if (vs_SoilSandContent<0) { cout << "SoilParameters::Error: Invalid soil sand content: "<< vs_SoilSandContent << endl; is_valid = false; } if (vs_SoilClayContent<0) { cout << "SoilParameters::Error: Invalid soil clay content: "<< vs_SoilClayContent << endl; is_valid = false; } if (vs_SoilpH<0) { cout << "SoilParameters::Error: Invalid soil ph value: "<< vs_SoilpH << endl; is_valid = false; } if (vs_SoilStoneContent<0) { cout << "SoilParameters::Error: Invalid soil stone content: "<< vs_SoilStoneContent << endl; is_valid = false; } if (vs_Saturation<0) { cout << "SoilParameters::Error: Invalid value for saturation: "<< vs_Saturation << endl; is_valid = false; } if (vs_PermanentWiltingPoint<0) { cout << "SoilParameters::Error: Invalid value for permanent wilting point: "<< vs_PermanentWiltingPoint << endl; is_valid = false; } if (_vs_SoilRawDensity<0) { cout << "SoilParameters::Error: Invalid soil raw density: "<< _vs_SoilRawDensity << endl; is_valid = false; } return is_valid; } /** * @brief Returns raw density of soil * @return raw density of soil */ double SoilParameters::vs_SoilRawDensity() const { // conversion from g cm-3 in kg m-3 return _vs_SoilRawDensity * 1000; } /** * @brief Sets soil raw density * @param srd New soil rad density */ void SoilParameters::set_vs_SoilRawDensity(double srd) { _vs_SoilRawDensity = srd; } /** * @brief Returns soil organic carbon. * @return soil organic carbon */ double SoilParameters::vs_SoilOrganicCarbon() const { if (_vs_SoilOrganicMatter < 0) return _vs_SoilOrganicCarbon; return _vs_SoilOrganicMatter * OrganicConstants::po_SOM_to_C; } /** * @brief Setter of soil organic carbon. * @param soc New soil organic carbon */ void SoilParameters::set_vs_SoilOrganicCarbon(double soc) { _vs_SoilOrganicCarbon = soc; } /** * @brief Getter for soil organic matter. * @return Soil organic matter */ double SoilParameters::vs_SoilOrganicMatter() const { if (_vs_SoilOrganicCarbon < 0) return _vs_SoilOrganicMatter; return _vs_SoilOrganicCarbon / OrganicConstants::po_SOM_to_C; } /** * @brief Setter for soil organic matter. * @param som New soil organic matter */ void SoilParameters::set_vs_SoilOrganicMatter(double som) { _vs_SoilOrganicMatter = som; } /** * @brief Getter for silt content * @return silt content */ double SoilParameters::vs_SoilSiltContent() const { if ((vs_SoilSandContent - 0.001) < 0 && (vs_SoilClayContent - 0.001) < 0) return 0; return 1 - vs_SoilSandContent - vs_SoilClayContent; } /** * @brief Getter for soil bulk density. * @return bulk density */ double SoilParameters::vs_SoilBulkDensity() const { return (_vs_SoilRawDensity + (0.009 * 100 * vs_SoilClayContent)) * 1000; } /** * @brief Serializes soil parameters into a string. * @return String of soil parameters */ string SoilParameters::toString() const { ostringstream s; s << "vs_Soilph: " << vs_SoilpH << endl << "vs_SoilOrganicCarbon: " << vs_SoilOrganicCarbon() << endl << "vs_SoilOrganicMatter: " << vs_SoilOrganicMatter() << endl << "vs_SoilRawDensity: " << vs_SoilRawDensity() << endl << "vs_SoilBulkDensity: " << vs_SoilBulkDensity() << endl << "vs_SoilSandContent: " << vs_SoilSandContent << endl << "vs_SoilClayContent: " << vs_SoilClayContent << endl << "vs_SoilSiltContent: " << vs_SoilSiltContent() << endl << "vs_SoilStoneContent: " << vs_SoilStoneContent << endl; return s.str(); } /** * @brief Returns lambda from soil texture * * @param lambda * * @return */ double SoilParameters::texture2lambda(double sand, double clay) { return Tools::texture2lambda(sand, clay); } //------------------------------------------------------------------------------ /** * @brief Overloaded function that returns soil parameter for ucker. * * Parameters are read from database. * * @param str * @param gps General parameters * @return Soil parameters */ const SoilPMs* Monica::ueckerSoilParameters(const std::string& str, const GeneralParameters& gps, bool loadSingleParameter) { //cout << "getting soilparameters for STR: " << str << endl; int lt = int(gps.ps_LayerThickness.front() * 100); //cm int maxDepth = int(gps.ps_ProfileDepth) * 100; //cm int maxNoOfLayers = int(double(maxDepth) / double(lt)); static L lockable; typedef map<string, SoilPMsPtr> Map; static bool initialized = false; static Map spss; if (!initialized) { L::Lock lock(lockable); if (!initialized) { DBPtr con(newConnection("landcare-dss")); DBRow row; ostringstream s; s << "select str, anzhor, hor, ho, hu, ph, corg, trd, s, t " "from mmk_profile " "where ho <= 201 "; if(loadSingleParameter) s << "and str = '" << str << "' "; s << "order by str, hor"; con->select(s.str().c_str()); while (!(row = con->getRow()).empty()) { string id = row[0]; Map::iterator spsi = spss.find(id); SoilPMsPtr sps; if (spsi == spss.end()) spss.insert(make_pair(id, sps = SoilPMsPtr(new SoilPMs))); else sps = spsi->second; int hcount = satoi(row[1]); int currenth = satoi(row[2]); int ho = sps->size() * lt; int hu = satoi(row[4]) ? satoi(row[4]) : maxDepth; int hsize = hu - ho; int subhcount = int(Tools::round(double(hsize) / double(lt)));//std::floor(double(hsize) / double(lt)); if (currenth == hcount && (int(sps->size()) + subhcount) < maxNoOfLayers) subhcount += maxNoOfLayers - sps->size() - subhcount; SoilParameters p; if (satof(row[5])) p.vs_SoilpH = satof(row[5]); p.set_vs_SoilOrganicCarbon(satof(row[6]) ? (satof(row[6]) / 100.0) : 0); p.set_vs_SoilRawDensity(satof(row[7])); p.vs_SoilSandContent = satof(row[8]) / 100.0; p.vs_SoilClayContent = satof(row[9]) / 100.0; p.vs_SoilTexture = texture2KA5(p.vs_SoilSandContent, p.vs_SoilClayContent); p.vs_SoilStoneContent = 0.0; p.vs_Lambda = texture2lambda(p.vs_SoilSandContent, p.vs_SoilClayContent); // initialization of saturation, field capacity and perm. wilting point soilCharacteristicsKA5(p); bool valid_soil_params = p.isValid(); if (!valid_soil_params) { cout << "Error in soil parameters. Aborting now simulation"; exit(-1); } for (int i = 0; i < subhcount; i++) sps->push_back(p); } initialized = true; // BOOST_FOREACH(Map::value_type p, spss) // { // cout << "code: " << p.first << endl; // BOOST_FOREACH(SoilParameters sp, *p.second) // { // cout << sp.toString(); // cout << "---------------------------------" << endl; // } // } } } static SoilPMs nothing; Map::const_iterator ci = spss.find(str); /* if(ci != spss.end()) { cout << "code: " << str << endl; BOOST_FOREACH(SoilParameters sp, *ci->second) { cout << sp.toString(); cout << "---------------------------------" << endl; } } */ return ci != spss.end() ? ci->second.get() : &nothing; } /** * @brief Overloaded function that returns soil parameter for ucker. * @param mmkGridId * @param gps General parameters * @return Soil parameters */ const SoilPMs* Monica::ueckerSoilParameters(int mmkGridId, const GeneralParameters& gps, bool loadSingleParameter) { //cout << "mmkGridId: " << mmkGridId << " -> str: " << ueckerGridId2STR(mmkGridId) << endl; string str = ueckerGridId2STR(mmkGridId); return str.empty() ? NULL : ueckerSoilParameters(str, gps, loadSingleParameter); } string Monica::ueckerGridId2STR(int ugid) { static L lockable; static bool initialized = false; typedef map<int, string> Map; static Map m; if (!initialized) { L::Lock lock(lockable); if (!initialized) { DBPtr con(newConnection("landcare-dss")); DBRow row; con->select("SELECT grid_id, str FROM uecker_grid_id_2_str"); while (!(row = con->getRow()).empty()) m.insert(make_pair(satoi(row[0]), row[1])); initialized = true; } } Map::const_iterator ci = m.find(ugid); return ci != m.end() ? ci->second : ""; } //---------------------------------------------------------------------------- /** * @brief Returns soil parameter of weisseritz * @param bk50GridId * @param gps General parameters * @return Soil parameters */ const SoilPMs* Monica::weisseritzSoilParameters(int bk50GridId, const GeneralParameters& gps, bool loadSingleParameter) { static SoilPMs nothing; int lt = int(gps.ps_LayerThickness.front() * 100); //cm int maxDepth = int(gps.ps_ProfileDepth) * 100; //cm int maxNoOfLayers = int(double(maxDepth) / double(lt)); static L lockable; typedef map<int, SoilPMsPtr> Map; static bool initialized = false; static Map spss; if(!initialized) { L::Lock lock(lockable); if (!initialized) { DBPtr con(newConnection("landcare-dss")); DBRow row; ostringstream s; s << "select b2.grid_id, bk.anzahl_horizonte, bk.horizont_id, " "bk.otief, bk.utief, bk.humus_st, bk.ld_eff, w.s, w.t " "from bk50_profile as bk inner join bk50_grid_id_2_aggnr as b2 on " "bk.aggnr = b2.aggnr inner join ka4wind as w on " "bk.boart = w.bodart "; if(loadSingleParameter) s << "where b2.grid_id = " << bk50GridId << " "; s << "order by b2.grid_id, bk.horizont_id"; set<int> skip; con->select(s.str().c_str()); while (!(row = con->getRow()).empty()) { int id = satoi(row[0]); //skip elements which are incomplete if(skip.find(id) != skip.end()) continue; SoilPMsPtr sps = spss[id]; if(!sps) { sps = SoilPMsPtr(new SoilPMs); spss[id] = sps; } int hcount = satoi(row[1]); int currenth = satoi(row[2]); int ho = sps->size() * lt; int hu = satof(row[4]) ? int(satof(row[4])*100) : maxDepth; int hsize = hu - ho; int subhcount = int(Tools::round(double(hsize) / double(lt)));//std::floor(double(hsize) / double(lt)); if (currenth == hcount && (int(sps->size()) + subhcount) < maxNoOfLayers) subhcount += maxNoOfLayers - sps->size() - subhcount; SoilParameters p; p.set_vs_SoilOrganicCarbon(humus_st2corg(satoi(row[5])) / 100.0); double clayPercent = satof(row[8]); p.set_vs_SoilRawDensity(ld_eff2trd(satoi(row[6]), clayPercent / 100.0)); p.vs_SoilSandContent = satof(row[7]) / 100.0; p.vs_SoilClayContent = clayPercent / 100.0; p.vs_SoilTexture = texture2KA5(p.vs_SoilSandContent, p.vs_SoilClayContent); p.vs_SoilStoneContent = 0.0; p.vs_Lambda = texture2lambda(p.vs_SoilSandContent, p.vs_SoilClayContent); // initialization of saturation, field capacity and perm. wilting point soilCharacteristicsKA5(p); if(!p.isValid()) { skip.insert(id); cout << "Error in soil parameters. Skipping bk50Id: " << id << endl; spss.erase(id); continue; } for (int i = 0; i < subhcount; i++) sps->push_back(p); } initialized = true; // BOOST_FOREACH(Map::value_type p, spss) // { // cout << "bk50Id: " << p.first << endl; // BOOST_FOREACH(const SoilParameters& sps, *(p.second.get())) // { // cout << sps.toString() << endl; // } // cout << "---------------------------------" << endl; // } } } Map::const_iterator ci = spss.find(bk50GridId); return ci != spss.end() ? ci->second.get() : &nothing; } /** * @brief Returns soil parameter of weisseritz * @param bk50GridId * @param gps General parameters * @return Soil parameters */ const SoilPMs* Monica::bk50SoilParameters(int bk50GridId, const GeneralParameters& gps, bool loadSingleParameter) { static SoilPMs nothing; int lt = int(gps.ps_LayerThickness.front() * 100); //cm int maxDepth = int(gps.ps_ProfileDepth) * 100; //cm int maxNoOfLayers = int(double(maxDepth) / double(lt)); static L lockable; typedef map<int, SoilPMsPtr> Map; static bool initialized = false; static Map spss; if(!initialized) { L::Lock lock(lockable); if (!initialized) { DBPtr con(newConnection("landcare-dss")); DBRow row; ostringstream s; s << "select bk.grid_id, bk.lower_depth_m, " "bk.humus_class, bk.ld_eff_class, w.s, w.t " "from bk50_sachsen_juli_2012 as bk inner join ka4wind as w on " "bk.ka4_soil_type = w.bodart "; if(loadSingleParameter) s << "where bk.grid_id = " << bk50GridId << " "; s << "order by bk.grid_id, bk.lower_depth_m"; ostringstream s2; s2 << "select grid_id, count(grid_id) " "from bk50_sachsen_juli_2012 " "group by grid_id"; con->select(s2.str().c_str()); map<int, int> id2layerCount; while (!(row = con->getRow()).empty()) id2layerCount[satoi(row[0])] = satoi(row[1]); con->freeResultSet(); set<int> skip; con->select(s.str().c_str()); int currenth = 0; while (!(row = con->getRow()).empty()) { int id = satoi(row[0]); //skip elements which are incomplete if(skip.find(id) != skip.end()) continue; SoilPMsPtr sps = spss[id]; if(!sps) { sps = SoilPMsPtr(new SoilPMs); spss[id] = sps; currenth = 0; } int hcount = id2layerCount[id]; currenth++; int ho = sps->size() * lt; int hu = int(satof(row[1])*100); int hsize = hu - ho; int subhcount = int(Tools::round(double(hsize) / double(lt)));//std::floor(double(hsize) / double(lt)); if (currenth == hcount && (int(sps->size()) + subhcount) < maxNoOfLayers) subhcount += maxNoOfLayers - sps->size() - subhcount; SoilParameters p; p.set_vs_SoilOrganicCarbon(humus_st2corg(satoi(row[2])) / 100.0); double clayPercent = satof(row[5]); p.set_vs_SoilRawDensity(ld_eff2trd(satoi(row[3]), clayPercent / 100.0)); p.vs_SoilSandContent = satof(row[4]) / 100.0; p.vs_SoilClayContent = clayPercent / 100.0; p.vs_SoilTexture = texture2KA5(p.vs_SoilSandContent, p.vs_SoilClayContent); p.vs_SoilStoneContent = 0.0; p.vs_Lambda = texture2lambda(p.vs_SoilSandContent, p.vs_SoilClayContent); // initialization of saturation, field capacity and perm. wilting point soilCharacteristicsKA5(p); if(!p.isValid()) { skip.insert(id); cout << "Error in soil parameters. Skipping bk50Id: " << id << endl; spss.erase(id); continue; } for (int i = 0; i < subhcount; i++) sps->push_back(p); } initialized = true; // BOOST_FOREACH(Map::value_type p, spss) // { // cout << "bk50Id: " << p.first << endl; // BOOST_FOREACH(const SoilParameters& sps, *(p.second.get())) // { // cout << sps.toString() << endl; // } // cout << "---------------------------------" << endl; // } } } Map::const_iterator ci = spss.find(bk50GridId); return ci != spss.end() ? ci->second.get() : &nothing; } string Monica::bk50GridId2ST(int bk50GridId) { static L lockable; typedef map<int, string> Map; static Map m; static bool initialized = false; if (!initialized) { L::Lock lock(lockable); if (!initialized) { DBPtr con(newConnection("landcare-dss")); con->setCharacterSet("utf8"); DBRow row; con->select("SELECT grid_id, st from bk50 where st is not null"); while (!(row = con->getRow()).empty()) m[satoi(row[0])] = row[1]; initialized = true; } } Map::const_iterator ci = m.find(bk50GridId); return ci != m.end() ? ci->second : "ST unbekannt"; } string Monica::bk50GridId2KA4Layers(int bk50GridId) { static L lockable; typedef map<int, string> Map; static Map m; static bool initialized = false; if (!initialized) { L::Lock lock(lockable); if (!initialized) { DBPtr con(newConnection("landcare-dss")); con->setCharacterSet("utf8"); DBRow row; con->select("SELECT grid_id, ka4_soil_type " "from bk50_sachsen_juli_2012 " "order by grid_id, lower_depth_m"); while (!(row = con->getRow()).empty()) { string pre = m[satoi(row[0])].empty() ? "" : "|"; m[satoi(row[0])].append(pre).append(row[1]); } initialized = true; } } Map::const_iterator ci = m.find(bk50GridId); return ci != m.end() ? ci->second : "Kein Bodenprofil vorhanden!"; } const SoilPMs* Monica::soilParametersFromHermesFile(int soilId, const string& pathToFile, const GeneralParameters& gps, double soil_ph) { debug() << pathToFile.c_str() << endl; int lt = int(gps.ps_LayerThickness.front() * 100); //cm int maxDepth = int(gps.ps_ProfileDepth) * 100; //cm int maxNoOfLayers = int(double(maxDepth) / double(lt)); static L lockable; typedef map<int, SoilPMsPtr> Map; static bool initialized = false; static Map spss; if (!initialized) { L::Lock lock(lockable); if (!initialized) { ifstream ifs(pathToFile.c_str(), ios::binary); string s; //skip first line(s) getline(ifs, s); int currenth = 1; while (getline(ifs, s)) { // cout << "s: " << s << endl; if (trim(s) == "end") break; //BdID Corg Bart UKT LD Stn C/N C/S Hy Wmx AzHo int ti; string ba, ts; int id, hu, ld, stone, cn, hcount; double corg, wmax; istringstream ss(s); ss >> id >> corg >> ba >> hu >> ld >> stone >> cn >> ts >> ti >> wmax >> hcount; //double vs_SoilSpecificMaxRootingDepth = wmax / 10.0; //[dm] --> [m] hu *= 10; //reset horizont count to start new soil definition if (hcount > 0) currenth = 1; Map::iterator spsi = spss.find(soilId); SoilPMsPtr sps; if (spsi == spss.end()) { spss.insert(make_pair(soilId, sps = SoilPMsPtr(new SoilPMs))); } else { sps = spsi->second; } int ho = sps->size() * lt; int hsize = hu - ho; int subhcount = int(Tools::round(double(hsize) / double(lt)));//std::floor(double(hsize) / double(lt)); if (currenth == hcount && (int(sps->size()) + subhcount) < maxNoOfLayers) subhcount += maxNoOfLayers - sps->size() - subhcount; if ((ba != "Ss") && (ba != "Sl2") && (ba != "Sl3") && (ba != "Sl4") && (ba != "Slu") && (ba != "St2") && (ba != "St3") && (ba != "Su2") && (ba != "Su3") && (ba != "Su4") && (ba != "Ls2") && (ba != "Ls3") && (ba != "Ls4") && (ba != "Lt2") && (ba != "Lt3") && (ba != "Lts") && (ba != "Lu") && (ba != "Uu") && (ba != "Uls") && (ba != "Us") && (ba != "Ut2") && (ba != "Ut3") && (ba != "Ut4") && (ba != "Tt") && (ba != "Tl") && (ba != "Tu2") && (ba != "Tu3") && (ba != "Tu4") && (ba != "Ts2") && (ba != "Ts3") && (ba != "Ts4") && (ba != "fS") && (ba != "fS") && (ba != "fSms") && (ba != "fSgs") && (ba != "mS") && (ba != "mSfs") && (ba != "mSgs") && (ba != "gS")){ cerr << "no valid texture class defined" << endl; exit(1); } SoilParameters p; // cout << "Bodenart:\t" << ba << "\tld: " << ld << endl; p.set_vs_SoilOrganicCarbon(corg / 100.0); p.set_vs_SoilRawDensity(ld_eff2trd(ld, KA52clay(ba))); p.vs_SoilSandContent = KA52sand(ba); p.vs_SoilClayContent = KA52clay(ba); p.vs_SoilStoneContent = stone / 100.0; p.vs_Lambda = texture2lambda(p.vs_SoilSandContent, p.vs_SoilClayContent); p.vs_SoilTexture = ba; if (soil_ph != -1.0) { p.vs_SoilpH = soil_ph; } // initialization of saturation, field capacity and perm. wilting point soilCharacteristicsKA5(p); // cout << p.toString() << endl; bool valid_soil_params = p.isValid(); if (!valid_soil_params) { cout << "Error in soil parameters. Aborting now simulation"; exit(-1); } for (int i = 0; i < subhcount; i++) sps->push_back(p); // cout << "sps: " << sps->size() << endl; currenth++; } initialized = true; // // for (Map::const_iterator it = spss.begin(); it != spss.end(); it++) { // cout << "code: " << it->first << endl; // for (vector<SoilParameters>::const_iterator it2 = it->second->begin(); it2 != it->second->end(); it2++) // cout << it2->toString(); // cout << "---------------------------------" << endl; // } } } static SoilPMs nothing; Map::const_iterator ci = spss.find(soilId); return ci != spss.end() ? ci->second.get() : &nothing; } //------------------------------------------------------------------------------ void Monica::soilCharacteristicsKA5(SoilParameters& soilParameter) { debug() << "soilCharacteristicsKA5" << endl; std::string vs_SoilTexture = soilParameter.vs_SoilTexture; double vs_SoilStoneContent = soilParameter.vs_SoilStoneContent; double vs_FieldCapacity; double vs_Saturation; double vs_PermanentWiltingPoint; if (vs_SoilTexture != "") { double vs_SoilRawDensity = soilParameter.vs_SoilRawDensity() / 1000.0; // [kg m-3] -> [g cm-3] double vs_SoilOrganicMatter = soilParameter.vs_SoilOrganicMatter() * 100.0; // [kg kg-1] -> [%] // *************************************************************************** // *** The following boundaries are extracted from: *** // *** Wessolek, G., M. Kaupenjohann, M. Renger (2009) Bodenphysikalische *** // *** Kennwerte und Berechnungsverfahren für die Praxis. Bodenökologie *** // *** und Bodengenese 40, Selbstverlag Technische Universität Berlin *** // *** (Tab. 4). *** // *************************************************************************** double vs_SoilRawDensityLowerBoundary=0.0; double vs_SoilRawDensityUpperBoundary=0.0; if (vs_SoilRawDensity < 1.1) { vs_SoilRawDensityLowerBoundary = 1.1; vs_SoilRawDensityUpperBoundary = 1.1; } else if ((vs_SoilRawDensity >= 1.1) && (vs_SoilRawDensity < 1.3)) { vs_SoilRawDensityLowerBoundary = 1.1; vs_SoilRawDensityUpperBoundary = 1.3; } else if ((vs_SoilRawDensity >= 1.3) && (vs_SoilRawDensity < 1.5)) { vs_SoilRawDensityLowerBoundary = 1.3; vs_SoilRawDensityUpperBoundary = 1.5; } else if ((vs_SoilRawDensity >= 1.5) && (vs_SoilRawDensity < 1.7)) { vs_SoilRawDensityLowerBoundary = 1.5; vs_SoilRawDensityUpperBoundary = 1.7; } else if ((vs_SoilRawDensity >= 1.7) && (vs_SoilRawDensity < 1.9)) { vs_SoilRawDensityLowerBoundary = 1.7; vs_SoilRawDensityUpperBoundary = 1.9; } else if (vs_SoilRawDensity >= 1.9) { vs_SoilRawDensityLowerBoundary = 1.9; vs_SoilRawDensityUpperBoundary = 1.9; } // special treatment for "torf" soils if (vs_SoilTexture=="Hh" || vs_SoilTexture=="Hn") { vs_SoilRawDensityLowerBoundary = -1; vs_SoilRawDensityUpperBoundary = -1; } // Boundaries for linear interpolation double vs_FieldCapacityLowerBoundary = 0.0; double vs_FieldCapacityUpperBoundary = 0.0; double vs_SaturationLowerBoundary = 0.0; double vs_SaturationUpperBoundary = 0.0; double vs_PermanentWiltingPointLowerBoundary = 0.0; double vs_PermanentWiltingPointUpperBoundary = 0.0; readPrincipalSoilCharacteristicData(vs_SoilTexture, vs_SoilRawDensityLowerBoundary, vs_SaturationLowerBoundary, vs_FieldCapacityLowerBoundary, vs_PermanentWiltingPointLowerBoundary); readPrincipalSoilCharacteristicData(vs_SoilTexture, vs_SoilRawDensityUpperBoundary, vs_SaturationUpperBoundary, vs_FieldCapacityUpperBoundary, vs_PermanentWiltingPointUpperBoundary); // cout << "Soil Raw Density:\t" << vs_SoilRawDensity << endl; // cout << "Saturation:\t\t" << vs_SaturationLowerBoundary << "\t" << vs_SaturationUpperBoundary << endl; // cout << "Field Capacity:\t" << vs_FieldCapacityLowerBoundary << "\t" << vs_FieldCapacityUpperBoundary << endl; // cout << "PermanentWP:\t" << vs_PermanentWiltingPointLowerBoundary << "\t" << vs_PermanentWiltingPointUpperBoundary << endl; // cout << "Soil Organic Matter:\t" << vs_SoilOrganicMatter << endl; // *************************************************************************** // *** The following boundaries are extracted from: *** // *** Wessolek, G., M. Kaupenjohann, M. Renger (2009) Bodenphysikalische *** // *** Kennwerte und Berechnungsverfahren für die Praxis. Bodenökologie *** // *** und Bodengenese 40, Selbstverlag Technische Universität Berlin *** // *** (Tab. 5). *** // *************************************************************************** double vs_SoilOrganicMatterLowerBoundary=0.0; double vs_SoilOrganicMatterUpperBoundary=0.0; if ((vs_SoilOrganicMatter >= 0.0) && (vs_SoilOrganicMatter < 1.0)) { vs_SoilOrganicMatterLowerBoundary = 0.0; vs_SoilOrganicMatterUpperBoundary = 0.0; } else if ((vs_SoilOrganicMatter >= 1.0) && (vs_SoilOrganicMatter < 1.5)) { vs_SoilOrganicMatterLowerBoundary = 0.0; vs_SoilOrganicMatterUpperBoundary = 1.5; } else if ((vs_SoilOrganicMatter >= 1.5) && (vs_SoilOrganicMatter < 3.0)) { vs_SoilOrganicMatterLowerBoundary = 1.5; vs_SoilOrganicMatterUpperBoundary = 3.0; } else if ((vs_SoilOrganicMatter >= 3.0) && (vs_SoilOrganicMatter < 6.0)) { vs_SoilOrganicMatterLowerBoundary = 3.0; vs_SoilOrganicMatterUpperBoundary = 6.0; } else if ((vs_SoilOrganicMatter >= 6.0) && (vs_SoilOrganicMatter < 11.5)) { vs_SoilOrganicMatterLowerBoundary = 6.0; vs_SoilOrganicMatterUpperBoundary = 11.5; } else if (vs_SoilOrganicMatter >= 11.5) { vs_SoilOrganicMatterLowerBoundary = 11.5; vs_SoilOrganicMatterUpperBoundary = 11.5; } // special treatment for "torf" soils if (vs_SoilTexture=="Hh" || vs_SoilTexture=="Hn") { vs_SoilOrganicMatterLowerBoundary = 0.0; vs_SoilOrganicMatterUpperBoundary = 0.0; } // Boundaries for linear interpolation double vs_FieldCapacityModifierLowerBoundary = 0.0; double vs_SaturationModifierLowerBoundary = 0.0; double vs_PermanentWiltingPointModifierLowerBoundary = 0.0; double vs_FieldCapacityModifierUpperBoundary = 0.0; double vs_SaturationModifierUpperBoundary = 0.0; double vs_PermanentWiltingPointModifierUpperBoundary = 0.0; // modifier values are given only for organic matter > 1.0% (class h2) if (vs_SoilOrganicMatterLowerBoundary != 0.0) { readSoilCharacteristicModifier(vs_SoilTexture, vs_SoilOrganicMatterLowerBoundary, vs_SaturationModifierLowerBoundary, vs_FieldCapacityModifierLowerBoundary, vs_PermanentWiltingPointModifierLowerBoundary); } else { vs_SaturationModifierLowerBoundary = 0.0; vs_FieldCapacityModifierLowerBoundary = 0.0; vs_PermanentWiltingPointModifierLowerBoundary = 0.0; } if (vs_SoilOrganicMatterUpperBoundary != 0.0) { readSoilCharacteristicModifier(vs_SoilTexture, vs_SoilOrganicMatterUpperBoundary, vs_SaturationModifierUpperBoundary, vs_FieldCapacityModifierUpperBoundary, vs_PermanentWiltingPointModifierUpperBoundary); } else { vs_SaturationModifierUpperBoundary = 0.0; vs_FieldCapacityModifierUpperBoundary = 0.0; vs_PermanentWiltingPointModifierUpperBoundary = 0.0; } // cout << "Saturation-Modifier:\t" << vs_SaturationModifierLowerBoundary << "\t" << vs_SaturationModifierUpperBoundary << endl; // cout << "Field capacity-Modifier:\t" << vs_FieldCapacityModifierLowerBoundary << "\t" << vs_FieldCapacityModifierUpperBoundary << endl; // cout << "PWP-Modifier:\t" << vs_PermanentWiltingPointModifierLowerBoundary << "\t" << vs_PermanentWiltingPointModifierUpperBoundary << endl; // Linear interpolation double vs_FieldCapacityUnmodified; double vs_SaturationUnmodified; double vs_PermanentWiltingPointUnmodified; if ((vs_FieldCapacityUpperBoundary < 0.5) && (vs_FieldCapacityLowerBoundary >= 1.0)) { vs_FieldCapacityUnmodified = vs_FieldCapacityLowerBoundary; } else if ((vs_FieldCapacityLowerBoundary < 0.5) && (vs_FieldCapacityUpperBoundary >= 1.0)) { vs_FieldCapacityUnmodified = vs_FieldCapacityUpperBoundary; } else if (vs_SoilRawDensityUpperBoundary != vs_SoilRawDensityLowerBoundary) { vs_FieldCapacityUnmodified = (vs_SoilRawDensity - vs_SoilRawDensityLowerBoundary) / (vs_SoilRawDensityUpperBoundary - vs_SoilRawDensityLowerBoundary) * (vs_FieldCapacityUpperBoundary - vs_FieldCapacityLowerBoundary) + vs_FieldCapacityLowerBoundary; } else { vs_FieldCapacityUnmodified = vs_FieldCapacityLowerBoundary; } if ((vs_SaturationUpperBoundary < 0.5) && (vs_SaturationLowerBoundary >= 1.0)) { vs_SaturationUnmodified = vs_SaturationLowerBoundary; } else if ((vs_SaturationLowerBoundary < 0.5) && (vs_SaturationUpperBoundary >= 1.0)) { vs_SaturationUnmodified = vs_SaturationUpperBoundary; } else if (vs_SoilRawDensityUpperBoundary != vs_SoilRawDensityLowerBoundary) { vs_SaturationUnmodified = (vs_SoilRawDensity - vs_SoilRawDensityLowerBoundary) / (vs_SoilRawDensityUpperBoundary - vs_SoilRawDensityLowerBoundary) * (vs_SaturationUpperBoundary - vs_SaturationLowerBoundary) + vs_SaturationLowerBoundary; } else { vs_SaturationUnmodified = vs_SaturationLowerBoundary; } if ((vs_PermanentWiltingPointUpperBoundary < 0.5) && (vs_PermanentWiltingPointLowerBoundary >= 1.0)) { vs_PermanentWiltingPointUnmodified = vs_PermanentWiltingPointLowerBoundary; } else if ((vs_PermanentWiltingPointLowerBoundary < 0.5) && (vs_PermanentWiltingPointUpperBoundary >= 1.0)) { vs_PermanentWiltingPointUnmodified = vs_PermanentWiltingPointUpperBoundary; } else if (vs_SoilRawDensityUpperBoundary != vs_SoilRawDensityLowerBoundary) { vs_PermanentWiltingPointUnmodified = (vs_SoilRawDensity - vs_SoilRawDensityLowerBoundary) / (vs_SoilRawDensityUpperBoundary - vs_SoilRawDensityLowerBoundary) * (vs_PermanentWiltingPointUpperBoundary - vs_PermanentWiltingPointLowerBoundary) + vs_PermanentWiltingPointLowerBoundary; } else { vs_PermanentWiltingPointUnmodified = vs_PermanentWiltingPointLowerBoundary; } double vs_FieldCapacityModifier; double vs_SaturationModifier; double vs_PermanentWiltingPointModifier; if (vs_SoilOrganicMatterUpperBoundary != vs_SoilOrganicMatterLowerBoundary) { vs_FieldCapacityModifier = (vs_SoilOrganicMatter - vs_SoilOrganicMatterLowerBoundary) / (vs_SoilOrganicMatterUpperBoundary - vs_SoilOrganicMatterLowerBoundary) * (vs_FieldCapacityModifierUpperBoundary - vs_FieldCapacityModifierLowerBoundary) + vs_FieldCapacityModifierLowerBoundary; vs_SaturationModifier = (vs_SoilOrganicMatter - vs_SoilOrganicMatterLowerBoundary) / (vs_SoilOrganicMatterUpperBoundary - vs_SoilOrganicMatterLowerBoundary) * (vs_SaturationModifierUpperBoundary - vs_SaturationModifierLowerBoundary) + vs_SaturationModifierLowerBoundary; vs_PermanentWiltingPointModifier = (vs_SoilOrganicMatter - vs_SoilOrganicMatterLowerBoundary) / (vs_SoilOrganicMatterUpperBoundary - vs_SoilOrganicMatterLowerBoundary) * (vs_PermanentWiltingPointModifierUpperBoundary - vs_PermanentWiltingPointModifierLowerBoundary) + vs_PermanentWiltingPointModifierLowerBoundary; } else { vs_FieldCapacityModifier = vs_FieldCapacityModifierLowerBoundary; vs_SaturationModifier = vs_SaturationModifierLowerBoundary; vs_PermanentWiltingPointModifier = vs_PermanentWiltingPointModifierLowerBoundary; // in this case upper and lower boundary are equal, so doesn't matter. } // Modifying the principal values by organic matter vs_FieldCapacity = (vs_FieldCapacityUnmodified + vs_FieldCapacityModifier) / 100.0; // [m3 m-3] vs_Saturation = (vs_SaturationUnmodified + vs_SaturationModifier) / 100.0; // [m3 m-3] vs_PermanentWiltingPoint = (vs_PermanentWiltingPointUnmodified + vs_PermanentWiltingPointModifier) / 100.0; // [m3 m-3] // Modifying the principal values by stone content vs_FieldCapacity *= (1.0 - vs_SoilStoneContent); vs_Saturation *= (1.0 - vs_SoilStoneContent); vs_PermanentWiltingPoint *= (1.0 - vs_SoilStoneContent); } else { vs_FieldCapacity = 0.0; vs_Saturation = 0.0; vs_PermanentWiltingPoint = 0.0; } debug() << "vs_SoilTexture:\t\t\t" << vs_SoilTexture << endl; debug() << "vs_Saturation:\t\t\t" << vs_Saturation << endl; debug() << "vs_FieldCapacity:\t\t" << vs_FieldCapacity << endl; debug() << "vs_PermanentWiltingPoint:\t" << vs_PermanentWiltingPoint << endl << endl; soilParameter.vs_FieldCapacity = vs_FieldCapacity; soilParameter.vs_Saturation = vs_Saturation; soilParameter.vs_PermanentWiltingPoint = vs_PermanentWiltingPoint; } //------------------------------------------------------------------------------ string Crop::toString(bool detailed) const { ostringstream s; s << "id: " << id() << " name: " << name() << " seedDate: " << seedDate().toString() << " harvestDate: " << harvestDate().toString(); if (detailed) { s << endl << "CropParameters: " << endl << cropParameters()->toString() << endl << "ResidueParameters: " << endl << residueParameters()->toString() << endl; } return s.str(); } //------------------------------------------------------------------------------ void Crop::writeCropParameters(std::string path) { ofstream parameter_output_file; parameter_output_file.open((path + "crop_parameters-" + _name.c_str() + ".txt").c_str()); if (parameter_output_file.fail()){ debug() << "Could not write file\"" << (path + "crop_parameters-" + _name.c_str() + ".txt").c_str() << "\"" << endl; return; } parameter_output_file << _cropParams->toString().c_str(); parameter_output_file.close(); } //------------------------------------------------------------------------------ /** * Default constructor for mineral fertilisers * @return */ MineralFertiliserParameters::MineralFertiliserParameters() : vo_Carbamid(0), vo_NH4(0), vo_NO3(0) {} /** * Constructor for mineral fertilisers * @param name Name of fertiliser * @param carbamid Carbamid part of fertiliser * @param no3 Nitrat part of fertiliser. * @param nh4 Ammonium part of fertiliser. * @return */ MineralFertiliserParameters:: MineralFertiliserParameters(const std::string& name, double carbamid, double no3, double nh4) : name(name), vo_Carbamid(carbamid), vo_NH4(nh4), vo_NO3(no3) {} /** * @brief Serializes all object information into a string. * @return String with parameter information. */ string MineralFertiliserParameters::toString() const { ostringstream s; s << "name: " << name << " carbamid: " << vo_Carbamid << " NH4: " << vo_NH4 << " NO3: " << vo_NO3; return s.str(); } /** * @brief Reads mineral fertiliser parameters from monica DB * @param id of the fertiliser * @return mineral fertiliser parameters value object with values from database */ MineralFertiliserParameters Monica::getMineralFertiliserParametersFromMonicaDB(int id) { static L lockable; static bool initialized = false; static map<int, MineralFertiliserParameters> m; if (!initialized) { L::Lock lock(lockable); if (!initialized) { DB *con = newConnection("monica"); DBRow row; con->select("select id, name, no3, nh4, carbamid from mineral_fertilisers"); while (!(row = con->getRow()).empty()) { int id = satoi(row[0]); string name = row[1]; double no3 = satof(row[2]); double nh4 = satof(row[3]); double carbamid = satof(row[4]); m.insert(make_pair(id, MineralFertiliserParameters(name, carbamid, no3, nh4))); } delete con; initialized = true; } } map<int, MineralFertiliserParameters>::const_iterator ci = m.find(id); return ci != m.end() ? ci->second : MineralFertiliserParameters(); } std::vector<ProductionProcess> Monica::attachFertiliserSA(std::vector<ProductionProcess> cropRotation, const std::string pathToFertiliserFile) { attachFertiliserApplicationsToCropRotation(cropRotation, pathToFertiliserFile); return cropRotation; } void Monica::attachFertiliserApplicationsToCropRotation(std::vector<ProductionProcess>& cr, const std::string& pathToFile) { ifstream ifs(pathToFile.c_str(), ios::binary); string s; std::vector<ProductionProcess>::iterator it = cr.begin(); if (it == cr.end()) return; //skip first line getline(ifs, s); Date currentEnd = it->end(); while (getline(ifs, s)) { if (trim(s) == "end") break; //Schlag_ID N FRT Date double sid; double n; string frt; string sfdate; bool incorp; istringstream ss(s); ss >> sid >> n >> frt >> sfdate >> incorp; //get data parsed and to use leap years if the crop rotation uses them Date fdate = parseDate(sfdate).toDate(it->crop()->seedDate().useLeapYears()); if (!fdate.isValid()) { debug() << "Error - Invalid date in \"" << pathToFile.c_str() << "\"" << endl; debug() << "Line: " << s.c_str() << endl; debug() << "Aborting simulation now!" << endl; exit(-1); } //cout << "PP start: " << it->start().toString() //<< " PP end: " << it->end().toString() << endl; //cout << "fdate: " << fdate.toString() //<< " currentEnd: " << currentEnd.toString() << endl; //if the currently read fertiliser date is after the current end //of the crop, move as long through the crop rotation as //we find an end date that lies after the currently read fertiliser date while (fdate > currentEnd) { //move to next crop and possibly exit at the end it++; if (it == cr.end()) break; currentEnd = it->end(); //cout << "new PP start: " << it->start().toString() //<< " new PP end: " << it->end().toString() << endl; //cout << "new currentEnd: " << currentEnd.toString() << endl; } //which type and id is the current fertiliser pair<FertiliserType, int> fertTypeAndId = hermesFertiliserName2monicaFertiliserId(frt); switch (fertTypeAndId.first) { case mineral: { //create mineral fertiliser application const MineralFertiliserParameters& mfp = getMineralFertiliserParametersFromMonicaDB(fertTypeAndId.second); it->addApplication(MineralFertiliserApplication(fdate, mfp, n)); break; } case organic: { //create organic fertiliser application OrganicMatterParameters* omp = getOrganicFertiliserParametersFromMonicaDB(fertTypeAndId.second); it->addApplication(OrganicFertiliserApplication(fdate, omp, n, incorp)); break; } case undefined: { break; } } //cout << "----------------------------------" << endl; } } //------------------------------------------------------------------------------ void Monica::attachIrrigationApplicationsToCropRotation(std::vector<ProductionProcess>& cr, const std::string& pathToFile) { ifstream ifs(pathToFile.c_str(), ios::in); if (!ifs.is_open()) { return; } string s; std::vector<ProductionProcess>::iterator it = cr.begin(); if (it == cr.end()) return; //skip first line getline(ifs, s); Date currentEnd = it->end(); while (getline(ifs, s)) { if (trim(s) == "end") break; //Field_ID mm SCc IrrDat NCc double fid; int mm; double scc; //sulfate concentration [mg dm-3] string irrDate; double ncc; //nitrate concentration [mg dm-3] istringstream ss(s); ss >> fid >> mm >> scc >> irrDate >> ncc; //get data parsed and to use leap years if the crop rotation uses them Date idate = parseDate(irrDate).toDate(it->crop()->seedDate().useLeapYears()); if (!idate.isValid()) { debug() << "Error - Invalid date in \"" << pathToFile.c_str() << "\"" << endl; debug() << "Line: " << s.c_str() << endl; debug() << "Aborting simulation now!" << endl; exit(-1); } //cout << "PP start: " << it->start().toString() //<< " PP end: " << it->end().toString() << endl; //cout << "irrigationDate: " << idate.toString() //<< " currentEnd: " << currentEnd.toString() << endl; //if the currently read irrigation date is after the current end //of the crop, move as long through the crop rotation as //we find an end date that lies after the currently read irrigation date while (idate > currentEnd) { //move to next crop and possibly exit at the end it++; if (it == cr.end()) break; currentEnd = it->end(); //cout << "new PP start: " << it->start().toString() //<< " new PP end: " << it->end().toString() << endl; //cout << "new currentEnd: " << currentEnd.toString() << endl; } //finally add the application to the current crops list it->addApplication(IrrigationApplication(idate, mm, IrrigationParameters(ncc, scc))); //cout << "----------------------------------" << endl; } } //------------------------------------------------------------------------------ /** * @brief Default constructor */ OrganicMatterParameters::OrganicMatterParameters() : name(""), vo_AOM_DryMatterContent(0.0), vo_AOM_NH4Content(0.0), vo_AOM_NO3Content(0.0), vo_AOM_CarbamidContent(0.0), vo_AOM_SlowDecCoeffStandard(0.0), vo_AOM_FastDecCoeffStandard(0.0), vo_PartAOM_to_AOM_Slow(0.0), vo_PartAOM_to_AOM_Fast(0.0), vo_CN_Ratio_AOM_Slow(0.0), vo_CN_Ratio_AOM_Fast(0.0), vo_PartAOM_Slow_to_SMB_Slow(0.0), vo_PartAOM_Slow_to_SMB_Fast(0.0), vo_NConcentration(0.0) {} OrganicMatterParameters::OrganicMatterParameters(const OrganicMatterParameters& omp) { this->vo_AOM_DryMatterContent = omp.vo_AOM_DryMatterContent; this->vo_AOM_NH4Content = omp.vo_AOM_NH4Content; this->vo_AOM_NO3Content = omp.vo_AOM_NO3Content; this->vo_AOM_CarbamidContent = omp.vo_AOM_CarbamidContent; this->vo_AOM_SlowDecCoeffStandard = omp.vo_AOM_SlowDecCoeffStandard; this->vo_AOM_FastDecCoeffStandard = omp.vo_AOM_FastDecCoeffStandard; this->vo_PartAOM_to_AOM_Slow = omp.vo_PartAOM_to_AOM_Slow; this->vo_PartAOM_to_AOM_Fast = omp.vo_PartAOM_to_AOM_Fast; this->vo_CN_Ratio_AOM_Slow = omp.vo_CN_Ratio_AOM_Slow; this->vo_CN_Ratio_AOM_Fast = omp.vo_CN_Ratio_AOM_Fast; this->vo_PartAOM_Slow_to_SMB_Slow = omp.vo_PartAOM_Slow_to_SMB_Slow; this->vo_PartAOM_Slow_to_SMB_Fast = omp.vo_PartAOM_Slow_to_SMB_Fast; this->vo_NConcentration = omp.vo_NConcentration; } /** * @brief Serializes all object information into a string. * @return String with parameter information. */ string OrganicMatterParameters::toString() const { ostringstream s; s << "Name: " << name << endl << "vo_NConcentration: " << vo_NConcentration << endl << "vo_DryMatter: " << vo_AOM_DryMatterContent << endl << "vo_NH4: " << vo_AOM_NH4Content << endl << "vo_NO3: " << vo_AOM_NO3Content << endl << "vo_NH2: " << vo_AOM_CarbamidContent << endl << "vo_kSlow: " << vo_AOM_SlowDecCoeffStandard << endl << "vo_kFast: " << vo_AOM_FastDecCoeffStandard << endl << "vo_PartSlow: " << vo_PartAOM_to_AOM_Slow << endl << "vo_PartFast: " << vo_PartAOM_to_AOM_Fast << endl << "vo_CNSlow: " << vo_CN_Ratio_AOM_Slow << endl << "vo_CNFast: " << vo_CN_Ratio_AOM_Fast << endl << "vo_SMBSlow: " << vo_PartAOM_Slow_to_SMB_Slow << endl << "vo_SMBFast: " << vo_PartAOM_Slow_to_SMB_Fast << endl; return s.str(); } /** * @brief Reads organic fertiliser parameters from monica DB * @param organ_fert_id ID of fertiliser * @return organic fertiliser parameters with values from database */ OrganicMatterParameters* Monica::getOrganicFertiliserParametersFromMonicaDB(int id) { static L lockable; static bool initialized = false; typedef map<int, OMPPtr> Map; static Map m; if (!initialized) { L::Lock lock(lockable); if (!initialized) { DB *con = newConnection("monica"); DBRow row; con->select("select om_Type, dm, nh4_n, no3_n, nh2_n, k_slow, k_fast, part_s, " "part_f, cn_s, cn_f, smb_s, smb_f, id " "from organic_fertiliser"); while (!(row = con->getRow()).empty()) { auto omp = OMPPtr(new OMP); omp->name = row[0]; omp->vo_AOM_DryMatterContent = satof(row[1]); omp->vo_AOM_NH4Content = satof(row[2]); omp->vo_AOM_NO3Content = satof(row[3]); omp->vo_AOM_CarbamidContent = satof(row[4]); omp->vo_AOM_SlowDecCoeffStandard = satof(row[5]); omp->vo_AOM_FastDecCoeffStandard = satof(row[6]); omp->vo_PartAOM_to_AOM_Slow = satof(row[7]); omp->vo_PartAOM_to_AOM_Fast = satof(row[8]); omp->vo_CN_Ratio_AOM_Slow = satof(row[9]); omp->vo_CN_Ratio_AOM_Fast = satof(row[10]); omp->vo_PartAOM_Slow_to_SMB_Slow = satof(row[11]); omp->vo_PartAOM_Slow_to_SMB_Fast = satof(row[12]); int id = satoi(row[13]); m.insert(make_pair(id, omp)); } delete con; initialized = true; } } static OrganicMatterParameters nothing; Map::const_iterator ci = m.find(id); return ci != m.end() ? ci->second.get() : &nothing; } /* ResidueParameters::ResidueParameters() : vo_AOM_DryMatterContent(0.289), vo_AOM_NH4Content(0.007), vo_AOM_NO3Content(0.0), vo_AOM_CarbamidContent(0.0), vo_AOM_SlowDecCoeffStandard(2.0e-4), vo_AOM_FastDecCoeffStandard(2.0e-3), vo_PartAOM_to_AOM_Slow(0.72), vo_PartAOM_to_AOM_Fast(0.18), vo_CN_Ratio_AOM_Slow(100.0), vo_CN_Ratio_AOM_Fast(7.3), vo_PartAOM_Slow_to_SMB_Slow(0.0), vo_PartAOM_Slow_to_SMB_Fast(1.0) { } */ /** * @brief Reads residue parameters from monica DB * @param crop_id ID of crop * @return Residues parameters with values from database */ const OrganicMatterParameters* Monica::getResidueParametersFromMonicaDB(int cropId) { static L lockable; static bool initialized = false; typedef map<int, OMPPtr> Map; static Map m; if (!initialized) { L::Lock lock(lockable); if (!initialized) { DB *con = newConnection("monica"); DBRow row; con->select("select residue_type, dm, nh4, no3, nh2, k_slow, k_fast, part_s, " "part_f, cn_s, cn_f, smb_s, smb_f, crop_id " "from residue_table"); while (!(row = con->getRow()).empty()) { auto omp = OMPPtr(new OMP); omp->name = row[0]; omp->vo_AOM_DryMatterContent = satoi(row[1]); omp->vo_AOM_NH4Content = satof(row[2]); omp->vo_AOM_NO3Content = satof(row[3]); omp->vo_AOM_CarbamidContent = satof(row[4]); omp->vo_AOM_SlowDecCoeffStandard = satof(row[5]); omp->vo_AOM_FastDecCoeffStandard = satof(row[6]); omp->vo_PartAOM_to_AOM_Slow = satof(row[7]); omp->vo_PartAOM_to_AOM_Fast = satof(row[8]); omp->vo_CN_Ratio_AOM_Slow = satof(row[9]); omp->vo_CN_Ratio_AOM_Fast = satof(row[10]); omp->vo_PartAOM_Slow_to_SMB_Slow = satof(row[11]); omp->vo_PartAOM_Slow_to_SMB_Fast = satof(row[12]); int id = satoi(row[13]); m.insert(make_pair(id, omp)); } delete con; initialized = true; } } static OrganicMatterParameters nothing; Map::const_iterator ci = m.find(cropId); return ci != m.end() ? ci->second.get() : &nothing; } //------------------------------------------------------------------------------ /** * @brief Constructor */ CentralParameterProvider::CentralParameterProvider() { for (int i=0; i<MONTH; i++) { precipCorrectionValues[i] = 1.0; } writeOutputFiles = false; } /** * Copy constructor * @param * @return */ CentralParameterProvider:: CentralParameterProvider(const CentralParameterProvider& cpp) { userCropParameters = cpp.userCropParameters; userEnvironmentParameters = cpp.userEnvironmentParameters; userSoilMoistureParameters = cpp.userSoilMoistureParameters; userSoilTemperatureParameters = cpp.userSoilTemperatureParameters; userSoilTransportParameters = cpp.userSoilTransportParameters; userSoilOrganicParameters = cpp.userSoilOrganicParameters; sensitivityAnalysisParameters = cpp.sensitivityAnalysisParameters; capillaryRiseRates = cpp.capillaryRiseRates; userInitValues = cpp.userInitValues; for (int i=0; i<12; i++) precipCorrectionValues[i] = cpp.precipCorrectionValues[i]; } /** * @brief Returns a precipitation correction value for a specific month. * @param month Month * @return Correction value that should be applied to precipitation value read from database. */ double CentralParameterProvider::getPrecipCorrectionValue(int month) const { assert(month<12); assert(month>=0); if (month<12) { return precipCorrectionValues[month]; } cerr << "Requested correction value for precipitation for an invalid month.\nMust be in range of 0<=value<12." << endl; return 1.0; } /** * Sets a correction value for a specific month. * @param month Month the value should be used for. * @param value Correction value that should be added. */ void CentralParameterProvider::setPrecipCorrectionValue(int month, double value) { assert(month<12); assert(month>=0); precipCorrectionValues[month]=value; // debug // cout << "Added precip correction value for month " << month << ":\t " << value << endl; } // -------------------------------------------------------------------- CentralParameterProvider Monica::readUserParameterFromDatabase(int type) { static L lockable; static bool initialized = false; static CentralParameterProvider centralParameterProvider; if (!initialized) { L::Lock lock(lockable); if (!initialized) { debug() << "DB Conncection user parameters" << endl; DB *con = newConnection("monica"); DBRow row; switch (type) { case Env::MODE_HERMES: con->select("select name, value_hermes from user_parameter"); break; case Env::MODE_EVA2: con->select("select name, value_eva2 from user_parameter"); break; default: con->select("select name, value_hermes from user_parameter"); break; } UserCropParameters& user_crops = centralParameterProvider.userCropParameters; UserEnvironmentParameters& user_env = centralParameterProvider.userEnvironmentParameters; UserSoilMoistureParameters& user_soil_moisture = centralParameterProvider.userSoilMoistureParameters; UserSoilTemperatureParameters& user_soil_temperature = centralParameterProvider.userSoilTemperatureParameters; UserSoilTransportParameters& user_soil_transport = centralParameterProvider.userSoilTransportParameters; UserSoilOrganicParameters& user_soil_organic = centralParameterProvider.userSoilOrganicParameters; UserInitialValues& user_init_values = centralParameterProvider.userInitValues; while (!(row = con->getRow()).empty()) { std::string name = row[0]; if (name == "tortuosity") user_crops.pc_Tortuosity = satof(row[1]); else if (name == "canopy_reflection_coefficient") user_crops.pc_CanopyReflectionCoefficient = satof(row[1]); else if (name == "reference_max_assimilation_rate") user_crops.pc_ReferenceMaxAssimilationRate = satof(row[1]); else if (name == "reference_leaf_area_index") user_crops.pc_ReferenceLeafAreaIndex = satof(row[1]); else if (name == "maintenance_respiration_parameter_2") user_crops.pc_MaintenanceRespirationParameter2 = satof(row[1]); else if (name == "maintenance_respiration_parameter_1") user_crops.pc_MaintenanceRespirationParameter1 = satof(row[1]); else if (name == "minimum_n_concentration_root") user_crops.pc_MinimumNConcentrationRoot = satof(row[1]); else if (name == "minimum_available_n") user_crops.pc_MinimumAvailableN = satof(row[1]); else if (name == "reference_albedo") user_crops.pc_ReferenceAlbedo = satof(row[1]); else if (name == "stomata_conductance_alpha") user_crops.pc_StomataConductanceAlpha = satof(row[1]); else if (name == "saturation_beta") user_crops.pc_SaturationBeta = satof(row[1]); else if (name == "growth_respiration_redux") user_crops.pc_GrowthRespirationRedux = satof(row[1]); else if (name == "max_crop_n_demand") user_crops.pc_MaxCropNDemand = satof(row[1]); else if (name == "growth_respiration_parameter_2") user_crops.pc_GrowthRespirationParameter2 = satof(row[1]); else if (name == "growth_respiration_parameter_1") user_crops.pc_GrowthRespirationParameter1 = satof(row[1]); else if (name == "use_automatic_irrigation") user_env.p_UseAutomaticIrrigation = satoi(row[1]) == 1; else if (name == "use_nmin_mineral_fertilising_method") user_env.p_UseNMinMineralFertilisingMethod = satoi(row[1]) == 1; else if (name == "layer_thickness") user_env.p_LayerThickness = satof(row[1]); else if (name == "number_of_layers") user_env.p_NumberOfLayers = satoi(row[1]); else if (name == "start_pv_index") user_env.p_StartPVIndex = satoi(row[1]); else if (name == "albedo") user_env.p_Albedo = satof(row[1]); else if (name == "athmospheric_co2") user_env.p_AthmosphericCO2 = satof(row[1]); else if (name == "wind_speed_height") user_env.p_WindSpeedHeight = satof(row[1]); else if (name == "use_secondary_yields") user_env.p_UseSecondaryYields = satoi(row[1]) == 1; else if (name == "julian_day_automatic_fertilising") user_env.p_JulianDayAutomaticFertilising = satoi(row[1]); else if (name == "critical_moisture_depth") user_soil_moisture.pm_CriticalMoistureDepth = satof(row[1]); else if (name == "saturated_hydraulic_conductivity") user_soil_moisture.pm_SaturatedHydraulicConductivity = satof(row[1]); else if (name == "surface_roughness") user_soil_moisture.pm_SurfaceRoughness = satof(row[1]); else if (name == "hydraulic_conductivity_redux") user_soil_moisture.pm_HydraulicConductivityRedux = satof(row[1]); else if (name == "snow_accumulation_treshold_temperature") user_soil_moisture.pm_SnowAccumulationTresholdTemperature = satof(row[1]); else if (name == "kc_factor") user_soil_moisture.pm_KcFactor = satof(row[1]); else if (name == "time_step") user_env.p_timeStep = satof(row[1]); else if (name == "temperature_limit_for_liquid_water") user_soil_moisture.pm_TemperatureLimitForLiquidWater = satof(row[1]); else if (name == "correction_snow") user_soil_moisture.pm_CorrectionSnow = satof(row[1]); else if (name == "correction_rain") user_soil_moisture.pm_CorrectionRain = satof(row[1]); else if (name == "snow_max_additional_density") user_soil_moisture.pm_SnowMaxAdditionalDensity = satof(row[1]); else if (name == "new_snow_density_min") user_soil_moisture.pm_NewSnowDensityMin = satof(row[1]); else if (name == "snow_retention_capacity_min") user_soil_moisture.pm_SnowRetentionCapacityMin = satof(row[1]); else if (name == "refreeze_parameter_2") user_soil_moisture.pm_RefreezeParameter2 = satof(row[1]); else if (name == "refreeze_parameter_1") user_soil_moisture.pm_RefreezeParameter1 = satof(row[1]); else if (name == "refreeze_temperature") user_soil_moisture.pm_RefreezeTemperature = satof(row[1]); else if (name == "snowmelt_temperature") user_soil_moisture.pm_SnowMeltTemperature = satof(row[1]); else if (name == "snow_packing") user_soil_moisture.pm_SnowPacking = satof(row[1]); else if (name == "snow_retention_capacity_max") user_soil_moisture.pm_SnowRetentionCapacityMax = satof(row[1]); else if (name == "evaporation_zeta") user_soil_moisture.pm_EvaporationZeta = satof(row[1]); else if (name == "xsa_critical_soil_moisture") user_soil_moisture.pm_XSACriticalSoilMoisture = satof(row[1]); else if (name == "maximum_evaporation_impact_depth") user_soil_moisture.pm_MaximumEvaporationImpactDepth = satof(row[1]); else if (name == "ntau") user_soil_temperature.pt_NTau = satof(row[1]); else if (name == "initial_surface_temperature") user_soil_temperature.pt_InitialSurfaceTemperature = satof(row[1]); else if (name == "base_temperature") user_soil_temperature.pt_BaseTemperature = satof(row[1]); else if (name == "quartz_raw_density") user_soil_temperature.pt_QuartzRawDensity = satof(row[1]); else if (name == "density_air") user_soil_temperature.pt_DensityAir = satof(row[1]); else if (name == "density_water") user_soil_temperature.pt_DensityWater = satof(row[1]); else if (name == "specific_heat_capacity_air") user_soil_temperature.pt_SpecificHeatCapacityAir = satof(row[1]); else if (name == "specific_heat_capacity_quartz") user_soil_temperature.pt_SpecificHeatCapacityQuartz = satof(row[1]); else if (name == "specific_heat_capacity_water") user_soil_temperature.pt_SpecificHeatCapacityWater = satof(row[1]); else if (name == "soil_albedo") user_soil_temperature.pt_SoilAlbedo = satof(row[1]); else if (name == "dispersion_length") user_soil_transport.pq_DispersionLength = satof(row[1]); else if (name == "AD") user_soil_transport.pq_AD = satof(row[1]); else if (name == "diffusion_coefficient_standard") user_soil_transport.pq_DiffusionCoefficientStandard = satof(row[1]); else if (name == "leaching_depth") user_env.p_LeachingDepth = satof(row[1]); else if (name == "groundwater_discharge") user_soil_moisture.pm_GroundwaterDischarge = satof(row[1]); else if (name == "density_humus") user_soil_temperature.pt_DensityHumus = satof(row[1]); else if (name == "specific_heat_capacity_humus") user_soil_temperature.pt_SpecificHeatCapacityHumus = satof(row[1]); else if (name == "max_percolation_rate") user_soil_moisture.pm_MaxPercolationRate = satof(row[1]); else if (name == "max_groundwater_depth") user_env.p_MaxGroundwaterDepth = satof(row[1]); else if (name == "min_groundwater_depth") user_env.p_MinGroundwaterDepth = satof(row[1]); else if (name == "min_groundwater_depth_month") user_env.p_MinGroundwaterDepthMonth = satoi(row[1]); else if (name == "SOM_SlowDecCoeffStandard") user_soil_organic.po_SOM_SlowDecCoeffStandard = satof(row[1]); else if (name == "SOM_FastDecCoeffStandard") user_soil_organic.po_SOM_FastDecCoeffStandard = satof(row[1]); else if (name == "SMB_SlowMaintRateStandard") user_soil_organic.po_SMB_SlowMaintRateStandard = satof(row[1]); else if (name == "SMB_FastMaintRateStandard") user_soil_organic.po_SMB_FastMaintRateStandard = satof(row[1]); else if (name == "SMB_SlowDeathRateStandard") user_soil_organic.po_SMB_SlowDeathRateStandard = satof(row[1]); else if (name == "SMB_FastDeathRateStandard") user_soil_organic.po_SMB_FastDeathRateStandard = satof(row[1]); else if (name == "SMB_UtilizationEfficiency") user_soil_organic.po_SMB_UtilizationEfficiency = satof(row[1]); else if (name == "SOM_SlowUtilizationEfficiency") user_soil_organic.po_SOM_SlowUtilizationEfficiency = satof(row[1]); else if (name == "SOM_FastUtilizationEfficiency") user_soil_organic.po_SOM_FastUtilizationEfficiency = satof(row[1]); else if (name == "AOM_SlowUtilizationEfficiency") user_soil_organic.po_AOM_SlowUtilizationEfficiency = satof(row[1]); else if (name == "AOM_FastUtilizationEfficiency") user_soil_organic.po_AOM_FastUtilizationEfficiency = satof(row[1]); else if (name == "AOM_FastMaxC_to_N") user_soil_organic.po_AOM_FastMaxC_to_N = satof(row[1]); else if (name == "PartSOM_Fast_to_SOM_Slow") user_soil_organic.po_PartSOM_Fast_to_SOM_Slow = satof(row[1]); else if (name == "PartSMB_Slow_to_SOM_Fast") user_soil_organic.po_PartSMB_Slow_to_SOM_Fast = satof(row[1]); else if (name == "PartSMB_Fast_to_SOM_Fast") user_soil_organic.po_PartSMB_Fast_to_SOM_Fast = satof(row[1]); else if (name == "PartSOM_to_SMB_Slow") user_soil_organic.po_PartSOM_to_SMB_Slow = satof(row[1]); else if (name == "PartSOM_to_SMB_Fast") user_soil_organic.po_PartSOM_to_SMB_Fast = satof(row[1]); else if (name == "CN_Ratio_SMB") user_soil_organic.po_CN_Ratio_SMB = satof(row[1]); else if (name == "LimitClayEffect") user_soil_organic.po_LimitClayEffect = satof(row[1]); else if (name == "AmmoniaOxidationRateCoeffStandard") user_soil_organic.po_AmmoniaOxidationRateCoeffStandard = satof(row[1]); else if (name == "NitriteOxidationRateCoeffStandard") user_soil_organic.po_NitriteOxidationRateCoeffStandard = satof(row[1]); else if (name == "TransportRateCoeff") user_soil_organic.po_TransportRateCoeff = satof(row[1]); else if (name == "SpecAnaerobDenitrification") user_soil_organic.po_SpecAnaerobDenitrification = satof(row[1]); else if (name == "ImmobilisationRateCoeffNO3") user_soil_organic.po_ImmobilisationRateCoeffNO3 = satof(row[1]); else if (name == "ImmobilisationRateCoeffNH4") user_soil_organic.po_ImmobilisationRateCoeffNH4 = satof(row[1]); else if (name == "Denit1") user_soil_organic.po_Denit1 = satof(row[1]); else if (name == "Denit2") user_soil_organic.po_Denit2 = satof(row[1]); else if (name == "Denit3") user_soil_organic.po_Denit3 = satof(row[1]); else if (name == "HydrolysisKM") user_soil_organic.po_HydrolysisKM = satof(row[1]); else if (name == "ActivationEnergy") user_soil_organic.po_ActivationEnergy = satof(row[1]); else if (name == "HydrolysisP1") user_soil_organic.po_HydrolysisP1 = satof(row[1]); else if (name == "HydrolysisP2") user_soil_organic.po_HydrolysisP2 = satof(row[1]); else if (name == "AtmosphericResistance") user_soil_organic.po_AtmosphericResistance = satof(row[1]); else if (name == "N2OProductionRate") user_soil_organic.po_N2OProductionRate = satof(row[1]); else if (name == "Inhibitor_NH3") user_soil_organic.po_Inhibitor_NH3 = satof(row[1]); } delete con; initialized = true; centralParameterProvider.capillaryRiseRates = readCapillaryRiseRates(); } } return centralParameterProvider; } //---------------------------------------------------------------------------- namespace { struct X { double sat, fc, pwp; static int makeInt(double value) { return int(Tools::round(value, 1)*10); } }; void readXSoilCharacteristicY(std::string key1, double key2, double &sat, double &fc, double &pwp, string query) { static L lockable; typedef map<int, X> M1; typedef map<string, M1> M2; typedef map<string, M2> M3; static M3 m; static bool initialized = false; if(!initialized) { L::Lock lock(lockable); if(!initialized) { // read soil characteristic like air-, field- and n-field-capacity from monica database DB *con = newConnection("monica"); con->select(query.c_str()); debug() << endl << query.c_str() << endl; DBRow row; while (!(row = con->getRow()).empty()) { double ac = satof(row[2]); double fc = satof(row[3]); double nfc = satof(row[4]); int r = X::makeInt(satof(row[1])); X& x = m[query][row[0]][r]; x.sat = ac + fc; x.fc = fc; x.pwp = fc - nfc; } delete con; initialized = true; } } M3::const_iterator qci = m.find(query); if(qci != m.end()) { const M2& m2 = qci->second; M2::const_iterator ci = m2.find(key1); // debug () <<"key1 " << key1.c_str() << endl; if(ci != m2.end()) { const M1& m1 = ci->second; M1::const_iterator ci2 = m1.find(X::makeInt(key2)); // debug () <<"key2 " << key2 << endl; if(ci2 != m1.end()) { const X& x = ci2->second; sat = x.sat; fc = x.fc; pwp = x.pwp; return; } } } sat = 0; fc = 0; pwp = 0; } } void Monica::readPrincipalSoilCharacteristicData(std::string soil_type, double raw_density, double &sat, double &fc, double &pwp) { static const string query = "select soil_type, soil_raw_density, air_capacity, " "field_capacity, n_field_capacity " "from soil_characteristic_data"; return readXSoilCharacteristicY(soil_type, raw_density, sat, fc, pwp, query); } void Monica::readSoilCharacteristicModifier(std::string soil_type, double organic_matter, double &sat, double &fc, double &pwp) { static const string query = "select soil_type, organic_matter, air_capacity, " "field_capacity, n_field_capacity " "from soil_aggregation_values"; return readXSoilCharacteristicY(soil_type, organic_matter, sat, fc, pwp, query); } /** * Simple output of climate data stored in given data accessor. * @param climateData Data structure that stores climate data. */ void Monica::testClimateData(Climate::DataAccessor &climateData) { for (int i = 0, size = climateData.noOfStepsPossible(); i < size; i++) { double tmin = climateData.dataForTimestep(Climate::tmin, i); double tavg = climateData.dataForTimestep(Climate::tavg, i); double tmax = climateData.dataForTimestep(Climate::tmax, i); double precip = climateData.dataForTimestep(Climate::precip, i); double wind = climateData.dataForTimestep(Climate::wind, i); double globrad = climateData.dataForTimestep(Climate::globrad, i); double relhumid = climateData.dataForTimestep(Climate::relhumid, i); double sunhours = climateData.dataForTimestep(Climate::sunhours, i); debug() << "day: " << i << " tmin: " << tmin << " tavg: " << tavg << " tmax: " << tmax << " precip: " << precip << " wind: " << wind << " globrad: " << globrad << " relhumid: " << relhumid << " sunhours: " << sunhours << endl; } } /** * Check, if some parameters should be changed according to sensitivity analysis simulation. * Replace old parameters with new values from sensitivity analysis object * @param ff * @param centralParameterProvider * @return New crop rotation vector */ std::vector<ProductionProcess> Monica::applySAChanges(std::vector<ProductionProcess> ff, const CentralParameterProvider &centralParameterProvider) { // cout << "Apply SA values method" << endl; std::vector<ProductionProcess> new_ff; BOOST_FOREACH(ProductionProcess pp, ff) { CropPtr crop = pp.crop(); const SensitivityAnalysisParameters& saps = centralParameterProvider.sensitivityAnalysisParameters; if (saps.sa_crop_id != crop->id() && saps.sa_crop_id>0){ // cout << "Do not apply SA values" << endl; continue; } else { // cout << "CropIds: SA:\t"<< saps.sa_crop_id << "\tMONICA:\t" << crop->id() << endl; } CropParameters* cps = new CropParameters((*crop->cropParameters())); // pc_DaylengthRequirement if (saps.crop_parameters.pc_DaylengthRequirement.size() > 0) { std::vector<double> new_values; for (unsigned int i=0; i<cps->pc_DaylengthRequirement.size(); i++) { double sa_value = saps.crop_parameters.pc_DaylengthRequirement.at(i); double default_value = cps->pc_DaylengthRequirement.at(i); if (sa_value == -9999) { new_values.push_back(default_value); } else { new_values.push_back(sa_value); } } cps->pc_DaylengthRequirement = new_values; } // pc_VernalisationRequirement if (saps.crop_parameters.pc_VernalisationRequirement.size() > 0) { std::vector<double> new_values; for (unsigned int i=0; i<cps->pc_VernalisationRequirement.size(); i++) { double sa_value = saps.crop_parameters.pc_VernalisationRequirement.at(i); double default_value = cps->pc_VernalisationRequirement.at(i); if (sa_value == -9999) { new_values.push_back(default_value); } else { new_values.push_back(sa_value); } } cps->pc_VernalisationRequirement = new_values; } if (saps.crop_parameters.pc_CriticalOxygenContent.size() > 0) { std::vector<double> new_values; for (unsigned int i=0; i<cps->pc_CriticalOxygenContent.size(); i++) { double sa_value = saps.crop_parameters.pc_CriticalOxygenContent.at(i); double default_value = cps->pc_CriticalOxygenContent.at(i); if (sa_value == -9999) { new_values.push_back(default_value); } else { new_values.push_back(sa_value); } } cps->pc_CriticalOxygenContent = new_values; } if (saps.crop_parameters.pc_InitialKcFactor != UNDEFINED) { cps->pc_InitialKcFactor = saps.crop_parameters.pc_InitialKcFactor; } if (saps.crop_parameters.pc_StageKcFactor.size() > 0) { std::vector<double> new_values; for (unsigned int i=0; i<cps->pc_StageKcFactor.size(); i++) { double sa_value = saps.crop_parameters.pc_StageKcFactor.at(i); double default_value = cps->pc_StageKcFactor.at(i); if (sa_value == -9999) { new_values.push_back(default_value); } else { new_values.push_back(sa_value); } } cps->pc_StageKcFactor = new_values; } // pc_StageAtMaxHeight if (saps.crop_parameters.pc_StageAtMaxHeight != UNDEFINED) { cps->pc_StageAtMaxHeight = saps.crop_parameters.pc_StageAtMaxHeight; } if (saps.crop_parameters.pc_CropHeightP1 != UNDEFINED) { cps->pc_CropHeightP1 = saps.crop_parameters.pc_CropHeightP1; } // pc_CropHeightP2 if (saps.crop_parameters.pc_CropHeightP2 != UNDEFINED) { cps->pc_CropHeightP2 = saps.crop_parameters.pc_CropHeightP2; } // pc_SpecificLeafArea if (saps.crop_parameters.pc_SpecificLeafArea.size() > 0) { std::vector<double> new_values; for (unsigned int i=0; i<cps->pc_SpecificLeafArea.size(); i++) { double sa_value = saps.crop_parameters.pc_SpecificLeafArea.at(i); double default_value = cps->pc_SpecificLeafArea.at(i); if (sa_value == -9999) { new_values.push_back(default_value); } else { new_values.push_back(sa_value); } } cps->pc_SpecificLeafArea = new_values; } // pc_StageTemperatureSum if (saps.crop_parameters.pc_StageTemperatureSum.size() > 0) { std::vector<double> new_values; for (unsigned int i=0; i<cps->pc_StageTemperatureSum.size(); i++) { double sa_value = saps.crop_parameters.pc_StageTemperatureSum.at(i); double default_value = cps->pc_StageTemperatureSum.at(i); if (sa_value == -9999) { new_values.push_back(default_value); } else { new_values.push_back(sa_value); } } cps->pc_StageTemperatureSum = new_values; } // pc_BaseTemperature if (saps.crop_parameters.pc_BaseTemperature.size() > 0) { std::vector<double> new_values; for (unsigned int i=0; i<cps->pc_BaseTemperature.size(); i++) { double sa_value = saps.crop_parameters.pc_BaseTemperature.at(i); double default_value = cps->pc_BaseTemperature.at(i); if (sa_value == -9999) { new_values.push_back(default_value); } else { new_values.push_back(sa_value); } } cps->pc_BaseTemperature = new_values; } // pc_LuxuryNCoeff if (saps.crop_parameters.pc_LuxuryNCoeff != UNDEFINED) { cps->pc_LuxuryNCoeff = saps.crop_parameters.pc_LuxuryNCoeff; } // pc_StageMaxRootNConcentration if (saps.crop_parameters.pc_StageMaxRootNConcentration.size() > 0) { std::vector<double> new_values; for (unsigned int i=0; i<cps->pc_StageMaxRootNConcentration.size(); i++) { double sa_value = saps.crop_parameters.pc_StageMaxRootNConcentration.at(i); double default_value = cps->pc_StageMaxRootNConcentration.at(i); if (sa_value == -9999) { new_values.push_back(default_value); } else { new_values.push_back(sa_value); } } cps->pc_StageMaxRootNConcentration = new_values; } // pc_ResidueNRatio if (saps.crop_parameters.pc_ResidueNRatio != UNDEFINED) { cps->pc_ResidueNRatio = saps.crop_parameters.pc_ResidueNRatio; } // pc_CropSpecificMaxRootingDepth if (saps.crop_parameters.pc_CropSpecificMaxRootingDepth != UNDEFINED) { cps->pc_CropSpecificMaxRootingDepth = saps.crop_parameters.pc_CropSpecificMaxRootingDepth; } // pc_RootPenetrationRate if (saps.crop_parameters.pc_RootPenetrationRate != UNDEFINED) { cps->pc_RootPenetrationRate = saps.crop_parameters.pc_RootPenetrationRate; } // pc_RootGrowthLag if (saps.crop_parameters.pc_RootGrowthLag != UNDEFINED) { cps->pc_RootGrowthLag = saps.crop_parameters.pc_RootGrowthLag; } // pc_InitialRootingDepth if (saps.crop_parameters.pc_InitialRootingDepth != UNDEFINED) { cps->pc_InitialRootingDepth = saps.crop_parameters.pc_InitialRootingDepth; } // pc_RootFormFactor if (saps.crop_parameters.pc_RootFormFactor != UNDEFINED) { cps->pc_RootFormFactor = saps.crop_parameters.pc_RootFormFactor; } // pc_MaxNUptakeParam if (saps.crop_parameters.pc_MaxNUptakeParam != UNDEFINED) { cps->pc_MaxNUptakeParam = saps.crop_parameters.pc_MaxNUptakeParam; } // pc_BaseDaylength if (saps.crop_parameters.pc_BaseDaylength.size() > 0) { std::vector<double> new_values; for (unsigned int i=0; i<cps->pc_BaseDaylength.size(); i++) { double sa_value = saps.crop_parameters.pc_BaseDaylength.at(i); double default_value = cps->pc_BaseDaylength.at(i); if (sa_value == -9999) { new_values.push_back(default_value); } else { new_values.push_back(sa_value); } } cps->pc_BaseDaylength = new_values; } // pc_CarboxylationPathway if (saps.crop_parameters.pc_CarboxylationPathway > -9999) { // UNDEFINED cps->pc_CarboxylationPathway = saps.crop_parameters.pc_CarboxylationPathway; } // pc_DefaultRadiationUseEfficiency if (saps.crop_parameters.pc_DefaultRadiationUseEfficiency != UNDEFINED) { cps->pc_DefaultRadiationUseEfficiency = saps.crop_parameters.pc_DefaultRadiationUseEfficiency; } // pc_DroughtStressThreshold { if (saps.crop_parameters.pc_DroughtStressThreshold.size() > 0) { std::vector<double> new_values; for (unsigned int i=0; i<cps->pc_DroughtStressThreshold.size(); i++) { double sa_value = saps.crop_parameters.pc_DroughtStressThreshold.at(i); double default_value = cps->pc_DroughtStressThreshold.at(i); if (sa_value == -9999) { new_values.push_back(default_value); } else { new_values.push_back(sa_value); } } cps->pc_DroughtStressThreshold = new_values; } // pc_MaxAssimilationRate if (saps.crop_parameters.pc_MaxAssimilationRate != UNDEFINED) { cps->pc_MaxAssimilationRate = saps.crop_parameters.pc_MaxAssimilationRate; } // pc_MaxCropDiameter if (saps.crop_parameters.pc_MaxCropDiameter != UNDEFINED) { cps->pc_MaxCropDiameter = saps.crop_parameters.pc_MaxCropDiameter; } // pc_MinimumNConcentration if (saps.crop_parameters.pc_MinimumNConcentration != UNDEFINED) { cps->pc_MinimumNConcentration = saps.crop_parameters.pc_MinimumNConcentration; } // pc_NConcentrationB0 if (saps.crop_parameters.pc_NConcentrationB0 != UNDEFINED) { cps->pc_NConcentrationB0 = saps.crop_parameters.pc_NConcentrationB0; } // pc_NConcentrationPN if (saps.crop_parameters.pc_NConcentrationPN != UNDEFINED) { cps->pc_NConcentrationPN = saps.crop_parameters.pc_NConcentrationPN; } // pc_NConcentrationRoot if (saps.crop_parameters.pc_NConcentrationRoot != UNDEFINED) { cps->pc_NConcentrationRoot = saps.crop_parameters.pc_NConcentrationRoot; } // pc_OrganGrowthRespiration if (saps.crop_parameters.pc_OrganGrowthRespiration.size() > 0) { cps->pc_OrganGrowthRespiration = saps.crop_parameters.pc_OrganGrowthRespiration; } // pc_OrganMaintenanceRespiration if (saps.crop_parameters.pc_OrganMaintenanceRespiration.size() > 0) { cps->pc_OrganMaintenanceRespiration = saps.crop_parameters.pc_OrganMaintenanceRespiration; } // pc_PlantDensity if (saps.crop_parameters.pc_PlantDensity != UNDEFINED) { cps->pc_PlantDensity = saps.crop_parameters.pc_PlantDensity; } // pc_ResidueNRatio if (saps.crop_parameters.pc_ResidueNRatio != UNDEFINED) { cps->pc_ResidueNRatio = saps.crop_parameters.pc_ResidueNRatio; } //cout << cps->toString().c_str() << endl; crop->setCropParameters(cps); new_ff.push_back(pp); } return ff; } CapillaryRiseRates Monica::readCapillaryRiseRates() { static L lockable; // static bool initialized = false; CapillaryRiseRates cap_rates; // if(!initialized) { L::Lock lock(lockable); // if(!initialized) // { static const string query = "select soil_type, distance, capillary_rate " "from capillary_rise_rate"; // read capillary rise rates from database DB *con = newConnection("monica"); con->select(query.c_str()); DBRow row; while (!(row = con->getRow()).empty()) { string soil_type = row[0]; int distance = satoi(row[1]); double rate = satof(row[2]); cap_rates.addRate(soil_type, distance, rate); } delete con; // initialized = true; } // } return cap_rates; } /* void Monica::Crop::applyCutting() { const CropParameters* cps = this->cropParameters(); } */
// @(#)root/treeplayer:$Id$ // Author: Rene Brun 29/10/09 /************************************************************************* * Copyright (C) 1995-2009, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // TTreePerfStats // // TTree I/O performance measurement. see example of use below. // // The function FileReadEvent is called from TFile::ReadBuffer. // For each call the following information is stored in fGraphIO // - x[i] = Tree entry number // - y[i] = 1e-6*(file position) // - ey[i] = 1e-9*number of bytes read // For each call the following information is stored in fGraphTime // - x[i] = Tree entry number // - y[i] = Time now // - ey[i] = readtime, eg timenow - start // The TTreePerfStats object can be saved in a ROOT file in such a way that // its inspection can be done outside the job that generated it. // // Example of use // { // TFile *f = TFile::Open("RelValMinBias-GEN-SIM-RECO.root"); // T = (TTree*)f->Get("Events"); // Long64_t nentries = T->GetEntries(); // T->SetCacheSize(10000000); // T->SetCacheEntryRange(0,nentries); // T->AddBranchToCache("*"); // // TTreePerfStats *ps= new TTreePerfStats("ioperf",T); // // for (Int_t i=0;i<nentries;i++) { // T->GetEntry(i); // } // ps->SaveAs("cmsperf.root"); // } // // then, in a root interactive session, one can do: // root > TFile f("cmsperf.root"); // root > ioperf->Draw(); // root > ioperf->Print(); // // The Draw or Print functions print the following information: // TreeCache = TTree cache size in MBytes // N leaves = Number of leaves in the TTree // ReadTotal = Total number of zipped bytes read // ReadUnZip = Total number of unzipped bytes read // ReadCalls = Total number of disk reads // ReadSize = Average read size in KBytes // Readahead = Readahead size in KBytes // Readextra = Readahead overhead in percent // Real Time = Real Time in seconds // CPU Time = CPU Time in seconds // Disk Time = Real Time spent in pure raw disk IO // Disk IO = Raw disk IO speed in MBytes/second // ReadUZRT = Unzipped MBytes per RT second // ReadUZCP = Unipped MBytes per CP second // ReadRT = Zipped MBytes per RT second // ReadCP = Zipped MBytes per CP second // ////////////////////////////////////////////////////////////////////////// #include "TTreePerfStats.h" #include "TROOT.h" #include "TSystem.h" #include "Riostream.h" #include "TFile.h" #include "TTree.h" #include "TAxis.h" #include "TBrowser.h" #include "TVirtualPad.h" #include "TPaveText.h" #include "TGraphErrors.h" #include "TStopwatch.h" #include "TGaxis.h" #include "TTimeStamp.h" #include "TDatime.h" const Double_t kScaleTime = 1e-20; ClassImp(TTreePerfStats) //______________________________________________________________________________ TTreePerfStats::TTreePerfStats() : TVirtualPerfStats() { // default constructor (used when reading an object only) fName = ""; fHostInfo = ""; fTree = 0; fNleaves = 0; fFile = 0; fGraphIO = 0; fGraphTime = 0; fWatch = 0; fPave = 0; fTreeCacheSize = 0; fReadCalls = 0; fReadaheadSize = 0; fBytesRead = 0; fBytesReadExtra= 0; fRealNorm = 0; fRealTime = 0; fCpuTime = 0; fDiskTime = 0; fCompress = 0; fRealTimeAxis = 0; fHostInfoText = 0; } //______________________________________________________________________________ TTreePerfStats::TTreePerfStats(const char *name, TTree *T) : TVirtualPerfStats() { // Create a TTree I/O perf stats object. fName = name; fTree = T; fNleaves= T->GetListOfLeaves()->GetEntries(); fFile = T->GetCurrentFile(); fGraphIO = new TGraphErrors(0); fGraphIO->SetName("ioperf"); fGraphIO->SetTitle(Form("%s/%s",fFile->GetName(),T->GetName())); fGraphIO->SetUniqueID(999999999); fGraphTime = new TGraphErrors(0); fGraphTime->SetLineColor(kRed); fGraphTime->SetName("iotime"); fGraphTime->SetTitle("Real time vs entries"); fWatch = new TStopwatch(); fWatch->Start(); fPave = 0; fTreeCacheSize = 0; fReadCalls = 0; fReadaheadSize = 0; fBytesRead = 0; fBytesReadExtra= 0; fRealNorm = 0; fRealTime = 0; fCpuTime = 0; fDiskTime = 0; fRealTimeAxis = 0; fCompress = (T->GetTotBytes()+0.00001)/T->GetZipBytes(); Bool_t isUNIX = strcmp(gSystem->GetName(), "Unix") == 0; if (isUNIX) fHostInfo = gSystem->GetFromPipe("uname -a"); else fHostInfo = "Windows "; fHostInfo.Resize(20); fHostInfo += Form("Root%s, SVN :%d",gROOT->GetVersion(),gROOT->GetSvnRevision()); TDatime dt; fHostInfo += Form(" %s",dt.AsString()); fHostInfoText = 0; gPerfStats = this; } //______________________________________________________________________________ TTreePerfStats::~TTreePerfStats() { // Destructor fTree = 0; fFile = 0; delete fGraphIO; delete fGraphTime; delete fPave; delete fWatch; delete fRealTimeAxis; delete fHostInfoText; } //______________________________________________________________________________ void TTreePerfStats::Browse(TBrowser * /*b*/) { // Browse Draw(); gPad->Update(); } //______________________________________________________________________________ Int_t TTreePerfStats::DistancetoPrimitive(Int_t px, Int_t py) { // Return distance to one of the objects in the TTreePerfStats const Int_t kMaxDiff = 7; Int_t puxmin = gPad->XtoAbsPixel(gPad->GetUxmin()); Int_t puymin = gPad->YtoAbsPixel(gPad->GetUymin()); Int_t puxmax = gPad->XtoAbsPixel(gPad->GetUxmax()); Int_t puymax = gPad->YtoAbsPixel(gPad->GetUymax()); if (py < puymax) return 9999; //on the fGraphIO ? Int_t distance = fGraphIO->DistancetoPrimitive(px,py); if (distance <kMaxDiff) {if (px > puxmin && py < puymin) gPad->SetSelected(fGraphIO); return distance;} // on the fGraphTime ? distance = fGraphTime->DistancetoPrimitive(px,py); if (distance <kMaxDiff) {if (px > puxmin && py < puymin) gPad->SetSelected(fGraphTime); return distance;} // on the pave ? distance = fPave->DistancetoPrimitive(px,py); if (distance <kMaxDiff) {gPad->SetSelected(fPave); return distance;} // on the real time axis ? distance = fRealTimeAxis->DistancetoPrimitive(px,py); if (distance <kMaxDiff) {gPad->SetSelected(fRealTimeAxis); return distance;} // on the host info label ? distance = fHostInfoText->DistancetoPrimitive(px,py); if (distance <kMaxDiff) {gPad->SetSelected(fHostInfoText); return distance;} if (px > puxmax-300) return 2; return 999; } //______________________________________________________________________________ void TTreePerfStats::Draw(Option_t *option) { // Draw the TTree I/O perf graph. // by default the graph is drawn with option "al" // Specify option ="ap" to show only the read blocks and not the line // connecting the blocks Finish(); TString opt = option; if (strlen(option)==0) opt = "al"; opt.ToLower(); if (gPad) { if (!gPad->IsEditable()) gROOT->MakeDefCanvas(); //the following statement is necessary in case one attempts to draw //a temporary histogram already in the current pad if (TestBit(kCanDelete)) gPad->GetListOfPrimitives()->Remove(this); } else { gROOT->MakeDefCanvas(); } if (opt.Contains("a")) { gPad->SetLeftMargin(0.35); gPad->Clear(); gPad->SetGridx(); gPad->SetGridy(); } AppendPad(opt.Data()); } //______________________________________________________________________________ void TTreePerfStats::ExecuteEvent(Int_t /*event*/, Int_t /*px*/, Int_t /*py*/) { // Return distance to one of the objects in the TTreePerfStats } //______________________________________________________________________________ void TTreePerfStats::FileReadEvent(TFile *file, Int_t len, Double_t start) { // Record TTree file read event. // start is the TimeStamp before reading // len is the number of bytes read Long64_t offset = file->GetRelOffset(); Int_t np = fGraphIO->GetN(); Int_t entry = fTree->GetReadEntry(); fGraphIO->SetPoint(np,entry,1e-6*offset); fGraphIO->SetPointError(np,0.001,1e-9*len); Double_t tnow = TTimeStamp(); Double_t dtime = tnow-start; fDiskTime += dtime; fGraphTime->SetPoint(np,entry,tnow); fGraphTime->SetPointError(np,0.001,dtime); } //______________________________________________________________________________ void TTreePerfStats::Finish() { // When the run is finished this function must be called // to save the current parameters in the file and Tree in this object // the function is automatically called by Draw and Print if (fReadCalls) return; //has already been called if (!fFile) return; if (!fTree) return; fReadCalls = fFile->GetReadCalls(); fTreeCacheSize = fTree->GetCacheSize(); fReadaheadSize = TFile::GetReadaheadSize(); fBytesRead = fFile->GetBytesRead(); fBytesReadExtra= fFile->GetBytesReadExtra(); fRealTime = fWatch->RealTime(); fCpuTime = fWatch->CpuTime(); Int_t npoints = fGraphIO->GetN(); if (!npoints) return; Double_t iomax = fGraphIO->GetY()[npoints-1]; fRealNorm = iomax/fRealTime; fGraphTime->GetY()[0] = fRealNorm*fGraphTime->GetEY()[0]; // we normalize the fGraphTime such that it can be drawn on top of fGraphIO for (Int_t i=1;i<npoints;i++) { fGraphTime->GetY()[i] = fGraphTime->GetY()[i-1] +fRealNorm*fGraphTime->GetEY()[i]; fGraphTime->GetEY()[i] = 0; } } //______________________________________________________________________________ void TTreePerfStats::Paint(Option_t *option) { // Draw the TTree I/O perf graph. Int_t npoints = fGraphIO->GetN(); if (!npoints) return; Double_t iomax = fGraphIO->GetY()[npoints-1]; Double_t toffset=1; if (iomax >= 1e9) toffset = 1.2; fGraphIO->GetXaxis()->SetTitle("Tree entry number"); fGraphIO->GetYaxis()->SetTitle("file position (MBytes) "); fGraphIO->GetYaxis()->SetTitleOffset(toffset); fGraphIO->GetXaxis()->SetLabelSize(0.03); fGraphIO->GetYaxis()->SetLabelSize(0.03); fGraphIO->Paint(option); //superimpose the time info (max 10 points) if (fGraphTime) { fGraphTime->Paint("l"); TText tdisk(fGraphTime->GetX()[npoints-1],1.1*fGraphTime->GetY()[npoints-1],"RAW IO"); tdisk.SetTextAlign(31); tdisk.SetTextSize(0.03); tdisk.SetTextColor(kRed); tdisk.Paint(); if (!fRealTimeAxis) { Double_t uxmax = gPad->GetUxmax(); Double_t uymax = gPad->GetUymax(); Double_t rtmax = fRealTime*uymax/iomax; fRealTimeAxis = new TGaxis(uxmax,0,uxmax,uymax,0.,rtmax,510,"+L"); fRealTimeAxis->SetName("RealTimeAxis"); fRealTimeAxis->SetLineColor(kRed); fRealTimeAxis->SetTitle("RealTime (s) "); fRealTimeAxis->SetTitleColor(kRed); toffset = 1; if (fRealTime >= 100) toffset = 1.2; if (fRealTime >= 1000) toffset = 1.4; fRealTimeAxis->SetTitleOffset(toffset); fRealTimeAxis->SetLabelSize(0.03); fRealTimeAxis->SetLabelColor(kRed); } fRealTimeAxis->Paint(); } Double_t extra = 100.*fBytesReadExtra/fBytesRead; if (!fPave) { fPave = new TPaveText(.01,.10,.24,.90,"brNDC"); fPave->SetTextAlign(12); fPave->AddText(Form("TreeCache = %d MB",fTreeCacheSize/1000000)); fPave->AddText(Form("N leaves = %d",fNleaves)); fPave->AddText(Form("ReadTotal = %g MB",1e-6*fBytesRead)); fPave->AddText(Form("ReadUnZip = %g MB",1e-6*fBytesRead*fCompress)); fPave->AddText(Form("ReadCalls = %d",fReadCalls)); fPave->AddText(Form("ReadSize = %7.3f KB",0.001*fBytesRead/fReadCalls)); fPave->AddText(Form("Readahead = %d KB",fReadaheadSize/1000)); fPave->AddText(Form("Readextra = %5.2f per cent",extra)); fPave->AddText(Form("Real Time = %7.3f s",fRealTime)); fPave->AddText(Form("CPU Time = %7.3f s",fCpuTime)); fPave->AddText(Form("Disk Time = %7.3f s",fDiskTime)); fPave->AddText(Form("Disk IO = %7.3f MB/s",1e-6*fBytesRead/fDiskTime)); fPave->AddText(Form("ReadUZRT = %7.3f MB/s",1e-6*fCompress*fBytesRead/fRealTime)); fPave->AddText(Form("ReadUZCP = %7.3f MB/s",1e-6*fCompress*fBytesRead/fCpuTime)); fPave->AddText(Form("ReadRT = %7.3f MB/s",1e-6*fBytesRead/fRealTime)); fPave->AddText(Form("ReadCP = %7.3f MB/s",1e-6*fBytesRead/fCpuTime)); } fPave->Paint(); if (!fHostInfoText) { fHostInfoText = new TText(0.01,0.01,fHostInfo.Data()); fHostInfoText->SetNDC(); fHostInfoText->SetTextSize(0.025); } fHostInfoText->Paint(); } //______________________________________________________________________________ void TTreePerfStats::Print(Option_t * /*option*/) const { // Print the TTree I/O perf stats. TTreePerfStats *ps = (TTreePerfStats*)this; ps->Finish(); Double_t extra = 100.*fBytesReadExtra/fBytesRead; printf("TreeCache = %d MBytes\n",Int_t(fTreeCacheSize/1000000)); printf("N leaves = %d\n",fNleaves); printf("ReadTotal = %g MBytes\n",1e-6*fBytesRead); printf("ReadUnZip = %g MBytes\n",1e-6*fBytesRead*fCompress); printf("ReadCalls = %d\n",fReadCalls); printf("ReadSize = %7.3f KBytes/read\n",0.001*fBytesRead/fReadCalls); printf("Readahead = %d KBytes\n",fReadaheadSize/1000); printf("Readextra = %5.2f per cent\n",extra); printf("Real Time = %7.3f seconds\n",fRealTime); printf("CPU Time = %7.3f seconds\n",fCpuTime); printf("Disk Time = %7.3f seconds\n",fDiskTime); printf("Disk IO = %7.3f MBytes/s\n",1e-6*fBytesRead/fDiskTime); printf("ReadUZRT = %7.3f MBytes/s\n",1e-6*fCompress*fBytesRead/fRealTime); printf("ReadUZCP = %7.3f MBytes/s\n",1e-6*fCompress*fBytesRead/fCpuTime); printf("ReadRT = %7.3f MBytes/s\n",1e-6*fBytesRead/fRealTime); printf("ReadCP = %7.3f MBytes/s\n",1e-6*fBytesRead/fCpuTime); } //______________________________________________________________________________ void TTreePerfStats::SaveAs(const char *filename, Option_t * /*option*/) const { // Save this object to filename TTreePerfStats *ps = (TTreePerfStats*)this; ps->Finish(); ps->TObject::SaveAs(filename); } //______________________________________________________________________________ void TTreePerfStats::SavePrimitive(ostream &out, Option_t *option /*= ""*/) { // Save primitive as a C++ statement(s) on output stream out char quote = '"'; out<<" "<<endl; if (gROOT->ClassSaved(TTreePerfStats::Class())) { out<<" "; } else { out<<" TTreePerfStats *"; } out<<"ps = new TTreePerfStats();"<<endl; out<<" ps->SetName("<<quote<<GetName()<<quote<<");"<<endl; out<<" ps->SetHostInfo("<<quote<<GetHostInfo()<<quote<<");"<<endl; out<<" ps->SetTreeCacheSize("<<fTreeCacheSize<<");"<<endl; out<<" ps->SetNleaves("<<fNleaves<<");"<<endl; out<<" ps->SetReadCalls("<<fReadCalls<<");"<<endl; out<<" ps->SetReadaheadSize("<<fReadaheadSize<<");"<<endl; out<<" ps->SetBytesRead("<<fBytesRead<<");"<<endl; out<<" ps->SetBytesReadExtra("<<fBytesReadExtra<<");"<<endl; out<<" ps->SetRealNorm("<<fRealNorm<<");"<<endl; out<<" ps->SetRealTime("<<fRealTime<<");"<<endl; out<<" ps->SetCpuTime("<<fCpuTime<<");"<<endl; out<<" ps->SetDiskTime("<<fDiskTime<<");"<<endl; out<<" ps->SetCompress("<<fCompress<<");"<<endl; Int_t i, npoints = fGraphIO->GetN(); out<<" TGraphErrors *psGraphIO = new TGraphErrors("<<npoints<<");"<<endl; out<<" psGraphIO->SetName("<<quote<<fGraphIO->GetName()<<quote<<");"<<endl; out<<" psGraphIO->SetTitle("<<quote<<fGraphIO->GetTitle()<<quote<<");"<<endl; out<<" ps->SetGraphIO(psGraphIO);"<<endl; fGraphIO->SaveFillAttributes(out,"psGraphIO",0,1001); fGraphIO->SaveLineAttributes(out,"psGraphIO",1,1,1); fGraphIO->SaveMarkerAttributes(out,"psGraphIO",1,1,1); for (i=0;i<npoints;i++) { out<<" psGraphIO->SetPoint("<<i<<","<<fGraphIO->GetX()[i]<<","<<fGraphIO->GetY()[i]<<");"<<endl; out<<" psGraphIO->SetPointError("<<i<<",0,"<<fGraphIO->GetEY()[i]<<");"<<endl; } npoints = fGraphTime->GetN(); out<<" TGraphErrors *psGraphTime = new TGraphErrors("<<npoints<<");"<<endl; out<<" psGraphTime->SetName("<<quote<<fGraphTime->GetName()<<quote<<");"<<endl; out<<" psGraphTime->SetTitle("<<quote<<fGraphTime->GetTitle()<<quote<<");"<<endl; out<<" ps->SetGraphTime(psGraphTime);"<<endl; fGraphTime->SaveFillAttributes(out,"psGraphTime",0,1001); fGraphTime->SaveLineAttributes(out,"psGraphTime",1,1,1); fGraphTime->SaveMarkerAttributes(out,"psGraphTime",1,1,1); for (i=0;i<npoints;i++) { out<<" psGraphTime->SetPoint("<<i<<","<<fGraphTime->GetX()[i]<<","<<fGraphTime->GetY()[i]<<");"<<endl; out<<" psGraphTime->SetPointError("<<i<<",0,"<<fGraphTime->GetEY()[i]<<");"<<endl; } out<<" ps->Draw("<<quote<<option<<quote<<");"<<endl; } Make sure that gPerfStats is properly updated if the TTreePerfStats is deleted! git-svn-id: acec3fd5b7ea1eb9e79d6329d318e8118ee2e14f@33146 27541ba8-7e3a-0410-8455-c3a389f83636 // @(#)root/treeplayer:$Id$ // Author: Rene Brun 29/10/09 /************************************************************************* * Copyright (C) 1995-2009, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // TTreePerfStats // // TTree I/O performance measurement. see example of use below. // // The function FileReadEvent is called from TFile::ReadBuffer. // For each call the following information is stored in fGraphIO // - x[i] = Tree entry number // - y[i] = 1e-6*(file position) // - ey[i] = 1e-9*number of bytes read // For each call the following information is stored in fGraphTime // - x[i] = Tree entry number // - y[i] = Time now // - ey[i] = readtime, eg timenow - start // The TTreePerfStats object can be saved in a ROOT file in such a way that // its inspection can be done outside the job that generated it. // // Example of use // { // TFile *f = TFile::Open("RelValMinBias-GEN-SIM-RECO.root"); // T = (TTree*)f->Get("Events"); // Long64_t nentries = T->GetEntries(); // T->SetCacheSize(10000000); // T->SetCacheEntryRange(0,nentries); // T->AddBranchToCache("*"); // // TTreePerfStats *ps= new TTreePerfStats("ioperf",T); // // for (Int_t i=0;i<nentries;i++) { // T->GetEntry(i); // } // ps->SaveAs("cmsperf.root"); // } // // then, in a root interactive session, one can do: // root > TFile f("cmsperf.root"); // root > ioperf->Draw(); // root > ioperf->Print(); // // The Draw or Print functions print the following information: // TreeCache = TTree cache size in MBytes // N leaves = Number of leaves in the TTree // ReadTotal = Total number of zipped bytes read // ReadUnZip = Total number of unzipped bytes read // ReadCalls = Total number of disk reads // ReadSize = Average read size in KBytes // Readahead = Readahead size in KBytes // Readextra = Readahead overhead in percent // Real Time = Real Time in seconds // CPU Time = CPU Time in seconds // Disk Time = Real Time spent in pure raw disk IO // Disk IO = Raw disk IO speed in MBytes/second // ReadUZRT = Unzipped MBytes per RT second // ReadUZCP = Unipped MBytes per CP second // ReadRT = Zipped MBytes per RT second // ReadCP = Zipped MBytes per CP second // ////////////////////////////////////////////////////////////////////////// #include "TTreePerfStats.h" #include "TROOT.h" #include "TSystem.h" #include "Riostream.h" #include "TFile.h" #include "TTree.h" #include "TAxis.h" #include "TBrowser.h" #include "TVirtualPad.h" #include "TPaveText.h" #include "TGraphErrors.h" #include "TStopwatch.h" #include "TGaxis.h" #include "TTimeStamp.h" #include "TDatime.h" const Double_t kScaleTime = 1e-20; ClassImp(TTreePerfStats) //______________________________________________________________________________ TTreePerfStats::TTreePerfStats() : TVirtualPerfStats() { // default constructor (used when reading an object only) fName = ""; fHostInfo = ""; fTree = 0; fNleaves = 0; fFile = 0; fGraphIO = 0; fGraphTime = 0; fWatch = 0; fPave = 0; fTreeCacheSize = 0; fReadCalls = 0; fReadaheadSize = 0; fBytesRead = 0; fBytesReadExtra= 0; fRealNorm = 0; fRealTime = 0; fCpuTime = 0; fDiskTime = 0; fCompress = 0; fRealTimeAxis = 0; fHostInfoText = 0; } //______________________________________________________________________________ TTreePerfStats::TTreePerfStats(const char *name, TTree *T) : TVirtualPerfStats() { // Create a TTree I/O perf stats object. fName = name; fTree = T; fNleaves= T->GetListOfLeaves()->GetEntries(); fFile = T->GetCurrentFile(); fGraphIO = new TGraphErrors(0); fGraphIO->SetName("ioperf"); fGraphIO->SetTitle(Form("%s/%s",fFile->GetName(),T->GetName())); fGraphIO->SetUniqueID(999999999); fGraphTime = new TGraphErrors(0); fGraphTime->SetLineColor(kRed); fGraphTime->SetName("iotime"); fGraphTime->SetTitle("Real time vs entries"); fWatch = new TStopwatch(); fWatch->Start(); fPave = 0; fTreeCacheSize = 0; fReadCalls = 0; fReadaheadSize = 0; fBytesRead = 0; fBytesReadExtra= 0; fRealNorm = 0; fRealTime = 0; fCpuTime = 0; fDiskTime = 0; fRealTimeAxis = 0; fCompress = (T->GetTotBytes()+0.00001)/T->GetZipBytes(); Bool_t isUNIX = strcmp(gSystem->GetName(), "Unix") == 0; if (isUNIX) fHostInfo = gSystem->GetFromPipe("uname -a"); else fHostInfo = "Windows "; fHostInfo.Resize(20); fHostInfo += Form("Root%s, SVN :%d",gROOT->GetVersion(),gROOT->GetSvnRevision()); TDatime dt; fHostInfo += Form(" %s",dt.AsString()); fHostInfoText = 0; gPerfStats = this; } //______________________________________________________________________________ TTreePerfStats::~TTreePerfStats() { // Destructor fTree = 0; fFile = 0; delete fGraphIO; delete fGraphTime; delete fPave; delete fWatch; delete fRealTimeAxis; delete fHostInfoText; if (gPerfStats == this) { gPerfStats = 0; } } //______________________________________________________________________________ void TTreePerfStats::Browse(TBrowser * /*b*/) { // Browse Draw(); gPad->Update(); } //______________________________________________________________________________ Int_t TTreePerfStats::DistancetoPrimitive(Int_t px, Int_t py) { // Return distance to one of the objects in the TTreePerfStats const Int_t kMaxDiff = 7; Int_t puxmin = gPad->XtoAbsPixel(gPad->GetUxmin()); Int_t puymin = gPad->YtoAbsPixel(gPad->GetUymin()); Int_t puxmax = gPad->XtoAbsPixel(gPad->GetUxmax()); Int_t puymax = gPad->YtoAbsPixel(gPad->GetUymax()); if (py < puymax) return 9999; //on the fGraphIO ? Int_t distance = fGraphIO->DistancetoPrimitive(px,py); if (distance <kMaxDiff) {if (px > puxmin && py < puymin) gPad->SetSelected(fGraphIO); return distance;} // on the fGraphTime ? distance = fGraphTime->DistancetoPrimitive(px,py); if (distance <kMaxDiff) {if (px > puxmin && py < puymin) gPad->SetSelected(fGraphTime); return distance;} // on the pave ? distance = fPave->DistancetoPrimitive(px,py); if (distance <kMaxDiff) {gPad->SetSelected(fPave); return distance;} // on the real time axis ? distance = fRealTimeAxis->DistancetoPrimitive(px,py); if (distance <kMaxDiff) {gPad->SetSelected(fRealTimeAxis); return distance;} // on the host info label ? distance = fHostInfoText->DistancetoPrimitive(px,py); if (distance <kMaxDiff) {gPad->SetSelected(fHostInfoText); return distance;} if (px > puxmax-300) return 2; return 999; } //______________________________________________________________________________ void TTreePerfStats::Draw(Option_t *option) { // Draw the TTree I/O perf graph. // by default the graph is drawn with option "al" // Specify option ="ap" to show only the read blocks and not the line // connecting the blocks Finish(); TString opt = option; if (strlen(option)==0) opt = "al"; opt.ToLower(); if (gPad) { if (!gPad->IsEditable()) gROOT->MakeDefCanvas(); //the following statement is necessary in case one attempts to draw //a temporary histogram already in the current pad if (TestBit(kCanDelete)) gPad->GetListOfPrimitives()->Remove(this); } else { gROOT->MakeDefCanvas(); } if (opt.Contains("a")) { gPad->SetLeftMargin(0.35); gPad->Clear(); gPad->SetGridx(); gPad->SetGridy(); } AppendPad(opt.Data()); } //______________________________________________________________________________ void TTreePerfStats::ExecuteEvent(Int_t /*event*/, Int_t /*px*/, Int_t /*py*/) { // Return distance to one of the objects in the TTreePerfStats } //______________________________________________________________________________ void TTreePerfStats::FileReadEvent(TFile *file, Int_t len, Double_t start) { // Record TTree file read event. // start is the TimeStamp before reading // len is the number of bytes read Long64_t offset = file->GetRelOffset(); Int_t np = fGraphIO->GetN(); Int_t entry = fTree->GetReadEntry(); fGraphIO->SetPoint(np,entry,1e-6*offset); fGraphIO->SetPointError(np,0.001,1e-9*len); Double_t tnow = TTimeStamp(); Double_t dtime = tnow-start; fDiskTime += dtime; fGraphTime->SetPoint(np,entry,tnow); fGraphTime->SetPointError(np,0.001,dtime); } //______________________________________________________________________________ void TTreePerfStats::Finish() { // When the run is finished this function must be called // to save the current parameters in the file and Tree in this object // the function is automatically called by Draw and Print if (fReadCalls) return; //has already been called if (!fFile) return; if (!fTree) return; fReadCalls = fFile->GetReadCalls(); fTreeCacheSize = fTree->GetCacheSize(); fReadaheadSize = TFile::GetReadaheadSize(); fBytesRead = fFile->GetBytesRead(); fBytesReadExtra= fFile->GetBytesReadExtra(); fRealTime = fWatch->RealTime(); fCpuTime = fWatch->CpuTime(); Int_t npoints = fGraphIO->GetN(); if (!npoints) return; Double_t iomax = fGraphIO->GetY()[npoints-1]; fRealNorm = iomax/fRealTime; fGraphTime->GetY()[0] = fRealNorm*fGraphTime->GetEY()[0]; // we normalize the fGraphTime such that it can be drawn on top of fGraphIO for (Int_t i=1;i<npoints;i++) { fGraphTime->GetY()[i] = fGraphTime->GetY()[i-1] +fRealNorm*fGraphTime->GetEY()[i]; fGraphTime->GetEY()[i] = 0; } } //______________________________________________________________________________ void TTreePerfStats::Paint(Option_t *option) { // Draw the TTree I/O perf graph. Int_t npoints = fGraphIO->GetN(); if (!npoints) return; Double_t iomax = fGraphIO->GetY()[npoints-1]; Double_t toffset=1; if (iomax >= 1e9) toffset = 1.2; fGraphIO->GetXaxis()->SetTitle("Tree entry number"); fGraphIO->GetYaxis()->SetTitle("file position (MBytes) "); fGraphIO->GetYaxis()->SetTitleOffset(toffset); fGraphIO->GetXaxis()->SetLabelSize(0.03); fGraphIO->GetYaxis()->SetLabelSize(0.03); fGraphIO->Paint(option); //superimpose the time info (max 10 points) if (fGraphTime) { fGraphTime->Paint("l"); TText tdisk(fGraphTime->GetX()[npoints-1],1.1*fGraphTime->GetY()[npoints-1],"RAW IO"); tdisk.SetTextAlign(31); tdisk.SetTextSize(0.03); tdisk.SetTextColor(kRed); tdisk.Paint(); if (!fRealTimeAxis) { Double_t uxmax = gPad->GetUxmax(); Double_t uymax = gPad->GetUymax(); Double_t rtmax = fRealTime*uymax/iomax; fRealTimeAxis = new TGaxis(uxmax,0,uxmax,uymax,0.,rtmax,510,"+L"); fRealTimeAxis->SetName("RealTimeAxis"); fRealTimeAxis->SetLineColor(kRed); fRealTimeAxis->SetTitle("RealTime (s) "); fRealTimeAxis->SetTitleColor(kRed); toffset = 1; if (fRealTime >= 100) toffset = 1.2; if (fRealTime >= 1000) toffset = 1.4; fRealTimeAxis->SetTitleOffset(toffset); fRealTimeAxis->SetLabelSize(0.03); fRealTimeAxis->SetLabelColor(kRed); } fRealTimeAxis->Paint(); } Double_t extra = 100.*fBytesReadExtra/fBytesRead; if (!fPave) { fPave = new TPaveText(.01,.10,.24,.90,"brNDC"); fPave->SetTextAlign(12); fPave->AddText(Form("TreeCache = %d MB",fTreeCacheSize/1000000)); fPave->AddText(Form("N leaves = %d",fNleaves)); fPave->AddText(Form("ReadTotal = %g MB",1e-6*fBytesRead)); fPave->AddText(Form("ReadUnZip = %g MB",1e-6*fBytesRead*fCompress)); fPave->AddText(Form("ReadCalls = %d",fReadCalls)); fPave->AddText(Form("ReadSize = %7.3f KB",0.001*fBytesRead/fReadCalls)); fPave->AddText(Form("Readahead = %d KB",fReadaheadSize/1000)); fPave->AddText(Form("Readextra = %5.2f per cent",extra)); fPave->AddText(Form("Real Time = %7.3f s",fRealTime)); fPave->AddText(Form("CPU Time = %7.3f s",fCpuTime)); fPave->AddText(Form("Disk Time = %7.3f s",fDiskTime)); fPave->AddText(Form("Disk IO = %7.3f MB/s",1e-6*fBytesRead/fDiskTime)); fPave->AddText(Form("ReadUZRT = %7.3f MB/s",1e-6*fCompress*fBytesRead/fRealTime)); fPave->AddText(Form("ReadUZCP = %7.3f MB/s",1e-6*fCompress*fBytesRead/fCpuTime)); fPave->AddText(Form("ReadRT = %7.3f MB/s",1e-6*fBytesRead/fRealTime)); fPave->AddText(Form("ReadCP = %7.3f MB/s",1e-6*fBytesRead/fCpuTime)); } fPave->Paint(); if (!fHostInfoText) { fHostInfoText = new TText(0.01,0.01,fHostInfo.Data()); fHostInfoText->SetNDC(); fHostInfoText->SetTextSize(0.025); } fHostInfoText->Paint(); } //______________________________________________________________________________ void TTreePerfStats::Print(Option_t * /*option*/) const { // Print the TTree I/O perf stats. TTreePerfStats *ps = (TTreePerfStats*)this; ps->Finish(); Double_t extra = 100.*fBytesReadExtra/fBytesRead; printf("TreeCache = %d MBytes\n",Int_t(fTreeCacheSize/1000000)); printf("N leaves = %d\n",fNleaves); printf("ReadTotal = %g MBytes\n",1e-6*fBytesRead); printf("ReadUnZip = %g MBytes\n",1e-6*fBytesRead*fCompress); printf("ReadCalls = %d\n",fReadCalls); printf("ReadSize = %7.3f KBytes/read\n",0.001*fBytesRead/fReadCalls); printf("Readahead = %d KBytes\n",fReadaheadSize/1000); printf("Readextra = %5.2f per cent\n",extra); printf("Real Time = %7.3f seconds\n",fRealTime); printf("CPU Time = %7.3f seconds\n",fCpuTime); printf("Disk Time = %7.3f seconds\n",fDiskTime); printf("Disk IO = %7.3f MBytes/s\n",1e-6*fBytesRead/fDiskTime); printf("ReadUZRT = %7.3f MBytes/s\n",1e-6*fCompress*fBytesRead/fRealTime); printf("ReadUZCP = %7.3f MBytes/s\n",1e-6*fCompress*fBytesRead/fCpuTime); printf("ReadRT = %7.3f MBytes/s\n",1e-6*fBytesRead/fRealTime); printf("ReadCP = %7.3f MBytes/s\n",1e-6*fBytesRead/fCpuTime); } //______________________________________________________________________________ void TTreePerfStats::SaveAs(const char *filename, Option_t * /*option*/) const { // Save this object to filename TTreePerfStats *ps = (TTreePerfStats*)this; ps->Finish(); ps->TObject::SaveAs(filename); } //______________________________________________________________________________ void TTreePerfStats::SavePrimitive(ostream &out, Option_t *option /*= ""*/) { // Save primitive as a C++ statement(s) on output stream out char quote = '"'; out<<" "<<endl; if (gROOT->ClassSaved(TTreePerfStats::Class())) { out<<" "; } else { out<<" TTreePerfStats *"; } out<<"ps = new TTreePerfStats();"<<endl; out<<" ps->SetName("<<quote<<GetName()<<quote<<");"<<endl; out<<" ps->SetHostInfo("<<quote<<GetHostInfo()<<quote<<");"<<endl; out<<" ps->SetTreeCacheSize("<<fTreeCacheSize<<");"<<endl; out<<" ps->SetNleaves("<<fNleaves<<");"<<endl; out<<" ps->SetReadCalls("<<fReadCalls<<");"<<endl; out<<" ps->SetReadaheadSize("<<fReadaheadSize<<");"<<endl; out<<" ps->SetBytesRead("<<fBytesRead<<");"<<endl; out<<" ps->SetBytesReadExtra("<<fBytesReadExtra<<");"<<endl; out<<" ps->SetRealNorm("<<fRealNorm<<");"<<endl; out<<" ps->SetRealTime("<<fRealTime<<");"<<endl; out<<" ps->SetCpuTime("<<fCpuTime<<");"<<endl; out<<" ps->SetDiskTime("<<fDiskTime<<");"<<endl; out<<" ps->SetCompress("<<fCompress<<");"<<endl; Int_t i, npoints = fGraphIO->GetN(); out<<" TGraphErrors *psGraphIO = new TGraphErrors("<<npoints<<");"<<endl; out<<" psGraphIO->SetName("<<quote<<fGraphIO->GetName()<<quote<<");"<<endl; out<<" psGraphIO->SetTitle("<<quote<<fGraphIO->GetTitle()<<quote<<");"<<endl; out<<" ps->SetGraphIO(psGraphIO);"<<endl; fGraphIO->SaveFillAttributes(out,"psGraphIO",0,1001); fGraphIO->SaveLineAttributes(out,"psGraphIO",1,1,1); fGraphIO->SaveMarkerAttributes(out,"psGraphIO",1,1,1); for (i=0;i<npoints;i++) { out<<" psGraphIO->SetPoint("<<i<<","<<fGraphIO->GetX()[i]<<","<<fGraphIO->GetY()[i]<<");"<<endl; out<<" psGraphIO->SetPointError("<<i<<",0,"<<fGraphIO->GetEY()[i]<<");"<<endl; } npoints = fGraphTime->GetN(); out<<" TGraphErrors *psGraphTime = new TGraphErrors("<<npoints<<");"<<endl; out<<" psGraphTime->SetName("<<quote<<fGraphTime->GetName()<<quote<<");"<<endl; out<<" psGraphTime->SetTitle("<<quote<<fGraphTime->GetTitle()<<quote<<");"<<endl; out<<" ps->SetGraphTime(psGraphTime);"<<endl; fGraphTime->SaveFillAttributes(out,"psGraphTime",0,1001); fGraphTime->SaveLineAttributes(out,"psGraphTime",1,1,1); fGraphTime->SaveMarkerAttributes(out,"psGraphTime",1,1,1); for (i=0;i<npoints;i++) { out<<" psGraphTime->SetPoint("<<i<<","<<fGraphTime->GetX()[i]<<","<<fGraphTime->GetY()[i]<<");"<<endl; out<<" psGraphTime->SetPointError("<<i<<",0,"<<fGraphTime->GetEY()[i]<<");"<<endl; } out<<" ps->Draw("<<quote<<option<<quote<<");"<<endl; }
/** @defgroup eosclienttool @section intro Introduction to cleos `cleos` is a command line tool that interfaces with the REST api exposed by @ref nodeos. In order to use `cleos` you will need to have a local copy of `nodeos` running and configured to load the 'eosio::chain_api_plugin'. cleos contains documentation for all of its commands. For a list of all commands known to cleos, simply run it with no arguments: ``` $ ./cleos Command Line Interface to EOSIO Client Usage: programs/cleos/cleos [OPTIONS] SUBCOMMAND Options: -h,--help Print this help message and exit -u,--url TEXT=http://localhost:8888/ the http/https URL where nodeos is running --wallet-url TEXT=http://localhost:8888/ the http/https URL where keosd is running -r,--header pass specific HTTP header, repeat this option to pass multiple headers -n,--no-verify don't verify peer certificate when using HTTPS -v,--verbose output verbose errors and action output Subcommands: version Retrieve version information create Create various items, on and off the blockchain get Retrieve various items and information from the blockchain set Set or update blockchain state transfer Transfer tokens from account to account net Interact with local p2p network connections wallet Interact with local wallet sign Sign a transaction push Push arbitrary transactions to the blockchain multisig Multisig contract commands ``` To get help with any particular subcommand, run it with no arguments as well: ``` $ ./cleos create Create various items, on and off the blockchain Usage: ./cleos create SUBCOMMAND Subcommands: key Create a new keypair and print the public and private keys account Create a new account on the blockchain (assumes system contract does not restrict RAM usage) $ ./cleos create account Create a new account on the blockchain (assumes system contract does not restrict RAM usage) Usage: ./cleos create account [OPTIONS] creator name OwnerKey ActiveKey Positionals: creator TEXT The name of the account creating the new account name TEXT The name of the new account OwnerKey TEXT The owner public key for the new account ActiveKey TEXT The active public key for the new account Options: -x,--expiration set the time in seconds before a transaction expires, defaults to 30s -f,--force-unique force the transaction to be unique. this will consume extra bandwidth and remove any protections against accidently issuing the same transaction multiple times -s,--skip-sign Specify if unlocked wallet keys should be used to sign transaction -d,--dont-broadcast don't broadcast transaction to the network (just print to stdout) -p,--permission TEXT ... An account and permission level to authorize, as in 'account@permission' (defaults to 'creator@active') ``` */ #include <pwd.h> #include <string> #include <vector> #include <regex> #include <iostream> #include <fc/crypto/hex.hpp> #include <fc/variant.hpp> #include <fc/io/datastream.hpp> #include <fc/io/json.hpp> #include <fc/io/console.hpp> #include <fc/exception/exception.hpp> #include <fc/variant_object.hpp> #include <fc/static_variant.hpp> #include <eosio/chain/name.hpp> #include <eosio/chain/config.hpp> #include <eosio/chain/wast_to_wasm.hpp> #include <eosio/chain/trace.hpp> #include <eosio/chain_plugin/chain_plugin.hpp> #include <eosio/chain/contract_types.hpp> #include <eosio/version/version.hpp> #pragma push_macro("N") #undef N #include <boost/asio.hpp> #include <boost/format.hpp> #include <boost/dll/runtime_symbol_info.hpp> #include <boost/filesystem.hpp> #include <boost/process.hpp> #include <boost/process/spawn.hpp> #include <boost/range/algorithm/find_if.hpp> #include <boost/range/algorithm/sort.hpp> #include <boost/range/adaptor/transformed.hpp> #include <boost/algorithm/string/predicate.hpp> #include <boost/algorithm/string/split.hpp> #include <boost/range/algorithm/copy.hpp> #include <boost/algorithm/string/classification.hpp> #pragma pop_macro("N") #include <Inline/BasicTypes.h> #include <IR/Module.h> #include <IR/Validate.h> #include <WASM/WASM.h> #include <Runtime/Runtime.h> #include <fc/io/fstream.hpp> #include "CLI11.hpp" #include "help_text.hpp" #include "localize.hpp" #include "config.hpp" #include "httpc.hpp" using namespace std; using namespace eosio; using namespace eosio::chain; using namespace eosio::client::help; using namespace eosio::client::http; using namespace eosio::client::localize; using namespace eosio::client::config; using namespace boost::filesystem; using auth_type = fc::static_variant<public_key_type, permission_level>; FC_DECLARE_EXCEPTION( explained_exception, 9000000, "explained exception, see error log" ); FC_DECLARE_EXCEPTION( localized_exception, 10000000, "an error occured" ); #define EOSC_ASSERT( TEST, ... ) \ FC_EXPAND_MACRO( \ FC_MULTILINE_MACRO_BEGIN \ if( UNLIKELY(!(TEST)) ) \ { \ std::cerr << localized( __VA_ARGS__ ) << std::endl; \ FC_THROW_EXCEPTION( explained_exception, #TEST ); \ } \ FC_MULTILINE_MACRO_END \ ) //copy pasta from keosd's main.cpp bfs::path determine_home_directory() { bfs::path home; struct passwd* pwd = getpwuid(getuid()); if(pwd) { home = pwd->pw_dir; } else { home = getenv("HOME"); } if(home.empty()) home = "./"; return home; } string url = "http://127.0.0.1:8888/"; string default_wallet_url = "unix://" + (determine_home_directory() / "eosio-wallet" / (string(key_store_executable_name) + ".sock")).string(); string wallet_url; //to be set to default_wallet_url in main bool no_verify = false; vector<string> headers; auto tx_expiration = fc::seconds(30); const fc::microseconds abi_serializer_max_time = fc::seconds(10); // No risk to client side serialization taking a long time string tx_ref_block_num_or_id; bool tx_force_unique = false; bool tx_dont_broadcast = false; bool tx_return_packed = false; bool tx_skip_sign = false; bool tx_print_json = false; bool tx_use_old_rpc = false; string tx_json_save_file; bool print_request = false; bool print_response = false; bool no_auto_keosd = false; bool verbose = false; uint8_t tx_max_cpu_usage = 0; uint32_t tx_max_net_usage = 0; uint32_t delaysec = 0; vector<string> tx_permission; eosio::client::http::http_context context; void add_standard_transaction_options(CLI::App* cmd, string default_permission = "") { CLI::callback_t parse_expiration = [](CLI::results_t res) -> bool { double value_s; if (res.size() == 0 || !CLI::detail::lexical_cast(res[0], value_s)) { return false; } tx_expiration = fc::seconds(static_cast<uint64_t>(value_s)); return true; }; cmd->add_option("-x,--expiration", parse_expiration, localized("Set the time in seconds before a transaction expires, defaults to 30s")); cmd->add_flag("-f,--force-unique", tx_force_unique, localized("Force the transaction to be unique. this will consume extra bandwidth and remove any protections against accidently issuing the same transaction multiple times")); cmd->add_flag("-s,--skip-sign", tx_skip_sign, localized("Specify if unlocked wallet keys should be used to sign transaction")); cmd->add_flag("-j,--json", tx_print_json, localized("Print result as JSON")); cmd->add_option("--json-file", tx_json_save_file, localized("Save result in JSON format into a file")); cmd->add_flag("-d,--dont-broadcast", tx_dont_broadcast, localized("Don't broadcast transaction to the network (just print to stdout)")); cmd->add_flag("--return-packed", tx_return_packed, localized("Used in conjunction with --dont-broadcast to get the packed transaction")); cmd->add_option("-r,--ref-block", tx_ref_block_num_or_id, (localized("Set the reference block num or block id used for TAPOS (Transaction as Proof-of-Stake)"))); cmd->add_flag("--use-old-rpc", tx_use_old_rpc, localized("Use old RPC push_transaction, rather than new RPC send_transaction")); string msg = "An account and permission level to authorize, as in 'account@permission'"; if(!default_permission.empty()) msg += " (defaults to '" + default_permission + "')"; cmd->add_option("-p,--permission", tx_permission, localized(msg.c_str())); cmd->add_option("--max-cpu-usage-ms", tx_max_cpu_usage, localized("Set an upper limit on the milliseconds of cpu usage budget, for the execution of the transaction (defaults to 0 which means no limit)")); cmd->add_option("--max-net-usage", tx_max_net_usage, localized("Set an upper limit on the net usage budget, in bytes, for the transaction (defaults to 0 which means no limit)")); cmd->add_option("--delay-sec", delaysec, localized("Set the delay_sec seconds, defaults to 0s")); } bool is_public_key_str(const std::string& potential_key_str) { return boost::istarts_with(potential_key_str, "EOS") || boost::istarts_with(potential_key_str, "PUB_R1") || boost::istarts_with(potential_key_str, "PUB_K1") || boost::istarts_with(potential_key_str, "PUB_WA"); } class signing_keys_option { public: signing_keys_option() {} void add_option(CLI::App* cmd) { cmd->add_option("--sign-with", public_key_json, localized("The public key or json array of public keys to sign with")); } std::vector<public_key_type> get_keys() { std::vector<public_key_type> signing_keys; if (!public_key_json.empty()) { if (is_public_key_str(public_key_json)) { try { signing_keys.push_back(public_key_type(public_key_json)); } EOS_RETHROW_EXCEPTIONS(public_key_type_exception, "Invalid public key: ${public_key}", ("public_key", public_key_json)) } else { fc::variant json_keys; try { json_keys = fc::json::from_string(public_key_json, fc::json::relaxed_parser); } EOS_RETHROW_EXCEPTIONS(json_parse_exception, "Fail to parse JSON from string: ${string}", ("string", public_key_json)); try { std::vector<public_key_type> keys = json_keys.template as<std::vector<public_key_type>>(); signing_keys = std::move(keys); } EOS_RETHROW_EXCEPTIONS(public_key_type_exception, "Invalid public key array format '${data}'", ("data", fc::json::to_string(json_keys, fc::time_point::maximum()))) } } return signing_keys; } private: string public_key_json; }; signing_keys_option signing_keys_opt; void add_standard_transaction_options_plus_signing(CLI::App* cmd, string default_permission = "") { add_standard_transaction_options(cmd, default_permission); signing_keys_opt.add_option(cmd); } vector<chain::permission_level> get_account_permissions(const vector<string>& permissions) { auto fixedPermissions = permissions | boost::adaptors::transformed([](const string& p) { vector<string> pieces; split(pieces, p, boost::algorithm::is_any_of("@")); if( pieces.size() == 1 ) pieces.push_back( "active" ); return chain::permission_level{ .actor = name(pieces[0]), .permission = name(pieces[1]) }; }); vector<chain::permission_level> accountPermissions; boost::range::copy(fixedPermissions, back_inserter(accountPermissions)); return accountPermissions; } vector<chain::permission_level> get_account_permissions(const vector<string>& permissions, const chain::permission_level& default_permission) { if (permissions.empty()) return vector<chain::permission_level>{default_permission}; else return get_account_permissions(tx_permission); } template<typename T> fc::variant call( const std::string& url, const std::string& path, const T& v ) { try { auto sp = std::make_unique<eosio::client::http::connection_param>(context, parse_url(url) + path, no_verify ? false : true, headers); return eosio::client::http::do_http_call(*sp, fc::variant(v), print_request, print_response ); } catch(boost::system::system_error& e) { if(url == ::url) std::cerr << localized("Failed to connect to ${n} at ${u}; is ${n} running?", ("n", node_executable_name)("u", url)) << std::endl; else if(url == ::wallet_url) std::cerr << localized("Failed to connect to ${k} at ${u}; is ${k} running?", ("k", key_store_executable_name)("u", url)) << std::endl; throw connection_exception(fc::log_messages{FC_LOG_MESSAGE(error, e.what())}); } } template<typename T> fc::variant call( const std::string& path, const T& v ) { return call( url, path, fc::variant(v) ); } template<> fc::variant call( const std::string& url, const std::string& path) { return call( url, path, fc::variant() ); } eosio::chain_apis::read_only::get_info_results get_info() { return call(url, get_info_func).as<eosio::chain_apis::read_only::get_info_results>(); } string generate_nonce_string() { return fc::to_string(fc::time_point::now().time_since_epoch().count()); } chain::action generate_nonce_action() { return chain::action( {}, config::null_account_name, name("nonce"), fc::raw::pack(fc::time_point::now().time_since_epoch().count())); } void prompt_for_wallet_password(string& pw, const string& name) { if(pw.size() == 0 && name != "SecureEnclave") { std::cout << localized("password: "); fc::set_console_echo(false); std::getline( std::cin, pw, '\n' ); fc::set_console_echo(true); } } fc::variant determine_required_keys(const signed_transaction& trx) { // TODO better error checking //wdump((trx)); const auto& public_keys = call(wallet_url, wallet_public_keys); auto get_arg = fc::mutable_variant_object ("transaction", (transaction)trx) ("available_keys", public_keys); const auto& required_keys = call(get_required_keys, get_arg); return required_keys["required_keys"]; } void sign_transaction(signed_transaction& trx, fc::variant& required_keys, const chain_id_type& chain_id) { fc::variants sign_args = {fc::variant(trx), required_keys, fc::variant(chain_id)}; const auto& signed_trx = call(wallet_url, wallet_sign_trx, sign_args); trx = signed_trx.as<signed_transaction>(); } fc::variant push_transaction( signed_transaction& trx, const std::vector<public_key_type>& signing_keys = std::vector<public_key_type>(), packed_transaction::compression_type compression = packed_transaction::compression_type::none ) { auto info = get_info(); if (trx.signatures.size() == 0) { // #5445 can't change txn content if already signed trx.expiration = info.head_block_time + tx_expiration; // Set tapos, default to last irreversible block if it's not specified by the user block_id_type ref_block_id = info.last_irreversible_block_id; try { fc::variant ref_block; if (!tx_ref_block_num_or_id.empty()) { ref_block = call(get_block_func, fc::mutable_variant_object("block_num_or_id", tx_ref_block_num_or_id)); ref_block_id = ref_block["id"].as<block_id_type>(); } } EOS_RETHROW_EXCEPTIONS(invalid_ref_block_exception, "Invalid reference block num or id: ${block_num_or_id}", ("block_num_or_id", tx_ref_block_num_or_id)); trx.set_reference_block(ref_block_id); if (tx_force_unique) { trx.context_free_actions.emplace_back( generate_nonce_action() ); } trx.max_cpu_usage_ms = tx_max_cpu_usage; trx.max_net_usage_words = (tx_max_net_usage + 7)/8; trx.delay_sec = delaysec; } if (!tx_skip_sign) { fc::variant required_keys; if (signing_keys.size() > 0) { required_keys = fc::variant(signing_keys); } else { required_keys = determine_required_keys(trx); } sign_transaction(trx, required_keys, info.chain_id); } if (!tx_dont_broadcast) { if (tx_use_old_rpc) { return call(push_txn_func, packed_transaction(trx, compression)); } else { try { return call(send_txn_func, packed_transaction(trx, compression)); } catch (chain::missing_chain_api_plugin_exception &) { std::cerr << "New RPC send_transaction may not be supported. Add flag --use-old-rpc to use old RPC push_transaction instead." << std::endl; throw; } } } else { if (!tx_return_packed) { return fc::variant(trx); } else { return fc::variant(packed_transaction(trx, compression)); } } } fc::variant push_actions(std::vector<chain::action>&& actions, packed_transaction::compression_type compression = packed_transaction::compression_type::none, const std::vector<public_key_type>& signing_keys = std::vector<public_key_type>() ) { signed_transaction trx; trx.actions = std::forward<decltype(actions)>(actions); return push_transaction(trx, signing_keys, compression); } void print_action( const fc::variant& at ) { const auto& receipt = at["receipt"]; auto receiver = receipt["receiver"].as_string(); const auto& act = at["act"].get_object(); auto code = act["account"].as_string(); auto func = act["name"].as_string(); auto args = fc::json::to_string( act["data"], fc::time_point::maximum() ); auto console = at["console"].as_string(); /* if( code == "eosio" && func == "setcode" ) args = args.substr(40)+"..."; if( name(code) == config::system_account_name && func == "setabi" ) args = args.substr(40)+"..."; */ if( args.size() > 100 ) args = args.substr(0,100) + "..."; cout << "#" << std::setw(14) << right << receiver << " <= " << std::setw(28) << std::left << (code +"::" + func) << " " << args << "\n"; if( console.size() ) { std::stringstream ss(console); string line; while( std::getline( ss, line ) ) { cout << ">> " << line << "\n"; if( !verbose ) break; } } } //resolver for ABI serializer to decode actions in proposed transaction in multisig contract auto abi_serializer_resolver = [](const name& account) -> fc::optional<abi_serializer> { static unordered_map<account_name, fc::optional<abi_serializer> > abi_cache; auto it = abi_cache.find( account ); if ( it == abi_cache.end() ) { auto result = call(get_abi_func, fc::mutable_variant_object("account_name", account)); auto abi_results = result.as<eosio::chain_apis::read_only::get_abi_results>(); fc::optional<abi_serializer> abis; if( abi_results.abi.valid() ) { abis.emplace( *abi_results.abi, abi_serializer_max_time ); } else { std::cerr << "ABI for contract " << account.to_string() << " not found. Action data will be shown in hex only." << std::endl; } abi_cache.emplace( account, abis ); return abis; } return it->second; }; bytes variant_to_bin( const account_name& account, const action_name& action, const fc::variant& action_args_var ) { auto abis = abi_serializer_resolver( account ); FC_ASSERT( abis.valid(), "No ABI found for ${contract}", ("contract", account)); auto action_type = abis->get_action_type( action ); FC_ASSERT( !action_type.empty(), "Unknown action ${action} in contract ${contract}", ("action", action)( "contract", account )); return abis->variant_to_binary( action_type, action_args_var, abi_serializer_max_time ); } fc::variant bin_to_variant( const account_name& account, const action_name& action, const bytes& action_args) { auto abis = abi_serializer_resolver( account ); FC_ASSERT( abis.valid(), "No ABI found for ${contract}", ("contract", account)); auto action_type = abis->get_action_type( action ); FC_ASSERT( !action_type.empty(), "Unknown action ${action} in contract ${contract}", ("action", action)( "contract", account )); return abis->binary_to_variant( action_type, action_args, abi_serializer_max_time ); } fc::variant json_from_file_or_string(const string& file_or_str, fc::json::parse_type ptype = fc::json::legacy_parser) { regex r("^[ \t]*[\{\[]"); if ( !regex_search(file_or_str, r) && fc::is_regular_file(file_or_str) ) { try { return fc::json::from_file(file_or_str, ptype); } EOS_RETHROW_EXCEPTIONS(json_parse_exception, "Fail to parse JSON from file: ${file}", ("file", file_or_str)); } else { try { return fc::json::from_string(file_or_str, ptype); } EOS_RETHROW_EXCEPTIONS(json_parse_exception, "Fail to parse JSON from string: ${string}", ("string", file_or_str)); } } bytes json_or_file_to_bin( const account_name& account, const action_name& action, const string& data_or_filename ) { fc::variant action_args_var; if( !data_or_filename.empty() ) { action_args_var = json_from_file_or_string(data_or_filename, fc::json::relaxed_parser); } return variant_to_bin( account, action, action_args_var ); } void print_action_tree( const fc::variant& action ) { print_action( action ); if( action.get_object().contains( "inline_traces" ) ) { const auto& inline_traces = action["inline_traces"].get_array(); for( const auto& t : inline_traces ) { print_action_tree( t ); } } } void print_result( const fc::variant& result ) { try { if (result.is_object() && result.get_object().contains("processed")) { const auto& processed = result["processed"]; const auto& transaction_id = processed["id"].as_string(); string status = "failed"; int64_t net = -1; int64_t cpu = -1; if( processed.get_object().contains( "receipt" )) { const auto& receipt = processed["receipt"]; if( receipt.is_object()) { status = receipt["status"].as_string(); net = receipt["net_usage_words"].as_int64() * 8; cpu = receipt["cpu_usage_us"].as_int64(); } } cerr << status << " transaction: " << transaction_id << " "; if( net < 0 ) { cerr << "<unknown>"; } else { cerr << net; } cerr << " bytes "; if( cpu < 0 ) { cerr << "<unknown>"; } else { cerr << cpu; } cerr << " us\n"; if( status == "failed" ) { auto soft_except = processed["except"].as<fc::optional<fc::exception>>(); if( soft_except ) { edump((soft_except->to_detail_string())); } } else { const auto& actions = processed["action_traces"].get_array(); for( const auto& a : actions ) { print_action_tree( a ); } wlog( "\rwarning: transaction executed locally, but may not be confirmed by the network yet" ); } } else { cerr << fc::json::to_pretty_string( result ) << endl; } } FC_CAPTURE_AND_RETHROW( (result) ) } using std::cout; void send_actions(std::vector<chain::action>&& actions, const std::vector<public_key_type>& signing_keys = std::vector<public_key_type>(), packed_transaction::compression_type compression = packed_transaction::compression_type::none ) { std::ofstream out; if (tx_json_save_file.length()) { out.open(tx_json_save_file); EOSC_ASSERT(!out.fail(), "ERROR: Failed to create file \"${p}\"", ("p", tx_json_save_file)); } auto result = push_actions( move(actions), compression, signing_keys); string jsonstr; if (tx_json_save_file.length()) { jsonstr = fc::json::to_pretty_string( result ); out << jsonstr; out.close(); } if( tx_print_json ) { if (jsonstr.length() == 0) { jsonstr = fc::json::to_pretty_string( result ); } cout << jsonstr << endl; } else { print_result( result ); } } chain::permission_level to_permission_level(const std::string& s) { auto at_pos = s.find('@'); return permission_level { name(s.substr(0, at_pos)), name(s.substr(at_pos + 1)) }; } chain::action create_newaccount(const name& creator, const name& newaccount, auth_type owner, auth_type active) { return action { get_account_permissions(tx_permission, {creator,config::active_name}), eosio::chain::newaccount{ .creator = creator, .name = newaccount, .owner = owner.contains<public_key_type>() ? authority(owner.get<public_key_type>()) : authority(owner.get<permission_level>()), .active = active.contains<public_key_type>() ? authority(active.get<public_key_type>()) : authority(active.get<permission_level>()) } }; } chain::action create_action(const vector<permission_level>& authorization, const account_name& code, const action_name& act, const fc::variant& args) { return chain::action{authorization, code, act, variant_to_bin(code, act, args)}; } chain::action create_buyram(const name& creator, const name& newaccount, const asset& quantity) { fc::variant act_payload = fc::mutable_variant_object() ("payer", creator.to_string()) ("receiver", newaccount.to_string()) ("quant", quantity.to_string()); return create_action(get_account_permissions(tx_permission, {creator,config::active_name}), config::system_account_name, N(buyram), act_payload); } chain::action create_buyrambytes(const name& creator, const name& newaccount, uint32_t numbytes) { fc::variant act_payload = fc::mutable_variant_object() ("payer", creator.to_string()) ("receiver", newaccount.to_string()) ("bytes", numbytes); return create_action(get_account_permissions(tx_permission, {creator,config::active_name}), config::system_account_name, N(buyrambytes), act_payload); } chain::action create_delegate(const name& from, const name& receiver, const asset& net, const asset& cpu, bool transfer) { fc::variant act_payload = fc::mutable_variant_object() ("from", from.to_string()) ("receiver", receiver.to_string()) ("stake_net_quantity", net.to_string()) ("stake_cpu_quantity", cpu.to_string()) ("transfer", transfer); return create_action(get_account_permissions(tx_permission, {from,config::active_name}), config::system_account_name, N(delegatebw), act_payload); } fc::variant regproducer_variant(const account_name& producer, const public_key_type& key, const string& url, uint16_t location) { return fc::mutable_variant_object() ("producer", producer) ("producer_key", key) ("url", url) ("location", location) ; } chain::action create_open(const string& contract, const name& owner, symbol sym, const name& ram_payer) { auto open_ = fc::mutable_variant_object ("owner", owner) ("symbol", sym) ("ram_payer", ram_payer); return action { get_account_permissions(tx_permission, {ram_payer, config::active_name}), name(contract), N(open), variant_to_bin( name(contract), N(open), open_ ) }; } chain::action create_transfer(const string& contract, const name& sender, const name& recipient, asset amount, const string& memo ) { auto transfer = fc::mutable_variant_object ("from", sender) ("to", recipient) ("quantity", amount) ("memo", memo); return action { get_account_permissions(tx_permission, {sender,config::active_name}), name(contract), N(transfer), variant_to_bin( name(contract), N(transfer), transfer ) }; } chain::action create_setabi(const name& account, const bytes& abi) { return action { get_account_permissions(tx_permission, {account,config::active_name}), setabi{ .account = account, .abi = abi } }; } chain::action create_setcode(const name& account, const bytes& code) { return action { get_account_permissions(tx_permission, {account,config::active_name}), setcode{ .account = account, .vmtype = 0, .vmversion = 0, .code = code } }; } chain::action create_updateauth(const name& account, const name& permission, const name& parent, const authority& auth) { return action { get_account_permissions(tx_permission, {account,config::active_name}), updateauth{account, permission, parent, auth}}; } chain::action create_deleteauth(const name& account, const name& permission) { return action { get_account_permissions(tx_permission, {account,config::active_name}), deleteauth{account, permission}}; } chain::action create_linkauth(const name& account, const name& code, const name& type, const name& requirement) { return action { get_account_permissions(tx_permission, {account,config::active_name}), linkauth{account, code, type, requirement}}; } chain::action create_unlinkauth(const name& account, const name& code, const name& type) { return action { get_account_permissions(tx_permission, {account,config::active_name}), unlinkauth{account, code, type}}; } authority parse_json_authority(const std::string& authorityJsonOrFile) { fc::variant authority_var = json_from_file_or_string(authorityJsonOrFile); try { return authority_var.as<authority>(); } EOS_RETHROW_EXCEPTIONS(authority_type_exception, "Invalid authority format '${data}'", ("data", fc::json::to_string(authority_var, fc::time_point::maximum()))) } authority parse_json_authority_or_key(const std::string& authorityJsonOrFile) { if (is_public_key_str(authorityJsonOrFile)) { try { return authority(public_key_type(authorityJsonOrFile)); } EOS_RETHROW_EXCEPTIONS(public_key_type_exception, "Invalid public key: ${public_key}", ("public_key", authorityJsonOrFile)) } else { auto result = parse_json_authority(authorityJsonOrFile); EOS_ASSERT( eosio::chain::validate(result), authority_type_exception, "Authority failed validation! ensure that keys, accounts, and waits are sorted and that the threshold is valid and satisfiable!"); return result; } } asset to_asset( account_name code, const string& s ) { static map< pair<account_name, eosio::chain::symbol_code>, eosio::chain::symbol> cache; auto a = asset::from_string( s ); eosio::chain::symbol_code sym = a.get_symbol().to_symbol_code(); auto it = cache.find( make_pair(code, sym) ); auto sym_str = a.symbol_name(); if ( it == cache.end() ) { auto json = call(get_currency_stats_func, fc::mutable_variant_object("json", false) ("code", code) ("symbol", sym_str) ); auto obj = json.get_object(); auto obj_it = obj.find( sym_str ); if (obj_it != obj.end()) { auto result = obj_it->value().as<eosio::chain_apis::read_only::get_currency_stats_result>(); auto p = cache.emplace( make_pair( code, sym ), result.max_supply.get_symbol() ); it = p.first; } else { EOS_THROW(symbol_type_exception, "Symbol ${s} is not supported by token contract ${c}", ("s", sym_str)("c", code)); } } auto expected_symbol = it->second; if ( a.decimals() < expected_symbol.decimals() ) { auto factor = expected_symbol.precision() / a.precision(); a = asset( a.get_amount() * factor, expected_symbol ); } else if ( a.decimals() > expected_symbol.decimals() ) { EOS_THROW(symbol_type_exception, "Too many decimal digits in ${a}, only ${d} supported", ("a", a)("d", expected_symbol.decimals())); } // else precision matches return a; } inline asset to_asset( const string& s ) { return to_asset( N(eosio.token), s ); } struct set_account_permission_subcommand { string account; string permission; string authority_json_or_file; string parent; bool add_code; bool remove_code; set_account_permission_subcommand(CLI::App* accountCmd) { auto permissions = accountCmd->add_subcommand("permission", localized("Set parameters dealing with account permissions")); permissions->add_option("account", account, localized("The account to set/delete a permission authority for"))->required(); permissions->add_option("permission", permission, localized("The permission name to set/delete an authority for"))->required(); permissions->add_option("authority", authority_json_or_file, localized("[delete] NULL, [create/update] public key, JSON string or filename defining the authority, [code] contract name")); permissions->add_option("parent", parent, localized("[create] The permission name of this parents permission, defaults to 'active'")); permissions->add_flag("--add-code", add_code, localized("[code] add '${code}' permission to specified permission authority", ("code", name(config::eosio_code_name)))); permissions->add_flag("--remove-code", remove_code, localized("[code] remove '${code}' permission from specified permission authority", ("code", name(config::eosio_code_name)))); add_standard_transaction_options(permissions, "account@active"); permissions->set_callback([this] { EOSC_ASSERT( !(add_code && remove_code), "ERROR: Either --add-code or --remove-code can be set" ); EOSC_ASSERT( (add_code ^ remove_code) || !authority_json_or_file.empty(), "ERROR: authority should be specified unless add or remove code permission" ); authority auth; bool need_parent = parent.empty() && (name(permission) != name("owner")); bool need_auth = add_code || remove_code; if ( !need_auth && boost::iequals(authority_json_or_file, "null") ) { send_actions( { create_deleteauth(name(account), name(permission)) } ); return; } if ( need_parent || need_auth ) { fc::variant json = call(get_account_func, fc::mutable_variant_object("account_name", account)); auto res = json.as<eosio::chain_apis::read_only::get_account_results>(); auto itr = std::find_if(res.permissions.begin(), res.permissions.end(), [&](const auto& perm) { return perm.perm_name == name(permission); }); if ( need_parent ) { // see if we can auto-determine the proper parent if ( itr != res.permissions.end() ) { parent = (*itr).parent.to_string(); } else { // if this is a new permission and there is no parent we default to "active" parent = config::active_name.to_string(); } } if ( need_auth ) { auto actor = (authority_json_or_file.empty()) ? name(account) : name(authority_json_or_file); auto code_name = config::eosio_code_name; if ( itr != res.permissions.end() ) { // fetch existing authority auth = std::move((*itr).required_auth); auto code_perm = permission_level { actor, code_name }; auto itr2 = std::lower_bound(auth.accounts.begin(), auth.accounts.end(), code_perm, [&](const auto& perm_level, const auto& value) { return perm_level.permission < value; // Safe since valid authorities must order the permissions in accounts in ascending order }); if ( add_code ) { if ( itr2 != auth.accounts.end() && itr2->permission == code_perm ) { // authority already contains code permission, promote its weight to satisfy threshold if ( (*itr2).weight < auth.threshold ) { if ( auth.threshold > std::numeric_limits<weight_type>::max() ) { std::cerr << "ERROR: Threshold is too high to be satisfied by sole code permission" << std::endl; return; } std::cerr << localized("The weight of '${actor}@${code}' in '${permission}' permission authority will be increased up to threshold", ("actor", actor)("code", code_name)("permission", permission)) << std::endl; (*itr2).weight = static_cast<weight_type>(auth.threshold); } else { std::cerr << localized("ERROR: The permission '${permission}' already contains '${actor}@${code}'", ("permission", permission)("actor", actor)("code", code_name)) << std::endl; return ; } } else { // add code permission to specified authority if ( auth.threshold > std::numeric_limits<weight_type>::max() ) { std::cerr << "ERROR: Threshold is too high to be satisfied by sole code permission" << std::endl; return; } auth.accounts.insert( itr2, permission_level_weight { .permission = { actor, code_name }, .weight = static_cast<weight_type>(auth.threshold) }); } } else { if ( itr2 != auth.accounts.end() && itr2->permission == code_perm ) { // remove code permission, if authority becomes empty by the removal of code permission, delete permission auth.accounts.erase( itr2 ); if ( auth.keys.empty() && auth.accounts.empty() && auth.waits.empty() ) { send_actions( { create_deleteauth(name(account), name(permission)) } ); return; } } else { // authority doesn't contain code permission std::cerr << localized("ERROR: '${actor}@${code}' does not exist in '${permission}' permission authority", ("actor", actor)("code", code_name)("permission", permission)) << std::endl; return; } } } else { if ( add_code ) { // create new permission including code permission auth.threshold = 1; auth.accounts.push_back( permission_level_weight { .permission = { actor, code_name }, .weight = 1 }); } else { // specified permission doesn't exist, so failed to remove code permission from it std::cerr << localized("ERROR: The permission '${permission}' does not exist", ("permission", permission)) << std::endl; return; } } } } if ( !need_auth ) { auth = parse_json_authority_or_key(authority_json_or_file); } send_actions( { create_updateauth(name(account), name(permission), name(parent), auth) } ); }); } }; struct set_action_permission_subcommand { string accountStr; string codeStr; string typeStr; string requirementStr; set_action_permission_subcommand(CLI::App* actionRoot) { auto permissions = actionRoot->add_subcommand("permission", localized("Set paramaters dealing with account permissions")); permissions->add_option("account", accountStr, localized("The account to set/delete a permission authority for"))->required(); permissions->add_option("code", codeStr, localized("The account that owns the code for the action"))->required(); permissions->add_option("type", typeStr, localized("The type of the action"))->required(); permissions->add_option("requirement", requirementStr, localized("[delete] NULL, [set/update] The permission name require for executing the given action"))->required(); add_standard_transaction_options_plus_signing(permissions, "account@active"); permissions->set_callback([this] { name account = name(accountStr); name code = name(codeStr); name type = name(typeStr); bool is_delete = boost::iequals(requirementStr, "null"); if (is_delete) { send_actions({create_unlinkauth(account, code, type)}, signing_keys_opt.get_keys()); } else { name requirement = name(requirementStr); send_actions({create_linkauth(account, code, type, requirement)}, signing_keys_opt.get_keys()); } }); } }; bool local_port_used() { using namespace boost::asio; io_service ios; local::stream_protocol::endpoint endpoint(wallet_url.substr(strlen("unix://"))); local::stream_protocol::socket socket(ios); boost::system::error_code ec; socket.connect(endpoint, ec); return !ec; } void try_local_port(uint32_t duration) { using namespace std::chrono; auto start_time = duration_cast<std::chrono::milliseconds>( system_clock::now().time_since_epoch() ).count(); while ( !local_port_used()) { if (duration_cast<std::chrono::milliseconds>( system_clock::now().time_since_epoch()).count() - start_time > duration ) { std::cerr << "Unable to connect to " << key_store_executable_name << ", if " << key_store_executable_name << " is running please kill the process and try again.\n"; throw connection_exception(fc::log_messages{FC_LOG_MESSAGE(error, "Unable to connect to ${k}", ("k", key_store_executable_name))}); } } } void ensure_keosd_running(CLI::App* app) { if (no_auto_keosd) return; // get, version, net, convert do not require keosd if (tx_skip_sign || app->got_subcommand("get") || app->got_subcommand("version") || app->got_subcommand("net") || app->got_subcommand("convert")) return; if (app->get_subcommand("create")->got_subcommand("key")) // create key does not require wallet return; if (app->get_subcommand("multisig")->got_subcommand("review")) // multisig review does not require wallet return; if (auto* subapp = app->get_subcommand("system")) { if (subapp->got_subcommand("listproducers") || subapp->got_subcommand("listbw") || subapp->got_subcommand("bidnameinfo")) // system list* do not require wallet return; } if (wallet_url != default_wallet_url) return; if (local_port_used()) return; boost::filesystem::path binPath = boost::dll::program_location(); binPath.remove_filename(); // This extra check is necessary when running cleos like this: ./cleos ... if (binPath.filename_is_dot()) binPath.remove_filename(); binPath.append(key_store_executable_name); // if cleos and keosd are in the same installation directory if (!boost::filesystem::exists(binPath)) { binPath.remove_filename().remove_filename().append("keosd").append(key_store_executable_name); } if (boost::filesystem::exists(binPath)) { namespace bp = boost::process; binPath = boost::filesystem::canonical(binPath); vector<std::string> pargs; pargs.push_back("--http-server-address"); pargs.push_back(""); pargs.push_back("--https-server-address"); pargs.push_back(""); pargs.push_back("--unix-socket-path"); pargs.push_back(string(key_store_executable_name) + ".sock"); ::boost::process::child keos(binPath, pargs, bp::std_in.close(), bp::std_out > bp::null, bp::std_err > bp::null); if (keos.running()) { std::cerr << binPath << " launched" << std::endl; keos.detach(); try_local_port(2000); } else { std::cerr << "No wallet service listening on " << wallet_url << ". Failed to launch " << binPath << std::endl; } } else { std::cerr << "No wallet service listening on " << ". Cannot automatically start " << key_store_executable_name << " because " << key_store_executable_name << " was not found." << std::endl; } } CLI::callback_t obsoleted_option_host_port = [](CLI::results_t) { std::cerr << localized("Host and port options (-H, --wallet-host, etc.) have been replaced with -u/--url and --wallet-url\n" "Use for example -u http://localhost:8888 or --url https://example.invalid/\n"); exit(1); return false; }; struct register_producer_subcommand { string producer_str; string producer_key_str; string url; uint16_t loc = 0; register_producer_subcommand(CLI::App* actionRoot) { auto register_producer = actionRoot->add_subcommand("regproducer", localized("Register a new producer")); register_producer->add_option("account", producer_str, localized("The account to register as a producer"))->required(); register_producer->add_option("producer_key", producer_key_str, localized("The producer's public key"))->required(); register_producer->add_option("url", url, localized("The URL where info about producer can be found"), true); register_producer->add_option("location", loc, localized("Relative location for purpose of nearest neighbor scheduling"), true); add_standard_transaction_options_plus_signing(register_producer, "account@active"); register_producer->set_callback([this] { public_key_type producer_key; try { producer_key = public_key_type(producer_key_str); } EOS_RETHROW_EXCEPTIONS(public_key_type_exception, "Invalid producer public key: ${public_key}", ("public_key", producer_key_str)) auto regprod_var = regproducer_variant(name(producer_str), producer_key, url, loc ); auto accountPermissions = get_account_permissions(tx_permission, {name(producer_str), config::active_name}); send_actions({create_action(accountPermissions, config::system_account_name, N(regproducer), regprod_var)}, signing_keys_opt.get_keys()); }); } }; struct create_account_subcommand { string creator; string account_name; string owner_key_str; string active_key_str; string stake_net; string stake_cpu; uint32_t buy_ram_bytes_in_kbytes = 0; uint32_t buy_ram_bytes = 0; string buy_ram_eos; bool transfer; bool simple; create_account_subcommand(CLI::App* actionRoot, bool s) : simple(s) { auto createAccount = actionRoot->add_subcommand( (simple ? "account" : "newaccount"), (simple ? localized("Create a new account on the blockchain (assumes system contract does not restrict RAM usage)") : localized("Create a new account on the blockchain with initial resources") ) ); createAccount->add_option("creator", creator, localized("The name of the account creating the new account"))->required(); createAccount->add_option("name", account_name, localized("The name of the new account"))->required(); createAccount->add_option("OwnerKey", owner_key_str, localized("The owner public key or permission level for the new account"))->required(); createAccount->add_option("ActiveKey", active_key_str, localized("The active public key or permission level for the new account")); if (!simple) { createAccount->add_option("--stake-net", stake_net, (localized("The amount of tokens delegated for net bandwidth")))->required(); createAccount->add_option("--stake-cpu", stake_cpu, (localized("The amount of tokens delegated for CPU bandwidth")))->required(); createAccount->add_option("--buy-ram-kbytes", buy_ram_bytes_in_kbytes, (localized("The amount of RAM bytes to purchase for the new account in kibibytes (KiB)"))); createAccount->add_option("--buy-ram-bytes", buy_ram_bytes, (localized("The amount of RAM bytes to purchase for the new account in bytes"))); createAccount->add_option("--buy-ram", buy_ram_eos, (localized("The amount of RAM bytes to purchase for the new account in tokens"))); createAccount->add_flag("--transfer", transfer, (localized("Transfer voting power and right to unstake tokens to receiver"))); } add_standard_transaction_options_plus_signing(createAccount, "creator@active"); createAccount->set_callback([this] { auth_type owner, active; if( owner_key_str.find('@') != string::npos ) { try { owner = to_permission_level(owner_key_str); } EOS_RETHROW_EXCEPTIONS( explained_exception, "Invalid owner permission level: ${permission}", ("permission", owner_key_str) ) } else { try { owner = public_key_type(owner_key_str); } EOS_RETHROW_EXCEPTIONS( public_key_type_exception, "Invalid owner public key: ${public_key}", ("public_key", owner_key_str) ); } if( active_key_str.empty() ) { active = owner; } else if( active_key_str.find('@') != string::npos ) { try { active = to_permission_level(active_key_str); } EOS_RETHROW_EXCEPTIONS( explained_exception, "Invalid active permission level: ${permission}", ("permission", active_key_str) ) } else { try { active = public_key_type(active_key_str); } EOS_RETHROW_EXCEPTIONS( public_key_type_exception, "Invalid active public key: ${public_key}", ("public_key", active_key_str) ); } auto create = create_newaccount(name(creator), name(account_name), owner, active); if (!simple) { EOSC_ASSERT( buy_ram_eos.size() || buy_ram_bytes_in_kbytes || buy_ram_bytes, "ERROR: One of --buy-ram, --buy-ram-kbytes or --buy-ram-bytes should have non-zero value" ); EOSC_ASSERT( !buy_ram_bytes_in_kbytes || !buy_ram_bytes, "ERROR: --buy-ram-kbytes and --buy-ram-bytes cannot be set at the same time" ); action buyram = !buy_ram_eos.empty() ? create_buyram(name(creator), name(account_name), to_asset(buy_ram_eos)) : create_buyrambytes(name(creator), name(account_name), (buy_ram_bytes_in_kbytes) ? (buy_ram_bytes_in_kbytes * 1024) : buy_ram_bytes); auto net = to_asset(stake_net); auto cpu = to_asset(stake_cpu); if ( net.get_amount() != 0 || cpu.get_amount() != 0 ) { action delegate = create_delegate( name(creator), name(account_name), net, cpu, transfer); send_actions( { create, buyram, delegate }, signing_keys_opt.get_keys()); } else { send_actions( { create, buyram }, signing_keys_opt.get_keys()); } } else { send_actions( { create }, signing_keys_opt.get_keys()); } }); } }; struct unregister_producer_subcommand { string producer_str; unregister_producer_subcommand(CLI::App* actionRoot) { auto unregister_producer = actionRoot->add_subcommand("unregprod", localized("Unregister an existing producer")); unregister_producer->add_option("account", producer_str, localized("The account to unregister as a producer"))->required(); add_standard_transaction_options_plus_signing(unregister_producer, "account@active"); unregister_producer->set_callback([this] { fc::variant act_payload = fc::mutable_variant_object() ("producer", producer_str); auto accountPermissions = get_account_permissions(tx_permission, {name(producer_str), config::active_name}); send_actions({create_action(accountPermissions, config::system_account_name, N(unregprod), act_payload)}, signing_keys_opt.get_keys()); }); } }; struct vote_producer_proxy_subcommand { string voter_str; string proxy_str; vote_producer_proxy_subcommand(CLI::App* actionRoot) { auto vote_proxy = actionRoot->add_subcommand("proxy", localized("Vote your stake through a proxy")); vote_proxy->add_option("voter", voter_str, localized("The voting account"))->required(); vote_proxy->add_option("proxy", proxy_str, localized("The proxy account"))->required(); add_standard_transaction_options_plus_signing(vote_proxy, "voter@active"); vote_proxy->set_callback([this] { fc::variant act_payload = fc::mutable_variant_object() ("voter", voter_str) ("proxy", proxy_str) ("producers", std::vector<account_name>{}); auto accountPermissions = get_account_permissions(tx_permission, {name(voter_str), config::active_name}); send_actions({create_action(accountPermissions, config::system_account_name, N(voteproducer), act_payload)}, signing_keys_opt.get_keys()); }); } }; struct vote_producers_subcommand { string voter_str; vector<std::string> producer_names; vote_producers_subcommand(CLI::App* actionRoot) { auto vote_producers = actionRoot->add_subcommand("prods", localized("Vote for one or more producers")); vote_producers->add_option("voter", voter_str, localized("The voting account"))->required(); vote_producers->add_option("producers", producer_names, localized("The account(s) to vote for. All options from this position and following will be treated as the producer list."))->required(); add_standard_transaction_options_plus_signing(vote_producers, "voter@active"); vote_producers->set_callback([this] { std::sort( producer_names.begin(), producer_names.end() ); fc::variant act_payload = fc::mutable_variant_object() ("voter", voter_str) ("proxy", "") ("producers", producer_names); auto accountPermissions = get_account_permissions(tx_permission, {name(voter_str), config::active_name}); send_actions({create_action(accountPermissions, config::system_account_name, N(voteproducer), act_payload)}, signing_keys_opt.get_keys()); }); } }; struct approve_producer_subcommand { string voter; string producer_name; approve_producer_subcommand(CLI::App* actionRoot) { auto approve_producer = actionRoot->add_subcommand("approve", localized("Add one producer to list of voted producers")); approve_producer->add_option("voter", voter, localized("The voting account"))->required(); approve_producer->add_option("producer", producer_name, localized("The account to vote for"))->required(); add_standard_transaction_options_plus_signing(approve_producer, "voter@active"); approve_producer->set_callback([this] { auto result = call(get_table_func, fc::mutable_variant_object("json", true) ("code", name(config::system_account_name).to_string()) ("scope", name(config::system_account_name).to_string()) ("table", "voters") ("table_key", "owner") ("lower_bound", name(voter).to_uint64_t()) ("upper_bound", name(voter).to_uint64_t() + 1) // Less than ideal upper_bound usage preserved so cleos can still work with old buggy nodeos versions // Change to voter.value when cleos no longer needs to support nodeos versions older than 1.5.0 ("limit", 1) ); auto res = result.as<eosio::chain_apis::read_only::get_table_rows_result>(); // Condition in if statement below can simply be res.rows.empty() when cleos no longer needs to support nodeos versions older than 1.5.0 // Although since this subcommand will actually change the voter's vote, it is probably better to just keep this check to protect // against future potential chain_plugin bugs. if( res.rows.empty() || res.rows[0].get_object()["owner"].as_string() != name(voter).to_string() ) { std::cerr << "Voter info not found for account " << voter << std::endl; return; } EOS_ASSERT( 1 == res.rows.size(), multiple_voter_info, "More than one voter_info for account" ); auto prod_vars = res.rows[0]["producers"].get_array(); vector<eosio::name> prods; for ( auto& x : prod_vars ) { prods.push_back( name(x.as_string()) ); } prods.push_back( name(producer_name) ); std::sort( prods.begin(), prods.end() ); auto it = std::unique( prods.begin(), prods.end() ); if (it != prods.end() ) { std::cerr << "Producer \"" << producer_name << "\" is already on the list." << std::endl; return; } fc::variant act_payload = fc::mutable_variant_object() ("voter", voter) ("proxy", "") ("producers", prods); auto accountPermissions = get_account_permissions(tx_permission, {name(voter), config::active_name}); send_actions({create_action(accountPermissions, config::system_account_name, N(voteproducer), act_payload)}, signing_keys_opt.get_keys()); }); } }; struct unapprove_producer_subcommand { string voter; string producer_name; unapprove_producer_subcommand(CLI::App* actionRoot) { auto approve_producer = actionRoot->add_subcommand("unapprove", localized("Remove one producer from list of voted producers")); approve_producer->add_option("voter", voter, localized("The voting account"))->required(); approve_producer->add_option("producer", producer_name, localized("The account to remove from voted producers"))->required(); add_standard_transaction_options_plus_signing(approve_producer, "voter@active"); approve_producer->set_callback([this] { auto result = call(get_table_func, fc::mutable_variant_object("json", true) ("code", name(config::system_account_name).to_string()) ("scope", name(config::system_account_name).to_string()) ("table", "voters") ("table_key", "owner") ("lower_bound", name(voter).to_uint64_t()) ("upper_bound", name(voter).to_uint64_t() + 1) // Less than ideal upper_bound usage preserved so cleos can still work with old buggy nodeos versions // Change to voter.value when cleos no longer needs to support nodeos versions older than 1.5.0 ("limit", 1) ); auto res = result.as<eosio::chain_apis::read_only::get_table_rows_result>(); // Condition in if statement below can simply be res.rows.empty() when cleos no longer needs to support nodeos versions older than 1.5.0 // Although since this subcommand will actually change the voter's vote, it is probably better to just keep this check to protect // against future potential chain_plugin bugs. if( res.rows.empty() || res.rows[0].get_object()["owner"].as_string() != name(voter).to_string() ) { std::cerr << "Voter info not found for account " << voter << std::endl; return; } EOS_ASSERT( 1 == res.rows.size(), multiple_voter_info, "More than one voter_info for account" ); auto prod_vars = res.rows[0]["producers"].get_array(); vector<eosio::name> prods; for ( auto& x : prod_vars ) { prods.push_back( name(x.as_string()) ); } auto it = std::remove( prods.begin(), prods.end(), name(producer_name) ); if (it == prods.end() ) { std::cerr << "Cannot remove: producer \"" << producer_name << "\" is not on the list." << std::endl; return; } prods.erase( it, prods.end() ); //should always delete only one element fc::variant act_payload = fc::mutable_variant_object() ("voter", voter) ("proxy", "") ("producers", prods); auto accountPermissions = get_account_permissions(tx_permission, {name(voter), config::active_name}); send_actions({create_action(accountPermissions, config::system_account_name, N(voteproducer), act_payload)}, signing_keys_opt.get_keys()); }); } }; struct list_producers_subcommand { bool print_json = false; uint32_t limit = 50; std::string lower; list_producers_subcommand(CLI::App* actionRoot) { auto list_producers = actionRoot->add_subcommand("listproducers", localized("List producers")); list_producers->add_flag("--json,-j", print_json, localized("Output in JSON format")); list_producers->add_option("-l,--limit", limit, localized("The maximum number of rows to return")); list_producers->add_option("-L,--lower", lower, localized("Lower bound value of key, defaults to first")); list_producers->set_callback([this] { auto rawResult = call(get_producers_func, fc::mutable_variant_object ("json", true)("lower_bound", lower)("limit", limit)); if ( print_json ) { std::cout << fc::json::to_pretty_string(rawResult) << std::endl; return; } auto result = rawResult.as<eosio::chain_apis::read_only::get_producers_result>(); if ( result.rows.empty() ) { std::cout << "No producers found" << std::endl; return; } auto weight = result.total_producer_vote_weight; if ( !weight ) weight = 1; printf("%-13s %-57s %-59s %s\n", "Producer", "Producer key", "Url", "Scaled votes"); for ( auto& row : result.rows ) printf("%-13.13s %-57.57s %-59.59s %1.4f\n", row["owner"].as_string().c_str(), row["producer_key"].as_string().c_str(), row["url"].as_string().c_str(), row["total_votes"].as_double() / weight); if ( !result.more.empty() ) std::cout << "-L " << result.more << " for more" << std::endl; }); } }; struct get_schedule_subcommand { bool print_json = false; void print(const char* name, const fc::variant& schedule) { if (schedule.is_null()) { printf("%s schedule empty\n\n", name); return; } printf("%s schedule version %s\n", name, schedule["version"].as_string().c_str()); printf(" %-13s %s\n", "Producer", "Producer Authority"); printf(" %-13s %s\n", "=============", "=================="); for( auto& row: schedule["producers"].get_array() ) { if( row.get_object().contains("block_signing_key") ) { // pre 2.0 printf( " %-13s %s\n", row["producer_name"].as_string().c_str(), row["block_signing_key"].as_string().c_str() ); } else { printf( " %-13s ", row["producer_name"].as_string().c_str() ); auto a = row["authority"].as<block_signing_authority>(); static_assert( std::is_same<decltype(a), static_variant<block_signing_authority_v0>>::value, "Updates maybe needed if block_signing_authority changes" ); block_signing_authority_v0 auth = a.get<block_signing_authority_v0>(); printf( "%s\n", fc::json::to_string( auth, fc::time_point::maximum() ).c_str() ); } } printf("\n"); } get_schedule_subcommand(CLI::App* actionRoot) { auto get_schedule = actionRoot->add_subcommand("schedule", localized("Retrieve the producer schedule")); get_schedule->add_flag("--json,-j", print_json, localized("Output in JSON format")); get_schedule->set_callback([this] { auto result = call(get_schedule_func, fc::mutable_variant_object()); if ( print_json ) { std::cout << fc::json::to_pretty_string(result) << std::endl; return; } print("active", result["active"]); print("pending", result["pending"]); print("proposed", result["proposed"]); }); } }; struct get_transaction_id_subcommand { string trx_to_check; get_transaction_id_subcommand(CLI::App* actionRoot) { auto get_transaction_id = actionRoot->add_subcommand("transaction_id", localized("Get transaction id given transaction object")); get_transaction_id->add_option("transaction", trx_to_check, localized("The JSON string or filename defining the transaction which transaction id we want to retrieve"))->required(); get_transaction_id->set_callback([&] { try { fc::variant trx_var = json_from_file_or_string(trx_to_check); if( trx_var.is_object() ) { fc::variant_object& vo = trx_var.get_object(); // if actions.data & actions.hex_data provided, use the hex_data since only currently support unexploded data if( vo.contains("actions") ) { if( vo["actions"].is_array() ) { fc::mutable_variant_object mvo = vo; fc::variants& action_variants = mvo["actions"].get_array(); for( auto& action_v : action_variants ) { if( !action_v.is_object() ) { std::cerr << "Empty 'action' in transaction" << endl; return; } fc::variant_object& action_vo = action_v.get_object(); if( action_vo.contains( "data" ) && action_vo.contains( "hex_data" ) ) { fc::mutable_variant_object maction_vo = action_vo; maction_vo["data"] = maction_vo["hex_data"]; action_vo = maction_vo; vo = mvo; } else if( action_vo.contains( "data" ) ) { if( !action_vo["data"].is_string() ) { std::cerr << "get transaction_id only supports un-exploded 'data' (hex form)" << std::endl; return; } } } } else { std::cerr << "transaction json 'actions' is not an array" << std::endl; return; } } else { std::cerr << "transaction json does not include 'actions'" << std::endl; return; } auto trx = trx_var.as<transaction>(); transaction_id_type id = trx.id(); if( id == transaction().id() ) { std::cerr << "file/string does not represent a transaction" << std::endl; } else { std::cout << string( id ) << std::endl; } } else { std::cerr << "file/string does not represent a transaction" << std::endl; } } EOS_RETHROW_EXCEPTIONS(transaction_type_exception, "Fail to parse transaction JSON '${data}'", ("data",trx_to_check)) }); } }; struct delegate_bandwidth_subcommand { string from_str; string receiver_str; string stake_net_amount; string stake_cpu_amount; string stake_storage_amount; string buy_ram_amount; uint32_t buy_ram_bytes = 0; bool transfer = false; delegate_bandwidth_subcommand(CLI::App* actionRoot) { auto delegate_bandwidth = actionRoot->add_subcommand("delegatebw", localized("Delegate bandwidth")); delegate_bandwidth->add_option("from", from_str, localized("The account to delegate bandwidth from"))->required(); delegate_bandwidth->add_option("receiver", receiver_str, localized("The account to receive the delegated bandwidth"))->required(); delegate_bandwidth->add_option("stake_net_quantity", stake_net_amount, localized("The amount of tokens to stake for network bandwidth"))->required(); delegate_bandwidth->add_option("stake_cpu_quantity", stake_cpu_amount, localized("The amount of tokens to stake for CPU bandwidth"))->required(); delegate_bandwidth->add_option("--buyram", buy_ram_amount, localized("The amount of tokens to buy RAM with")); delegate_bandwidth->add_option("--buy-ram-bytes", buy_ram_bytes, localized("The amount of RAM to buy in bytes")); delegate_bandwidth->add_flag("--transfer", transfer, localized("Transfer voting power and right to unstake tokens to receiver")); add_standard_transaction_options_plus_signing(delegate_bandwidth, "from@active"); delegate_bandwidth->set_callback([this] { fc::variant act_payload = fc::mutable_variant_object() ("from", from_str) ("receiver", receiver_str) ("stake_net_quantity", to_asset(stake_net_amount)) ("stake_cpu_quantity", to_asset(stake_cpu_amount)) ("transfer", transfer); auto accountPermissions = get_account_permissions(tx_permission, {name(from_str), config::active_name}); std::vector<chain::action> acts{create_action(accountPermissions, config::system_account_name, N(delegatebw), act_payload)}; EOSC_ASSERT( !(buy_ram_amount.size()) || !buy_ram_bytes, "ERROR: --buyram and --buy-ram-bytes cannot be set at the same time" ); if (buy_ram_amount.size()) { acts.push_back( create_buyram(name(from_str), name(receiver_str), to_asset(buy_ram_amount)) ); } else if (buy_ram_bytes) { acts.push_back( create_buyrambytes(name(from_str), name(receiver_str), buy_ram_bytes) ); } send_actions(std::move(acts), signing_keys_opt.get_keys()); }); } }; struct undelegate_bandwidth_subcommand { string from_str; string receiver_str; string unstake_net_amount; string unstake_cpu_amount; uint64_t unstake_storage_bytes; undelegate_bandwidth_subcommand(CLI::App* actionRoot) { auto undelegate_bandwidth = actionRoot->add_subcommand("undelegatebw", localized("Undelegate bandwidth")); undelegate_bandwidth->add_option("from", from_str, localized("The account undelegating bandwidth"))->required(); undelegate_bandwidth->add_option("receiver", receiver_str, localized("The account to undelegate bandwidth from"))->required(); undelegate_bandwidth->add_option("unstake_net_quantity", unstake_net_amount, localized("The amount of tokens to undelegate for network bandwidth"))->required(); undelegate_bandwidth->add_option("unstake_cpu_quantity", unstake_cpu_amount, localized("The amount of tokens to undelegate for CPU bandwidth"))->required(); add_standard_transaction_options_plus_signing(undelegate_bandwidth, "from@active"); undelegate_bandwidth->set_callback([this] { fc::variant act_payload = fc::mutable_variant_object() ("from", from_str) ("receiver", receiver_str) ("unstake_net_quantity", to_asset(unstake_net_amount)) ("unstake_cpu_quantity", to_asset(unstake_cpu_amount)); auto accountPermissions = get_account_permissions(tx_permission, {name(from_str), config::active_name}); send_actions({create_action(accountPermissions, config::system_account_name, N(undelegatebw), act_payload)}, signing_keys_opt.get_keys()); }); } }; struct bidname_subcommand { string bidder_str; string newname_str; string bid_amount; bidname_subcommand(CLI::App *actionRoot) { auto bidname = actionRoot->add_subcommand("bidname", localized("Name bidding")); bidname->add_option("bidder", bidder_str, localized("The bidding account"))->required(); bidname->add_option("newname", newname_str, localized("The bidding name"))->required(); bidname->add_option("bid", bid_amount, localized("The amount of tokens to bid"))->required(); add_standard_transaction_options_plus_signing(bidname, "bidder@active"); bidname->set_callback([this] { fc::variant act_payload = fc::mutable_variant_object() ("bidder", bidder_str) ("newname", newname_str) ("bid", to_asset(bid_amount)); auto accountPermissions = get_account_permissions(tx_permission, {name(bidder_str), config::active_name}); send_actions({create_action(accountPermissions, config::system_account_name, N(bidname), act_payload)}, signing_keys_opt.get_keys()); }); } }; struct bidname_info_subcommand { bool print_json = false; string newname; bidname_info_subcommand(CLI::App* actionRoot) { auto list_producers = actionRoot->add_subcommand("bidnameinfo", localized("Get bidname info")); list_producers->add_flag("--json,-j", print_json, localized("Output in JSON format")); list_producers->add_option("newname", newname, localized("The bidding name"))->required(); list_producers->set_callback([this] { auto rawResult = call(get_table_func, fc::mutable_variant_object("json", true) ("code", name(config::system_account_name).to_string()) ("scope", name(config::system_account_name).to_string()) ("table", "namebids") ("lower_bound", name(newname).to_uint64_t()) ("upper_bound", name(newname).to_uint64_t() + 1) // Less than ideal upper_bound usage preserved so cleos can still work with old buggy nodeos versions // Change to newname.value when cleos no longer needs to support nodeos versions older than 1.5.0 ("limit", 1)); if ( print_json ) { std::cout << fc::json::to_pretty_string(rawResult) << std::endl; return; } auto result = rawResult.as<eosio::chain_apis::read_only::get_table_rows_result>(); // Condition in if statement below can simply be res.rows.empty() when cleos no longer needs to support nodeos versions older than 1.5.0 if( result.rows.empty() || result.rows[0].get_object()["newname"].as_string() != name(newname).to_string() ) { std::cout << "No bidname record found" << std::endl; return; } const auto& row = result.rows[0]; string time = row["last_bid_time"].as_string(); try { time = (string)fc::time_point(fc::microseconds(to_uint64(time))); } catch (fc::parse_error_exception&) { } int64_t bid = row["high_bid"].as_int64(); std::cout << std::left << std::setw(18) << "bidname:" << std::right << std::setw(24) << row["newname"].as_string() << "\n" << std::left << std::setw(18) << "highest bidder:" << std::right << std::setw(24) << row["high_bidder"].as_string() << "\n" << std::left << std::setw(18) << "highest bid:" << std::right << std::setw(24) << (bid > 0 ? bid : -bid) << "\n" << std::left << std::setw(18) << "last bid time:" << std::right << std::setw(24) << time << std::endl; if (bid < 0) std::cout << "This auction has already closed" << std::endl; }); } }; struct list_bw_subcommand { string account; bool print_json = false; list_bw_subcommand(CLI::App* actionRoot) { auto list_bw = actionRoot->add_subcommand("listbw", localized("List delegated bandwidth")); list_bw->add_option("account", account, localized("The account delegated bandwidth"))->required(); list_bw->add_flag("--json,-j", print_json, localized("Output in JSON format") ); list_bw->set_callback([this] { //get entire table in scope of user account auto result = call(get_table_func, fc::mutable_variant_object("json", true) ("code", name(config::system_account_name).to_string()) ("scope", name(account).to_string()) ("table", "delband") ); if (!print_json) { auto res = result.as<eosio::chain_apis::read_only::get_table_rows_result>(); if ( !res.rows.empty() ) { std::cout << std::setw(13) << std::left << "Receiver" << std::setw(21) << std::left << "Net bandwidth" << std::setw(21) << std::left << "CPU bandwidth" << std::endl; for ( auto& r : res.rows ){ std::cout << std::setw(13) << std::left << r["to"].as_string() << std::setw(21) << std::left << r["net_weight"].as_string() << std::setw(21) << std::left << r["cpu_weight"].as_string() << std::endl; } } else { std::cerr << "Delegated bandwidth not found" << std::endl; } } else { std::cout << fc::json::to_pretty_string(result) << std::endl; } }); } }; struct buyram_subcommand { string from_str; string receiver_str; string amount; bool kbytes = false; bool bytes = false; buyram_subcommand(CLI::App* actionRoot) { auto buyram = actionRoot->add_subcommand("buyram", localized("Buy RAM")); buyram->add_option("payer", from_str, localized("The account paying for RAM"))->required(); buyram->add_option("receiver", receiver_str, localized("The account receiving bought RAM"))->required(); buyram->add_option("amount", amount, localized("The amount of tokens to pay for RAM, or number of bytes/kibibytes of RAM if --bytes/--kbytes is set"))->required(); buyram->add_flag("--kbytes,-k", kbytes, localized("The amount to buy in kibibytes (KiB)")); buyram->add_flag("--bytes,-b", bytes, localized("The amount to buy in bytes")); add_standard_transaction_options_plus_signing(buyram, "payer@active"); buyram->set_callback([this] { EOSC_ASSERT( !kbytes || !bytes, "ERROR: --kbytes and --bytes cannot be set at the same time" ); if (kbytes || bytes) { send_actions( { create_buyrambytes(name(from_str), name(receiver_str), fc::to_uint64(amount) * ((kbytes) ? 1024ull : 1ull)) }, signing_keys_opt.get_keys()); } else { send_actions( { create_buyram(name(from_str), name(receiver_str), to_asset(amount)) }, signing_keys_opt.get_keys()); } }); } }; struct sellram_subcommand { string from_str; string receiver_str; uint64_t amount; sellram_subcommand(CLI::App* actionRoot) { auto sellram = actionRoot->add_subcommand("sellram", localized("Sell RAM")); sellram->add_option("account", receiver_str, localized("The account to receive tokens for sold RAM"))->required(); sellram->add_option("bytes", amount, localized("The amount of RAM bytes to sell"))->required(); add_standard_transaction_options_plus_signing(sellram, "account@active"); sellram->set_callback([this] { fc::variant act_payload = fc::mutable_variant_object() ("account", receiver_str) ("bytes", amount); auto accountPermissions = get_account_permissions(tx_permission, {name(receiver_str), config::active_name}); send_actions({create_action(accountPermissions, config::system_account_name, N(sellram), act_payload)}, signing_keys_opt.get_keys()); }); } }; struct claimrewards_subcommand { string owner; claimrewards_subcommand(CLI::App* actionRoot) { auto claim_rewards = actionRoot->add_subcommand("claimrewards", localized("Claim producer rewards")); claim_rewards->add_option("owner", owner, localized("The account to claim rewards for"))->required(); add_standard_transaction_options_plus_signing(claim_rewards, "owner@active"); claim_rewards->set_callback([this] { fc::variant act_payload = fc::mutable_variant_object() ("owner", owner); auto accountPermissions = get_account_permissions(tx_permission, {name(owner), config::active_name}); send_actions({create_action(accountPermissions, config::system_account_name, N(claimrewards), act_payload)}, signing_keys_opt.get_keys()); }); } }; struct regproxy_subcommand { string proxy; regproxy_subcommand(CLI::App* actionRoot) { auto register_proxy = actionRoot->add_subcommand("regproxy", localized("Register an account as a proxy (for voting)")); register_proxy->add_option("proxy", proxy, localized("The proxy account to register"))->required(); add_standard_transaction_options_plus_signing(register_proxy, "proxy@active"); register_proxy->set_callback([this] { fc::variant act_payload = fc::mutable_variant_object() ("proxy", proxy) ("isproxy", true); auto accountPermissions = get_account_permissions(tx_permission, {name(proxy), config::active_name}); send_actions({create_action(accountPermissions, config::system_account_name, N(regproxy), act_payload)}, signing_keys_opt.get_keys()); }); } }; struct unregproxy_subcommand { string proxy; unregproxy_subcommand(CLI::App* actionRoot) { auto unregister_proxy = actionRoot->add_subcommand("unregproxy", localized("Unregister an account as a proxy (for voting)")); unregister_proxy->add_option("proxy", proxy, localized("The proxy account to unregister"))->required(); add_standard_transaction_options_plus_signing(unregister_proxy, "proxy@active"); unregister_proxy->set_callback([this] { fc::variant act_payload = fc::mutable_variant_object() ("proxy", proxy) ("isproxy", false); auto accountPermissions = get_account_permissions(tx_permission, {name(proxy), config::active_name}); send_actions({create_action(accountPermissions, config::system_account_name, N(regproxy), act_payload)}, signing_keys_opt.get_keys()); }); } }; struct canceldelay_subcommand { string canceling_account; string canceling_permission; string trx_id; canceldelay_subcommand(CLI::App* actionRoot) { auto cancel_delay = actionRoot->add_subcommand("canceldelay", localized("Cancel a delayed transaction")); cancel_delay->add_option("canceling_account", canceling_account, localized("Account from authorization on the original delayed transaction"))->required(); cancel_delay->add_option("canceling_permission", canceling_permission, localized("Permission from authorization on the original delayed transaction"))->required(); cancel_delay->add_option("trx_id", trx_id, localized("The transaction id of the original delayed transaction"))->required(); add_standard_transaction_options_plus_signing(cancel_delay, "canceling_account@canceling_permission"); cancel_delay->set_callback([this] { auto canceling_auth = permission_level{name(canceling_account), name(canceling_permission)}; fc::variant act_payload = fc::mutable_variant_object() ("canceling_auth", canceling_auth) ("trx_id", trx_id); auto accountPermissions = get_account_permissions(tx_permission, canceling_auth); send_actions({create_action(accountPermissions, config::system_account_name, N(canceldelay), act_payload)}, signing_keys_opt.get_keys()); }); } }; struct deposit_subcommand { string owner_str; string amount_str; const name act_name{ N(deposit) }; deposit_subcommand(CLI::App* actionRoot) { auto deposit = actionRoot->add_subcommand("deposit", localized("Deposit into owner's REX fund by transfering from owner's liquid token balance")); deposit->add_option("owner", owner_str, localized("Account which owns the REX fund"))->required(); deposit->add_option("amount", amount_str, localized("Amount to be deposited into REX fund"))->required(); add_standard_transaction_options_plus_signing(deposit, "owner@active"); deposit->set_callback([this] { fc::variant act_payload = fc::mutable_variant_object() ("owner", owner_str) ("amount", amount_str); auto accountPermissions = get_account_permissions(tx_permission, {name(owner_str), config::active_name}); send_actions({create_action(accountPermissions, config::system_account_name, act_name, act_payload)}, signing_keys_opt.get_keys()); }); } }; struct withdraw_subcommand { string owner_str; string amount_str; const name act_name{ N(withdraw) }; withdraw_subcommand(CLI::App* actionRoot) { auto withdraw = actionRoot->add_subcommand("withdraw", localized("Withdraw from owner's REX fund by transfering to owner's liquid token balance")); withdraw->add_option("owner", owner_str, localized("Account which owns the REX fund"))->required(); withdraw->add_option("amount", amount_str, localized("Amount to be withdrawn from REX fund"))->required(); add_standard_transaction_options_plus_signing(withdraw, "owner@active"); withdraw->set_callback([this] { fc::variant act_payload = fc::mutable_variant_object() ("owner", owner_str) ("amount", amount_str); auto accountPermissions = get_account_permissions(tx_permission, {name(owner_str), config::active_name}); send_actions({create_action(accountPermissions, config::system_account_name, act_name, act_payload)}, signing_keys_opt.get_keys()); }); } }; struct buyrex_subcommand { string from_str; string amount_str; const name act_name{ N(buyrex) }; buyrex_subcommand(CLI::App* actionRoot) { auto buyrex = actionRoot->add_subcommand("buyrex", localized("Buy REX using tokens in owner's REX fund")); buyrex->add_option("from", from_str, localized("Account buying REX tokens"))->required(); buyrex->add_option("amount", amount_str, localized("Amount to be taken from REX fund and used in buying REX"))->required(); add_standard_transaction_options_plus_signing(buyrex, "from@active"); buyrex->set_callback([this] { fc::variant act_payload = fc::mutable_variant_object() ("from", from_str) ("amount", amount_str); auto accountPermissions = get_account_permissions(tx_permission, {name(from_str), config::active_name}); send_actions({create_action(accountPermissions, config::system_account_name, act_name, act_payload)}, signing_keys_opt.get_keys()); }); } }; struct lendrex_subcommand { string from_str; string amount_str; const name act_name1{ N(deposit) }; const name act_name2{ N(buyrex) }; lendrex_subcommand(CLI::App* actionRoot) { auto lendrex = actionRoot->add_subcommand("lendrex", localized("Deposit tokens to REX fund and use the tokens to buy REX")); lendrex->add_option("from", from_str, localized("Account buying REX tokens"))->required(); lendrex->add_option("amount", amount_str, localized("Amount of liquid tokens to be used in buying REX"))->required(); add_standard_transaction_options_plus_signing(lendrex, "from@active"); lendrex->set_callback([this] { fc::variant act_payload1 = fc::mutable_variant_object() ("owner", from_str) ("amount", amount_str); fc::variant act_payload2 = fc::mutable_variant_object() ("from", from_str) ("amount", amount_str); auto accountPermissions = get_account_permissions(tx_permission, {name(from_str), config::active_name}); send_actions({create_action(accountPermissions, config::system_account_name, act_name1, act_payload1), create_action(accountPermissions, config::system_account_name, act_name2, act_payload2)}, signing_keys_opt.get_keys()); }); } }; struct unstaketorex_subcommand { string owner_str; string receiver_str; string from_net_str; string from_cpu_str; const name act_name{ N(unstaketorex) }; unstaketorex_subcommand(CLI::App* actionRoot) { auto unstaketorex = actionRoot->add_subcommand("unstaketorex", localized("Buy REX using staked tokens")); unstaketorex->add_option("owner", owner_str, localized("Account buying REX tokens"))->required(); unstaketorex->add_option("receiver", receiver_str, localized("Account that tokens have been staked to"))->required(); unstaketorex->add_option("from_net", from_net_str, localized("Amount to be unstaked from Net resources and used in REX purchase"))->required(); unstaketorex->add_option("from_cpu", from_cpu_str, localized("Amount to be unstaked from CPU resources and used in REX purchase"))->required(); add_standard_transaction_options_plus_signing(unstaketorex, "owner@active"); unstaketorex->set_callback([this] { fc::variant act_payload = fc::mutable_variant_object() ("owner", owner_str) ("receiver", receiver_str) ("from_net", from_net_str) ("from_cpu", from_cpu_str); auto accountPermissions = get_account_permissions(tx_permission, {name(owner_str), config::active_name}); send_actions({create_action(accountPermissions, config::system_account_name, act_name, act_payload)}, signing_keys_opt.get_keys()); }); } }; struct sellrex_subcommand { string from_str; string rex_str; const name act_name{ N(sellrex) }; sellrex_subcommand(CLI::App* actionRoot) { auto sellrex = actionRoot->add_subcommand("sellrex", localized("Sell REX tokens")); sellrex->add_option("from", from_str, localized("Account selling REX tokens"))->required(); sellrex->add_option("rex", rex_str, localized("Amount of REX tokens to be sold"))->required(); add_standard_transaction_options_plus_signing(sellrex, "from@active"); sellrex->set_callback([this] { fc::variant act_payload = fc::mutable_variant_object() ("from", from_str) ("rex", rex_str); auto accountPermissions = get_account_permissions(tx_permission, {name(from_str), config::active_name}); send_actions({create_action(accountPermissions, config::system_account_name, act_name, act_payload)}, signing_keys_opt.get_keys()); }); } }; struct cancelrexorder_subcommand { string owner_str; const name act_name{ N(cnclrexorder) }; cancelrexorder_subcommand(CLI::App* actionRoot) { auto cancelrexorder = actionRoot->add_subcommand("cancelrexorder", localized("Cancel queued REX sell order if one exists")); cancelrexorder->add_option("owner", owner_str, localized("Owner account of sell order"))->required(); add_standard_transaction_options_plus_signing(cancelrexorder, "owner@active"); cancelrexorder->set_callback([this] { fc::variant act_payload = fc::mutable_variant_object()("owner", owner_str); auto accountPermissions = get_account_permissions(tx_permission, {name(owner_str), config::active_name}); send_actions({create_action(accountPermissions, config::system_account_name, act_name, act_payload)}, signing_keys_opt.get_keys()); }); } }; struct rentcpu_subcommand { string from_str; string receiver_str; string loan_payment_str; string loan_fund_str; const name act_name{ N(rentcpu) }; rentcpu_subcommand(CLI::App* actionRoot) { auto rentcpu = actionRoot->add_subcommand("rentcpu", localized("Rent CPU bandwidth for 30 days")); rentcpu->add_option("from", from_str, localized("Account paying rent fees"))->required(); rentcpu->add_option("receiver", receiver_str, localized("Account to whom rented CPU bandwidth is staked"))->required(); rentcpu->add_option("loan_payment", loan_payment_str, localized("Loan fee to be paid, used to calculate amount of rented bandwidth"))->required(); rentcpu->add_option("loan_fund", loan_fund_str, localized("Loan fund to be used in automatic renewal, can be 0 tokens"))->required(); add_standard_transaction_options_plus_signing(rentcpu, "from@active"); rentcpu->set_callback([this] { fc::variant act_payload = fc::mutable_variant_object() ("from", from_str) ("receiver", receiver_str) ("loan_payment", loan_payment_str) ("loan_fund", loan_fund_str); auto accountPermissions = get_account_permissions(tx_permission, {name(from_str), config::active_name}); send_actions({create_action(accountPermissions, config::system_account_name, act_name, act_payload)}, signing_keys_opt.get_keys()); }); } }; struct rentnet_subcommand { string from_str; string receiver_str; string loan_payment_str; string loan_fund_str; const name act_name{ N(rentnet) }; rentnet_subcommand(CLI::App* actionRoot) { auto rentnet = actionRoot->add_subcommand("rentnet", localized("Rent Network bandwidth for 30 days")); rentnet->add_option("from", from_str, localized("Account paying rent fees"))->required(); rentnet->add_option("receiver", receiver_str, localized("Account to whom rented Network bandwidth is staked"))->required(); rentnet->add_option("loan_payment", loan_payment_str, localized("Loan fee to be paid, used to calculate amount of rented bandwidth"))->required(); rentnet->add_option("loan_fund", loan_fund_str, localized("Loan fund to be used in automatic renewal, can be 0 tokens"))->required(); add_standard_transaction_options_plus_signing(rentnet, "from@active"); rentnet->set_callback([this] { fc::variant act_payload = fc::mutable_variant_object() ("from", from_str) ("receiver", receiver_str) ("loan_payment", loan_payment_str) ("loan_fund", loan_fund_str); auto accountPermissions = get_account_permissions(tx_permission, {name(from_str), config::active_name}); send_actions({create_action(accountPermissions, config::system_account_name, act_name, act_payload)}, signing_keys_opt.get_keys()); }); } }; struct fundcpuloan_subcommand { string from_str; string loan_num_str; string payment_str; const name act_name{ N(fundcpuloan) }; fundcpuloan_subcommand(CLI::App* actionRoot) { auto fundcpuloan = actionRoot->add_subcommand("fundcpuloan", localized("Deposit into a CPU loan fund")); fundcpuloan->add_option("from", from_str, localized("Loan owner"))->required(); fundcpuloan->add_option("loan_num", loan_num_str, localized("Loan ID"))->required(); fundcpuloan->add_option("payment", payment_str, localized("Amount to be deposited"))->required(); add_standard_transaction_options_plus_signing(fundcpuloan, "from@active"); fundcpuloan->set_callback([this] { fc::variant act_payload = fc::mutable_variant_object() ("from", from_str) ("loan_num", loan_num_str) ("payment", payment_str); auto accountPermissions = get_account_permissions(tx_permission, {name(from_str), config::active_name}); send_actions({create_action(accountPermissions, config::system_account_name, act_name, act_payload)}, signing_keys_opt.get_keys()); }); } }; struct fundnetloan_subcommand { string from_str; string loan_num_str; string payment_str; const name act_name{ N(fundnetloan) }; fundnetloan_subcommand(CLI::App* actionRoot) { auto fundnetloan = actionRoot->add_subcommand("fundnetloan", localized("Deposit into a Network loan fund")); fundnetloan->add_option("from", from_str, localized("Loan owner"))->required(); fundnetloan->add_option("loan_num", loan_num_str, localized("Loan ID"))->required(); fundnetloan->add_option("payment", payment_str, localized("Amount to be deposited"))->required(); add_standard_transaction_options_plus_signing(fundnetloan, "from@active"); fundnetloan->set_callback([this] { fc::variant act_payload = fc::mutable_variant_object() ("from", from_str) ("loan_num", loan_num_str) ("payment", payment_str); auto accountPermissions = get_account_permissions(tx_permission, {name(from_str), config::active_name}); send_actions({create_action(accountPermissions, config::system_account_name, act_name, act_payload)}, signing_keys_opt.get_keys()); }); } }; struct defcpuloan_subcommand { string from_str; string loan_num_str; string amount_str; const name act_name{ N(defcpuloan) }; defcpuloan_subcommand(CLI::App* actionRoot) { auto defcpuloan = actionRoot->add_subcommand("defundcpuloan", localized("Withdraw from a CPU loan fund")); defcpuloan->add_option("from", from_str, localized("Loan owner"))->required(); defcpuloan->add_option("loan_num", loan_num_str, localized("Loan ID"))->required(); defcpuloan->add_option("amount", amount_str, localized("Amount to be withdrawn"))->required(); add_standard_transaction_options_plus_signing(defcpuloan, "from@active"); defcpuloan->set_callback([this] { fc::variant act_payload = fc::mutable_variant_object() ("from", from_str) ("loan_num", loan_num_str) ("amount", amount_str); auto accountPermissions = get_account_permissions(tx_permission, {name(from_str), config::active_name}); send_actions({create_action(accountPermissions, config::system_account_name, act_name, act_payload)}, signing_keys_opt.get_keys()); }); } }; struct defnetloan_subcommand { string from_str; string loan_num_str; string amount_str; const name act_name{ N(defnetloan) }; defnetloan_subcommand(CLI::App* actionRoot) { auto defnetloan = actionRoot->add_subcommand("defundnetloan", localized("Withdraw from a Network loan fund")); defnetloan->add_option("from", from_str, localized("Loan owner"))->required(); defnetloan->add_option("loan_num", loan_num_str, localized("Loan ID"))->required(); defnetloan->add_option("amount", amount_str, localized("Amount to be withdrawn"))->required(); add_standard_transaction_options_plus_signing(defnetloan, "from@active"); defnetloan->set_callback([this] { fc::variant act_payload = fc::mutable_variant_object() ("from", from_str) ("loan_num", loan_num_str) ("amount", amount_str); auto accountPermissions = get_account_permissions(tx_permission, {name(from_str), config::active_name}); send_actions({create_action(accountPermissions, config::system_account_name, act_name, act_payload)}, signing_keys_opt.get_keys()); }); } }; struct mvtosavings_subcommand { string owner_str; string rex_str; const name act_name{ N(mvtosavings) }; mvtosavings_subcommand(CLI::App* actionRoot) { auto mvtosavings = actionRoot->add_subcommand("mvtosavings", localized("Move REX tokens to savings bucket")); mvtosavings->add_option("owner", owner_str, localized("REX owner"))->required(); mvtosavings->add_option("rex", rex_str, localized("Amount of REX to be moved to savings bucket"))->required(); add_standard_transaction_options_plus_signing(mvtosavings, "owner@active"); mvtosavings->set_callback([this] { fc::variant act_payload = fc::mutable_variant_object() ("owner", owner_str) ("rex", rex_str); auto accountPermissions = get_account_permissions(tx_permission, {name(owner_str), config::active_name}); send_actions({create_action(accountPermissions, config::system_account_name, act_name, act_payload)}, signing_keys_opt.get_keys()); }); } }; struct mvfrsavings_subcommand { string owner_str; string rex_str; const name act_name{ N(mvfrsavings) }; mvfrsavings_subcommand(CLI::App* actionRoot) { auto mvfrsavings = actionRoot->add_subcommand("mvfromsavings", localized("Move REX tokens out of savings bucket")); mvfrsavings->add_option("owner", owner_str, localized("REX owner"))->required(); mvfrsavings->add_option("rex", rex_str, localized("Amount of REX to be moved out of savings bucket"))->required(); add_standard_transaction_options_plus_signing(mvfrsavings, "owner@active"); mvfrsavings->set_callback([this] { fc::variant act_payload = fc::mutable_variant_object() ("owner", owner_str) ("rex", rex_str); auto accountPermissions = get_account_permissions(tx_permission, {name(owner_str), config::active_name}); send_actions({create_action(accountPermissions, config::system_account_name, act_name, act_payload)}, signing_keys_opt.get_keys()); }); } }; struct updaterex_subcommand { string owner_str; const name act_name{ N(updaterex) }; updaterex_subcommand(CLI::App* actionRoot) { auto updaterex = actionRoot->add_subcommand("updaterex", localized("Update REX owner vote stake and vote weight")); updaterex->add_option("owner", owner_str, localized("REX owner"))->required(); add_standard_transaction_options_plus_signing(updaterex, "owner@active"); updaterex->set_callback([this] { fc::variant act_payload = fc::mutable_variant_object()("owner", owner_str); auto accountPermissions = get_account_permissions(tx_permission, {name(owner_str), config::active_name}); send_actions({create_action(accountPermissions, config::system_account_name, act_name, act_payload)}, signing_keys_opt.get_keys()); }); } }; struct consolidate_subcommand { string owner_str; const name act_name{ N(consolidate) }; consolidate_subcommand(CLI::App* actionRoot) { auto consolidate = actionRoot->add_subcommand("consolidate", localized("Consolidate REX maturity buckets into one that matures in 4 days")); consolidate->add_option("owner", owner_str, localized("REX owner"))->required(); add_standard_transaction_options_plus_signing(consolidate, "owner@active"); consolidate->set_callback([this] { fc::variant act_payload = fc::mutable_variant_object()("owner", owner_str); auto accountPermissions = get_account_permissions(tx_permission, {name(owner_str), config::active_name}); send_actions({create_action(accountPermissions, config::system_account_name, act_name, act_payload)}, signing_keys_opt.get_keys()); }); } }; struct rexexec_subcommand { string user_str; string max_str; const name act_name{ N(rexexec) }; rexexec_subcommand(CLI::App* actionRoot) { auto rexexec = actionRoot->add_subcommand("rexexec", localized("Perform REX maintenance by processing expired loans and unfilled sell orders")); rexexec->add_option("user", user_str, localized("User executing the action"))->required(); rexexec->add_option("max", max_str, localized("Maximum number of CPU loans, Network loans, and sell orders to be processed"))->required(); add_standard_transaction_options_plus_signing(rexexec, "user@active"); rexexec->set_callback([this] { fc::variant act_payload = fc::mutable_variant_object() ("user", user_str) ("max", max_str); auto accountPermissions = get_account_permissions(tx_permission, {name(user_str), config::active_name}); send_actions({create_action(accountPermissions, config::system_account_name, act_name, act_payload)}, signing_keys_opt.get_keys()); }); } }; struct closerex_subcommand { string owner_str; const name act_name{ N(closerex) }; closerex_subcommand(CLI::App* actionRoot) { auto closerex = actionRoot->add_subcommand("closerex", localized("Delete unused REX-related user table entries")); closerex->add_option("owner", owner_str, localized("REX owner"))->required(); add_standard_transaction_options_plus_signing(closerex, "owner@active"); closerex->set_callback([this] { fc::variant act_payload = fc::mutable_variant_object()("owner", owner_str); auto accountPermissions = get_account_permissions(tx_permission, {name(owner_str), config::active_name}); send_actions({create_action(accountPermissions, config::system_account_name, act_name, act_payload)}, signing_keys_opt.get_keys()); }); } }; void get_account( const string& accountName, const string& coresym, bool json_format ) { fc::variant json; if (coresym.empty()) { json = call(get_account_func, fc::mutable_variant_object("account_name", accountName)); } else { json = call(get_account_func, fc::mutable_variant_object("account_name", accountName)("expected_core_symbol", symbol::from_string(coresym))); } auto res = json.as<eosio::chain_apis::read_only::get_account_results>(); if (!json_format) { asset staked; asset unstaking; if( res.core_liquid_balance.valid() ) { unstaking = asset( 0, res.core_liquid_balance->get_symbol() ); // Correct core symbol for unstaking asset. staked = asset( 0, res.core_liquid_balance->get_symbol() ); // Correct core symbol for staked asset. } std::cout << "created: " << string(res.created) << std::endl; if(res.privileged) std::cout << "privileged: true" << std::endl; constexpr size_t indent_size = 5; const string indent(indent_size, ' '); std::cout << "permissions: " << std::endl; unordered_map<name, vector<name>/*children*/> tree; vector<name> roots; //we don't have multiple roots, but we can easily handle them here, so let's do it just in case unordered_map<name, eosio::chain_apis::permission> cache; for ( auto& perm : res.permissions ) { if ( perm.parent ) { tree[perm.parent].push_back( perm.perm_name ); } else { roots.push_back( perm.perm_name ); } auto name = perm.perm_name; //keep copy before moving `perm`, since thirst argument of emplace can be evaluated first // looks a little crazy, but should be efficient cache.insert( std::make_pair(name, std::move(perm)) ); } std::function<void (account_name, int)> dfs_print = [&]( account_name name, int depth ) -> void { auto& p = cache.at(name); std::cout << indent << std::string(depth*3, ' ') << name << ' ' << std::setw(5) << p.required_auth.threshold << ": "; const char *sep = ""; for ( auto it = p.required_auth.keys.begin(); it != p.required_auth.keys.end(); ++it ) { std::cout << sep << it->weight << ' ' << it->key.to_string(); sep = ", "; } for ( auto& acc : p.required_auth.accounts ) { std::cout << sep << acc.weight << ' ' << acc.permission.actor.to_string() << '@' << acc.permission.permission.to_string(); sep = ", "; } std::cout << std::endl; auto it = tree.find( name ); if (it != tree.end()) { auto& children = it->second; sort( children.begin(), children.end() ); for ( auto& n : children ) { // we have a tree, not a graph, so no need to check for already visited nodes dfs_print( n, depth+1 ); } } // else it's a leaf node }; std::sort(roots.begin(), roots.end()); for ( auto r : roots ) { dfs_print( r, 0 ); } auto to_pretty_net = []( int64_t nbytes, uint8_t width_for_units = 5 ) { if(nbytes == -1) { // special case. Treat it as unlimited return std::string("unlimited"); } string unit = "bytes"; double bytes = static_cast<double> (nbytes); if (bytes >= 1024 * 1024 * 1024 * 1024ll) { unit = "TiB"; bytes /= 1024 * 1024 * 1024 * 1024ll; } else if (bytes >= 1024 * 1024 * 1024) { unit = "GiB"; bytes /= 1024 * 1024 * 1024; } else if (bytes >= 1024 * 1024) { unit = "MiB"; bytes /= 1024 * 1024; } else if (bytes >= 1024) { unit = "KiB"; bytes /= 1024; } std::stringstream ss; ss << setprecision(4); ss << bytes << " "; if( width_for_units > 0 ) ss << std::left << setw( width_for_units ); ss << unit; return ss.str(); }; std::cout << "memory: " << std::endl << indent << "quota: " << std::setw(15) << to_pretty_net(res.ram_quota) << " used: " << std::setw(15) << to_pretty_net(res.ram_usage) << std::endl << std::endl; std::cout << "net bandwidth: " << std::endl; if ( res.total_resources.is_object() ) { auto net_total = to_asset(res.total_resources.get_object()["net_weight"].as_string()); if( net_total.get_symbol() != unstaking.get_symbol() ) { // Core symbol of nodeos responding to the request is different than core symbol built into cleos unstaking = asset( 0, net_total.get_symbol() ); // Correct core symbol for unstaking asset. staked = asset( 0, net_total.get_symbol() ); // Correct core symbol for staked asset. } if( res.self_delegated_bandwidth.is_object() ) { asset net_own = asset::from_string( res.self_delegated_bandwidth.get_object()["net_weight"].as_string() ); staked = net_own; auto net_others = net_total - net_own; std::cout << indent << "staked:" << std::setw(20) << net_own << std::string(11, ' ') << "(total stake delegated from account to self)" << std::endl << indent << "delegated:" << std::setw(17) << net_others << std::string(11, ' ') << "(total staked delegated to account from others)" << std::endl; } else { auto net_others = net_total; std::cout << indent << "delegated:" << std::setw(17) << net_others << std::string(11, ' ') << "(total staked delegated to account from others)" << std::endl; } } auto to_pretty_time = []( int64_t nmicro, uint8_t width_for_units = 5 ) { if(nmicro == -1) { // special case. Treat it as unlimited return std::string("unlimited"); } string unit = "us"; double micro = static_cast<double>(nmicro); if( micro > 1000000*60*60ll ) { micro /= 1000000*60*60ll; unit = "hr"; } else if( micro > 1000000*60 ) { micro /= 1000000*60; unit = "min"; } else if( micro > 1000000 ) { micro /= 1000000; unit = "sec"; } else if( micro > 1000 ) { micro /= 1000; unit = "ms"; } std::stringstream ss; ss << setprecision(4); ss << micro << " "; if( width_for_units > 0 ) ss << std::left << setw( width_for_units ); ss << unit; return ss.str(); }; std::cout << std::fixed << setprecision(3); std::cout << indent << std::left << std::setw(11) << "used:" << std::right << std::setw(18) << to_pretty_net( res.net_limit.used ) << "\n"; std::cout << indent << std::left << std::setw(11) << "available:" << std::right << std::setw(18) << to_pretty_net( res.net_limit.available ) << "\n"; std::cout << indent << std::left << std::setw(11) << "limit:" << std::right << std::setw(18) << to_pretty_net( res.net_limit.max ) << "\n"; std::cout << std::endl; std::cout << "cpu bandwidth:" << std::endl; if ( res.total_resources.is_object() ) { auto cpu_total = to_asset(res.total_resources.get_object()["cpu_weight"].as_string()); if( res.self_delegated_bandwidth.is_object() ) { asset cpu_own = asset::from_string( res.self_delegated_bandwidth.get_object()["cpu_weight"].as_string() ); staked += cpu_own; auto cpu_others = cpu_total - cpu_own; std::cout << indent << "staked:" << std::setw(20) << cpu_own << std::string(11, ' ') << "(total stake delegated from account to self)" << std::endl << indent << "delegated:" << std::setw(17) << cpu_others << std::string(11, ' ') << "(total staked delegated to account from others)" << std::endl; } else { auto cpu_others = cpu_total; std::cout << indent << "delegated:" << std::setw(17) << cpu_others << std::string(11, ' ') << "(total staked delegated to account from others)" << std::endl; } } std::cout << std::fixed << setprecision(3); std::cout << indent << std::left << std::setw(11) << "used:" << std::right << std::setw(18) << to_pretty_time( res.cpu_limit.used ) << "\n"; std::cout << indent << std::left << std::setw(11) << "available:" << std::right << std::setw(18) << to_pretty_time( res.cpu_limit.available ) << "\n"; std::cout << indent << std::left << std::setw(11) << "limit:" << std::right << std::setw(18) << to_pretty_time( res.cpu_limit.max ) << "\n"; std::cout << std::endl; if( res.refund_request.is_object() ) { auto obj = res.refund_request.get_object(); auto request_time = fc::time_point_sec::from_iso_string( obj["request_time"].as_string() ); fc::time_point refund_time = request_time + fc::days(3); auto now = res.head_block_time; asset net = asset::from_string( obj["net_amount"].as_string() ); asset cpu = asset::from_string( obj["cpu_amount"].as_string() ); unstaking = net + cpu; if( unstaking > asset( 0, unstaking.get_symbol() ) ) { std::cout << std::fixed << setprecision(3); std::cout << "unstaking tokens:" << std::endl; std::cout << indent << std::left << std::setw(25) << "time of unstake request:" << std::right << std::setw(20) << string(request_time); if( now >= refund_time ) { std::cout << " (available to claim now with 'eosio::refund' action)\n"; } else { std::cout << " (funds will be available in " << to_pretty_time( (refund_time - now).count(), 0 ) << ")\n"; } std::cout << indent << std::left << std::setw(25) << "from net bandwidth:" << std::right << std::setw(18) << net << std::endl; std::cout << indent << std::left << std::setw(25) << "from cpu bandwidth:" << std::right << std::setw(18) << cpu << std::endl; std::cout << indent << std::left << std::setw(25) << "total:" << std::right << std::setw(18) << unstaking << std::endl; std::cout << std::endl; } } if( res.core_liquid_balance.valid() ) { std::cout << res.core_liquid_balance->get_symbol().name() << " balances: " << std::endl; std::cout << indent << std::left << std::setw(11) << "liquid:" << std::right << std::setw(18) << *res.core_liquid_balance << std::endl; std::cout << indent << std::left << std::setw(11) << "staked:" << std::right << std::setw(18) << staked << std::endl; std::cout << indent << std::left << std::setw(11) << "unstaking:" << std::right << std::setw(18) << unstaking << std::endl; std::cout << indent << std::left << std::setw(11) << "total:" << std::right << std::setw(18) << (*res.core_liquid_balance + staked + unstaking) << std::endl; std::cout << std::endl; } if( res.rex_info.is_object() ) { auto& obj = res.rex_info.get_object(); asset vote_stake = asset::from_string( obj["vote_stake"].as_string() ); asset rex_balance = asset::from_string( obj["rex_balance"].as_string() ); std::cout << rex_balance.get_symbol().name() << " balances: " << std::endl; std::cout << indent << std::left << std::setw(11) << "balance:" << std::right << std::setw(18) << rex_balance << std::endl; std::cout << indent << std::left << std::setw(11) << "staked:" << std::right << std::setw(18) << vote_stake << std::endl; std::cout << std::endl; } if ( res.voter_info.is_object() ) { auto& obj = res.voter_info.get_object(); string proxy = obj["proxy"].as_string(); if ( proxy.empty() ) { auto& prods = obj["producers"].get_array(); std::cout << "producers:"; if ( !prods.empty() ) { for ( size_t i = 0; i < prods.size(); ++i ) { if ( i%3 == 0 ) { std::cout << std::endl << indent; } std::cout << std::setw(16) << std::left << prods[i].as_string(); } std::cout << std::endl; } else { std::cout << indent << "<not voted>" << std::endl; } } else { std::cout << "proxy:" << indent << proxy << std::endl; } } std::cout << std::endl; } else { std::cout << fc::json::to_pretty_string(json) << std::endl; } } CLI::callback_t header_opt_callback = [](CLI::results_t res) { vector<string>::iterator itr; for (itr = res.begin(); itr != res.end(); itr++) { headers.push_back(*itr); } return true; }; int main( int argc, char** argv ) { fc::logger::get(DEFAULT_LOGGER).set_log_level(fc::log_level::debug); context = eosio::client::http::create_http_context(); wallet_url = default_wallet_url; CLI::App app{"Command Line Interface to EOSIO Client"}; app.require_subcommand(); app.add_option( "-H,--host", obsoleted_option_host_port, localized("The host where ${n} is running", ("n", node_executable_name)) )->group("hidden"); app.add_option( "-p,--port", obsoleted_option_host_port, localized("The port where ${n} is running", ("n", node_executable_name)) )->group("hidden"); app.add_option( "--wallet-host", obsoleted_option_host_port, localized("The host where ${k} is running", ("k", key_store_executable_name)) )->group("hidden"); app.add_option( "--wallet-port", obsoleted_option_host_port, localized("The port where ${k} is running", ("k", key_store_executable_name)) )->group("hidden"); app.add_option( "-u,--url", url, localized("The http/https URL where ${n} is running", ("n", node_executable_name)), true ); app.add_option( "--wallet-url", wallet_url, localized("The http/https URL where ${k} is running", ("k", key_store_executable_name)), true ); app.add_option( "-r,--header", header_opt_callback, localized("Pass specific HTTP header; repeat this option to pass multiple headers")); app.add_flag( "-n,--no-verify", no_verify, localized("Don't verify peer certificate when using HTTPS")); app.add_flag( "--no-auto-" + string(key_store_executable_name), no_auto_keosd, localized("Don't automatically launch a ${k} if one is not currently running", ("k", key_store_executable_name))); app.set_callback([&app]{ ensure_keosd_running(&app);}); app.add_flag( "-v,--verbose", verbose, localized("Output verbose errors and action console output")); app.add_flag("--print-request", print_request, localized("Print HTTP request to STDERR")); app.add_flag("--print-response", print_response, localized("Print HTTP response to STDERR")); auto version = app.add_subcommand("version", localized("Retrieve version information"), false); version->require_subcommand(); version->add_subcommand("client", localized("Retrieve basic version information of the client"))->set_callback([] { std::cout << eosio::version::version_client() << '\n'; }); version->add_subcommand("full", localized("Retrieve full version information of the client"))->set_callback([] { std::cout << eosio::version::version_full() << '\n'; }); // Create subcommand auto create = app.add_subcommand("create", localized("Create various items, on and off the blockchain"), false); create->require_subcommand(); bool r1 = false; string key_file; bool print_console = false; // create key auto create_key = create->add_subcommand("key", localized("Create a new keypair and print the public and private keys"))->set_callback( [&r1, &key_file, &print_console](){ if (key_file.empty() && !print_console) { std::cerr << "ERROR: Either indicate a file using \"--file\" or pass \"--to-console\"" << std::endl; return; } auto pk = r1 ? private_key_type::generate_r1() : private_key_type::generate(); auto privs = pk.to_string(); auto pubs = pk.get_public_key().to_string(); if (print_console) { std::cout << localized("Private key: ${key}", ("key", privs) ) << std::endl; std::cout << localized("Public key: ${key}", ("key", pubs ) ) << std::endl; } else { std::cerr << localized("saving keys to ${filename}", ("filename", key_file)) << std::endl; std::ofstream out( key_file.c_str() ); out << localized("Private key: ${key}", ("key", privs) ) << std::endl; out << localized("Public key: ${key}", ("key", pubs ) ) << std::endl; } }); create_key->add_flag( "--r1", r1, "Generate a key using the R1 curve (iPhone), instead of the K1 curve (Bitcoin)" ); create_key->add_option("-f,--file", key_file, localized("Name of file to write private/public key output to. (Must be set, unless \"--to-console\" is passed")); create_key->add_flag( "--to-console", print_console, localized("Print private/public keys to console.")); // create account auto createAccount = create_account_subcommand( create, true /*simple*/ ); // convert subcommand auto convert = app.add_subcommand("convert", localized("Pack and unpack transactions"), false); // TODO also add converting action args based on abi from here ? convert->require_subcommand(); // pack transaction string plain_signed_transaction_json; bool pack_action_data_flag = false; auto pack_transaction = convert->add_subcommand("pack_transaction", localized("From plain signed JSON to packed form")); pack_transaction->add_option("transaction", plain_signed_transaction_json, localized("The plain signed JSON (string)"))->required(); pack_transaction->add_flag("--pack-action-data", pack_action_data_flag, localized("Pack all action data within transaction, needs interaction with ${n}", ("n", node_executable_name))); pack_transaction->set_callback([&] { fc::variant trx_var = json_from_file_or_string( plain_signed_transaction_json ); if( pack_action_data_flag ) { signed_transaction trx; try { abi_serializer::from_variant( trx_var, trx, abi_serializer_resolver, abi_serializer_max_time ); } EOS_RETHROW_EXCEPTIONS( transaction_type_exception, "Invalid transaction format: '${data}'", ("data", fc::json::to_string(trx_var, fc::time_point::maximum()))) std::cout << fc::json::to_pretty_string( packed_transaction( trx, packed_transaction::compression_type::none )) << std::endl; } else { try { signed_transaction trx = trx_var.as<signed_transaction>(); std::cout << fc::json::to_pretty_string( fc::variant( packed_transaction( trx, packed_transaction::compression_type::none ))) << std::endl; } EOS_RETHROW_EXCEPTIONS( transaction_type_exception, "Fail to convert transaction, --pack-action-data likely needed" ) } }); // unpack transaction string packed_transaction_json; bool unpack_action_data_flag = false; auto unpack_transaction = convert->add_subcommand("unpack_transaction", localized("From packed to plain signed JSON form")); unpack_transaction->add_option("transaction", packed_transaction_json, localized("The packed transaction JSON (string containing packed_trx and optionally compression fields)"))->required(); unpack_transaction->add_flag("--unpack-action-data", unpack_action_data_flag, localized("Unpack all action data within transaction, needs interaction with ${n}", ("n", node_executable_name))); unpack_transaction->set_callback([&] { fc::variant packed_trx_var = json_from_file_or_string( packed_transaction_json ); packed_transaction packed_trx; try { fc::from_variant<packed_transaction>( packed_trx_var, packed_trx ); } EOS_RETHROW_EXCEPTIONS( transaction_type_exception, "Invalid packed transaction format: '${data}'", ("data", fc::json::to_string(packed_trx_var, fc::time_point::maximum()))) signed_transaction strx = packed_trx.get_signed_transaction(); fc::variant trx_var; if( unpack_action_data_flag ) { abi_serializer::to_variant( strx, trx_var, abi_serializer_resolver, abi_serializer_max_time ); } else { trx_var = strx; } std::cout << fc::json::to_pretty_string( trx_var ) << std::endl; }); // pack action data string unpacked_action_data_account_string; string unpacked_action_data_name_string; string unpacked_action_data_string; auto pack_action_data = convert->add_subcommand("pack_action_data", localized("From JSON action data to packed form")); pack_action_data->add_option("account", unpacked_action_data_account_string, localized("The name of the account hosting the contract"))->required(); pack_action_data->add_option("name", unpacked_action_data_name_string, localized("The name of the function called by this action"))->required(); pack_action_data->add_option("unpacked_action_data", unpacked_action_data_string, localized("The action data expressed as JSON"))->required(); pack_action_data->set_callback([&] { fc::variant unpacked_action_data_json = json_from_file_or_string(unpacked_action_data_string); bytes packed_action_data_string; try { packed_action_data_string = variant_to_bin(name(unpacked_action_data_account_string), name(unpacked_action_data_name_string), unpacked_action_data_json); } EOS_RETHROW_EXCEPTIONS(transaction_type_exception, "Fail to parse unpacked action data JSON") std::cout << fc::to_hex(packed_action_data_string.data(), packed_action_data_string.size()) << std::endl; }); // unpack action data string packed_action_data_account_string; string packed_action_data_name_string; string packed_action_data_string; auto unpack_action_data = convert->add_subcommand("unpack_action_data", localized("From packed to JSON action data form")); unpack_action_data->add_option("account", packed_action_data_account_string, localized("The name of the account that hosts the contract"))->required(); unpack_action_data->add_option("name", packed_action_data_name_string, localized("The name of the function that's called by this action"))->required(); unpack_action_data->add_option("packed_action_data", packed_action_data_string, localized("The action data expressed as packed hex string"))->required(); unpack_action_data->set_callback([&] { EOS_ASSERT( packed_action_data_string.size() >= 2, transaction_type_exception, "No packed_action_data found" ); vector<char> packed_action_data_blob(packed_action_data_string.size()/2); fc::from_hex(packed_action_data_string, packed_action_data_blob.data(), packed_action_data_blob.size()); fc::variant unpacked_action_data_json = bin_to_variant(name(packed_action_data_account_string), name(packed_action_data_name_string), packed_action_data_blob); std::cout << fc::json::to_pretty_string(unpacked_action_data_json) << std::endl; }); // Get subcommand auto get = app.add_subcommand("get", localized("Retrieve various items and information from the blockchain"), false); get->require_subcommand(); // get info get->add_subcommand("info", localized("Get current blockchain information"))->set_callback([] { std::cout << fc::json::to_pretty_string(get_info()) << std::endl; }); // get block string blockArg; bool get_bhs = false; auto getBlock = get->add_subcommand("block", localized("Retrieve a full block from the blockchain"), false); getBlock->add_option("block", blockArg, localized("The number or ID of the block to retrieve"))->required(); getBlock->add_flag("--header-state", get_bhs, localized("Get block header state from fork database instead") ); getBlock->set_callback([&blockArg,&get_bhs] { auto arg = fc::mutable_variant_object("block_num_or_id", blockArg); if( get_bhs ) { std::cout << fc::json::to_pretty_string(call(get_block_header_state_func, arg)) << std::endl; } else { std::cout << fc::json::to_pretty_string(call(get_block_func, arg)) << std::endl; } }); // get account string accountName; string coresym; bool print_json; auto getAccount = get->add_subcommand("account", localized("Retrieve an account from the blockchain"), false); getAccount->add_option("name", accountName, localized("The name of the account to retrieve"))->required(); getAccount->add_option("core-symbol", coresym, localized("The expected core symbol of the chain you are querying")); getAccount->add_flag("--json,-j", print_json, localized("Output in JSON format") ); getAccount->set_callback([&]() { get_account(accountName, coresym, print_json); }); // get code string codeFilename; string abiFilename; bool code_as_wasm = false; auto getCode = get->add_subcommand("code", localized("Retrieve the code and ABI for an account"), false); getCode->add_option("name", accountName, localized("The name of the account whose code should be retrieved"))->required(); getCode->add_option("-c,--code",codeFilename, localized("The name of the file to save the contract .wast/wasm to") ); getCode->add_option("-a,--abi",abiFilename, localized("The name of the file to save the contract .abi to") ); getCode->add_flag("--wasm", code_as_wasm, localized("Save contract as wasm")); getCode->set_callback([&] { string code_hash, wasm, wast, abi; try { const auto result = call(get_raw_code_and_abi_func, fc::mutable_variant_object("account_name", accountName)); const std::vector<char> wasm_v = result["wasm"].as_blob().data; const std::vector<char> abi_v = result["abi"].as_blob().data; fc::sha256 hash; if(wasm_v.size()) hash = fc::sha256::hash(wasm_v.data(), wasm_v.size()); code_hash = (string)hash; wasm = string(wasm_v.begin(), wasm_v.end()); if(!code_as_wasm && wasm_v.size()) wast = wasm_to_wast((const uint8_t*)wasm_v.data(), wasm_v.size(), false); abi_def abi_d; if(abi_serializer::to_abi(abi_v, abi_d)) abi = fc::json::to_pretty_string(abi_d); } catch(chain::missing_chain_api_plugin_exception&) { //see if this is an old nodeos that doesn't support get_raw_code_and_abi const auto old_result = call(get_code_func, fc::mutable_variant_object("account_name", accountName)("code_as_wasm",code_as_wasm)); code_hash = old_result["code_hash"].as_string(); if(code_as_wasm) { wasm = old_result["wasm"].as_string(); std::cout << localized("Warning: communicating to older ${n} which returns malformed binary wasm", ("n", node_executable_name)) << std::endl; } else wast = old_result["wast"].as_string(); abi = fc::json::to_pretty_string(old_result["abi"]); } std::cout << localized("code hash: ${code_hash}", ("code_hash", code_hash)) << std::endl; if( codeFilename.size() ){ std::cout << localized("saving ${type} to ${codeFilename}", ("type", (code_as_wasm ? "wasm" : "wast"))("codeFilename", codeFilename)) << std::endl; std::ofstream out( codeFilename.c_str() ); if(code_as_wasm) out << wasm; else out << wast; } if( abiFilename.size() ) { std::cout << localized("saving abi to ${abiFilename}", ("abiFilename", abiFilename)) << std::endl; std::ofstream abiout( abiFilename.c_str() ); abiout << abi; } }); // get abi string filename; auto getAbi = get->add_subcommand("abi", localized("Retrieve the ABI for an account"), false); getAbi->add_option("name", accountName, localized("The name of the account whose abi should be retrieved"))->required(); getAbi->add_option("-f,--file",filename, localized("The name of the file to save the contract .abi to instead of writing to console") ); getAbi->set_callback([&] { auto result = call(get_abi_func, fc::mutable_variant_object("account_name", accountName)); auto abi = fc::json::to_pretty_string( result["abi"] ); if( filename.size() ) { std::cerr << localized("saving abi to ${filename}", ("filename", filename)) << std::endl; std::ofstream abiout( filename.c_str() ); abiout << abi; } else { std::cout << abi << "\n"; } }); // get table string scope; string code; string table; string lower; string upper; string table_key; string key_type; string encode_type{"dec"}; bool binary = false; uint32_t limit = 10; string index_position; bool reverse = false; bool show_payer = false; auto getTable = get->add_subcommand( "table", localized("Retrieve the contents of a database table"), false); getTable->add_option( "account", code, localized("The account who owns the table") )->required(); getTable->add_option( "scope", scope, localized("The scope within the contract in which the table is found") )->required(); getTable->add_option( "table", table, localized("The name of the table as specified by the contract abi") )->required(); getTable->add_option( "-l,--limit", limit, localized("The maximum number of rows to return") ); getTable->add_option( "-k,--key", table_key, localized("Deprecated") ); getTable->add_option( "-L,--lower", lower, localized("JSON representation of lower bound value of key, defaults to first") ); getTable->add_option( "-U,--upper", upper, localized("JSON representation of upper bound value of key, defaults to last") ); getTable->add_option( "--index", index_position, localized("Index number, 1 - primary (first), 2 - secondary index (in order defined by multi_index), 3 - third index, etc.\n" "\t\t\t\tNumber or name of index can be specified, e.g. 'secondary' or '2'.")); getTable->add_option( "--key-type", key_type, localized("The key type of --index, primary only supports (i64), all others support (i64, i128, i256, float64, float128, ripemd160, sha256).\n" "\t\t\t\tSpecial type 'name' indicates an account name.")); getTable->add_option( "--encode-type", encode_type, localized("The encoding type of key_type (i64 , i128 , float64, float128) only support decimal encoding e.g. 'dec'" "i256 - supports both 'dec' and 'hex', ripemd160 and sha256 is 'hex' only")); getTable->add_flag("-b,--binary", binary, localized("Return the value as BINARY rather than using abi to interpret as JSON")); getTable->add_flag("-r,--reverse", reverse, localized("Iterate in reverse order")); getTable->add_flag("--show-payer", show_payer, localized("Show RAM payer")); getTable->set_callback([&] { auto result = call(get_table_func, fc::mutable_variant_object("json", !binary) ("code",code) ("scope",scope) ("table",table) ("table_key",table_key) // not used ("lower_bound",lower) ("upper_bound",upper) ("limit",limit) ("key_type",key_type) ("index_position", index_position) ("encode_type", encode_type) ("reverse", reverse) ("show_payer", show_payer) ); std::cout << fc::json::to_pretty_string(result) << std::endl; }); auto getScope = get->add_subcommand( "scope", localized("Retrieve a list of scopes and tables owned by a contract"), false); getScope->add_option( "contract", code, localized("The contract who owns the table") )->required(); getScope->add_option( "-t,--table", table, localized("The name of the table as filter") ); getScope->add_option( "-l,--limit", limit, localized("The maximum number of rows to return") ); getScope->add_option( "-L,--lower", lower, localized("Lower bound of scope") ); getScope->add_option( "-U,--upper", upper, localized("Upper bound of scope") ); getScope->add_flag("-r,--reverse", reverse, localized("Iterate in reverse order")); getScope->set_callback([&] { auto result = call(get_table_by_scope_func, fc::mutable_variant_object("code",code) ("table",table) ("lower_bound",lower) ("upper_bound",upper) ("limit",limit) ("reverse", reverse) ); std::cout << fc::json::to_pretty_string(result) << std::endl; }); // currency accessors // get currency balance string symbol; bool currency_balance_print_json = false; auto get_currency = get->add_subcommand( "currency", localized("Retrieve information related to standard currencies"), true); get_currency->require_subcommand(); auto get_balance = get_currency->add_subcommand( "balance", localized("Retrieve the balance of an account for a given currency"), false); get_balance->add_option( "contract", code, localized("The contract that operates the currency") )->required(); get_balance->add_option( "account", accountName, localized("The account to query balances for") )->required(); get_balance->add_option( "symbol", symbol, localized("The symbol for the currency if the contract operates multiple currencies") ); get_balance->add_flag("--json,-j", currency_balance_print_json, localized("Output in JSON format") ); get_balance->set_callback([&] { auto result = call(get_currency_balance_func, fc::mutable_variant_object ("account", accountName) ("code", code) ("symbol", symbol.empty() ? fc::variant() : symbol) ); if (!currency_balance_print_json) { const auto& rows = result.get_array(); for( const auto& r : rows ) { std::cout << r.as_string() << std::endl; } } else { std::cout << fc::json::to_pretty_string(result) << std::endl; } }); auto get_currency_stats = get_currency->add_subcommand( "stats", localized("Retrieve the stats of for a given currency"), false); get_currency_stats->add_option( "contract", code, localized("The contract that operates the currency") )->required(); get_currency_stats->add_option( "symbol", symbol, localized("The symbol for the currency if the contract operates multiple currencies") )->required(); get_currency_stats->set_callback([&] { auto result = call(get_currency_stats_func, fc::mutable_variant_object("json", false) ("code", code) ("symbol", symbol) ); std::cout << fc::json::to_pretty_string(result) << std::endl; }); // get accounts string public_key_str; auto getAccounts = get->add_subcommand("accounts", localized("Retrieve accounts associated with a public key"), false); getAccounts->add_option("public_key", public_key_str, localized("The public key to retrieve accounts for"))->required(); getAccounts->set_callback([&] { public_key_type public_key; try { public_key = public_key_type(public_key_str); } EOS_RETHROW_EXCEPTIONS(public_key_type_exception, "Invalid public key: ${public_key}", ("public_key", public_key_str)) auto arg = fc::mutable_variant_object( "public_key", public_key); std::cout << fc::json::to_pretty_string(call(get_key_accounts_func, arg)) << std::endl; }); // get servants string controllingAccount; auto getServants = get->add_subcommand("servants", localized("Retrieve accounts which are servants of a given account "), false); getServants->add_option("account", controllingAccount, localized("The name of the controlling account"))->required(); getServants->set_callback([&] { auto arg = fc::mutable_variant_object( "controlling_account", controllingAccount); std::cout << fc::json::to_pretty_string(call(get_controlled_accounts_func, arg)) << std::endl; }); // get transaction string transaction_id_str; uint32_t block_num_hint = 0; auto getTransaction = get->add_subcommand("transaction", localized("Retrieve a transaction from the blockchain"), false); getTransaction->add_option("id", transaction_id_str, localized("ID of the transaction to retrieve"))->required(); getTransaction->add_option( "-b,--block-hint", block_num_hint, localized("The block number this transaction may be in") ); getTransaction->set_callback([&] { auto arg= fc::mutable_variant_object( "id", transaction_id_str); if ( block_num_hint > 0 ) { arg = arg("block_num_hint", block_num_hint); } std::cout << fc::json::to_pretty_string(call(get_transaction_func, arg)) << std::endl; }); // get actions string account_name; string skip_seq_str; string num_seq_str; bool printjson = false; bool fullact = false; bool prettyact = false; bool printconsole = false; int32_t pos_seq = -1; int32_t offset = -20; auto getActions = get->add_subcommand("actions", localized("Retrieve all actions with specific account name referenced in authorization or receiver"), false); getActions->add_option("account_name", account_name, localized("Name of account to query on"))->required(); getActions->add_option("pos", pos_seq, localized("Sequence number of action for this account, -1 for last")); getActions->add_option("offset", offset, localized("Get actions [pos,pos+offset] for positive offset or [pos-offset,pos) for negative offset")); getActions->add_flag("--json,-j", printjson, localized("Print full JSON")); getActions->add_flag("--full", fullact, localized("Don't truncate action output")); getActions->add_flag("--pretty", prettyact, localized("Pretty print full action JSON")); getActions->add_flag("--console", printconsole, localized("Print console output generated by action ")); getActions->set_callback([&] { fc::mutable_variant_object arg; arg( "account_name", account_name ); arg( "pos", pos_seq ); arg( "offset", offset); auto result = call(get_actions_func, arg); if( printjson ) { std::cout << fc::json::to_pretty_string(result) << std::endl; } else { auto& traces = result["actions"].get_array(); uint32_t lib = result["last_irreversible_block"].as_uint64(); cout << "#" << setw(5) << "seq" << " " << setw( 24 ) << left << "when"<< " " << setw(24) << right << "contract::action" << " => " << setw(13) << left << "receiver" << " " << setw(11) << left << "trx id..." << " args\n"; cout << "================================================================================================================\n"; for( const auto& trace: traces ) { std::stringstream out; if( trace["block_num"].as_uint64() <= lib ) out << "#"; else out << "?"; out << setw(5) << trace["account_action_seq"].as_uint64() <<" "; out << setw(24) << trace["block_time"].as_string() <<" "; const auto& at = trace["action_trace"].get_object(); auto id = at["trx_id"].as_string(); const auto& receipt = at["receipt"]; auto receiver = receipt["receiver"].as_string(); const auto& act = at["act"].get_object(); auto code = act["account"].as_string(); auto func = act["name"].as_string(); string args; if( prettyact ) { args = fc::json::to_pretty_string( act["data"] ); } else { args = fc::json::to_string( act["data"], fc::time_point::maximum() ); if( !fullact ) { args = args.substr(0,60) + "..."; } } out << std::setw(24) << std::right<< (code +"::" + func) << " => " << left << std::setw(13) << receiver; out << " " << setw(11) << (id.substr(0,8) + "..."); if( fullact || prettyact ) out << "\n"; else out << " "; out << args ;//<< "\n"; if( trace["block_num"].as_uint64() <= lib ) { dlog( "\r${m}", ("m",out.str()) ); } else { wlog( "\r${m}", ("m",out.str()) ); } if( printconsole ) { auto console = at["console"].as_string(); if( console.size() ) { stringstream out; std::stringstream ss(console); string line; while( std::getline( ss, line ) ) { out << ">> " << line << "\n"; if( !fullact ) break; } cerr << out.str(); //ilog( "\r${m} ", ("m",out.str()) ); } } } } }); auto getSchedule = get_schedule_subcommand{get}; auto getTransactionId = get_transaction_id_subcommand{get}; /* auto getTransactions = get->add_subcommand("transactions", localized("Retrieve all transactions with specific account name referenced in their scope"), false); getTransactions->add_option("account_name", account_name, localized("Name of account to query on"))->required(); getTransactions->add_option("skip_seq", skip_seq_str, localized("Number of most recent transactions to skip (0 would start at most recent transaction)")); getTransactions->add_option("num_seq", num_seq_str, localized("Number of transactions to return")); getTransactions->add_flag("--json,-j", printjson, localized("Print full json")); getTransactions->set_callback([&] { fc::mutable_variant_object arg; if (skip_seq_str.empty()) { arg = fc::mutable_variant_object( "account_name", account_name); } else { uint64_t skip_seq; try { skip_seq = boost::lexical_cast<uint64_t>(skip_seq_str); } EOS_RETHROW_EXCEPTIONS(chain_type_exception, "Invalid Skip Seq: ${skip_seq}", ("skip_seq", skip_seq_str)) if (num_seq_str.empty()) { arg = fc::mutable_variant_object( "account_name", account_name)("skip_seq", skip_seq); } else { uint64_t num_seq; try { num_seq = boost::lexical_cast<uint64_t>(num_seq_str); } EOS_RETHROW_EXCEPTIONS(chain_type_exception, "Invalid Num Seq: ${num_seq}", ("num_seq", num_seq_str)) arg = fc::mutable_variant_object( "account_name", account_name)("skip_seq", skip_seq_str)("num_seq", num_seq); } } auto result = call(get_transactions_func, arg); if( printjson ) { std::cout << fc::json::to_pretty_string(result) << std::endl; } else { const auto& trxs = result.get_object()["transactions"].get_array(); for( const auto& t : trxs ) { const auto& tobj = t.get_object(); const auto& trx = tobj["transaction"].get_object(); const auto& data = trx["transaction"].get_object(); const auto& msgs = data["actions"].get_array(); for( const auto& msg : msgs ) { int64_t seq_num = tobj["seq_num"].as<int64_t>(); string id = tobj["transaction_id"].as_string(); const auto& exp = data["expiration"].as<fc::time_point_sec>(); std::cout << tobj["seq_num"].as_string() <<"] " << id.substr(0,8) << "... " << data["expiration"].as_string() << " "; auto code = msg["account"].as_string(); auto func = msg["name"].as_string(); auto args = fc::json::to_string( msg["data"] ); std::cout << setw(26) << left << (code + "::" + func) << " " << args; std::cout << std::endl; } } } }); */ // set subcommand auto setSubcommand = app.add_subcommand("set", localized("Set or update blockchain state")); setSubcommand->require_subcommand(); // set contract subcommand string account; string contractPath; string wasmPath; string abiPath; bool shouldSend = true; bool contract_clear = false; bool suppress_duplicate_check = false; auto codeSubcommand = setSubcommand->add_subcommand("code", localized("Create or update the code on an account")); codeSubcommand->add_option("account", account, localized("The account to set code for"))->required(); codeSubcommand->add_option("code-file", wasmPath, localized("The path containing the contract WASM"));//->required(); codeSubcommand->add_flag( "-c,--clear", contract_clear, localized("Remove code on an account")); codeSubcommand->add_flag( "--suppress-duplicate-check", suppress_duplicate_check, localized("Don't check for duplicate")); auto abiSubcommand = setSubcommand->add_subcommand("abi", localized("Create or update the abi on an account")); abiSubcommand->add_option("account", account, localized("The account to set the ABI for"))->required(); abiSubcommand->add_option("abi-file", abiPath, localized("The path containing the contract ABI"));//->required(); abiSubcommand->add_flag( "-c,--clear", contract_clear, localized("Remove abi on an account")); abiSubcommand->add_flag( "--suppress-duplicate-check", suppress_duplicate_check, localized("Don't check for duplicate")); auto contractSubcommand = setSubcommand->add_subcommand("contract", localized("Create or update the contract on an account")); contractSubcommand->add_option("account", account, localized("The account to publish a contract for")) ->required(); contractSubcommand->add_option("contract-dir", contractPath, localized("The path containing the .wasm and .abi")); // ->required(); contractSubcommand->add_option("wasm-file", wasmPath, localized("The file containing the contract WASM relative to contract-dir")); // ->check(CLI::ExistingFile); auto abi = contractSubcommand->add_option("abi-file,-a,--abi", abiPath, localized("The ABI for the contract relative to contract-dir")); // ->check(CLI::ExistingFile); contractSubcommand->add_flag( "-c,--clear", contract_clear, localized("Remove contract on an account")); contractSubcommand->add_flag( "--suppress-duplicate-check", suppress_duplicate_check, localized("Don't check for duplicate")); std::vector<chain::action> actions; auto set_code_callback = [&]() { std::vector<char> old_wasm; bool duplicate = false; fc::sha256 old_hash, new_hash; if (!suppress_duplicate_check) { try { const auto result = call(get_code_hash_func, fc::mutable_variant_object("account_name", account)); old_hash = fc::sha256(result["code_hash"].as_string()); } catch (...) { std::cerr << "Failed to get existing code hash, continue without duplicate check..." << std::endl; suppress_duplicate_check = true; } } bytes code_bytes; if(!contract_clear){ std::string wasm; fc::path cpath = fc::canonical(fc::path(contractPath)); if( wasmPath.empty() ) { wasmPath = (cpath / (cpath.filename().generic_string()+".wasm")).generic_string(); } else if ( boost::filesystem::path(wasmPath).is_relative() ) { wasmPath = (cpath / wasmPath).generic_string(); } std::cerr << localized(("Reading WASM from " + wasmPath + "...").c_str()) << std::endl; fc::read_file_contents(wasmPath, wasm); EOS_ASSERT( !wasm.empty(), wasm_file_not_found, "no wasm file found ${f}", ("f", wasmPath) ); const string binary_wasm_header("\x00\x61\x73\x6d\x01\x00\x00\x00", 8); if(wasm.compare(0, 8, binary_wasm_header)) std::cerr << localized("WARNING: ") << wasmPath << localized(" doesn't look like a binary WASM file. Is it something else, like WAST? Trying anyways...") << std::endl; code_bytes = bytes(wasm.begin(), wasm.end()); } else { code_bytes = bytes(); } if (!suppress_duplicate_check) { if (code_bytes.size()) { new_hash = fc::sha256::hash(&(code_bytes[0]), code_bytes.size()); } duplicate = (old_hash == new_hash); } if (!duplicate) { actions.emplace_back( create_setcode(name(account), code_bytes ) ); if ( shouldSend ) { std::cerr << localized("Setting Code...") << std::endl; send_actions(std::move(actions), signing_keys_opt.get_keys(), packed_transaction::compression_type::zlib); } } else { std::cerr << localized("Skipping set code because the new code is the same as the existing code") << std::endl; } }; auto set_abi_callback = [&]() { bytes old_abi; bool duplicate = false; if (!suppress_duplicate_check) { try { const auto result = call(get_raw_abi_func, fc::mutable_variant_object("account_name", account)); old_abi = result["abi"].as_blob().data; } catch (...) { std::cerr << "Failed to get existing raw abi, continue without duplicate check..." << std::endl; suppress_duplicate_check = true; } } bytes abi_bytes; if(!contract_clear){ fc::path cpath = fc::canonical(fc::path(contractPath)); if( abiPath.empty() ) { abiPath = (cpath / (cpath.filename().generic_string()+".abi")).generic_string(); } else if ( boost::filesystem::path(abiPath).is_relative() ) { abiPath = (cpath / abiPath).generic_string(); } EOS_ASSERT( fc::exists( abiPath ), abi_file_not_found, "no abi file found ${f}", ("f", abiPath) ); abi_bytes = fc::raw::pack(fc::json::from_file(abiPath).as<abi_def>()); } else { abi_bytes = bytes(); } if (!suppress_duplicate_check) { duplicate = (old_abi.size() == abi_bytes.size() && std::equal(old_abi.begin(), old_abi.end(), abi_bytes.begin())); } if (!duplicate) { try { actions.emplace_back( create_setabi(name(account), abi_bytes) ); } EOS_RETHROW_EXCEPTIONS(abi_type_exception, "Fail to parse ABI JSON") if ( shouldSend ) { std::cerr << localized("Setting ABI...") << std::endl; send_actions(std::move(actions), signing_keys_opt.get_keys(), packed_transaction::compression_type::zlib); } } else { std::cerr << localized("Skipping set abi because the new abi is the same as the existing abi") << std::endl; } }; add_standard_transaction_options_plus_signing(contractSubcommand, "account@active"); add_standard_transaction_options_plus_signing(codeSubcommand, "account@active"); add_standard_transaction_options_plus_signing(abiSubcommand, "account@active"); contractSubcommand->set_callback([&] { if(!contract_clear) EOS_ASSERT( !contractPath.empty(), contract_exception, " contract-dir is null ", ("f", contractPath) ); shouldSend = false; set_code_callback(); set_abi_callback(); if (actions.size()) { std::cerr << localized("Publishing contract...") << std::endl; send_actions(std::move(actions), signing_keys_opt.get_keys(), packed_transaction::compression_type::zlib); } else { std::cout << "no transaction is sent" << std::endl; } }); codeSubcommand->set_callback(set_code_callback); abiSubcommand->set_callback(set_abi_callback); // set account auto setAccount = setSubcommand->add_subcommand("account", localized("Set or update blockchain account state"))->require_subcommand(); // set account permission auto setAccountPermission = set_account_permission_subcommand(setAccount); // set action auto setAction = setSubcommand->add_subcommand("action", localized("Set or update blockchain action state"))->require_subcommand(); // set action permission auto setActionPermission = set_action_permission_subcommand(setAction); // Transfer subcommand string con = "eosio.token"; string sender; string recipient; string amount; string memo; bool pay_ram = false; auto transfer = app.add_subcommand("transfer", localized("Transfer tokens from account to account"), false); transfer->add_option("sender", sender, localized("The account sending tokens"))->required(); transfer->add_option("recipient", recipient, localized("The account receiving tokens"))->required(); transfer->add_option("amount", amount, localized("The amount of tokens to send"))->required(); transfer->add_option("memo", memo, localized("The memo for the transfer")); transfer->add_option("--contract,-c", con, localized("The contract that controls the token")); transfer->add_flag("--pay-ram-to-open", pay_ram, localized("Pay RAM to open recipient's token balance row")); add_standard_transaction_options_plus_signing(transfer, "sender@active"); transfer->set_callback([&] { if (tx_force_unique && memo.size() == 0) { // use the memo to add a nonce memo = generate_nonce_string(); tx_force_unique = false; } auto transfer_amount = to_asset(name(con), amount); auto transfer = create_transfer(con, name(sender), name(recipient), transfer_amount, memo); if (!pay_ram) { send_actions( { transfer }, signing_keys_opt.get_keys()); } else { auto open_ = create_open(con, name(recipient), transfer_amount.get_symbol(), name(sender)); send_actions( { open_, transfer }, signing_keys_opt.get_keys()); } }); // Net subcommand string new_host; auto net = app.add_subcommand( "net", localized("Interact with local p2p network connections"), false ); net->require_subcommand(); auto connect = net->add_subcommand("connect", localized("Start a new connection to a peer"), false); connect->add_option("host", new_host, localized("The hostname:port to connect to."))->required(); connect->set_callback([&] { const auto& v = call(url, net_connect, new_host); std::cout << fc::json::to_pretty_string(v) << std::endl; }); auto disconnect = net->add_subcommand("disconnect", localized("Close an existing connection"), false); disconnect->add_option("host", new_host, localized("The hostname:port to disconnect from."))->required(); disconnect->set_callback([&] { const auto& v = call(url, net_disconnect, new_host); std::cout << fc::json::to_pretty_string(v) << std::endl; }); auto status = net->add_subcommand("status", localized("Status of existing connection"), false); status->add_option("host", new_host, localized("The hostname:port to query status of connection"))->required(); status->set_callback([&] { const auto& v = call(url, net_status, new_host); std::cout << fc::json::to_pretty_string(v) << std::endl; }); auto connections = net->add_subcommand("peers", localized("Status of all existing peers"), false); connections->set_callback([&] { const auto& v = call(url, net_connections, new_host); std::cout << fc::json::to_pretty_string(v) << std::endl; }); // Wallet subcommand auto wallet = app.add_subcommand( "wallet", localized("Interact with local wallet"), false ); wallet->require_subcommand(); // create wallet string wallet_name = "default"; string password_file; auto createWallet = wallet->add_subcommand("create", localized("Create a new wallet locally"), false); createWallet->add_option("-n,--name", wallet_name, localized("The name of the new wallet"), true); createWallet->add_option("-f,--file", password_file, localized("Name of file to write wallet password output to. (Must be set, unless \"--to-console\" is passed")); createWallet->add_flag( "--to-console", print_console, localized("Print password to console.")); createWallet->set_callback([&wallet_name, &password_file, &print_console] { EOSC_ASSERT( !password_file.empty() ^ print_console, "ERROR: Either indicate a file using \"--file\" or pass \"--to-console\"" ); EOSC_ASSERT( password_file.empty() || !std::ofstream(password_file.c_str()).fail(), "ERROR: Failed to create file in specified path" ); const auto& v = call(wallet_url, wallet_create, wallet_name); std::cout << localized("Creating wallet: ${wallet_name}", ("wallet_name", wallet_name)) << std::endl; std::cout << localized("Save password to use in the future to unlock this wallet.") << std::endl; std::cout << localized("Without password imported keys will not be retrievable.") << std::endl; if (print_console) { std::cout << fc::json::to_pretty_string(v) << std::endl; } else { std::cerr << localized("saving password to ${filename}", ("filename", password_file)) << std::endl; auto password_str = fc::json::to_pretty_string(v); boost::replace_all(password_str, "\"", ""); std::ofstream out( password_file.c_str() ); out << password_str; } }); // open wallet auto openWallet = wallet->add_subcommand("open", localized("Open an existing wallet"), false); openWallet->add_option("-n,--name", wallet_name, localized("The name of the wallet to open")); openWallet->set_callback([&wallet_name] { call(wallet_url, wallet_open, wallet_name); std::cout << localized("Opened: ${wallet_name}", ("wallet_name", wallet_name)) << std::endl; }); // lock wallet auto lockWallet = wallet->add_subcommand("lock", localized("Lock wallet"), false); lockWallet->add_option("-n,--name", wallet_name, localized("The name of the wallet to lock")); lockWallet->set_callback([&wallet_name] { call(wallet_url, wallet_lock, wallet_name); std::cout << localized("Locked: ${wallet_name}", ("wallet_name", wallet_name)) << std::endl; }); // lock all wallets auto locakAllWallets = wallet->add_subcommand("lock_all", localized("Lock all unlocked wallets"), false); locakAllWallets->set_callback([] { call(wallet_url, wallet_lock_all); std::cout << localized("Locked All Wallets") << std::endl; }); // unlock wallet string wallet_pw; auto unlockWallet = wallet->add_subcommand("unlock", localized("Unlock wallet"), false); unlockWallet->add_option("-n,--name", wallet_name, localized("The name of the wallet to unlock")); unlockWallet->add_option("--password", wallet_pw, localized("The password returned by wallet create")); unlockWallet->set_callback([&wallet_name, &wallet_pw] { prompt_for_wallet_password(wallet_pw, wallet_name); fc::variants vs = {fc::variant(wallet_name), fc::variant(wallet_pw)}; call(wallet_url, wallet_unlock, vs); std::cout << localized("Unlocked: ${wallet_name}", ("wallet_name", wallet_name)) << std::endl; }); // import keys into wallet string wallet_key_str; auto importWallet = wallet->add_subcommand("import", localized("Import private key into wallet"), false); importWallet->add_option("-n,--name", wallet_name, localized("The name of the wallet to import key into")); importWallet->add_option("--private-key", wallet_key_str, localized("Private key in WIF format to import")); importWallet->set_callback([&wallet_name, &wallet_key_str] { if( wallet_key_str.size() == 0 ) { std::cout << localized("private key: "); fc::set_console_echo(false); std::getline( std::cin, wallet_key_str, '\n' ); fc::set_console_echo(true); } private_key_type wallet_key; try { wallet_key = private_key_type( wallet_key_str ); } catch (...) { EOS_THROW(private_key_type_exception, "Invalid private key") } public_key_type pubkey = wallet_key.get_public_key(); fc::variants vs = {fc::variant(wallet_name), fc::variant(wallet_key)}; call(wallet_url, wallet_import_key, vs); std::cout << localized("imported private key for: ${pubkey}", ("pubkey", pubkey.to_string())) << std::endl; }); // remove keys from wallet string wallet_rm_key_str; auto removeKeyWallet = wallet->add_subcommand("remove_key", localized("Remove key from wallet"), false); removeKeyWallet->add_option("-n,--name", wallet_name, localized("The name of the wallet to remove key from")); removeKeyWallet->add_option("key", wallet_rm_key_str, localized("Public key in WIF format to remove"))->required(); removeKeyWallet->add_option("--password", wallet_pw, localized("The password returned by wallet create")); removeKeyWallet->set_callback([&wallet_name, &wallet_pw, &wallet_rm_key_str] { prompt_for_wallet_password(wallet_pw, wallet_name); public_key_type pubkey; try { pubkey = public_key_type( wallet_rm_key_str ); } catch (...) { EOS_THROW(public_key_type_exception, "Invalid public key: ${public_key}", ("public_key", wallet_rm_key_str)) } fc::variants vs = {fc::variant(wallet_name), fc::variant(wallet_pw), fc::variant(wallet_rm_key_str)}; call(wallet_url, wallet_remove_key, vs); std::cout << localized("removed private key for: ${pubkey}", ("pubkey", wallet_rm_key_str)) << std::endl; }); // create a key within wallet string wallet_create_key_type; auto createKeyInWallet = wallet->add_subcommand("create_key", localized("Create private key within wallet"), false); createKeyInWallet->add_option("-n,--name", wallet_name, localized("The name of the wallet to create key into"), true); createKeyInWallet->add_option("key_type", wallet_create_key_type, localized("Key type to create (K1/R1)"), true)->set_type_name("K1/R1"); createKeyInWallet->set_callback([&wallet_name, &wallet_create_key_type] { //an empty key type is allowed -- it will let the underlying wallet pick which type it prefers fc::variants vs = {fc::variant(wallet_name), fc::variant(wallet_create_key_type)}; const auto& v = call(wallet_url, wallet_create_key, vs); std::cout << localized("Created new private key with a public key of: ") << fc::json::to_pretty_string(v) << std::endl; }); // list wallets auto listWallet = wallet->add_subcommand("list", localized("List opened wallets, * = unlocked"), false); listWallet->set_callback([] { std::cout << localized("Wallets:") << std::endl; const auto& v = call(wallet_url, wallet_list); std::cout << fc::json::to_pretty_string(v) << std::endl; }); // list keys auto listKeys = wallet->add_subcommand("keys", localized("List of public keys from all unlocked wallets."), false); listKeys->set_callback([] { const auto& v = call(wallet_url, wallet_public_keys); std::cout << fc::json::to_pretty_string(v) << std::endl; }); // list private keys auto listPrivKeys = wallet->add_subcommand("private_keys", localized("List of private keys from an unlocked wallet in wif or PVT_R1 format."), false); listPrivKeys->add_option("-n,--name", wallet_name, localized("The name of the wallet to list keys from"), true); listPrivKeys->add_option("--password", wallet_pw, localized("The password returned by wallet create")); listPrivKeys->set_callback([&wallet_name, &wallet_pw] { prompt_for_wallet_password(wallet_pw, wallet_name); fc::variants vs = {fc::variant(wallet_name), fc::variant(wallet_pw)}; const auto& v = call(wallet_url, wallet_list_keys, vs); std::cout << fc::json::to_pretty_string(v) << std::endl; }); auto stopKeosd = wallet->add_subcommand("stop", localized("Stop ${k}.", ("k", key_store_executable_name)), false); stopKeosd->set_callback([] { const auto& v = call(wallet_url, keosd_stop); if ( !v.is_object() || v.get_object().size() != 0 ) { //on success keosd responds with empty object std::cerr << fc::json::to_pretty_string(v) << std::endl; } else { std::cout << "OK" << std::endl; } }); // sign subcommand string trx_json_to_sign; string str_private_key; string str_chain_id; string str_private_key_file; string str_public_key; bool push_trx = false; auto sign = app.add_subcommand("sign", localized("Sign a transaction"), false); sign->add_option("transaction", trx_json_to_sign, localized("The JSON string or filename defining the transaction to sign"), true)->required(); sign->add_option("-k,--private-key", str_private_key, localized("The private key that will be used to sign the transaction")); sign->add_option("--public-key", str_public_key, localized("Ask ${exec} to sign with the corresponding private key of the given public key", ("exec", key_store_executable_name))); sign->add_option("-c,--chain-id", str_chain_id, localized("The chain id that will be used to sign the transaction")); sign->add_flag("-p,--push-transaction", push_trx, localized("Push transaction after signing")); sign->set_callback([&] { EOSC_ASSERT( str_private_key.empty() || str_public_key.empty(), "ERROR: Either -k/--private-key or --public-key or none of them can be set" ); fc::variant trx_var = json_from_file_or_string(trx_json_to_sign); signed_transaction trx; try { trx = trx_var.as<signed_transaction>(); } EOS_RETHROW_EXCEPTIONS(transaction_type_exception, "Invalid transaction format: '${data}'", ("data", fc::json::to_string(trx_var, fc::time_point::maximum()))) fc::optional<chain_id_type> chain_id; if( str_chain_id.size() == 0 ) { ilog( "grabbing chain_id from ${n}", ("n", node_executable_name) ); auto info = get_info(); chain_id = info.chain_id; } else { chain_id = chain_id_type(str_chain_id); } if( str_public_key.size() > 0 ) { public_key_type pub_key; try { pub_key = public_key_type(str_public_key); } EOS_RETHROW_EXCEPTIONS(public_key_type_exception, "Invalid public key: ${public_key}", ("public_key", str_public_key)) fc::variant keys_var(flat_set<public_key_type>{ pub_key }); sign_transaction(trx, keys_var, *chain_id); } else { if( str_private_key.size() == 0 ) { std::cerr << localized("private key: "); fc::set_console_echo(false); std::getline( std::cin, str_private_key, '\n' ); fc::set_console_echo(true); } private_key_type priv_key; try { priv_key = private_key_type(str_private_key); } EOS_RETHROW_EXCEPTIONS(private_key_type_exception, "Invalid private key") trx.sign(priv_key, *chain_id); } if(push_trx) { auto trx_result = call(push_txn_func, packed_transaction(trx, packed_transaction::compression_type::none)); std::cout << fc::json::to_pretty_string(trx_result) << std::endl; } else { std::cout << fc::json::to_pretty_string(trx) << std::endl; } }); // Push subcommand auto push = app.add_subcommand("push", localized("Push arbitrary transactions to the blockchain"), false); push->require_subcommand(); // push action string contract_account; string action; string data; vector<string> permissions; auto actionsSubcommand = push->add_subcommand("action", localized("Push a transaction with a single action")); actionsSubcommand->fallthrough(false); actionsSubcommand->add_option("account", contract_account, localized("The account providing the contract to execute"), true)->required(); actionsSubcommand->add_option("action", action, localized("A JSON string or filename defining the action to execute on the contract"), true)->required(); actionsSubcommand->add_option("data", data, localized("The arguments to the contract"))->required(); add_standard_transaction_options_plus_signing(actionsSubcommand); actionsSubcommand->set_callback([&] { fc::variant action_args_var; if( !data.empty() ) { action_args_var = json_from_file_or_string(data, fc::json::relaxed_parser); } auto accountPermissions = get_account_permissions(tx_permission); send_actions({chain::action{accountPermissions, name(contract_account), name(action), variant_to_bin( name(contract_account), name(action), action_args_var ) }}, signing_keys_opt.get_keys()); }); // push transaction string trx_to_push; auto trxSubcommand = push->add_subcommand("transaction", localized("Push an arbitrary JSON transaction")); trxSubcommand->add_option("transaction", trx_to_push, localized("The JSON string or filename defining the transaction to push"))->required(); add_standard_transaction_options_plus_signing(trxSubcommand); trxSubcommand->set_callback([&] { fc::variant trx_var = json_from_file_or_string(trx_to_push); try { signed_transaction trx = trx_var.as<signed_transaction>(); std::cout << fc::json::to_pretty_string( push_transaction( trx, signing_keys_opt.get_keys() )) << std::endl; } catch( fc::exception& ) { // unable to convert so try via abi signed_transaction trx; abi_serializer::from_variant( trx_var, trx, abi_serializer_resolver, abi_serializer_max_time ); std::cout << fc::json::to_pretty_string( push_transaction( trx, signing_keys_opt.get_keys() )) << std::endl; } }); // push transactions string trxsJson; auto trxsSubcommand = push->add_subcommand("transactions", localized("Push an array of arbitrary JSON transactions")); trxsSubcommand->add_option("transactions", trxsJson, localized("The JSON string or filename defining the array of the transactions to push"))->required(); trxsSubcommand->set_callback([&] { fc::variant trx_var = json_from_file_or_string(trxsJson); auto trxs_result = call(push_txns_func, trx_var); std::cout << fc::json::to_pretty_string(trxs_result) << std::endl; }); // multisig subcommand auto msig = app.add_subcommand("multisig", localized("Multisig contract commands"), false); msig->require_subcommand(); // multisig propose string proposal_name; string requested_perm; string transaction_perm; string proposed_transaction; string proposed_contract; string proposed_action; string proposer; unsigned int proposal_expiration_hours = 24; CLI::callback_t parse_expiration_hours = [&](CLI::results_t res) -> bool { unsigned int value_s; if (res.size() == 0 || !CLI::detail::lexical_cast(res[0], value_s)) { return false; } proposal_expiration_hours = static_cast<uint64_t>(value_s); return true; }; auto propose_action = msig->add_subcommand("propose", localized("Propose action")); add_standard_transaction_options_plus_signing(propose_action, "proposer@active"); propose_action->add_option("proposal_name", proposal_name, localized("The proposal name (string)"))->required(); propose_action->add_option("requested_permissions", requested_perm, localized("The JSON string or filename defining requested permissions"))->required(); propose_action->add_option("trx_permissions", transaction_perm, localized("The JSON string or filename defining transaction permissions"))->required(); propose_action->add_option("contract", proposed_contract, localized("The contract to which deferred transaction should be delivered"))->required(); propose_action->add_option("action", proposed_action, localized("The action of deferred transaction"))->required(); propose_action->add_option("data", proposed_transaction, localized("The JSON string or filename defining the action to propose"))->required(); propose_action->add_option("proposer", proposer, localized("Account proposing the transaction")); propose_action->add_option("proposal_expiration", parse_expiration_hours, localized("Proposal expiration interval in hours")); propose_action->set_callback([&] { fc::variant requested_perm_var = json_from_file_or_string(requested_perm); fc::variant transaction_perm_var = json_from_file_or_string(transaction_perm); fc::variant trx_var = json_from_file_or_string(proposed_transaction); transaction proposed_trx; try { proposed_trx = trx_var.as<transaction>(); } EOS_RETHROW_EXCEPTIONS(transaction_type_exception, "Invalid transaction format: '${data}'", ("data", fc::json::to_string(trx_var, fc::time_point::maximum()))) bytes proposed_trx_serialized = variant_to_bin( name(proposed_contract), name(proposed_action), trx_var ); vector<permission_level> reqperm; try { reqperm = requested_perm_var.as<vector<permission_level>>(); } EOS_RETHROW_EXCEPTIONS(transaction_type_exception, "Wrong requested permissions format: '${data}'", ("data",requested_perm_var)); vector<permission_level> trxperm; try { trxperm = transaction_perm_var.as<vector<permission_level>>(); } EOS_RETHROW_EXCEPTIONS(transaction_type_exception, "Wrong transaction permissions format: '${data}'", ("data",transaction_perm_var)); auto accountPermissions = get_account_permissions(tx_permission); if (accountPermissions.empty()) { if (!proposer.empty()) { accountPermissions = vector<permission_level>{{name(proposer), config::active_name}}; } else { EOS_THROW(missing_auth_exception, "Authority is not provided (either by multisig parameter <proposer> or -p)"); } } if (proposer.empty()) { proposer = name(accountPermissions.at(0).actor).to_string(); } transaction trx; trx.expiration = fc::time_point_sec( fc::time_point::now() + fc::hours(proposal_expiration_hours) ); trx.ref_block_num = 0; trx.ref_block_prefix = 0; trx.max_net_usage_words = 0; trx.max_cpu_usage_ms = 0; trx.delay_sec = 0; trx.actions = { chain::action(trxperm, name(proposed_contract), name(proposed_action), proposed_trx_serialized) }; fc::to_variant(trx, trx_var); auto args = fc::mutable_variant_object() ("proposer", proposer ) ("proposal_name", proposal_name) ("requested", requested_perm_var) ("trx", trx_var); send_actions({chain::action{accountPermissions, N(eosio.msig), N(propose), variant_to_bin( N(eosio.msig), N(propose), args ) }}, signing_keys_opt.get_keys()); }); //multisig propose transaction auto propose_trx = msig->add_subcommand("propose_trx", localized("Propose transaction")); add_standard_transaction_options_plus_signing(propose_trx, "proposer@active"); propose_trx->add_option("proposal_name", proposal_name, localized("The proposal name (string)"))->required(); propose_trx->add_option("requested_permissions", requested_perm, localized("The JSON string or filename defining requested permissions"))->required(); propose_trx->add_option("transaction", trx_to_push, localized("The JSON string or filename defining the transaction to push"))->required(); propose_trx->add_option("proposer", proposer, localized("Account proposing the transaction")); propose_trx->set_callback([&] { fc::variant requested_perm_var = json_from_file_or_string(requested_perm); fc::variant trx_var = json_from_file_or_string(trx_to_push); auto accountPermissions = get_account_permissions(tx_permission); if (accountPermissions.empty()) { if (!proposer.empty()) { accountPermissions = vector<permission_level>{{name(proposer), config::active_name}}; } else { EOS_THROW(missing_auth_exception, "Authority is not provided (either by multisig parameter <proposer> or -p)"); } } if (proposer.empty()) { proposer = name(accountPermissions.at(0).actor).to_string(); } auto args = fc::mutable_variant_object() ("proposer", proposer ) ("proposal_name", proposal_name) ("requested", requested_perm_var) ("trx", trx_var); send_actions({chain::action{accountPermissions, N(eosio.msig), N(propose), variant_to_bin( N(eosio.msig), N(propose), args ) }}, signing_keys_opt.get_keys()); }); // multisig review bool show_approvals_in_multisig_review = false; auto review = msig->add_subcommand("review", localized("Review transaction")); review->add_option("proposer", proposer, localized("The proposer name (string)"))->required(); review->add_option("proposal_name", proposal_name, localized("The proposal name (string)"))->required(); review->add_flag( "--show-approvals", show_approvals_in_multisig_review, localized("Show the status of the approvals requested within the proposal") ); review->set_callback([&] { const auto result1 = call(get_table_func, fc::mutable_variant_object("json", true) ("code", "eosio.msig") ("scope", proposer) ("table", "proposal") ("table_key", "") ("lower_bound", name(proposal_name).to_uint64_t()) ("upper_bound", name(proposal_name).to_uint64_t() + 1) // Less than ideal upper_bound usage preserved so cleos can still work with old buggy nodeos versions // Change to name(proposal_name).value when cleos no longer needs to support nodeos versions older than 1.5.0 ("limit", 1) ); //std::cout << fc::json::to_pretty_string(result) << std::endl; const auto& rows1 = result1.get_object()["rows"].get_array(); // Condition in if statement below can simply be rows.empty() when cleos no longer needs to support nodeos versions older than 1.5.0 if( rows1.empty() || rows1[0].get_object()["proposal_name"] != proposal_name ) { std::cerr << "Proposal not found" << std::endl; return; } const auto& proposal_object = rows1[0].get_object(); enum class approval_status { unapproved, approved, invalidated }; std::map<permission_level, std::pair<fc::time_point, approval_status>> all_approvals; std::map<eosio::account_name, std::pair<fc::time_point, vector<decltype(all_approvals)::iterator>>> provided_approvers; bool new_multisig = true; if( show_approvals_in_multisig_review ) { fc::variants rows2; try { const auto& result2 = call(get_table_func, fc::mutable_variant_object("json", true) ("code", "eosio.msig") ("scope", proposer) ("table", "approvals2") ("table_key", "") ("lower_bound", name(proposal_name).to_uint64_t()) ("upper_bound", name(proposal_name).to_uint64_t() + 1) // Less than ideal upper_bound usage preserved so cleos can still work with old buggy nodeos versions // Change to name(proposal_name).value when cleos no longer needs to support nodeos versions older than 1.5.0 ("limit", 1) ); rows2 = result2.get_object()["rows"].get_array(); } catch( ... ) { new_multisig = false; } if( !rows2.empty() && rows2[0].get_object()["proposal_name"] == proposal_name ) { const auto& approvals_object = rows2[0].get_object(); for( const auto& ra : approvals_object["requested_approvals"].get_array() ) { const auto& ra_obj = ra.get_object(); auto pl = ra["level"].as<permission_level>(); all_approvals.emplace( pl, std::make_pair(ra["time"].as<fc::time_point>(), approval_status::unapproved) ); } for( const auto& pa : approvals_object["provided_approvals"].get_array() ) { const auto& pa_obj = pa.get_object(); auto pl = pa["level"].as<permission_level>(); auto res = all_approvals.emplace( pl, std::make_pair(pa["time"].as<fc::time_point>(), approval_status::approved) ); provided_approvers[pl.actor].second.push_back( res.first ); } } else { const auto result3 = call(get_table_func, fc::mutable_variant_object("json", true) ("code", "eosio.msig") ("scope", proposer) ("table", "approvals") ("table_key", "") ("lower_bound", name(proposal_name).to_uint64_t()) ("upper_bound", name(proposal_name).to_uint64_t() + 1) // Less than ideal upper_bound usage preserved so cleos can still work with old buggy nodeos versions // Change to name(proposal_name).value when cleos no longer needs to support nodeos versions older than 1.5.0 ("limit", 1) ); const auto& rows3 = result3.get_object()["rows"].get_array(); if( rows3.empty() || rows3[0].get_object()["proposal_name"] != proposal_name ) { std::cerr << "Proposal not found" << std::endl; return; } const auto& approvals_object = rows3[0].get_object(); for( const auto& ra : approvals_object["requested_approvals"].get_array() ) { auto pl = ra.as<permission_level>(); all_approvals.emplace( pl, std::make_pair(fc::time_point{}, approval_status::unapproved) ); } for( const auto& pa : approvals_object["provided_approvals"].get_array() ) { auto pl = pa.as<permission_level>(); auto res = all_approvals.emplace( pl, std::make_pair(fc::time_point{}, approval_status::approved) ); provided_approvers[pl.actor].second.push_back( res.first ); } } if( new_multisig ) { for( auto& a : provided_approvers ) { const auto result4 = call(get_table_func, fc::mutable_variant_object("json", true) ("code", "eosio.msig") ("scope", "eosio.msig") ("table", "invals") ("table_key", "") ("lower_bound", a.first.to_uint64_t()) ("upper_bound", a.first.to_uint64_t() + 1) // Less than ideal upper_bound usage preserved so cleos can still work with old buggy nodeos versions // Change to name(proposal_name).value when cleos no longer needs to support nodeos versions older than 1.5.0 ("limit", 1) ); const auto& rows4 = result4.get_object()["rows"].get_array(); if( rows4.empty() || rows4[0].get_object()["account"].as<eosio::name>() != a.first ) { continue; } auto invalidation_time = rows4[0].get_object()["last_invalidation_time"].as<fc::time_point>(); a.second.first = invalidation_time; for( auto& itr : a.second.second ) { if( invalidation_time >= itr->second.first ) { itr->second.second = approval_status::invalidated; } } } } } auto trx_hex = proposal_object["packed_transaction"].as_string(); vector<char> trx_blob(trx_hex.size()/2); fc::from_hex(trx_hex, trx_blob.data(), trx_blob.size()); transaction trx = fc::raw::unpack<transaction>(trx_blob); fc::mutable_variant_object obj; obj["proposer"] = proposer; obj["proposal_name"] = proposal_object["proposal_name"]; obj["transaction_id"] = trx.id(); for( const auto& entry : proposal_object ) { if( entry.key() == "proposal_name" ) continue; obj.set( entry.key(), entry.value() ); } fc::variant trx_var; abi_serializer abi; abi.to_variant(trx, trx_var, abi_serializer_resolver, abi_serializer_max_time); obj["transaction"] = trx_var; if( show_approvals_in_multisig_review ) { fc::variants approvals; for( const auto& approval : all_approvals ) { fc::mutable_variant_object approval_obj; approval_obj["level"] = approval.first; switch( approval.second.second ) { case approval_status::unapproved: { approval_obj["status"] = "unapproved"; if( approval.second.first != fc::time_point{} ) { approval_obj["last_unapproval_time"] = approval.second.first; } } break; case approval_status::approved: { approval_obj["status"] = "approved"; if( new_multisig ) { approval_obj["last_approval_time"] = approval.second.first; } } break; case approval_status::invalidated: { approval_obj["status"] = "invalidated"; approval_obj["last_approval_time"] = approval.second.first; approval_obj["invalidation_time"] = provided_approvers[approval.first.actor].first; } break; } approvals.push_back( std::move(approval_obj) ); } obj["approvals"] = std::move(approvals); } std::cout << fc::json::to_pretty_string(obj) << std::endl; }); string perm; string proposal_hash; auto approve_or_unapprove = [&](const string& action) { fc::variant perm_var = json_from_file_or_string(perm); auto args = fc::mutable_variant_object() ("proposer", proposer) ("proposal_name", proposal_name) ("level", perm_var); if( proposal_hash.size() ) { args("proposal_hash", proposal_hash); } auto accountPermissions = get_account_permissions(tx_permission, {name(proposer), config::active_name}); send_actions({chain::action{accountPermissions, N(eosio.msig), name(action), variant_to_bin( N(eosio.msig), name(action), args ) }}, signing_keys_opt.get_keys()); }; // multisig approve auto approve = msig->add_subcommand("approve", localized("Approve proposed transaction")); add_standard_transaction_options_plus_signing(approve, "proposer@active"); approve->add_option("proposer", proposer, localized("The proposer name (string)"))->required(); approve->add_option("proposal_name", proposal_name, localized("The proposal name (string)"))->required(); approve->add_option("permissions", perm, localized("The JSON string of filename defining approving permissions"))->required(); approve->add_option("proposal_hash", proposal_hash, localized("Hash of proposed transaction (i.e. transaction ID) to optionally enforce as a condition of the approval")); approve->set_callback([&] { approve_or_unapprove("approve"); }); // multisig unapprove auto unapprove = msig->add_subcommand("unapprove", localized("Unapprove proposed transaction")); add_standard_transaction_options_plus_signing(unapprove, "proposer@active"); unapprove->add_option("proposer", proposer, localized("The proposer name (string)"))->required(); unapprove->add_option("proposal_name", proposal_name, localized("The proposal name (string)"))->required(); unapprove->add_option("permissions", perm, localized("The JSON string of filename defining approving permissions"))->required(); unapprove->set_callback([&] { approve_or_unapprove("unapprove"); }); // multisig invalidate string invalidator; auto invalidate = msig->add_subcommand("invalidate", localized("Invalidate all multisig approvals of an account")); add_standard_transaction_options_plus_signing(invalidate, "invalidator@active"); invalidate->add_option("invalidator", invalidator, localized("Invalidator name (string)"))->required(); invalidate->set_callback([&] { auto args = fc::mutable_variant_object() ("account", invalidator); auto accountPermissions = get_account_permissions(tx_permission, {name(invalidator), config::active_name}); send_actions({chain::action{accountPermissions, N(eosio.msig), N(invalidate), variant_to_bin( N(eosio.msig), N(invalidate), args ) }}, signing_keys_opt.get_keys()); }); // multisig cancel string canceler; auto cancel = msig->add_subcommand("cancel", localized("Cancel proposed transaction")); add_standard_transaction_options_plus_signing(cancel, "canceler@active"); cancel->add_option("proposer", proposer, localized("The proposer name (string)"))->required(); cancel->add_option("proposal_name", proposal_name, localized("The proposal name (string)"))->required(); cancel->add_option("canceler", canceler, localized("The canceler name (string)")); cancel->set_callback([&]() { auto accountPermissions = get_account_permissions(tx_permission); if (accountPermissions.empty()) { if (!canceler.empty()) { accountPermissions = vector<permission_level>{{name(canceler), config::active_name}}; } else { EOS_THROW(missing_auth_exception, "Authority is not provided (either by multisig parameter <canceler> or -p)"); } } if (canceler.empty()) { canceler = name(accountPermissions.at(0).actor).to_string(); } auto args = fc::mutable_variant_object() ("proposer", proposer) ("proposal_name", proposal_name) ("canceler", canceler); send_actions({chain::action{accountPermissions, N(eosio.msig), N(cancel), variant_to_bin( N(eosio.msig), N(cancel), args ) }}, signing_keys_opt.get_keys()); } ); // multisig exec string executer; auto exec = msig->add_subcommand("exec", localized("Execute proposed transaction")); add_standard_transaction_options_plus_signing(exec, "executer@active"); exec->add_option("proposer", proposer, localized("The proposer name (string)"))->required(); exec->add_option("proposal_name", proposal_name, localized("The proposal name (string)"))->required(); exec->add_option("executer", executer, localized("The account paying for execution (string)")); exec->set_callback([&] { auto accountPermissions = get_account_permissions(tx_permission); if (accountPermissions.empty()) { if (!executer.empty()) { accountPermissions = vector<permission_level>{{name(executer), config::active_name}}; } else { EOS_THROW(missing_auth_exception, "Authority is not provided (either by multisig parameter <executer> or -p)"); } } if (executer.empty()) { executer = name(accountPermissions.at(0).actor).to_string(); } auto args = fc::mutable_variant_object() ("proposer", proposer ) ("proposal_name", proposal_name) ("executer", executer); send_actions({chain::action{accountPermissions, N(eosio.msig), N(exec), variant_to_bin( N(eosio.msig), N(exec), args ) }}, signing_keys_opt.get_keys()); } ); // wrap subcommand auto wrap = app.add_subcommand("wrap", localized("Wrap contract commands"), false); wrap->require_subcommand(); // wrap exec string wrap_con = "eosio.wrap"; executer = ""; string trx_to_exec; auto wrap_exec = wrap->add_subcommand("exec", localized("Execute a transaction while bypassing authorization checks")); add_standard_transaction_options_plus_signing(wrap_exec, "executer@active & --contract@active"); wrap_exec->add_option("executer", executer, localized("Account executing the transaction and paying for the deferred transaction RAM"))->required(); wrap_exec->add_option("transaction", trx_to_exec, localized("The JSON string or filename defining the transaction to execute"))->required(); wrap_exec->add_option("--contract,-c", wrap_con, localized("The account which controls the wrap contract")); wrap_exec->set_callback([&] { fc::variant trx_var = json_from_file_or_string(trx_to_exec); auto accountPermissions = get_account_permissions(tx_permission); if( accountPermissions.empty() ) { accountPermissions = vector<permission_level>{{name(executer), config::active_name}, {name(wrap_con), config::active_name}}; } auto args = fc::mutable_variant_object() ("executer", executer ) ("trx", trx_var); send_actions({chain::action{accountPermissions, name(wrap_con), N(exec), variant_to_bin( name(wrap_con), N(exec), args ) }}, signing_keys_opt.get_keys()); }); // system subcommand auto system = app.add_subcommand("system", localized("Send eosio.system contract action to the blockchain."), false); system->require_subcommand(); auto createAccountSystem = create_account_subcommand( system, false /*simple*/ ); auto registerProducer = register_producer_subcommand(system); auto unregisterProducer = unregister_producer_subcommand(system); auto voteProducer = system->add_subcommand("voteproducer", localized("Vote for a producer")); voteProducer->require_subcommand(); auto voteProxy = vote_producer_proxy_subcommand(voteProducer); auto voteProducers = vote_producers_subcommand(voteProducer); auto approveProducer = approve_producer_subcommand(voteProducer); auto unapproveProducer = unapprove_producer_subcommand(voteProducer); auto listProducers = list_producers_subcommand(system); auto delegateBandWidth = delegate_bandwidth_subcommand(system); auto undelegateBandWidth = undelegate_bandwidth_subcommand(system); auto listBandWidth = list_bw_subcommand(system); auto bidname = bidname_subcommand(system); auto bidnameinfo = bidname_info_subcommand(system); auto buyram = buyram_subcommand(system); auto sellram = sellram_subcommand(system); auto claimRewards = claimrewards_subcommand(system); auto regProxy = regproxy_subcommand(system); auto unregProxy = unregproxy_subcommand(system); auto cancelDelay = canceldelay_subcommand(system); auto rex = system->add_subcommand("rex", localized("Actions related to REX (the resource exchange)")); rex->require_subcommand(); auto deposit = deposit_subcommand(rex); auto withdraw = withdraw_subcommand(rex); auto buyrex = buyrex_subcommand(rex); auto lendrex = lendrex_subcommand(rex); auto unstaketorex = unstaketorex_subcommand(rex); auto sellrex = sellrex_subcommand(rex); auto cancelrexorder = cancelrexorder_subcommand(rex); auto mvtosavings = mvtosavings_subcommand(rex); auto mvfromsavings = mvfrsavings_subcommand(rex); auto rentcpu = rentcpu_subcommand(rex); auto rentnet = rentnet_subcommand(rex); auto fundcpuloan = fundcpuloan_subcommand(rex); auto fundnetloan = fundnetloan_subcommand(rex); auto defcpuloan = defcpuloan_subcommand(rex); auto defnetloan = defnetloan_subcommand(rex); auto consolidate = consolidate_subcommand(rex); auto updaterex = updaterex_subcommand(rex); auto rexexec = rexexec_subcommand(rex); auto closerex = closerex_subcommand(rex); try { app.parse(argc, argv); } catch (const CLI::ParseError &e) { return app.exit(e); } catch (const explained_exception& e) { return 1; } catch (connection_exception& e) { if (verbose) { elog("connect error: ${e}", ("e", e.to_detail_string())); } return 1; } catch (const fc::exception& e) { // attempt to extract the error code if one is present if (!print_recognized_errors(e, verbose)) { // Error is not recognized if (!print_help_text(e) || verbose) { elog("Failed with error: ${e}", ("e", verbose ? e.to_detail_string() : e.to_string())); } } return 1; } return 0; } cleos: receiver moved /** @defgroup eosclienttool @section intro Introduction to cleos `cleos` is a command line tool that interfaces with the REST api exposed by @ref nodeos. In order to use `cleos` you will need to have a local copy of `nodeos` running and configured to load the 'eosio::chain_api_plugin'. cleos contains documentation for all of its commands. For a list of all commands known to cleos, simply run it with no arguments: ``` $ ./cleos Command Line Interface to EOSIO Client Usage: programs/cleos/cleos [OPTIONS] SUBCOMMAND Options: -h,--help Print this help message and exit -u,--url TEXT=http://localhost:8888/ the http/https URL where nodeos is running --wallet-url TEXT=http://localhost:8888/ the http/https URL where keosd is running -r,--header pass specific HTTP header, repeat this option to pass multiple headers -n,--no-verify don't verify peer certificate when using HTTPS -v,--verbose output verbose errors and action output Subcommands: version Retrieve version information create Create various items, on and off the blockchain get Retrieve various items and information from the blockchain set Set or update blockchain state transfer Transfer tokens from account to account net Interact with local p2p network connections wallet Interact with local wallet sign Sign a transaction push Push arbitrary transactions to the blockchain multisig Multisig contract commands ``` To get help with any particular subcommand, run it with no arguments as well: ``` $ ./cleos create Create various items, on and off the blockchain Usage: ./cleos create SUBCOMMAND Subcommands: key Create a new keypair and print the public and private keys account Create a new account on the blockchain (assumes system contract does not restrict RAM usage) $ ./cleos create account Create a new account on the blockchain (assumes system contract does not restrict RAM usage) Usage: ./cleos create account [OPTIONS] creator name OwnerKey ActiveKey Positionals: creator TEXT The name of the account creating the new account name TEXT The name of the new account OwnerKey TEXT The owner public key for the new account ActiveKey TEXT The active public key for the new account Options: -x,--expiration set the time in seconds before a transaction expires, defaults to 30s -f,--force-unique force the transaction to be unique. this will consume extra bandwidth and remove any protections against accidently issuing the same transaction multiple times -s,--skip-sign Specify if unlocked wallet keys should be used to sign transaction -d,--dont-broadcast don't broadcast transaction to the network (just print to stdout) -p,--permission TEXT ... An account and permission level to authorize, as in 'account@permission' (defaults to 'creator@active') ``` */ #include <pwd.h> #include <string> #include <vector> #include <regex> #include <iostream> #include <fc/crypto/hex.hpp> #include <fc/variant.hpp> #include <fc/io/datastream.hpp> #include <fc/io/json.hpp> #include <fc/io/console.hpp> #include <fc/exception/exception.hpp> #include <fc/variant_object.hpp> #include <fc/static_variant.hpp> #include <eosio/chain/name.hpp> #include <eosio/chain/config.hpp> #include <eosio/chain/wast_to_wasm.hpp> #include <eosio/chain/trace.hpp> #include <eosio/chain_plugin/chain_plugin.hpp> #include <eosio/chain/contract_types.hpp> #include <eosio/version/version.hpp> #pragma push_macro("N") #undef N #include <boost/asio.hpp> #include <boost/format.hpp> #include <boost/dll/runtime_symbol_info.hpp> #include <boost/filesystem.hpp> #include <boost/process.hpp> #include <boost/process/spawn.hpp> #include <boost/range/algorithm/find_if.hpp> #include <boost/range/algorithm/sort.hpp> #include <boost/range/adaptor/transformed.hpp> #include <boost/algorithm/string/predicate.hpp> #include <boost/algorithm/string/split.hpp> #include <boost/range/algorithm/copy.hpp> #include <boost/algorithm/string/classification.hpp> #pragma pop_macro("N") #include <Inline/BasicTypes.h> #include <IR/Module.h> #include <IR/Validate.h> #include <WASM/WASM.h> #include <Runtime/Runtime.h> #include <fc/io/fstream.hpp> #include "CLI11.hpp" #include "help_text.hpp" #include "localize.hpp" #include "config.hpp" #include "httpc.hpp" using namespace std; using namespace eosio; using namespace eosio::chain; using namespace eosio::client::help; using namespace eosio::client::http; using namespace eosio::client::localize; using namespace eosio::client::config; using namespace boost::filesystem; using auth_type = fc::static_variant<public_key_type, permission_level>; FC_DECLARE_EXCEPTION( explained_exception, 9000000, "explained exception, see error log" ); FC_DECLARE_EXCEPTION( localized_exception, 10000000, "an error occured" ); #define EOSC_ASSERT( TEST, ... ) \ FC_EXPAND_MACRO( \ FC_MULTILINE_MACRO_BEGIN \ if( UNLIKELY(!(TEST)) ) \ { \ std::cerr << localized( __VA_ARGS__ ) << std::endl; \ FC_THROW_EXCEPTION( explained_exception, #TEST ); \ } \ FC_MULTILINE_MACRO_END \ ) //copy pasta from keosd's main.cpp bfs::path determine_home_directory() { bfs::path home; struct passwd* pwd = getpwuid(getuid()); if(pwd) { home = pwd->pw_dir; } else { home = getenv("HOME"); } if(home.empty()) home = "./"; return home; } string url = "http://127.0.0.1:8888/"; string default_wallet_url = "unix://" + (determine_home_directory() / "eosio-wallet" / (string(key_store_executable_name) + ".sock")).string(); string wallet_url; //to be set to default_wallet_url in main bool no_verify = false; vector<string> headers; auto tx_expiration = fc::seconds(30); const fc::microseconds abi_serializer_max_time = fc::seconds(10); // No risk to client side serialization taking a long time string tx_ref_block_num_or_id; bool tx_force_unique = false; bool tx_dont_broadcast = false; bool tx_return_packed = false; bool tx_skip_sign = false; bool tx_print_json = false; bool tx_use_old_rpc = false; string tx_json_save_file; bool print_request = false; bool print_response = false; bool no_auto_keosd = false; bool verbose = false; uint8_t tx_max_cpu_usage = 0; uint32_t tx_max_net_usage = 0; uint32_t delaysec = 0; vector<string> tx_permission; eosio::client::http::http_context context; void add_standard_transaction_options(CLI::App* cmd, string default_permission = "") { CLI::callback_t parse_expiration = [](CLI::results_t res) -> bool { double value_s; if (res.size() == 0 || !CLI::detail::lexical_cast(res[0], value_s)) { return false; } tx_expiration = fc::seconds(static_cast<uint64_t>(value_s)); return true; }; cmd->add_option("-x,--expiration", parse_expiration, localized("Set the time in seconds before a transaction expires, defaults to 30s")); cmd->add_flag("-f,--force-unique", tx_force_unique, localized("Force the transaction to be unique. this will consume extra bandwidth and remove any protections against accidently issuing the same transaction multiple times")); cmd->add_flag("-s,--skip-sign", tx_skip_sign, localized("Specify if unlocked wallet keys should be used to sign transaction")); cmd->add_flag("-j,--json", tx_print_json, localized("Print result as JSON")); cmd->add_option("--json-file", tx_json_save_file, localized("Save result in JSON format into a file")); cmd->add_flag("-d,--dont-broadcast", tx_dont_broadcast, localized("Don't broadcast transaction to the network (just print to stdout)")); cmd->add_flag("--return-packed", tx_return_packed, localized("Used in conjunction with --dont-broadcast to get the packed transaction")); cmd->add_option("-r,--ref-block", tx_ref_block_num_or_id, (localized("Set the reference block num or block id used for TAPOS (Transaction as Proof-of-Stake)"))); cmd->add_flag("--use-old-rpc", tx_use_old_rpc, localized("Use old RPC push_transaction, rather than new RPC send_transaction")); string msg = "An account and permission level to authorize, as in 'account@permission'"; if(!default_permission.empty()) msg += " (defaults to '" + default_permission + "')"; cmd->add_option("-p,--permission", tx_permission, localized(msg.c_str())); cmd->add_option("--max-cpu-usage-ms", tx_max_cpu_usage, localized("Set an upper limit on the milliseconds of cpu usage budget, for the execution of the transaction (defaults to 0 which means no limit)")); cmd->add_option("--max-net-usage", tx_max_net_usage, localized("Set an upper limit on the net usage budget, in bytes, for the transaction (defaults to 0 which means no limit)")); cmd->add_option("--delay-sec", delaysec, localized("Set the delay_sec seconds, defaults to 0s")); } bool is_public_key_str(const std::string& potential_key_str) { return boost::istarts_with(potential_key_str, "EOS") || boost::istarts_with(potential_key_str, "PUB_R1") || boost::istarts_with(potential_key_str, "PUB_K1") || boost::istarts_with(potential_key_str, "PUB_WA"); } class signing_keys_option { public: signing_keys_option() {} void add_option(CLI::App* cmd) { cmd->add_option("--sign-with", public_key_json, localized("The public key or json array of public keys to sign with")); } std::vector<public_key_type> get_keys() { std::vector<public_key_type> signing_keys; if (!public_key_json.empty()) { if (is_public_key_str(public_key_json)) { try { signing_keys.push_back(public_key_type(public_key_json)); } EOS_RETHROW_EXCEPTIONS(public_key_type_exception, "Invalid public key: ${public_key}", ("public_key", public_key_json)) } else { fc::variant json_keys; try { json_keys = fc::json::from_string(public_key_json, fc::json::relaxed_parser); } EOS_RETHROW_EXCEPTIONS(json_parse_exception, "Fail to parse JSON from string: ${string}", ("string", public_key_json)); try { std::vector<public_key_type> keys = json_keys.template as<std::vector<public_key_type>>(); signing_keys = std::move(keys); } EOS_RETHROW_EXCEPTIONS(public_key_type_exception, "Invalid public key array format '${data}'", ("data", fc::json::to_string(json_keys, fc::time_point::maximum()))) } } return signing_keys; } private: string public_key_json; }; signing_keys_option signing_keys_opt; void add_standard_transaction_options_plus_signing(CLI::App* cmd, string default_permission = "") { add_standard_transaction_options(cmd, default_permission); signing_keys_opt.add_option(cmd); } vector<chain::permission_level> get_account_permissions(const vector<string>& permissions) { auto fixedPermissions = permissions | boost::adaptors::transformed([](const string& p) { vector<string> pieces; split(pieces, p, boost::algorithm::is_any_of("@")); if( pieces.size() == 1 ) pieces.push_back( "active" ); return chain::permission_level{ .actor = name(pieces[0]), .permission = name(pieces[1]) }; }); vector<chain::permission_level> accountPermissions; boost::range::copy(fixedPermissions, back_inserter(accountPermissions)); return accountPermissions; } vector<chain::permission_level> get_account_permissions(const vector<string>& permissions, const chain::permission_level& default_permission) { if (permissions.empty()) return vector<chain::permission_level>{default_permission}; else return get_account_permissions(tx_permission); } template<typename T> fc::variant call( const std::string& url, const std::string& path, const T& v ) { try { auto sp = std::make_unique<eosio::client::http::connection_param>(context, parse_url(url) + path, no_verify ? false : true, headers); return eosio::client::http::do_http_call(*sp, fc::variant(v), print_request, print_response ); } catch(boost::system::system_error& e) { if(url == ::url) std::cerr << localized("Failed to connect to ${n} at ${u}; is ${n} running?", ("n", node_executable_name)("u", url)) << std::endl; else if(url == ::wallet_url) std::cerr << localized("Failed to connect to ${k} at ${u}; is ${k} running?", ("k", key_store_executable_name)("u", url)) << std::endl; throw connection_exception(fc::log_messages{FC_LOG_MESSAGE(error, e.what())}); } } template<typename T> fc::variant call( const std::string& path, const T& v ) { return call( url, path, fc::variant(v) ); } template<> fc::variant call( const std::string& url, const std::string& path) { return call( url, path, fc::variant() ); } eosio::chain_apis::read_only::get_info_results get_info() { return call(url, get_info_func).as<eosio::chain_apis::read_only::get_info_results>(); } string generate_nonce_string() { return fc::to_string(fc::time_point::now().time_since_epoch().count()); } chain::action generate_nonce_action() { return chain::action( {}, config::null_account_name, name("nonce"), fc::raw::pack(fc::time_point::now().time_since_epoch().count())); } void prompt_for_wallet_password(string& pw, const string& name) { if(pw.size() == 0 && name != "SecureEnclave") { std::cout << localized("password: "); fc::set_console_echo(false); std::getline( std::cin, pw, '\n' ); fc::set_console_echo(true); } } fc::variant determine_required_keys(const signed_transaction& trx) { // TODO better error checking //wdump((trx)); const auto& public_keys = call(wallet_url, wallet_public_keys); auto get_arg = fc::mutable_variant_object ("transaction", (transaction)trx) ("available_keys", public_keys); const auto& required_keys = call(get_required_keys, get_arg); return required_keys["required_keys"]; } void sign_transaction(signed_transaction& trx, fc::variant& required_keys, const chain_id_type& chain_id) { fc::variants sign_args = {fc::variant(trx), required_keys, fc::variant(chain_id)}; const auto& signed_trx = call(wallet_url, wallet_sign_trx, sign_args); trx = signed_trx.as<signed_transaction>(); } fc::variant push_transaction( signed_transaction& trx, const std::vector<public_key_type>& signing_keys = std::vector<public_key_type>(), packed_transaction::compression_type compression = packed_transaction::compression_type::none ) { auto info = get_info(); if (trx.signatures.size() == 0) { // #5445 can't change txn content if already signed trx.expiration = info.head_block_time + tx_expiration; // Set tapos, default to last irreversible block if it's not specified by the user block_id_type ref_block_id = info.last_irreversible_block_id; try { fc::variant ref_block; if (!tx_ref_block_num_or_id.empty()) { ref_block = call(get_block_func, fc::mutable_variant_object("block_num_or_id", tx_ref_block_num_or_id)); ref_block_id = ref_block["id"].as<block_id_type>(); } } EOS_RETHROW_EXCEPTIONS(invalid_ref_block_exception, "Invalid reference block num or id: ${block_num_or_id}", ("block_num_or_id", tx_ref_block_num_or_id)); trx.set_reference_block(ref_block_id); if (tx_force_unique) { trx.context_free_actions.emplace_back( generate_nonce_action() ); } trx.max_cpu_usage_ms = tx_max_cpu_usage; trx.max_net_usage_words = (tx_max_net_usage + 7)/8; trx.delay_sec = delaysec; } if (!tx_skip_sign) { fc::variant required_keys; if (signing_keys.size() > 0) { required_keys = fc::variant(signing_keys); } else { required_keys = determine_required_keys(trx); } sign_transaction(trx, required_keys, info.chain_id); } if (!tx_dont_broadcast) { if (tx_use_old_rpc) { return call(push_txn_func, packed_transaction(trx, compression)); } else { try { return call(send_txn_func, packed_transaction(trx, compression)); } catch (chain::missing_chain_api_plugin_exception &) { std::cerr << "New RPC send_transaction may not be supported. Add flag --use-old-rpc to use old RPC push_transaction instead." << std::endl; throw; } } } else { if (!tx_return_packed) { return fc::variant(trx); } else { return fc::variant(packed_transaction(trx, compression)); } } } fc::variant push_actions(std::vector<chain::action>&& actions, packed_transaction::compression_type compression = packed_transaction::compression_type::none, const std::vector<public_key_type>& signing_keys = std::vector<public_key_type>() ) { signed_transaction trx; trx.actions = std::forward<decltype(actions)>(actions); return push_transaction(trx, signing_keys, compression); } void print_action( const fc::variant& at ) { auto receiver = at["receiver"].as_string(); const auto& act = at["act"].get_object(); auto code = act["account"].as_string(); auto func = act["name"].as_string(); auto args = fc::json::to_string( act["data"], fc::time_point::maximum() ); auto console = at["console"].as_string(); /* if( code == "eosio" && func == "setcode" ) args = args.substr(40)+"..."; if( name(code) == config::system_account_name && func == "setabi" ) args = args.substr(40)+"..."; */ if( args.size() > 100 ) args = args.substr(0,100) + "..."; cout << "#" << std::setw(14) << right << receiver << " <= " << std::setw(28) << std::left << (code +"::" + func) << " " << args << "\n"; if( console.size() ) { std::stringstream ss(console); string line; while( std::getline( ss, line ) ) { cout << ">> " << line << "\n"; if( !verbose ) break; } } } //resolver for ABI serializer to decode actions in proposed transaction in multisig contract auto abi_serializer_resolver = [](const name& account) -> fc::optional<abi_serializer> { static unordered_map<account_name, fc::optional<abi_serializer> > abi_cache; auto it = abi_cache.find( account ); if ( it == abi_cache.end() ) { auto result = call(get_abi_func, fc::mutable_variant_object("account_name", account)); auto abi_results = result.as<eosio::chain_apis::read_only::get_abi_results>(); fc::optional<abi_serializer> abis; if( abi_results.abi.valid() ) { abis.emplace( *abi_results.abi, abi_serializer_max_time ); } else { std::cerr << "ABI for contract " << account.to_string() << " not found. Action data will be shown in hex only." << std::endl; } abi_cache.emplace( account, abis ); return abis; } return it->second; }; bytes variant_to_bin( const account_name& account, const action_name& action, const fc::variant& action_args_var ) { auto abis = abi_serializer_resolver( account ); FC_ASSERT( abis.valid(), "No ABI found for ${contract}", ("contract", account)); auto action_type = abis->get_action_type( action ); FC_ASSERT( !action_type.empty(), "Unknown action ${action} in contract ${contract}", ("action", action)( "contract", account )); return abis->variant_to_binary( action_type, action_args_var, abi_serializer_max_time ); } fc::variant bin_to_variant( const account_name& account, const action_name& action, const bytes& action_args) { auto abis = abi_serializer_resolver( account ); FC_ASSERT( abis.valid(), "No ABI found for ${contract}", ("contract", account)); auto action_type = abis->get_action_type( action ); FC_ASSERT( !action_type.empty(), "Unknown action ${action} in contract ${contract}", ("action", action)( "contract", account )); return abis->binary_to_variant( action_type, action_args, abi_serializer_max_time ); } fc::variant json_from_file_or_string(const string& file_or_str, fc::json::parse_type ptype = fc::json::legacy_parser) { regex r("^[ \t]*[\{\[]"); if ( !regex_search(file_or_str, r) && fc::is_regular_file(file_or_str) ) { try { return fc::json::from_file(file_or_str, ptype); } EOS_RETHROW_EXCEPTIONS(json_parse_exception, "Fail to parse JSON from file: ${file}", ("file", file_or_str)); } else { try { return fc::json::from_string(file_or_str, ptype); } EOS_RETHROW_EXCEPTIONS(json_parse_exception, "Fail to parse JSON from string: ${string}", ("string", file_or_str)); } } bytes json_or_file_to_bin( const account_name& account, const action_name& action, const string& data_or_filename ) { fc::variant action_args_var; if( !data_or_filename.empty() ) { action_args_var = json_from_file_or_string(data_or_filename, fc::json::relaxed_parser); } return variant_to_bin( account, action, action_args_var ); } void print_action_tree( const fc::variant& action ) { print_action( action ); if( action.get_object().contains( "inline_traces" ) ) { const auto& inline_traces = action["inline_traces"].get_array(); for( const auto& t : inline_traces ) { print_action_tree( t ); } } } void print_result( const fc::variant& result ) { try { if (result.is_object() && result.get_object().contains("processed")) { const auto& processed = result["processed"]; const auto& transaction_id = processed["id"].as_string(); string status = "failed"; int64_t net = -1; int64_t cpu = -1; if( processed.get_object().contains( "receipt" )) { const auto& receipt = processed["receipt"]; if( receipt.is_object()) { status = receipt["status"].as_string(); net = receipt["net_usage_words"].as_int64() * 8; cpu = receipt["cpu_usage_us"].as_int64(); } } cerr << status << " transaction: " << transaction_id << " "; if( net < 0 ) { cerr << "<unknown>"; } else { cerr << net; } cerr << " bytes "; if( cpu < 0 ) { cerr << "<unknown>"; } else { cerr << cpu; } cerr << " us\n"; if( status == "failed" ) { auto soft_except = processed["except"].as<fc::optional<fc::exception>>(); if( soft_except ) { edump((soft_except->to_detail_string())); } } else { const auto& actions = processed["action_traces"].get_array(); for( const auto& a : actions ) { print_action_tree( a ); } wlog( "\rwarning: transaction executed locally, but may not be confirmed by the network yet" ); } } else { cerr << fc::json::to_pretty_string( result ) << endl; } } FC_CAPTURE_AND_RETHROW( (result) ) } using std::cout; void send_actions(std::vector<chain::action>&& actions, const std::vector<public_key_type>& signing_keys = std::vector<public_key_type>(), packed_transaction::compression_type compression = packed_transaction::compression_type::none ) { std::ofstream out; if (tx_json_save_file.length()) { out.open(tx_json_save_file); EOSC_ASSERT(!out.fail(), "ERROR: Failed to create file \"${p}\"", ("p", tx_json_save_file)); } auto result = push_actions( move(actions), compression, signing_keys); string jsonstr; if (tx_json_save_file.length()) { jsonstr = fc::json::to_pretty_string( result ); out << jsonstr; out.close(); } if( tx_print_json ) { if (jsonstr.length() == 0) { jsonstr = fc::json::to_pretty_string( result ); } cout << jsonstr << endl; } else { print_result( result ); } } chain::permission_level to_permission_level(const std::string& s) { auto at_pos = s.find('@'); return permission_level { name(s.substr(0, at_pos)), name(s.substr(at_pos + 1)) }; } chain::action create_newaccount(const name& creator, const name& newaccount, auth_type owner, auth_type active) { return action { get_account_permissions(tx_permission, {creator,config::active_name}), eosio::chain::newaccount{ .creator = creator, .name = newaccount, .owner = owner.contains<public_key_type>() ? authority(owner.get<public_key_type>()) : authority(owner.get<permission_level>()), .active = active.contains<public_key_type>() ? authority(active.get<public_key_type>()) : authority(active.get<permission_level>()) } }; } chain::action create_action(const vector<permission_level>& authorization, const account_name& code, const action_name& act, const fc::variant& args) { return chain::action{authorization, code, act, variant_to_bin(code, act, args)}; } chain::action create_buyram(const name& creator, const name& newaccount, const asset& quantity) { fc::variant act_payload = fc::mutable_variant_object() ("payer", creator.to_string()) ("receiver", newaccount.to_string()) ("quant", quantity.to_string()); return create_action(get_account_permissions(tx_permission, {creator,config::active_name}), config::system_account_name, N(buyram), act_payload); } chain::action create_buyrambytes(const name& creator, const name& newaccount, uint32_t numbytes) { fc::variant act_payload = fc::mutable_variant_object() ("payer", creator.to_string()) ("receiver", newaccount.to_string()) ("bytes", numbytes); return create_action(get_account_permissions(tx_permission, {creator,config::active_name}), config::system_account_name, N(buyrambytes), act_payload); } chain::action create_delegate(const name& from, const name& receiver, const asset& net, const asset& cpu, bool transfer) { fc::variant act_payload = fc::mutable_variant_object() ("from", from.to_string()) ("receiver", receiver.to_string()) ("stake_net_quantity", net.to_string()) ("stake_cpu_quantity", cpu.to_string()) ("transfer", transfer); return create_action(get_account_permissions(tx_permission, {from,config::active_name}), config::system_account_name, N(delegatebw), act_payload); } fc::variant regproducer_variant(const account_name& producer, const public_key_type& key, const string& url, uint16_t location) { return fc::mutable_variant_object() ("producer", producer) ("producer_key", key) ("url", url) ("location", location) ; } chain::action create_open(const string& contract, const name& owner, symbol sym, const name& ram_payer) { auto open_ = fc::mutable_variant_object ("owner", owner) ("symbol", sym) ("ram_payer", ram_payer); return action { get_account_permissions(tx_permission, {ram_payer, config::active_name}), name(contract), N(open), variant_to_bin( name(contract), N(open), open_ ) }; } chain::action create_transfer(const string& contract, const name& sender, const name& recipient, asset amount, const string& memo ) { auto transfer = fc::mutable_variant_object ("from", sender) ("to", recipient) ("quantity", amount) ("memo", memo); return action { get_account_permissions(tx_permission, {sender,config::active_name}), name(contract), N(transfer), variant_to_bin( name(contract), N(transfer), transfer ) }; } chain::action create_setabi(const name& account, const bytes& abi) { return action { get_account_permissions(tx_permission, {account,config::active_name}), setabi{ .account = account, .abi = abi } }; } chain::action create_setcode(const name& account, const bytes& code) { return action { get_account_permissions(tx_permission, {account,config::active_name}), setcode{ .account = account, .vmtype = 0, .vmversion = 0, .code = code } }; } chain::action create_updateauth(const name& account, const name& permission, const name& parent, const authority& auth) { return action { get_account_permissions(tx_permission, {account,config::active_name}), updateauth{account, permission, parent, auth}}; } chain::action create_deleteauth(const name& account, const name& permission) { return action { get_account_permissions(tx_permission, {account,config::active_name}), deleteauth{account, permission}}; } chain::action create_linkauth(const name& account, const name& code, const name& type, const name& requirement) { return action { get_account_permissions(tx_permission, {account,config::active_name}), linkauth{account, code, type, requirement}}; } chain::action create_unlinkauth(const name& account, const name& code, const name& type) { return action { get_account_permissions(tx_permission, {account,config::active_name}), unlinkauth{account, code, type}}; } authority parse_json_authority(const std::string& authorityJsonOrFile) { fc::variant authority_var = json_from_file_or_string(authorityJsonOrFile); try { return authority_var.as<authority>(); } EOS_RETHROW_EXCEPTIONS(authority_type_exception, "Invalid authority format '${data}'", ("data", fc::json::to_string(authority_var, fc::time_point::maximum()))) } authority parse_json_authority_or_key(const std::string& authorityJsonOrFile) { if (is_public_key_str(authorityJsonOrFile)) { try { return authority(public_key_type(authorityJsonOrFile)); } EOS_RETHROW_EXCEPTIONS(public_key_type_exception, "Invalid public key: ${public_key}", ("public_key", authorityJsonOrFile)) } else { auto result = parse_json_authority(authorityJsonOrFile); EOS_ASSERT( eosio::chain::validate(result), authority_type_exception, "Authority failed validation! ensure that keys, accounts, and waits are sorted and that the threshold is valid and satisfiable!"); return result; } } asset to_asset( account_name code, const string& s ) { static map< pair<account_name, eosio::chain::symbol_code>, eosio::chain::symbol> cache; auto a = asset::from_string( s ); eosio::chain::symbol_code sym = a.get_symbol().to_symbol_code(); auto it = cache.find( make_pair(code, sym) ); auto sym_str = a.symbol_name(); if ( it == cache.end() ) { auto json = call(get_currency_stats_func, fc::mutable_variant_object("json", false) ("code", code) ("symbol", sym_str) ); auto obj = json.get_object(); auto obj_it = obj.find( sym_str ); if (obj_it != obj.end()) { auto result = obj_it->value().as<eosio::chain_apis::read_only::get_currency_stats_result>(); auto p = cache.emplace( make_pair( code, sym ), result.max_supply.get_symbol() ); it = p.first; } else { EOS_THROW(symbol_type_exception, "Symbol ${s} is not supported by token contract ${c}", ("s", sym_str)("c", code)); } } auto expected_symbol = it->second; if ( a.decimals() < expected_symbol.decimals() ) { auto factor = expected_symbol.precision() / a.precision(); a = asset( a.get_amount() * factor, expected_symbol ); } else if ( a.decimals() > expected_symbol.decimals() ) { EOS_THROW(symbol_type_exception, "Too many decimal digits in ${a}, only ${d} supported", ("a", a)("d", expected_symbol.decimals())); } // else precision matches return a; } inline asset to_asset( const string& s ) { return to_asset( N(eosio.token), s ); } struct set_account_permission_subcommand { string account; string permission; string authority_json_or_file; string parent; bool add_code; bool remove_code; set_account_permission_subcommand(CLI::App* accountCmd) { auto permissions = accountCmd->add_subcommand("permission", localized("Set parameters dealing with account permissions")); permissions->add_option("account", account, localized("The account to set/delete a permission authority for"))->required(); permissions->add_option("permission", permission, localized("The permission name to set/delete an authority for"))->required(); permissions->add_option("authority", authority_json_or_file, localized("[delete] NULL, [create/update] public key, JSON string or filename defining the authority, [code] contract name")); permissions->add_option("parent", parent, localized("[create] The permission name of this parents permission, defaults to 'active'")); permissions->add_flag("--add-code", add_code, localized("[code] add '${code}' permission to specified permission authority", ("code", name(config::eosio_code_name)))); permissions->add_flag("--remove-code", remove_code, localized("[code] remove '${code}' permission from specified permission authority", ("code", name(config::eosio_code_name)))); add_standard_transaction_options(permissions, "account@active"); permissions->set_callback([this] { EOSC_ASSERT( !(add_code && remove_code), "ERROR: Either --add-code or --remove-code can be set" ); EOSC_ASSERT( (add_code ^ remove_code) || !authority_json_or_file.empty(), "ERROR: authority should be specified unless add or remove code permission" ); authority auth; bool need_parent = parent.empty() && (name(permission) != name("owner")); bool need_auth = add_code || remove_code; if ( !need_auth && boost::iequals(authority_json_or_file, "null") ) { send_actions( { create_deleteauth(name(account), name(permission)) } ); return; } if ( need_parent || need_auth ) { fc::variant json = call(get_account_func, fc::mutable_variant_object("account_name", account)); auto res = json.as<eosio::chain_apis::read_only::get_account_results>(); auto itr = std::find_if(res.permissions.begin(), res.permissions.end(), [&](const auto& perm) { return perm.perm_name == name(permission); }); if ( need_parent ) { // see if we can auto-determine the proper parent if ( itr != res.permissions.end() ) { parent = (*itr).parent.to_string(); } else { // if this is a new permission and there is no parent we default to "active" parent = config::active_name.to_string(); } } if ( need_auth ) { auto actor = (authority_json_or_file.empty()) ? name(account) : name(authority_json_or_file); auto code_name = config::eosio_code_name; if ( itr != res.permissions.end() ) { // fetch existing authority auth = std::move((*itr).required_auth); auto code_perm = permission_level { actor, code_name }; auto itr2 = std::lower_bound(auth.accounts.begin(), auth.accounts.end(), code_perm, [&](const auto& perm_level, const auto& value) { return perm_level.permission < value; // Safe since valid authorities must order the permissions in accounts in ascending order }); if ( add_code ) { if ( itr2 != auth.accounts.end() && itr2->permission == code_perm ) { // authority already contains code permission, promote its weight to satisfy threshold if ( (*itr2).weight < auth.threshold ) { if ( auth.threshold > std::numeric_limits<weight_type>::max() ) { std::cerr << "ERROR: Threshold is too high to be satisfied by sole code permission" << std::endl; return; } std::cerr << localized("The weight of '${actor}@${code}' in '${permission}' permission authority will be increased up to threshold", ("actor", actor)("code", code_name)("permission", permission)) << std::endl; (*itr2).weight = static_cast<weight_type>(auth.threshold); } else { std::cerr << localized("ERROR: The permission '${permission}' already contains '${actor}@${code}'", ("permission", permission)("actor", actor)("code", code_name)) << std::endl; return ; } } else { // add code permission to specified authority if ( auth.threshold > std::numeric_limits<weight_type>::max() ) { std::cerr << "ERROR: Threshold is too high to be satisfied by sole code permission" << std::endl; return; } auth.accounts.insert( itr2, permission_level_weight { .permission = { actor, code_name }, .weight = static_cast<weight_type>(auth.threshold) }); } } else { if ( itr2 != auth.accounts.end() && itr2->permission == code_perm ) { // remove code permission, if authority becomes empty by the removal of code permission, delete permission auth.accounts.erase( itr2 ); if ( auth.keys.empty() && auth.accounts.empty() && auth.waits.empty() ) { send_actions( { create_deleteauth(name(account), name(permission)) } ); return; } } else { // authority doesn't contain code permission std::cerr << localized("ERROR: '${actor}@${code}' does not exist in '${permission}' permission authority", ("actor", actor)("code", code_name)("permission", permission)) << std::endl; return; } } } else { if ( add_code ) { // create new permission including code permission auth.threshold = 1; auth.accounts.push_back( permission_level_weight { .permission = { actor, code_name }, .weight = 1 }); } else { // specified permission doesn't exist, so failed to remove code permission from it std::cerr << localized("ERROR: The permission '${permission}' does not exist", ("permission", permission)) << std::endl; return; } } } } if ( !need_auth ) { auth = parse_json_authority_or_key(authority_json_or_file); } send_actions( { create_updateauth(name(account), name(permission), name(parent), auth) } ); }); } }; struct set_action_permission_subcommand { string accountStr; string codeStr; string typeStr; string requirementStr; set_action_permission_subcommand(CLI::App* actionRoot) { auto permissions = actionRoot->add_subcommand("permission", localized("Set paramaters dealing with account permissions")); permissions->add_option("account", accountStr, localized("The account to set/delete a permission authority for"))->required(); permissions->add_option("code", codeStr, localized("The account that owns the code for the action"))->required(); permissions->add_option("type", typeStr, localized("The type of the action"))->required(); permissions->add_option("requirement", requirementStr, localized("[delete] NULL, [set/update] The permission name require for executing the given action"))->required(); add_standard_transaction_options_plus_signing(permissions, "account@active"); permissions->set_callback([this] { name account = name(accountStr); name code = name(codeStr); name type = name(typeStr); bool is_delete = boost::iequals(requirementStr, "null"); if (is_delete) { send_actions({create_unlinkauth(account, code, type)}, signing_keys_opt.get_keys()); } else { name requirement = name(requirementStr); send_actions({create_linkauth(account, code, type, requirement)}, signing_keys_opt.get_keys()); } }); } }; bool local_port_used() { using namespace boost::asio; io_service ios; local::stream_protocol::endpoint endpoint(wallet_url.substr(strlen("unix://"))); local::stream_protocol::socket socket(ios); boost::system::error_code ec; socket.connect(endpoint, ec); return !ec; } void try_local_port(uint32_t duration) { using namespace std::chrono; auto start_time = duration_cast<std::chrono::milliseconds>( system_clock::now().time_since_epoch() ).count(); while ( !local_port_used()) { if (duration_cast<std::chrono::milliseconds>( system_clock::now().time_since_epoch()).count() - start_time > duration ) { std::cerr << "Unable to connect to " << key_store_executable_name << ", if " << key_store_executable_name << " is running please kill the process and try again.\n"; throw connection_exception(fc::log_messages{FC_LOG_MESSAGE(error, "Unable to connect to ${k}", ("k", key_store_executable_name))}); } } } void ensure_keosd_running(CLI::App* app) { if (no_auto_keosd) return; // get, version, net, convert do not require keosd if (tx_skip_sign || app->got_subcommand("get") || app->got_subcommand("version") || app->got_subcommand("net") || app->got_subcommand("convert")) return; if (app->get_subcommand("create")->got_subcommand("key")) // create key does not require wallet return; if (app->get_subcommand("multisig")->got_subcommand("review")) // multisig review does not require wallet return; if (auto* subapp = app->get_subcommand("system")) { if (subapp->got_subcommand("listproducers") || subapp->got_subcommand("listbw") || subapp->got_subcommand("bidnameinfo")) // system list* do not require wallet return; } if (wallet_url != default_wallet_url) return; if (local_port_used()) return; boost::filesystem::path binPath = boost::dll::program_location(); binPath.remove_filename(); // This extra check is necessary when running cleos like this: ./cleos ... if (binPath.filename_is_dot()) binPath.remove_filename(); binPath.append(key_store_executable_name); // if cleos and keosd are in the same installation directory if (!boost::filesystem::exists(binPath)) { binPath.remove_filename().remove_filename().append("keosd").append(key_store_executable_name); } if (boost::filesystem::exists(binPath)) { namespace bp = boost::process; binPath = boost::filesystem::canonical(binPath); vector<std::string> pargs; pargs.push_back("--http-server-address"); pargs.push_back(""); pargs.push_back("--https-server-address"); pargs.push_back(""); pargs.push_back("--unix-socket-path"); pargs.push_back(string(key_store_executable_name) + ".sock"); ::boost::process::child keos(binPath, pargs, bp::std_in.close(), bp::std_out > bp::null, bp::std_err > bp::null); if (keos.running()) { std::cerr << binPath << " launched" << std::endl; keos.detach(); try_local_port(2000); } else { std::cerr << "No wallet service listening on " << wallet_url << ". Failed to launch " << binPath << std::endl; } } else { std::cerr << "No wallet service listening on " << ". Cannot automatically start " << key_store_executable_name << " because " << key_store_executable_name << " was not found." << std::endl; } } CLI::callback_t obsoleted_option_host_port = [](CLI::results_t) { std::cerr << localized("Host and port options (-H, --wallet-host, etc.) have been replaced with -u/--url and --wallet-url\n" "Use for example -u http://localhost:8888 or --url https://example.invalid/\n"); exit(1); return false; }; struct register_producer_subcommand { string producer_str; string producer_key_str; string url; uint16_t loc = 0; register_producer_subcommand(CLI::App* actionRoot) { auto register_producer = actionRoot->add_subcommand("regproducer", localized("Register a new producer")); register_producer->add_option("account", producer_str, localized("The account to register as a producer"))->required(); register_producer->add_option("producer_key", producer_key_str, localized("The producer's public key"))->required(); register_producer->add_option("url", url, localized("The URL where info about producer can be found"), true); register_producer->add_option("location", loc, localized("Relative location for purpose of nearest neighbor scheduling"), true); add_standard_transaction_options_plus_signing(register_producer, "account@active"); register_producer->set_callback([this] { public_key_type producer_key; try { producer_key = public_key_type(producer_key_str); } EOS_RETHROW_EXCEPTIONS(public_key_type_exception, "Invalid producer public key: ${public_key}", ("public_key", producer_key_str)) auto regprod_var = regproducer_variant(name(producer_str), producer_key, url, loc ); auto accountPermissions = get_account_permissions(tx_permission, {name(producer_str), config::active_name}); send_actions({create_action(accountPermissions, config::system_account_name, N(regproducer), regprod_var)}, signing_keys_opt.get_keys()); }); } }; struct create_account_subcommand { string creator; string account_name; string owner_key_str; string active_key_str; string stake_net; string stake_cpu; uint32_t buy_ram_bytes_in_kbytes = 0; uint32_t buy_ram_bytes = 0; string buy_ram_eos; bool transfer; bool simple; create_account_subcommand(CLI::App* actionRoot, bool s) : simple(s) { auto createAccount = actionRoot->add_subcommand( (simple ? "account" : "newaccount"), (simple ? localized("Create a new account on the blockchain (assumes system contract does not restrict RAM usage)") : localized("Create a new account on the blockchain with initial resources") ) ); createAccount->add_option("creator", creator, localized("The name of the account creating the new account"))->required(); createAccount->add_option("name", account_name, localized("The name of the new account"))->required(); createAccount->add_option("OwnerKey", owner_key_str, localized("The owner public key or permission level for the new account"))->required(); createAccount->add_option("ActiveKey", active_key_str, localized("The active public key or permission level for the new account")); if (!simple) { createAccount->add_option("--stake-net", stake_net, (localized("The amount of tokens delegated for net bandwidth")))->required(); createAccount->add_option("--stake-cpu", stake_cpu, (localized("The amount of tokens delegated for CPU bandwidth")))->required(); createAccount->add_option("--buy-ram-kbytes", buy_ram_bytes_in_kbytes, (localized("The amount of RAM bytes to purchase for the new account in kibibytes (KiB)"))); createAccount->add_option("--buy-ram-bytes", buy_ram_bytes, (localized("The amount of RAM bytes to purchase for the new account in bytes"))); createAccount->add_option("--buy-ram", buy_ram_eos, (localized("The amount of RAM bytes to purchase for the new account in tokens"))); createAccount->add_flag("--transfer", transfer, (localized("Transfer voting power and right to unstake tokens to receiver"))); } add_standard_transaction_options_plus_signing(createAccount, "creator@active"); createAccount->set_callback([this] { auth_type owner, active; if( owner_key_str.find('@') != string::npos ) { try { owner = to_permission_level(owner_key_str); } EOS_RETHROW_EXCEPTIONS( explained_exception, "Invalid owner permission level: ${permission}", ("permission", owner_key_str) ) } else { try { owner = public_key_type(owner_key_str); } EOS_RETHROW_EXCEPTIONS( public_key_type_exception, "Invalid owner public key: ${public_key}", ("public_key", owner_key_str) ); } if( active_key_str.empty() ) { active = owner; } else if( active_key_str.find('@') != string::npos ) { try { active = to_permission_level(active_key_str); } EOS_RETHROW_EXCEPTIONS( explained_exception, "Invalid active permission level: ${permission}", ("permission", active_key_str) ) } else { try { active = public_key_type(active_key_str); } EOS_RETHROW_EXCEPTIONS( public_key_type_exception, "Invalid active public key: ${public_key}", ("public_key", active_key_str) ); } auto create = create_newaccount(name(creator), name(account_name), owner, active); if (!simple) { EOSC_ASSERT( buy_ram_eos.size() || buy_ram_bytes_in_kbytes || buy_ram_bytes, "ERROR: One of --buy-ram, --buy-ram-kbytes or --buy-ram-bytes should have non-zero value" ); EOSC_ASSERT( !buy_ram_bytes_in_kbytes || !buy_ram_bytes, "ERROR: --buy-ram-kbytes and --buy-ram-bytes cannot be set at the same time" ); action buyram = !buy_ram_eos.empty() ? create_buyram(name(creator), name(account_name), to_asset(buy_ram_eos)) : create_buyrambytes(name(creator), name(account_name), (buy_ram_bytes_in_kbytes) ? (buy_ram_bytes_in_kbytes * 1024) : buy_ram_bytes); auto net = to_asset(stake_net); auto cpu = to_asset(stake_cpu); if ( net.get_amount() != 0 || cpu.get_amount() != 0 ) { action delegate = create_delegate( name(creator), name(account_name), net, cpu, transfer); send_actions( { create, buyram, delegate }, signing_keys_opt.get_keys()); } else { send_actions( { create, buyram }, signing_keys_opt.get_keys()); } } else { send_actions( { create }, signing_keys_opt.get_keys()); } }); } }; struct unregister_producer_subcommand { string producer_str; unregister_producer_subcommand(CLI::App* actionRoot) { auto unregister_producer = actionRoot->add_subcommand("unregprod", localized("Unregister an existing producer")); unregister_producer->add_option("account", producer_str, localized("The account to unregister as a producer"))->required(); add_standard_transaction_options_plus_signing(unregister_producer, "account@active"); unregister_producer->set_callback([this] { fc::variant act_payload = fc::mutable_variant_object() ("producer", producer_str); auto accountPermissions = get_account_permissions(tx_permission, {name(producer_str), config::active_name}); send_actions({create_action(accountPermissions, config::system_account_name, N(unregprod), act_payload)}, signing_keys_opt.get_keys()); }); } }; struct vote_producer_proxy_subcommand { string voter_str; string proxy_str; vote_producer_proxy_subcommand(CLI::App* actionRoot) { auto vote_proxy = actionRoot->add_subcommand("proxy", localized("Vote your stake through a proxy")); vote_proxy->add_option("voter", voter_str, localized("The voting account"))->required(); vote_proxy->add_option("proxy", proxy_str, localized("The proxy account"))->required(); add_standard_transaction_options_plus_signing(vote_proxy, "voter@active"); vote_proxy->set_callback([this] { fc::variant act_payload = fc::mutable_variant_object() ("voter", voter_str) ("proxy", proxy_str) ("producers", std::vector<account_name>{}); auto accountPermissions = get_account_permissions(tx_permission, {name(voter_str), config::active_name}); send_actions({create_action(accountPermissions, config::system_account_name, N(voteproducer), act_payload)}, signing_keys_opt.get_keys()); }); } }; struct vote_producers_subcommand { string voter_str; vector<std::string> producer_names; vote_producers_subcommand(CLI::App* actionRoot) { auto vote_producers = actionRoot->add_subcommand("prods", localized("Vote for one or more producers")); vote_producers->add_option("voter", voter_str, localized("The voting account"))->required(); vote_producers->add_option("producers", producer_names, localized("The account(s) to vote for. All options from this position and following will be treated as the producer list."))->required(); add_standard_transaction_options_plus_signing(vote_producers, "voter@active"); vote_producers->set_callback([this] { std::sort( producer_names.begin(), producer_names.end() ); fc::variant act_payload = fc::mutable_variant_object() ("voter", voter_str) ("proxy", "") ("producers", producer_names); auto accountPermissions = get_account_permissions(tx_permission, {name(voter_str), config::active_name}); send_actions({create_action(accountPermissions, config::system_account_name, N(voteproducer), act_payload)}, signing_keys_opt.get_keys()); }); } }; struct approve_producer_subcommand { string voter; string producer_name; approve_producer_subcommand(CLI::App* actionRoot) { auto approve_producer = actionRoot->add_subcommand("approve", localized("Add one producer to list of voted producers")); approve_producer->add_option("voter", voter, localized("The voting account"))->required(); approve_producer->add_option("producer", producer_name, localized("The account to vote for"))->required(); add_standard_transaction_options_plus_signing(approve_producer, "voter@active"); approve_producer->set_callback([this] { auto result = call(get_table_func, fc::mutable_variant_object("json", true) ("code", name(config::system_account_name).to_string()) ("scope", name(config::system_account_name).to_string()) ("table", "voters") ("table_key", "owner") ("lower_bound", name(voter).to_uint64_t()) ("upper_bound", name(voter).to_uint64_t() + 1) // Less than ideal upper_bound usage preserved so cleos can still work with old buggy nodeos versions // Change to voter.value when cleos no longer needs to support nodeos versions older than 1.5.0 ("limit", 1) ); auto res = result.as<eosio::chain_apis::read_only::get_table_rows_result>(); // Condition in if statement below can simply be res.rows.empty() when cleos no longer needs to support nodeos versions older than 1.5.0 // Although since this subcommand will actually change the voter's vote, it is probably better to just keep this check to protect // against future potential chain_plugin bugs. if( res.rows.empty() || res.rows[0].get_object()["owner"].as_string() != name(voter).to_string() ) { std::cerr << "Voter info not found for account " << voter << std::endl; return; } EOS_ASSERT( 1 == res.rows.size(), multiple_voter_info, "More than one voter_info for account" ); auto prod_vars = res.rows[0]["producers"].get_array(); vector<eosio::name> prods; for ( auto& x : prod_vars ) { prods.push_back( name(x.as_string()) ); } prods.push_back( name(producer_name) ); std::sort( prods.begin(), prods.end() ); auto it = std::unique( prods.begin(), prods.end() ); if (it != prods.end() ) { std::cerr << "Producer \"" << producer_name << "\" is already on the list." << std::endl; return; } fc::variant act_payload = fc::mutable_variant_object() ("voter", voter) ("proxy", "") ("producers", prods); auto accountPermissions = get_account_permissions(tx_permission, {name(voter), config::active_name}); send_actions({create_action(accountPermissions, config::system_account_name, N(voteproducer), act_payload)}, signing_keys_opt.get_keys()); }); } }; struct unapprove_producer_subcommand { string voter; string producer_name; unapprove_producer_subcommand(CLI::App* actionRoot) { auto approve_producer = actionRoot->add_subcommand("unapprove", localized("Remove one producer from list of voted producers")); approve_producer->add_option("voter", voter, localized("The voting account"))->required(); approve_producer->add_option("producer", producer_name, localized("The account to remove from voted producers"))->required(); add_standard_transaction_options_plus_signing(approve_producer, "voter@active"); approve_producer->set_callback([this] { auto result = call(get_table_func, fc::mutable_variant_object("json", true) ("code", name(config::system_account_name).to_string()) ("scope", name(config::system_account_name).to_string()) ("table", "voters") ("table_key", "owner") ("lower_bound", name(voter).to_uint64_t()) ("upper_bound", name(voter).to_uint64_t() + 1) // Less than ideal upper_bound usage preserved so cleos can still work with old buggy nodeos versions // Change to voter.value when cleos no longer needs to support nodeos versions older than 1.5.0 ("limit", 1) ); auto res = result.as<eosio::chain_apis::read_only::get_table_rows_result>(); // Condition in if statement below can simply be res.rows.empty() when cleos no longer needs to support nodeos versions older than 1.5.0 // Although since this subcommand will actually change the voter's vote, it is probably better to just keep this check to protect // against future potential chain_plugin bugs. if( res.rows.empty() || res.rows[0].get_object()["owner"].as_string() != name(voter).to_string() ) { std::cerr << "Voter info not found for account " << voter << std::endl; return; } EOS_ASSERT( 1 == res.rows.size(), multiple_voter_info, "More than one voter_info for account" ); auto prod_vars = res.rows[0]["producers"].get_array(); vector<eosio::name> prods; for ( auto& x : prod_vars ) { prods.push_back( name(x.as_string()) ); } auto it = std::remove( prods.begin(), prods.end(), name(producer_name) ); if (it == prods.end() ) { std::cerr << "Cannot remove: producer \"" << producer_name << "\" is not on the list." << std::endl; return; } prods.erase( it, prods.end() ); //should always delete only one element fc::variant act_payload = fc::mutable_variant_object() ("voter", voter) ("proxy", "") ("producers", prods); auto accountPermissions = get_account_permissions(tx_permission, {name(voter), config::active_name}); send_actions({create_action(accountPermissions, config::system_account_name, N(voteproducer), act_payload)}, signing_keys_opt.get_keys()); }); } }; struct list_producers_subcommand { bool print_json = false; uint32_t limit = 50; std::string lower; list_producers_subcommand(CLI::App* actionRoot) { auto list_producers = actionRoot->add_subcommand("listproducers", localized("List producers")); list_producers->add_flag("--json,-j", print_json, localized("Output in JSON format")); list_producers->add_option("-l,--limit", limit, localized("The maximum number of rows to return")); list_producers->add_option("-L,--lower", lower, localized("Lower bound value of key, defaults to first")); list_producers->set_callback([this] { auto rawResult = call(get_producers_func, fc::mutable_variant_object ("json", true)("lower_bound", lower)("limit", limit)); if ( print_json ) { std::cout << fc::json::to_pretty_string(rawResult) << std::endl; return; } auto result = rawResult.as<eosio::chain_apis::read_only::get_producers_result>(); if ( result.rows.empty() ) { std::cout << "No producers found" << std::endl; return; } auto weight = result.total_producer_vote_weight; if ( !weight ) weight = 1; printf("%-13s %-57s %-59s %s\n", "Producer", "Producer key", "Url", "Scaled votes"); for ( auto& row : result.rows ) printf("%-13.13s %-57.57s %-59.59s %1.4f\n", row["owner"].as_string().c_str(), row["producer_key"].as_string().c_str(), row["url"].as_string().c_str(), row["total_votes"].as_double() / weight); if ( !result.more.empty() ) std::cout << "-L " << result.more << " for more" << std::endl; }); } }; struct get_schedule_subcommand { bool print_json = false; void print(const char* name, const fc::variant& schedule) { if (schedule.is_null()) { printf("%s schedule empty\n\n", name); return; } printf("%s schedule version %s\n", name, schedule["version"].as_string().c_str()); printf(" %-13s %s\n", "Producer", "Producer Authority"); printf(" %-13s %s\n", "=============", "=================="); for( auto& row: schedule["producers"].get_array() ) { if( row.get_object().contains("block_signing_key") ) { // pre 2.0 printf( " %-13s %s\n", row["producer_name"].as_string().c_str(), row["block_signing_key"].as_string().c_str() ); } else { printf( " %-13s ", row["producer_name"].as_string().c_str() ); auto a = row["authority"].as<block_signing_authority>(); static_assert( std::is_same<decltype(a), static_variant<block_signing_authority_v0>>::value, "Updates maybe needed if block_signing_authority changes" ); block_signing_authority_v0 auth = a.get<block_signing_authority_v0>(); printf( "%s\n", fc::json::to_string( auth, fc::time_point::maximum() ).c_str() ); } } printf("\n"); } get_schedule_subcommand(CLI::App* actionRoot) { auto get_schedule = actionRoot->add_subcommand("schedule", localized("Retrieve the producer schedule")); get_schedule->add_flag("--json,-j", print_json, localized("Output in JSON format")); get_schedule->set_callback([this] { auto result = call(get_schedule_func, fc::mutable_variant_object()); if ( print_json ) { std::cout << fc::json::to_pretty_string(result) << std::endl; return; } print("active", result["active"]); print("pending", result["pending"]); print("proposed", result["proposed"]); }); } }; struct get_transaction_id_subcommand { string trx_to_check; get_transaction_id_subcommand(CLI::App* actionRoot) { auto get_transaction_id = actionRoot->add_subcommand("transaction_id", localized("Get transaction id given transaction object")); get_transaction_id->add_option("transaction", trx_to_check, localized("The JSON string or filename defining the transaction which transaction id we want to retrieve"))->required(); get_transaction_id->set_callback([&] { try { fc::variant trx_var = json_from_file_or_string(trx_to_check); if( trx_var.is_object() ) { fc::variant_object& vo = trx_var.get_object(); // if actions.data & actions.hex_data provided, use the hex_data since only currently support unexploded data if( vo.contains("actions") ) { if( vo["actions"].is_array() ) { fc::mutable_variant_object mvo = vo; fc::variants& action_variants = mvo["actions"].get_array(); for( auto& action_v : action_variants ) { if( !action_v.is_object() ) { std::cerr << "Empty 'action' in transaction" << endl; return; } fc::variant_object& action_vo = action_v.get_object(); if( action_vo.contains( "data" ) && action_vo.contains( "hex_data" ) ) { fc::mutable_variant_object maction_vo = action_vo; maction_vo["data"] = maction_vo["hex_data"]; action_vo = maction_vo; vo = mvo; } else if( action_vo.contains( "data" ) ) { if( !action_vo["data"].is_string() ) { std::cerr << "get transaction_id only supports un-exploded 'data' (hex form)" << std::endl; return; } } } } else { std::cerr << "transaction json 'actions' is not an array" << std::endl; return; } } else { std::cerr << "transaction json does not include 'actions'" << std::endl; return; } auto trx = trx_var.as<transaction>(); transaction_id_type id = trx.id(); if( id == transaction().id() ) { std::cerr << "file/string does not represent a transaction" << std::endl; } else { std::cout << string( id ) << std::endl; } } else { std::cerr << "file/string does not represent a transaction" << std::endl; } } EOS_RETHROW_EXCEPTIONS(transaction_type_exception, "Fail to parse transaction JSON '${data}'", ("data",trx_to_check)) }); } }; struct delegate_bandwidth_subcommand { string from_str; string receiver_str; string stake_net_amount; string stake_cpu_amount; string stake_storage_amount; string buy_ram_amount; uint32_t buy_ram_bytes = 0; bool transfer = false; delegate_bandwidth_subcommand(CLI::App* actionRoot) { auto delegate_bandwidth = actionRoot->add_subcommand("delegatebw", localized("Delegate bandwidth")); delegate_bandwidth->add_option("from", from_str, localized("The account to delegate bandwidth from"))->required(); delegate_bandwidth->add_option("receiver", receiver_str, localized("The account to receive the delegated bandwidth"))->required(); delegate_bandwidth->add_option("stake_net_quantity", stake_net_amount, localized("The amount of tokens to stake for network bandwidth"))->required(); delegate_bandwidth->add_option("stake_cpu_quantity", stake_cpu_amount, localized("The amount of tokens to stake for CPU bandwidth"))->required(); delegate_bandwidth->add_option("--buyram", buy_ram_amount, localized("The amount of tokens to buy RAM with")); delegate_bandwidth->add_option("--buy-ram-bytes", buy_ram_bytes, localized("The amount of RAM to buy in bytes")); delegate_bandwidth->add_flag("--transfer", transfer, localized("Transfer voting power and right to unstake tokens to receiver")); add_standard_transaction_options_plus_signing(delegate_bandwidth, "from@active"); delegate_bandwidth->set_callback([this] { fc::variant act_payload = fc::mutable_variant_object() ("from", from_str) ("receiver", receiver_str) ("stake_net_quantity", to_asset(stake_net_amount)) ("stake_cpu_quantity", to_asset(stake_cpu_amount)) ("transfer", transfer); auto accountPermissions = get_account_permissions(tx_permission, {name(from_str), config::active_name}); std::vector<chain::action> acts{create_action(accountPermissions, config::system_account_name, N(delegatebw), act_payload)}; EOSC_ASSERT( !(buy_ram_amount.size()) || !buy_ram_bytes, "ERROR: --buyram and --buy-ram-bytes cannot be set at the same time" ); if (buy_ram_amount.size()) { acts.push_back( create_buyram(name(from_str), name(receiver_str), to_asset(buy_ram_amount)) ); } else if (buy_ram_bytes) { acts.push_back( create_buyrambytes(name(from_str), name(receiver_str), buy_ram_bytes) ); } send_actions(std::move(acts), signing_keys_opt.get_keys()); }); } }; struct undelegate_bandwidth_subcommand { string from_str; string receiver_str; string unstake_net_amount; string unstake_cpu_amount; uint64_t unstake_storage_bytes; undelegate_bandwidth_subcommand(CLI::App* actionRoot) { auto undelegate_bandwidth = actionRoot->add_subcommand("undelegatebw", localized("Undelegate bandwidth")); undelegate_bandwidth->add_option("from", from_str, localized("The account undelegating bandwidth"))->required(); undelegate_bandwidth->add_option("receiver", receiver_str, localized("The account to undelegate bandwidth from"))->required(); undelegate_bandwidth->add_option("unstake_net_quantity", unstake_net_amount, localized("The amount of tokens to undelegate for network bandwidth"))->required(); undelegate_bandwidth->add_option("unstake_cpu_quantity", unstake_cpu_amount, localized("The amount of tokens to undelegate for CPU bandwidth"))->required(); add_standard_transaction_options_plus_signing(undelegate_bandwidth, "from@active"); undelegate_bandwidth->set_callback([this] { fc::variant act_payload = fc::mutable_variant_object() ("from", from_str) ("receiver", receiver_str) ("unstake_net_quantity", to_asset(unstake_net_amount)) ("unstake_cpu_quantity", to_asset(unstake_cpu_amount)); auto accountPermissions = get_account_permissions(tx_permission, {name(from_str), config::active_name}); send_actions({create_action(accountPermissions, config::system_account_name, N(undelegatebw), act_payload)}, signing_keys_opt.get_keys()); }); } }; struct bidname_subcommand { string bidder_str; string newname_str; string bid_amount; bidname_subcommand(CLI::App *actionRoot) { auto bidname = actionRoot->add_subcommand("bidname", localized("Name bidding")); bidname->add_option("bidder", bidder_str, localized("The bidding account"))->required(); bidname->add_option("newname", newname_str, localized("The bidding name"))->required(); bidname->add_option("bid", bid_amount, localized("The amount of tokens to bid"))->required(); add_standard_transaction_options_plus_signing(bidname, "bidder@active"); bidname->set_callback([this] { fc::variant act_payload = fc::mutable_variant_object() ("bidder", bidder_str) ("newname", newname_str) ("bid", to_asset(bid_amount)); auto accountPermissions = get_account_permissions(tx_permission, {name(bidder_str), config::active_name}); send_actions({create_action(accountPermissions, config::system_account_name, N(bidname), act_payload)}, signing_keys_opt.get_keys()); }); } }; struct bidname_info_subcommand { bool print_json = false; string newname; bidname_info_subcommand(CLI::App* actionRoot) { auto list_producers = actionRoot->add_subcommand("bidnameinfo", localized("Get bidname info")); list_producers->add_flag("--json,-j", print_json, localized("Output in JSON format")); list_producers->add_option("newname", newname, localized("The bidding name"))->required(); list_producers->set_callback([this] { auto rawResult = call(get_table_func, fc::mutable_variant_object("json", true) ("code", name(config::system_account_name).to_string()) ("scope", name(config::system_account_name).to_string()) ("table", "namebids") ("lower_bound", name(newname).to_uint64_t()) ("upper_bound", name(newname).to_uint64_t() + 1) // Less than ideal upper_bound usage preserved so cleos can still work with old buggy nodeos versions // Change to newname.value when cleos no longer needs to support nodeos versions older than 1.5.0 ("limit", 1)); if ( print_json ) { std::cout << fc::json::to_pretty_string(rawResult) << std::endl; return; } auto result = rawResult.as<eosio::chain_apis::read_only::get_table_rows_result>(); // Condition in if statement below can simply be res.rows.empty() when cleos no longer needs to support nodeos versions older than 1.5.0 if( result.rows.empty() || result.rows[0].get_object()["newname"].as_string() != name(newname).to_string() ) { std::cout << "No bidname record found" << std::endl; return; } const auto& row = result.rows[0]; string time = row["last_bid_time"].as_string(); try { time = (string)fc::time_point(fc::microseconds(to_uint64(time))); } catch (fc::parse_error_exception&) { } int64_t bid = row["high_bid"].as_int64(); std::cout << std::left << std::setw(18) << "bidname:" << std::right << std::setw(24) << row["newname"].as_string() << "\n" << std::left << std::setw(18) << "highest bidder:" << std::right << std::setw(24) << row["high_bidder"].as_string() << "\n" << std::left << std::setw(18) << "highest bid:" << std::right << std::setw(24) << (bid > 0 ? bid : -bid) << "\n" << std::left << std::setw(18) << "last bid time:" << std::right << std::setw(24) << time << std::endl; if (bid < 0) std::cout << "This auction has already closed" << std::endl; }); } }; struct list_bw_subcommand { string account; bool print_json = false; list_bw_subcommand(CLI::App* actionRoot) { auto list_bw = actionRoot->add_subcommand("listbw", localized("List delegated bandwidth")); list_bw->add_option("account", account, localized("The account delegated bandwidth"))->required(); list_bw->add_flag("--json,-j", print_json, localized("Output in JSON format") ); list_bw->set_callback([this] { //get entire table in scope of user account auto result = call(get_table_func, fc::mutable_variant_object("json", true) ("code", name(config::system_account_name).to_string()) ("scope", name(account).to_string()) ("table", "delband") ); if (!print_json) { auto res = result.as<eosio::chain_apis::read_only::get_table_rows_result>(); if ( !res.rows.empty() ) { std::cout << std::setw(13) << std::left << "Receiver" << std::setw(21) << std::left << "Net bandwidth" << std::setw(21) << std::left << "CPU bandwidth" << std::endl; for ( auto& r : res.rows ){ std::cout << std::setw(13) << std::left << r["to"].as_string() << std::setw(21) << std::left << r["net_weight"].as_string() << std::setw(21) << std::left << r["cpu_weight"].as_string() << std::endl; } } else { std::cerr << "Delegated bandwidth not found" << std::endl; } } else { std::cout << fc::json::to_pretty_string(result) << std::endl; } }); } }; struct buyram_subcommand { string from_str; string receiver_str; string amount; bool kbytes = false; bool bytes = false; buyram_subcommand(CLI::App* actionRoot) { auto buyram = actionRoot->add_subcommand("buyram", localized("Buy RAM")); buyram->add_option("payer", from_str, localized("The account paying for RAM"))->required(); buyram->add_option("receiver", receiver_str, localized("The account receiving bought RAM"))->required(); buyram->add_option("amount", amount, localized("The amount of tokens to pay for RAM, or number of bytes/kibibytes of RAM if --bytes/--kbytes is set"))->required(); buyram->add_flag("--kbytes,-k", kbytes, localized("The amount to buy in kibibytes (KiB)")); buyram->add_flag("--bytes,-b", bytes, localized("The amount to buy in bytes")); add_standard_transaction_options_plus_signing(buyram, "payer@active"); buyram->set_callback([this] { EOSC_ASSERT( !kbytes || !bytes, "ERROR: --kbytes and --bytes cannot be set at the same time" ); if (kbytes || bytes) { send_actions( { create_buyrambytes(name(from_str), name(receiver_str), fc::to_uint64(amount) * ((kbytes) ? 1024ull : 1ull)) }, signing_keys_opt.get_keys()); } else { send_actions( { create_buyram(name(from_str), name(receiver_str), to_asset(amount)) }, signing_keys_opt.get_keys()); } }); } }; struct sellram_subcommand { string from_str; string receiver_str; uint64_t amount; sellram_subcommand(CLI::App* actionRoot) { auto sellram = actionRoot->add_subcommand("sellram", localized("Sell RAM")); sellram->add_option("account", receiver_str, localized("The account to receive tokens for sold RAM"))->required(); sellram->add_option("bytes", amount, localized("The amount of RAM bytes to sell"))->required(); add_standard_transaction_options_plus_signing(sellram, "account@active"); sellram->set_callback([this] { fc::variant act_payload = fc::mutable_variant_object() ("account", receiver_str) ("bytes", amount); auto accountPermissions = get_account_permissions(tx_permission, {name(receiver_str), config::active_name}); send_actions({create_action(accountPermissions, config::system_account_name, N(sellram), act_payload)}, signing_keys_opt.get_keys()); }); } }; struct claimrewards_subcommand { string owner; claimrewards_subcommand(CLI::App* actionRoot) { auto claim_rewards = actionRoot->add_subcommand("claimrewards", localized("Claim producer rewards")); claim_rewards->add_option("owner", owner, localized("The account to claim rewards for"))->required(); add_standard_transaction_options_plus_signing(claim_rewards, "owner@active"); claim_rewards->set_callback([this] { fc::variant act_payload = fc::mutable_variant_object() ("owner", owner); auto accountPermissions = get_account_permissions(tx_permission, {name(owner), config::active_name}); send_actions({create_action(accountPermissions, config::system_account_name, N(claimrewards), act_payload)}, signing_keys_opt.get_keys()); }); } }; struct regproxy_subcommand { string proxy; regproxy_subcommand(CLI::App* actionRoot) { auto register_proxy = actionRoot->add_subcommand("regproxy", localized("Register an account as a proxy (for voting)")); register_proxy->add_option("proxy", proxy, localized("The proxy account to register"))->required(); add_standard_transaction_options_plus_signing(register_proxy, "proxy@active"); register_proxy->set_callback([this] { fc::variant act_payload = fc::mutable_variant_object() ("proxy", proxy) ("isproxy", true); auto accountPermissions = get_account_permissions(tx_permission, {name(proxy), config::active_name}); send_actions({create_action(accountPermissions, config::system_account_name, N(regproxy), act_payload)}, signing_keys_opt.get_keys()); }); } }; struct unregproxy_subcommand { string proxy; unregproxy_subcommand(CLI::App* actionRoot) { auto unregister_proxy = actionRoot->add_subcommand("unregproxy", localized("Unregister an account as a proxy (for voting)")); unregister_proxy->add_option("proxy", proxy, localized("The proxy account to unregister"))->required(); add_standard_transaction_options_plus_signing(unregister_proxy, "proxy@active"); unregister_proxy->set_callback([this] { fc::variant act_payload = fc::mutable_variant_object() ("proxy", proxy) ("isproxy", false); auto accountPermissions = get_account_permissions(tx_permission, {name(proxy), config::active_name}); send_actions({create_action(accountPermissions, config::system_account_name, N(regproxy), act_payload)}, signing_keys_opt.get_keys()); }); } }; struct canceldelay_subcommand { string canceling_account; string canceling_permission; string trx_id; canceldelay_subcommand(CLI::App* actionRoot) { auto cancel_delay = actionRoot->add_subcommand("canceldelay", localized("Cancel a delayed transaction")); cancel_delay->add_option("canceling_account", canceling_account, localized("Account from authorization on the original delayed transaction"))->required(); cancel_delay->add_option("canceling_permission", canceling_permission, localized("Permission from authorization on the original delayed transaction"))->required(); cancel_delay->add_option("trx_id", trx_id, localized("The transaction id of the original delayed transaction"))->required(); add_standard_transaction_options_plus_signing(cancel_delay, "canceling_account@canceling_permission"); cancel_delay->set_callback([this] { auto canceling_auth = permission_level{name(canceling_account), name(canceling_permission)}; fc::variant act_payload = fc::mutable_variant_object() ("canceling_auth", canceling_auth) ("trx_id", trx_id); auto accountPermissions = get_account_permissions(tx_permission, canceling_auth); send_actions({create_action(accountPermissions, config::system_account_name, N(canceldelay), act_payload)}, signing_keys_opt.get_keys()); }); } }; struct deposit_subcommand { string owner_str; string amount_str; const name act_name{ N(deposit) }; deposit_subcommand(CLI::App* actionRoot) { auto deposit = actionRoot->add_subcommand("deposit", localized("Deposit into owner's REX fund by transfering from owner's liquid token balance")); deposit->add_option("owner", owner_str, localized("Account which owns the REX fund"))->required(); deposit->add_option("amount", amount_str, localized("Amount to be deposited into REX fund"))->required(); add_standard_transaction_options_plus_signing(deposit, "owner@active"); deposit->set_callback([this] { fc::variant act_payload = fc::mutable_variant_object() ("owner", owner_str) ("amount", amount_str); auto accountPermissions = get_account_permissions(tx_permission, {name(owner_str), config::active_name}); send_actions({create_action(accountPermissions, config::system_account_name, act_name, act_payload)}, signing_keys_opt.get_keys()); }); } }; struct withdraw_subcommand { string owner_str; string amount_str; const name act_name{ N(withdraw) }; withdraw_subcommand(CLI::App* actionRoot) { auto withdraw = actionRoot->add_subcommand("withdraw", localized("Withdraw from owner's REX fund by transfering to owner's liquid token balance")); withdraw->add_option("owner", owner_str, localized("Account which owns the REX fund"))->required(); withdraw->add_option("amount", amount_str, localized("Amount to be withdrawn from REX fund"))->required(); add_standard_transaction_options_plus_signing(withdraw, "owner@active"); withdraw->set_callback([this] { fc::variant act_payload = fc::mutable_variant_object() ("owner", owner_str) ("amount", amount_str); auto accountPermissions = get_account_permissions(tx_permission, {name(owner_str), config::active_name}); send_actions({create_action(accountPermissions, config::system_account_name, act_name, act_payload)}, signing_keys_opt.get_keys()); }); } }; struct buyrex_subcommand { string from_str; string amount_str; const name act_name{ N(buyrex) }; buyrex_subcommand(CLI::App* actionRoot) { auto buyrex = actionRoot->add_subcommand("buyrex", localized("Buy REX using tokens in owner's REX fund")); buyrex->add_option("from", from_str, localized("Account buying REX tokens"))->required(); buyrex->add_option("amount", amount_str, localized("Amount to be taken from REX fund and used in buying REX"))->required(); add_standard_transaction_options_plus_signing(buyrex, "from@active"); buyrex->set_callback([this] { fc::variant act_payload = fc::mutable_variant_object() ("from", from_str) ("amount", amount_str); auto accountPermissions = get_account_permissions(tx_permission, {name(from_str), config::active_name}); send_actions({create_action(accountPermissions, config::system_account_name, act_name, act_payload)}, signing_keys_opt.get_keys()); }); } }; struct lendrex_subcommand { string from_str; string amount_str; const name act_name1{ N(deposit) }; const name act_name2{ N(buyrex) }; lendrex_subcommand(CLI::App* actionRoot) { auto lendrex = actionRoot->add_subcommand("lendrex", localized("Deposit tokens to REX fund and use the tokens to buy REX")); lendrex->add_option("from", from_str, localized("Account buying REX tokens"))->required(); lendrex->add_option("amount", amount_str, localized("Amount of liquid tokens to be used in buying REX"))->required(); add_standard_transaction_options_plus_signing(lendrex, "from@active"); lendrex->set_callback([this] { fc::variant act_payload1 = fc::mutable_variant_object() ("owner", from_str) ("amount", amount_str); fc::variant act_payload2 = fc::mutable_variant_object() ("from", from_str) ("amount", amount_str); auto accountPermissions = get_account_permissions(tx_permission, {name(from_str), config::active_name}); send_actions({create_action(accountPermissions, config::system_account_name, act_name1, act_payload1), create_action(accountPermissions, config::system_account_name, act_name2, act_payload2)}, signing_keys_opt.get_keys()); }); } }; struct unstaketorex_subcommand { string owner_str; string receiver_str; string from_net_str; string from_cpu_str; const name act_name{ N(unstaketorex) }; unstaketorex_subcommand(CLI::App* actionRoot) { auto unstaketorex = actionRoot->add_subcommand("unstaketorex", localized("Buy REX using staked tokens")); unstaketorex->add_option("owner", owner_str, localized("Account buying REX tokens"))->required(); unstaketorex->add_option("receiver", receiver_str, localized("Account that tokens have been staked to"))->required(); unstaketorex->add_option("from_net", from_net_str, localized("Amount to be unstaked from Net resources and used in REX purchase"))->required(); unstaketorex->add_option("from_cpu", from_cpu_str, localized("Amount to be unstaked from CPU resources and used in REX purchase"))->required(); add_standard_transaction_options_plus_signing(unstaketorex, "owner@active"); unstaketorex->set_callback([this] { fc::variant act_payload = fc::mutable_variant_object() ("owner", owner_str) ("receiver", receiver_str) ("from_net", from_net_str) ("from_cpu", from_cpu_str); auto accountPermissions = get_account_permissions(tx_permission, {name(owner_str), config::active_name}); send_actions({create_action(accountPermissions, config::system_account_name, act_name, act_payload)}, signing_keys_opt.get_keys()); }); } }; struct sellrex_subcommand { string from_str; string rex_str; const name act_name{ N(sellrex) }; sellrex_subcommand(CLI::App* actionRoot) { auto sellrex = actionRoot->add_subcommand("sellrex", localized("Sell REX tokens")); sellrex->add_option("from", from_str, localized("Account selling REX tokens"))->required(); sellrex->add_option("rex", rex_str, localized("Amount of REX tokens to be sold"))->required(); add_standard_transaction_options_plus_signing(sellrex, "from@active"); sellrex->set_callback([this] { fc::variant act_payload = fc::mutable_variant_object() ("from", from_str) ("rex", rex_str); auto accountPermissions = get_account_permissions(tx_permission, {name(from_str), config::active_name}); send_actions({create_action(accountPermissions, config::system_account_name, act_name, act_payload)}, signing_keys_opt.get_keys()); }); } }; struct cancelrexorder_subcommand { string owner_str; const name act_name{ N(cnclrexorder) }; cancelrexorder_subcommand(CLI::App* actionRoot) { auto cancelrexorder = actionRoot->add_subcommand("cancelrexorder", localized("Cancel queued REX sell order if one exists")); cancelrexorder->add_option("owner", owner_str, localized("Owner account of sell order"))->required(); add_standard_transaction_options_plus_signing(cancelrexorder, "owner@active"); cancelrexorder->set_callback([this] { fc::variant act_payload = fc::mutable_variant_object()("owner", owner_str); auto accountPermissions = get_account_permissions(tx_permission, {name(owner_str), config::active_name}); send_actions({create_action(accountPermissions, config::system_account_name, act_name, act_payload)}, signing_keys_opt.get_keys()); }); } }; struct rentcpu_subcommand { string from_str; string receiver_str; string loan_payment_str; string loan_fund_str; const name act_name{ N(rentcpu) }; rentcpu_subcommand(CLI::App* actionRoot) { auto rentcpu = actionRoot->add_subcommand("rentcpu", localized("Rent CPU bandwidth for 30 days")); rentcpu->add_option("from", from_str, localized("Account paying rent fees"))->required(); rentcpu->add_option("receiver", receiver_str, localized("Account to whom rented CPU bandwidth is staked"))->required(); rentcpu->add_option("loan_payment", loan_payment_str, localized("Loan fee to be paid, used to calculate amount of rented bandwidth"))->required(); rentcpu->add_option("loan_fund", loan_fund_str, localized("Loan fund to be used in automatic renewal, can be 0 tokens"))->required(); add_standard_transaction_options_plus_signing(rentcpu, "from@active"); rentcpu->set_callback([this] { fc::variant act_payload = fc::mutable_variant_object() ("from", from_str) ("receiver", receiver_str) ("loan_payment", loan_payment_str) ("loan_fund", loan_fund_str); auto accountPermissions = get_account_permissions(tx_permission, {name(from_str), config::active_name}); send_actions({create_action(accountPermissions, config::system_account_name, act_name, act_payload)}, signing_keys_opt.get_keys()); }); } }; struct rentnet_subcommand { string from_str; string receiver_str; string loan_payment_str; string loan_fund_str; const name act_name{ N(rentnet) }; rentnet_subcommand(CLI::App* actionRoot) { auto rentnet = actionRoot->add_subcommand("rentnet", localized("Rent Network bandwidth for 30 days")); rentnet->add_option("from", from_str, localized("Account paying rent fees"))->required(); rentnet->add_option("receiver", receiver_str, localized("Account to whom rented Network bandwidth is staked"))->required(); rentnet->add_option("loan_payment", loan_payment_str, localized("Loan fee to be paid, used to calculate amount of rented bandwidth"))->required(); rentnet->add_option("loan_fund", loan_fund_str, localized("Loan fund to be used in automatic renewal, can be 0 tokens"))->required(); add_standard_transaction_options_plus_signing(rentnet, "from@active"); rentnet->set_callback([this] { fc::variant act_payload = fc::mutable_variant_object() ("from", from_str) ("receiver", receiver_str) ("loan_payment", loan_payment_str) ("loan_fund", loan_fund_str); auto accountPermissions = get_account_permissions(tx_permission, {name(from_str), config::active_name}); send_actions({create_action(accountPermissions, config::system_account_name, act_name, act_payload)}, signing_keys_opt.get_keys()); }); } }; struct fundcpuloan_subcommand { string from_str; string loan_num_str; string payment_str; const name act_name{ N(fundcpuloan) }; fundcpuloan_subcommand(CLI::App* actionRoot) { auto fundcpuloan = actionRoot->add_subcommand("fundcpuloan", localized("Deposit into a CPU loan fund")); fundcpuloan->add_option("from", from_str, localized("Loan owner"))->required(); fundcpuloan->add_option("loan_num", loan_num_str, localized("Loan ID"))->required(); fundcpuloan->add_option("payment", payment_str, localized("Amount to be deposited"))->required(); add_standard_transaction_options_plus_signing(fundcpuloan, "from@active"); fundcpuloan->set_callback([this] { fc::variant act_payload = fc::mutable_variant_object() ("from", from_str) ("loan_num", loan_num_str) ("payment", payment_str); auto accountPermissions = get_account_permissions(tx_permission, {name(from_str), config::active_name}); send_actions({create_action(accountPermissions, config::system_account_name, act_name, act_payload)}, signing_keys_opt.get_keys()); }); } }; struct fundnetloan_subcommand { string from_str; string loan_num_str; string payment_str; const name act_name{ N(fundnetloan) }; fundnetloan_subcommand(CLI::App* actionRoot) { auto fundnetloan = actionRoot->add_subcommand("fundnetloan", localized("Deposit into a Network loan fund")); fundnetloan->add_option("from", from_str, localized("Loan owner"))->required(); fundnetloan->add_option("loan_num", loan_num_str, localized("Loan ID"))->required(); fundnetloan->add_option("payment", payment_str, localized("Amount to be deposited"))->required(); add_standard_transaction_options_plus_signing(fundnetloan, "from@active"); fundnetloan->set_callback([this] { fc::variant act_payload = fc::mutable_variant_object() ("from", from_str) ("loan_num", loan_num_str) ("payment", payment_str); auto accountPermissions = get_account_permissions(tx_permission, {name(from_str), config::active_name}); send_actions({create_action(accountPermissions, config::system_account_name, act_name, act_payload)}, signing_keys_opt.get_keys()); }); } }; struct defcpuloan_subcommand { string from_str; string loan_num_str; string amount_str; const name act_name{ N(defcpuloan) }; defcpuloan_subcommand(CLI::App* actionRoot) { auto defcpuloan = actionRoot->add_subcommand("defundcpuloan", localized("Withdraw from a CPU loan fund")); defcpuloan->add_option("from", from_str, localized("Loan owner"))->required(); defcpuloan->add_option("loan_num", loan_num_str, localized("Loan ID"))->required(); defcpuloan->add_option("amount", amount_str, localized("Amount to be withdrawn"))->required(); add_standard_transaction_options_plus_signing(defcpuloan, "from@active"); defcpuloan->set_callback([this] { fc::variant act_payload = fc::mutable_variant_object() ("from", from_str) ("loan_num", loan_num_str) ("amount", amount_str); auto accountPermissions = get_account_permissions(tx_permission, {name(from_str), config::active_name}); send_actions({create_action(accountPermissions, config::system_account_name, act_name, act_payload)}, signing_keys_opt.get_keys()); }); } }; struct defnetloan_subcommand { string from_str; string loan_num_str; string amount_str; const name act_name{ N(defnetloan) }; defnetloan_subcommand(CLI::App* actionRoot) { auto defnetloan = actionRoot->add_subcommand("defundnetloan", localized("Withdraw from a Network loan fund")); defnetloan->add_option("from", from_str, localized("Loan owner"))->required(); defnetloan->add_option("loan_num", loan_num_str, localized("Loan ID"))->required(); defnetloan->add_option("amount", amount_str, localized("Amount to be withdrawn"))->required(); add_standard_transaction_options_plus_signing(defnetloan, "from@active"); defnetloan->set_callback([this] { fc::variant act_payload = fc::mutable_variant_object() ("from", from_str) ("loan_num", loan_num_str) ("amount", amount_str); auto accountPermissions = get_account_permissions(tx_permission, {name(from_str), config::active_name}); send_actions({create_action(accountPermissions, config::system_account_name, act_name, act_payload)}, signing_keys_opt.get_keys()); }); } }; struct mvtosavings_subcommand { string owner_str; string rex_str; const name act_name{ N(mvtosavings) }; mvtosavings_subcommand(CLI::App* actionRoot) { auto mvtosavings = actionRoot->add_subcommand("mvtosavings", localized("Move REX tokens to savings bucket")); mvtosavings->add_option("owner", owner_str, localized("REX owner"))->required(); mvtosavings->add_option("rex", rex_str, localized("Amount of REX to be moved to savings bucket"))->required(); add_standard_transaction_options_plus_signing(mvtosavings, "owner@active"); mvtosavings->set_callback([this] { fc::variant act_payload = fc::mutable_variant_object() ("owner", owner_str) ("rex", rex_str); auto accountPermissions = get_account_permissions(tx_permission, {name(owner_str), config::active_name}); send_actions({create_action(accountPermissions, config::system_account_name, act_name, act_payload)}, signing_keys_opt.get_keys()); }); } }; struct mvfrsavings_subcommand { string owner_str; string rex_str; const name act_name{ N(mvfrsavings) }; mvfrsavings_subcommand(CLI::App* actionRoot) { auto mvfrsavings = actionRoot->add_subcommand("mvfromsavings", localized("Move REX tokens out of savings bucket")); mvfrsavings->add_option("owner", owner_str, localized("REX owner"))->required(); mvfrsavings->add_option("rex", rex_str, localized("Amount of REX to be moved out of savings bucket"))->required(); add_standard_transaction_options_plus_signing(mvfrsavings, "owner@active"); mvfrsavings->set_callback([this] { fc::variant act_payload = fc::mutable_variant_object() ("owner", owner_str) ("rex", rex_str); auto accountPermissions = get_account_permissions(tx_permission, {name(owner_str), config::active_name}); send_actions({create_action(accountPermissions, config::system_account_name, act_name, act_payload)}, signing_keys_opt.get_keys()); }); } }; struct updaterex_subcommand { string owner_str; const name act_name{ N(updaterex) }; updaterex_subcommand(CLI::App* actionRoot) { auto updaterex = actionRoot->add_subcommand("updaterex", localized("Update REX owner vote stake and vote weight")); updaterex->add_option("owner", owner_str, localized("REX owner"))->required(); add_standard_transaction_options_plus_signing(updaterex, "owner@active"); updaterex->set_callback([this] { fc::variant act_payload = fc::mutable_variant_object()("owner", owner_str); auto accountPermissions = get_account_permissions(tx_permission, {name(owner_str), config::active_name}); send_actions({create_action(accountPermissions, config::system_account_name, act_name, act_payload)}, signing_keys_opt.get_keys()); }); } }; struct consolidate_subcommand { string owner_str; const name act_name{ N(consolidate) }; consolidate_subcommand(CLI::App* actionRoot) { auto consolidate = actionRoot->add_subcommand("consolidate", localized("Consolidate REX maturity buckets into one that matures in 4 days")); consolidate->add_option("owner", owner_str, localized("REX owner"))->required(); add_standard_transaction_options_plus_signing(consolidate, "owner@active"); consolidate->set_callback([this] { fc::variant act_payload = fc::mutable_variant_object()("owner", owner_str); auto accountPermissions = get_account_permissions(tx_permission, {name(owner_str), config::active_name}); send_actions({create_action(accountPermissions, config::system_account_name, act_name, act_payload)}, signing_keys_opt.get_keys()); }); } }; struct rexexec_subcommand { string user_str; string max_str; const name act_name{ N(rexexec) }; rexexec_subcommand(CLI::App* actionRoot) { auto rexexec = actionRoot->add_subcommand("rexexec", localized("Perform REX maintenance by processing expired loans and unfilled sell orders")); rexexec->add_option("user", user_str, localized("User executing the action"))->required(); rexexec->add_option("max", max_str, localized("Maximum number of CPU loans, Network loans, and sell orders to be processed"))->required(); add_standard_transaction_options_plus_signing(rexexec, "user@active"); rexexec->set_callback([this] { fc::variant act_payload = fc::mutable_variant_object() ("user", user_str) ("max", max_str); auto accountPermissions = get_account_permissions(tx_permission, {name(user_str), config::active_name}); send_actions({create_action(accountPermissions, config::system_account_name, act_name, act_payload)}, signing_keys_opt.get_keys()); }); } }; struct closerex_subcommand { string owner_str; const name act_name{ N(closerex) }; closerex_subcommand(CLI::App* actionRoot) { auto closerex = actionRoot->add_subcommand("closerex", localized("Delete unused REX-related user table entries")); closerex->add_option("owner", owner_str, localized("REX owner"))->required(); add_standard_transaction_options_plus_signing(closerex, "owner@active"); closerex->set_callback([this] { fc::variant act_payload = fc::mutable_variant_object()("owner", owner_str); auto accountPermissions = get_account_permissions(tx_permission, {name(owner_str), config::active_name}); send_actions({create_action(accountPermissions, config::system_account_name, act_name, act_payload)}, signing_keys_opt.get_keys()); }); } }; void get_account( const string& accountName, const string& coresym, bool json_format ) { fc::variant json; if (coresym.empty()) { json = call(get_account_func, fc::mutable_variant_object("account_name", accountName)); } else { json = call(get_account_func, fc::mutable_variant_object("account_name", accountName)("expected_core_symbol", symbol::from_string(coresym))); } auto res = json.as<eosio::chain_apis::read_only::get_account_results>(); if (!json_format) { asset staked; asset unstaking; if( res.core_liquid_balance.valid() ) { unstaking = asset( 0, res.core_liquid_balance->get_symbol() ); // Correct core symbol for unstaking asset. staked = asset( 0, res.core_liquid_balance->get_symbol() ); // Correct core symbol for staked asset. } std::cout << "created: " << string(res.created) << std::endl; if(res.privileged) std::cout << "privileged: true" << std::endl; constexpr size_t indent_size = 5; const string indent(indent_size, ' '); std::cout << "permissions: " << std::endl; unordered_map<name, vector<name>/*children*/> tree; vector<name> roots; //we don't have multiple roots, but we can easily handle them here, so let's do it just in case unordered_map<name, eosio::chain_apis::permission> cache; for ( auto& perm : res.permissions ) { if ( perm.parent ) { tree[perm.parent].push_back( perm.perm_name ); } else { roots.push_back( perm.perm_name ); } auto name = perm.perm_name; //keep copy before moving `perm`, since thirst argument of emplace can be evaluated first // looks a little crazy, but should be efficient cache.insert( std::make_pair(name, std::move(perm)) ); } std::function<void (account_name, int)> dfs_print = [&]( account_name name, int depth ) -> void { auto& p = cache.at(name); std::cout << indent << std::string(depth*3, ' ') << name << ' ' << std::setw(5) << p.required_auth.threshold << ": "; const char *sep = ""; for ( auto it = p.required_auth.keys.begin(); it != p.required_auth.keys.end(); ++it ) { std::cout << sep << it->weight << ' ' << it->key.to_string(); sep = ", "; } for ( auto& acc : p.required_auth.accounts ) { std::cout << sep << acc.weight << ' ' << acc.permission.actor.to_string() << '@' << acc.permission.permission.to_string(); sep = ", "; } std::cout << std::endl; auto it = tree.find( name ); if (it != tree.end()) { auto& children = it->second; sort( children.begin(), children.end() ); for ( auto& n : children ) { // we have a tree, not a graph, so no need to check for already visited nodes dfs_print( n, depth+1 ); } } // else it's a leaf node }; std::sort(roots.begin(), roots.end()); for ( auto r : roots ) { dfs_print( r, 0 ); } auto to_pretty_net = []( int64_t nbytes, uint8_t width_for_units = 5 ) { if(nbytes == -1) { // special case. Treat it as unlimited return std::string("unlimited"); } string unit = "bytes"; double bytes = static_cast<double> (nbytes); if (bytes >= 1024 * 1024 * 1024 * 1024ll) { unit = "TiB"; bytes /= 1024 * 1024 * 1024 * 1024ll; } else if (bytes >= 1024 * 1024 * 1024) { unit = "GiB"; bytes /= 1024 * 1024 * 1024; } else if (bytes >= 1024 * 1024) { unit = "MiB"; bytes /= 1024 * 1024; } else if (bytes >= 1024) { unit = "KiB"; bytes /= 1024; } std::stringstream ss; ss << setprecision(4); ss << bytes << " "; if( width_for_units > 0 ) ss << std::left << setw( width_for_units ); ss << unit; return ss.str(); }; std::cout << "memory: " << std::endl << indent << "quota: " << std::setw(15) << to_pretty_net(res.ram_quota) << " used: " << std::setw(15) << to_pretty_net(res.ram_usage) << std::endl << std::endl; std::cout << "net bandwidth: " << std::endl; if ( res.total_resources.is_object() ) { auto net_total = to_asset(res.total_resources.get_object()["net_weight"].as_string()); if( net_total.get_symbol() != unstaking.get_symbol() ) { // Core symbol of nodeos responding to the request is different than core symbol built into cleos unstaking = asset( 0, net_total.get_symbol() ); // Correct core symbol for unstaking asset. staked = asset( 0, net_total.get_symbol() ); // Correct core symbol for staked asset. } if( res.self_delegated_bandwidth.is_object() ) { asset net_own = asset::from_string( res.self_delegated_bandwidth.get_object()["net_weight"].as_string() ); staked = net_own; auto net_others = net_total - net_own; std::cout << indent << "staked:" << std::setw(20) << net_own << std::string(11, ' ') << "(total stake delegated from account to self)" << std::endl << indent << "delegated:" << std::setw(17) << net_others << std::string(11, ' ') << "(total staked delegated to account from others)" << std::endl; } else { auto net_others = net_total; std::cout << indent << "delegated:" << std::setw(17) << net_others << std::string(11, ' ') << "(total staked delegated to account from others)" << std::endl; } } auto to_pretty_time = []( int64_t nmicro, uint8_t width_for_units = 5 ) { if(nmicro == -1) { // special case. Treat it as unlimited return std::string("unlimited"); } string unit = "us"; double micro = static_cast<double>(nmicro); if( micro > 1000000*60*60ll ) { micro /= 1000000*60*60ll; unit = "hr"; } else if( micro > 1000000*60 ) { micro /= 1000000*60; unit = "min"; } else if( micro > 1000000 ) { micro /= 1000000; unit = "sec"; } else if( micro > 1000 ) { micro /= 1000; unit = "ms"; } std::stringstream ss; ss << setprecision(4); ss << micro << " "; if( width_for_units > 0 ) ss << std::left << setw( width_for_units ); ss << unit; return ss.str(); }; std::cout << std::fixed << setprecision(3); std::cout << indent << std::left << std::setw(11) << "used:" << std::right << std::setw(18) << to_pretty_net( res.net_limit.used ) << "\n"; std::cout << indent << std::left << std::setw(11) << "available:" << std::right << std::setw(18) << to_pretty_net( res.net_limit.available ) << "\n"; std::cout << indent << std::left << std::setw(11) << "limit:" << std::right << std::setw(18) << to_pretty_net( res.net_limit.max ) << "\n"; std::cout << std::endl; std::cout << "cpu bandwidth:" << std::endl; if ( res.total_resources.is_object() ) { auto cpu_total = to_asset(res.total_resources.get_object()["cpu_weight"].as_string()); if( res.self_delegated_bandwidth.is_object() ) { asset cpu_own = asset::from_string( res.self_delegated_bandwidth.get_object()["cpu_weight"].as_string() ); staked += cpu_own; auto cpu_others = cpu_total - cpu_own; std::cout << indent << "staked:" << std::setw(20) << cpu_own << std::string(11, ' ') << "(total stake delegated from account to self)" << std::endl << indent << "delegated:" << std::setw(17) << cpu_others << std::string(11, ' ') << "(total staked delegated to account from others)" << std::endl; } else { auto cpu_others = cpu_total; std::cout << indent << "delegated:" << std::setw(17) << cpu_others << std::string(11, ' ') << "(total staked delegated to account from others)" << std::endl; } } std::cout << std::fixed << setprecision(3); std::cout << indent << std::left << std::setw(11) << "used:" << std::right << std::setw(18) << to_pretty_time( res.cpu_limit.used ) << "\n"; std::cout << indent << std::left << std::setw(11) << "available:" << std::right << std::setw(18) << to_pretty_time( res.cpu_limit.available ) << "\n"; std::cout << indent << std::left << std::setw(11) << "limit:" << std::right << std::setw(18) << to_pretty_time( res.cpu_limit.max ) << "\n"; std::cout << std::endl; if( res.refund_request.is_object() ) { auto obj = res.refund_request.get_object(); auto request_time = fc::time_point_sec::from_iso_string( obj["request_time"].as_string() ); fc::time_point refund_time = request_time + fc::days(3); auto now = res.head_block_time; asset net = asset::from_string( obj["net_amount"].as_string() ); asset cpu = asset::from_string( obj["cpu_amount"].as_string() ); unstaking = net + cpu; if( unstaking > asset( 0, unstaking.get_symbol() ) ) { std::cout << std::fixed << setprecision(3); std::cout << "unstaking tokens:" << std::endl; std::cout << indent << std::left << std::setw(25) << "time of unstake request:" << std::right << std::setw(20) << string(request_time); if( now >= refund_time ) { std::cout << " (available to claim now with 'eosio::refund' action)\n"; } else { std::cout << " (funds will be available in " << to_pretty_time( (refund_time - now).count(), 0 ) << ")\n"; } std::cout << indent << std::left << std::setw(25) << "from net bandwidth:" << std::right << std::setw(18) << net << std::endl; std::cout << indent << std::left << std::setw(25) << "from cpu bandwidth:" << std::right << std::setw(18) << cpu << std::endl; std::cout << indent << std::left << std::setw(25) << "total:" << std::right << std::setw(18) << unstaking << std::endl; std::cout << std::endl; } } if( res.core_liquid_balance.valid() ) { std::cout << res.core_liquid_balance->get_symbol().name() << " balances: " << std::endl; std::cout << indent << std::left << std::setw(11) << "liquid:" << std::right << std::setw(18) << *res.core_liquid_balance << std::endl; std::cout << indent << std::left << std::setw(11) << "staked:" << std::right << std::setw(18) << staked << std::endl; std::cout << indent << std::left << std::setw(11) << "unstaking:" << std::right << std::setw(18) << unstaking << std::endl; std::cout << indent << std::left << std::setw(11) << "total:" << std::right << std::setw(18) << (*res.core_liquid_balance + staked + unstaking) << std::endl; std::cout << std::endl; } if( res.rex_info.is_object() ) { auto& obj = res.rex_info.get_object(); asset vote_stake = asset::from_string( obj["vote_stake"].as_string() ); asset rex_balance = asset::from_string( obj["rex_balance"].as_string() ); std::cout << rex_balance.get_symbol().name() << " balances: " << std::endl; std::cout << indent << std::left << std::setw(11) << "balance:" << std::right << std::setw(18) << rex_balance << std::endl; std::cout << indent << std::left << std::setw(11) << "staked:" << std::right << std::setw(18) << vote_stake << std::endl; std::cout << std::endl; } if ( res.voter_info.is_object() ) { auto& obj = res.voter_info.get_object(); string proxy = obj["proxy"].as_string(); if ( proxy.empty() ) { auto& prods = obj["producers"].get_array(); std::cout << "producers:"; if ( !prods.empty() ) { for ( size_t i = 0; i < prods.size(); ++i ) { if ( i%3 == 0 ) { std::cout << std::endl << indent; } std::cout << std::setw(16) << std::left << prods[i].as_string(); } std::cout << std::endl; } else { std::cout << indent << "<not voted>" << std::endl; } } else { std::cout << "proxy:" << indent << proxy << std::endl; } } std::cout << std::endl; } else { std::cout << fc::json::to_pretty_string(json) << std::endl; } } CLI::callback_t header_opt_callback = [](CLI::results_t res) { vector<string>::iterator itr; for (itr = res.begin(); itr != res.end(); itr++) { headers.push_back(*itr); } return true; }; int main( int argc, char** argv ) { fc::logger::get(DEFAULT_LOGGER).set_log_level(fc::log_level::debug); context = eosio::client::http::create_http_context(); wallet_url = default_wallet_url; CLI::App app{"Command Line Interface to EOSIO Client"}; app.require_subcommand(); app.add_option( "-H,--host", obsoleted_option_host_port, localized("The host where ${n} is running", ("n", node_executable_name)) )->group("hidden"); app.add_option( "-p,--port", obsoleted_option_host_port, localized("The port where ${n} is running", ("n", node_executable_name)) )->group("hidden"); app.add_option( "--wallet-host", obsoleted_option_host_port, localized("The host where ${k} is running", ("k", key_store_executable_name)) )->group("hidden"); app.add_option( "--wallet-port", obsoleted_option_host_port, localized("The port where ${k} is running", ("k", key_store_executable_name)) )->group("hidden"); app.add_option( "-u,--url", url, localized("The http/https URL where ${n} is running", ("n", node_executable_name)), true ); app.add_option( "--wallet-url", wallet_url, localized("The http/https URL where ${k} is running", ("k", key_store_executable_name)), true ); app.add_option( "-r,--header", header_opt_callback, localized("Pass specific HTTP header; repeat this option to pass multiple headers")); app.add_flag( "-n,--no-verify", no_verify, localized("Don't verify peer certificate when using HTTPS")); app.add_flag( "--no-auto-" + string(key_store_executable_name), no_auto_keosd, localized("Don't automatically launch a ${k} if one is not currently running", ("k", key_store_executable_name))); app.set_callback([&app]{ ensure_keosd_running(&app);}); app.add_flag( "-v,--verbose", verbose, localized("Output verbose errors and action console output")); app.add_flag("--print-request", print_request, localized("Print HTTP request to STDERR")); app.add_flag("--print-response", print_response, localized("Print HTTP response to STDERR")); auto version = app.add_subcommand("version", localized("Retrieve version information"), false); version->require_subcommand(); version->add_subcommand("client", localized("Retrieve basic version information of the client"))->set_callback([] { std::cout << eosio::version::version_client() << '\n'; }); version->add_subcommand("full", localized("Retrieve full version information of the client"))->set_callback([] { std::cout << eosio::version::version_full() << '\n'; }); // Create subcommand auto create = app.add_subcommand("create", localized("Create various items, on and off the blockchain"), false); create->require_subcommand(); bool r1 = false; string key_file; bool print_console = false; // create key auto create_key = create->add_subcommand("key", localized("Create a new keypair and print the public and private keys"))->set_callback( [&r1, &key_file, &print_console](){ if (key_file.empty() && !print_console) { std::cerr << "ERROR: Either indicate a file using \"--file\" or pass \"--to-console\"" << std::endl; return; } auto pk = r1 ? private_key_type::generate_r1() : private_key_type::generate(); auto privs = pk.to_string(); auto pubs = pk.get_public_key().to_string(); if (print_console) { std::cout << localized("Private key: ${key}", ("key", privs) ) << std::endl; std::cout << localized("Public key: ${key}", ("key", pubs ) ) << std::endl; } else { std::cerr << localized("saving keys to ${filename}", ("filename", key_file)) << std::endl; std::ofstream out( key_file.c_str() ); out << localized("Private key: ${key}", ("key", privs) ) << std::endl; out << localized("Public key: ${key}", ("key", pubs ) ) << std::endl; } }); create_key->add_flag( "--r1", r1, "Generate a key using the R1 curve (iPhone), instead of the K1 curve (Bitcoin)" ); create_key->add_option("-f,--file", key_file, localized("Name of file to write private/public key output to. (Must be set, unless \"--to-console\" is passed")); create_key->add_flag( "--to-console", print_console, localized("Print private/public keys to console.")); // create account auto createAccount = create_account_subcommand( create, true /*simple*/ ); // convert subcommand auto convert = app.add_subcommand("convert", localized("Pack and unpack transactions"), false); // TODO also add converting action args based on abi from here ? convert->require_subcommand(); // pack transaction string plain_signed_transaction_json; bool pack_action_data_flag = false; auto pack_transaction = convert->add_subcommand("pack_transaction", localized("From plain signed JSON to packed form")); pack_transaction->add_option("transaction", plain_signed_transaction_json, localized("The plain signed JSON (string)"))->required(); pack_transaction->add_flag("--pack-action-data", pack_action_data_flag, localized("Pack all action data within transaction, needs interaction with ${n}", ("n", node_executable_name))); pack_transaction->set_callback([&] { fc::variant trx_var = json_from_file_or_string( plain_signed_transaction_json ); if( pack_action_data_flag ) { signed_transaction trx; try { abi_serializer::from_variant( trx_var, trx, abi_serializer_resolver, abi_serializer_max_time ); } EOS_RETHROW_EXCEPTIONS( transaction_type_exception, "Invalid transaction format: '${data}'", ("data", fc::json::to_string(trx_var, fc::time_point::maximum()))) std::cout << fc::json::to_pretty_string( packed_transaction( trx, packed_transaction::compression_type::none )) << std::endl; } else { try { signed_transaction trx = trx_var.as<signed_transaction>(); std::cout << fc::json::to_pretty_string( fc::variant( packed_transaction( trx, packed_transaction::compression_type::none ))) << std::endl; } EOS_RETHROW_EXCEPTIONS( transaction_type_exception, "Fail to convert transaction, --pack-action-data likely needed" ) } }); // unpack transaction string packed_transaction_json; bool unpack_action_data_flag = false; auto unpack_transaction = convert->add_subcommand("unpack_transaction", localized("From packed to plain signed JSON form")); unpack_transaction->add_option("transaction", packed_transaction_json, localized("The packed transaction JSON (string containing packed_trx and optionally compression fields)"))->required(); unpack_transaction->add_flag("--unpack-action-data", unpack_action_data_flag, localized("Unpack all action data within transaction, needs interaction with ${n}", ("n", node_executable_name))); unpack_transaction->set_callback([&] { fc::variant packed_trx_var = json_from_file_or_string( packed_transaction_json ); packed_transaction packed_trx; try { fc::from_variant<packed_transaction>( packed_trx_var, packed_trx ); } EOS_RETHROW_EXCEPTIONS( transaction_type_exception, "Invalid packed transaction format: '${data}'", ("data", fc::json::to_string(packed_trx_var, fc::time_point::maximum()))) signed_transaction strx = packed_trx.get_signed_transaction(); fc::variant trx_var; if( unpack_action_data_flag ) { abi_serializer::to_variant( strx, trx_var, abi_serializer_resolver, abi_serializer_max_time ); } else { trx_var = strx; } std::cout << fc::json::to_pretty_string( trx_var ) << std::endl; }); // pack action data string unpacked_action_data_account_string; string unpacked_action_data_name_string; string unpacked_action_data_string; auto pack_action_data = convert->add_subcommand("pack_action_data", localized("From JSON action data to packed form")); pack_action_data->add_option("account", unpacked_action_data_account_string, localized("The name of the account hosting the contract"))->required(); pack_action_data->add_option("name", unpacked_action_data_name_string, localized("The name of the function called by this action"))->required(); pack_action_data->add_option("unpacked_action_data", unpacked_action_data_string, localized("The action data expressed as JSON"))->required(); pack_action_data->set_callback([&] { fc::variant unpacked_action_data_json = json_from_file_or_string(unpacked_action_data_string); bytes packed_action_data_string; try { packed_action_data_string = variant_to_bin(name(unpacked_action_data_account_string), name(unpacked_action_data_name_string), unpacked_action_data_json); } EOS_RETHROW_EXCEPTIONS(transaction_type_exception, "Fail to parse unpacked action data JSON") std::cout << fc::to_hex(packed_action_data_string.data(), packed_action_data_string.size()) << std::endl; }); // unpack action data string packed_action_data_account_string; string packed_action_data_name_string; string packed_action_data_string; auto unpack_action_data = convert->add_subcommand("unpack_action_data", localized("From packed to JSON action data form")); unpack_action_data->add_option("account", packed_action_data_account_string, localized("The name of the account that hosts the contract"))->required(); unpack_action_data->add_option("name", packed_action_data_name_string, localized("The name of the function that's called by this action"))->required(); unpack_action_data->add_option("packed_action_data", packed_action_data_string, localized("The action data expressed as packed hex string"))->required(); unpack_action_data->set_callback([&] { EOS_ASSERT( packed_action_data_string.size() >= 2, transaction_type_exception, "No packed_action_data found" ); vector<char> packed_action_data_blob(packed_action_data_string.size()/2); fc::from_hex(packed_action_data_string, packed_action_data_blob.data(), packed_action_data_blob.size()); fc::variant unpacked_action_data_json = bin_to_variant(name(packed_action_data_account_string), name(packed_action_data_name_string), packed_action_data_blob); std::cout << fc::json::to_pretty_string(unpacked_action_data_json) << std::endl; }); // Get subcommand auto get = app.add_subcommand("get", localized("Retrieve various items and information from the blockchain"), false); get->require_subcommand(); // get info get->add_subcommand("info", localized("Get current blockchain information"))->set_callback([] { std::cout << fc::json::to_pretty_string(get_info()) << std::endl; }); // get block string blockArg; bool get_bhs = false; auto getBlock = get->add_subcommand("block", localized("Retrieve a full block from the blockchain"), false); getBlock->add_option("block", blockArg, localized("The number or ID of the block to retrieve"))->required(); getBlock->add_flag("--header-state", get_bhs, localized("Get block header state from fork database instead") ); getBlock->set_callback([&blockArg,&get_bhs] { auto arg = fc::mutable_variant_object("block_num_or_id", blockArg); if( get_bhs ) { std::cout << fc::json::to_pretty_string(call(get_block_header_state_func, arg)) << std::endl; } else { std::cout << fc::json::to_pretty_string(call(get_block_func, arg)) << std::endl; } }); // get account string accountName; string coresym; bool print_json; auto getAccount = get->add_subcommand("account", localized("Retrieve an account from the blockchain"), false); getAccount->add_option("name", accountName, localized("The name of the account to retrieve"))->required(); getAccount->add_option("core-symbol", coresym, localized("The expected core symbol of the chain you are querying")); getAccount->add_flag("--json,-j", print_json, localized("Output in JSON format") ); getAccount->set_callback([&]() { get_account(accountName, coresym, print_json); }); // get code string codeFilename; string abiFilename; bool code_as_wasm = false; auto getCode = get->add_subcommand("code", localized("Retrieve the code and ABI for an account"), false); getCode->add_option("name", accountName, localized("The name of the account whose code should be retrieved"))->required(); getCode->add_option("-c,--code",codeFilename, localized("The name of the file to save the contract .wast/wasm to") ); getCode->add_option("-a,--abi",abiFilename, localized("The name of the file to save the contract .abi to") ); getCode->add_flag("--wasm", code_as_wasm, localized("Save contract as wasm")); getCode->set_callback([&] { string code_hash, wasm, wast, abi; try { const auto result = call(get_raw_code_and_abi_func, fc::mutable_variant_object("account_name", accountName)); const std::vector<char> wasm_v = result["wasm"].as_blob().data; const std::vector<char> abi_v = result["abi"].as_blob().data; fc::sha256 hash; if(wasm_v.size()) hash = fc::sha256::hash(wasm_v.data(), wasm_v.size()); code_hash = (string)hash; wasm = string(wasm_v.begin(), wasm_v.end()); if(!code_as_wasm && wasm_v.size()) wast = wasm_to_wast((const uint8_t*)wasm_v.data(), wasm_v.size(), false); abi_def abi_d; if(abi_serializer::to_abi(abi_v, abi_d)) abi = fc::json::to_pretty_string(abi_d); } catch(chain::missing_chain_api_plugin_exception&) { //see if this is an old nodeos that doesn't support get_raw_code_and_abi const auto old_result = call(get_code_func, fc::mutable_variant_object("account_name", accountName)("code_as_wasm",code_as_wasm)); code_hash = old_result["code_hash"].as_string(); if(code_as_wasm) { wasm = old_result["wasm"].as_string(); std::cout << localized("Warning: communicating to older ${n} which returns malformed binary wasm", ("n", node_executable_name)) << std::endl; } else wast = old_result["wast"].as_string(); abi = fc::json::to_pretty_string(old_result["abi"]); } std::cout << localized("code hash: ${code_hash}", ("code_hash", code_hash)) << std::endl; if( codeFilename.size() ){ std::cout << localized("saving ${type} to ${codeFilename}", ("type", (code_as_wasm ? "wasm" : "wast"))("codeFilename", codeFilename)) << std::endl; std::ofstream out( codeFilename.c_str() ); if(code_as_wasm) out << wasm; else out << wast; } if( abiFilename.size() ) { std::cout << localized("saving abi to ${abiFilename}", ("abiFilename", abiFilename)) << std::endl; std::ofstream abiout( abiFilename.c_str() ); abiout << abi; } }); // get abi string filename; auto getAbi = get->add_subcommand("abi", localized("Retrieve the ABI for an account"), false); getAbi->add_option("name", accountName, localized("The name of the account whose abi should be retrieved"))->required(); getAbi->add_option("-f,--file",filename, localized("The name of the file to save the contract .abi to instead of writing to console") ); getAbi->set_callback([&] { auto result = call(get_abi_func, fc::mutable_variant_object("account_name", accountName)); auto abi = fc::json::to_pretty_string( result["abi"] ); if( filename.size() ) { std::cerr << localized("saving abi to ${filename}", ("filename", filename)) << std::endl; std::ofstream abiout( filename.c_str() ); abiout << abi; } else { std::cout << abi << "\n"; } }); // get table string scope; string code; string table; string lower; string upper; string table_key; string key_type; string encode_type{"dec"}; bool binary = false; uint32_t limit = 10; string index_position; bool reverse = false; bool show_payer = false; auto getTable = get->add_subcommand( "table", localized("Retrieve the contents of a database table"), false); getTable->add_option( "account", code, localized("The account who owns the table") )->required(); getTable->add_option( "scope", scope, localized("The scope within the contract in which the table is found") )->required(); getTable->add_option( "table", table, localized("The name of the table as specified by the contract abi") )->required(); getTable->add_option( "-l,--limit", limit, localized("The maximum number of rows to return") ); getTable->add_option( "-k,--key", table_key, localized("Deprecated") ); getTable->add_option( "-L,--lower", lower, localized("JSON representation of lower bound value of key, defaults to first") ); getTable->add_option( "-U,--upper", upper, localized("JSON representation of upper bound value of key, defaults to last") ); getTable->add_option( "--index", index_position, localized("Index number, 1 - primary (first), 2 - secondary index (in order defined by multi_index), 3 - third index, etc.\n" "\t\t\t\tNumber or name of index can be specified, e.g. 'secondary' or '2'.")); getTable->add_option( "--key-type", key_type, localized("The key type of --index, primary only supports (i64), all others support (i64, i128, i256, float64, float128, ripemd160, sha256).\n" "\t\t\t\tSpecial type 'name' indicates an account name.")); getTable->add_option( "--encode-type", encode_type, localized("The encoding type of key_type (i64 , i128 , float64, float128) only support decimal encoding e.g. 'dec'" "i256 - supports both 'dec' and 'hex', ripemd160 and sha256 is 'hex' only")); getTable->add_flag("-b,--binary", binary, localized("Return the value as BINARY rather than using abi to interpret as JSON")); getTable->add_flag("-r,--reverse", reverse, localized("Iterate in reverse order")); getTable->add_flag("--show-payer", show_payer, localized("Show RAM payer")); getTable->set_callback([&] { auto result = call(get_table_func, fc::mutable_variant_object("json", !binary) ("code",code) ("scope",scope) ("table",table) ("table_key",table_key) // not used ("lower_bound",lower) ("upper_bound",upper) ("limit",limit) ("key_type",key_type) ("index_position", index_position) ("encode_type", encode_type) ("reverse", reverse) ("show_payer", show_payer) ); std::cout << fc::json::to_pretty_string(result) << std::endl; }); auto getScope = get->add_subcommand( "scope", localized("Retrieve a list of scopes and tables owned by a contract"), false); getScope->add_option( "contract", code, localized("The contract who owns the table") )->required(); getScope->add_option( "-t,--table", table, localized("The name of the table as filter") ); getScope->add_option( "-l,--limit", limit, localized("The maximum number of rows to return") ); getScope->add_option( "-L,--lower", lower, localized("Lower bound of scope") ); getScope->add_option( "-U,--upper", upper, localized("Upper bound of scope") ); getScope->add_flag("-r,--reverse", reverse, localized("Iterate in reverse order")); getScope->set_callback([&] { auto result = call(get_table_by_scope_func, fc::mutable_variant_object("code",code) ("table",table) ("lower_bound",lower) ("upper_bound",upper) ("limit",limit) ("reverse", reverse) ); std::cout << fc::json::to_pretty_string(result) << std::endl; }); // currency accessors // get currency balance string symbol; bool currency_balance_print_json = false; auto get_currency = get->add_subcommand( "currency", localized("Retrieve information related to standard currencies"), true); get_currency->require_subcommand(); auto get_balance = get_currency->add_subcommand( "balance", localized("Retrieve the balance of an account for a given currency"), false); get_balance->add_option( "contract", code, localized("The contract that operates the currency") )->required(); get_balance->add_option( "account", accountName, localized("The account to query balances for") )->required(); get_balance->add_option( "symbol", symbol, localized("The symbol for the currency if the contract operates multiple currencies") ); get_balance->add_flag("--json,-j", currency_balance_print_json, localized("Output in JSON format") ); get_balance->set_callback([&] { auto result = call(get_currency_balance_func, fc::mutable_variant_object ("account", accountName) ("code", code) ("symbol", symbol.empty() ? fc::variant() : symbol) ); if (!currency_balance_print_json) { const auto& rows = result.get_array(); for( const auto& r : rows ) { std::cout << r.as_string() << std::endl; } } else { std::cout << fc::json::to_pretty_string(result) << std::endl; } }); auto get_currency_stats = get_currency->add_subcommand( "stats", localized("Retrieve the stats of for a given currency"), false); get_currency_stats->add_option( "contract", code, localized("The contract that operates the currency") )->required(); get_currency_stats->add_option( "symbol", symbol, localized("The symbol for the currency if the contract operates multiple currencies") )->required(); get_currency_stats->set_callback([&] { auto result = call(get_currency_stats_func, fc::mutable_variant_object("json", false) ("code", code) ("symbol", symbol) ); std::cout << fc::json::to_pretty_string(result) << std::endl; }); // get accounts string public_key_str; auto getAccounts = get->add_subcommand("accounts", localized("Retrieve accounts associated with a public key"), false); getAccounts->add_option("public_key", public_key_str, localized("The public key to retrieve accounts for"))->required(); getAccounts->set_callback([&] { public_key_type public_key; try { public_key = public_key_type(public_key_str); } EOS_RETHROW_EXCEPTIONS(public_key_type_exception, "Invalid public key: ${public_key}", ("public_key", public_key_str)) auto arg = fc::mutable_variant_object( "public_key", public_key); std::cout << fc::json::to_pretty_string(call(get_key_accounts_func, arg)) << std::endl; }); // get servants string controllingAccount; auto getServants = get->add_subcommand("servants", localized("Retrieve accounts which are servants of a given account "), false); getServants->add_option("account", controllingAccount, localized("The name of the controlling account"))->required(); getServants->set_callback([&] { auto arg = fc::mutable_variant_object( "controlling_account", controllingAccount); std::cout << fc::json::to_pretty_string(call(get_controlled_accounts_func, arg)) << std::endl; }); // get transaction string transaction_id_str; uint32_t block_num_hint = 0; auto getTransaction = get->add_subcommand("transaction", localized("Retrieve a transaction from the blockchain"), false); getTransaction->add_option("id", transaction_id_str, localized("ID of the transaction to retrieve"))->required(); getTransaction->add_option( "-b,--block-hint", block_num_hint, localized("The block number this transaction may be in") ); getTransaction->set_callback([&] { auto arg= fc::mutable_variant_object( "id", transaction_id_str); if ( block_num_hint > 0 ) { arg = arg("block_num_hint", block_num_hint); } std::cout << fc::json::to_pretty_string(call(get_transaction_func, arg)) << std::endl; }); // get actions string account_name; string skip_seq_str; string num_seq_str; bool printjson = false; bool fullact = false; bool prettyact = false; bool printconsole = false; int32_t pos_seq = -1; int32_t offset = -20; auto getActions = get->add_subcommand("actions", localized("Retrieve all actions with specific account name referenced in authorization or receiver"), false); getActions->add_option("account_name", account_name, localized("Name of account to query on"))->required(); getActions->add_option("pos", pos_seq, localized("Sequence number of action for this account, -1 for last")); getActions->add_option("offset", offset, localized("Get actions [pos,pos+offset] for positive offset or [pos-offset,pos) for negative offset")); getActions->add_flag("--json,-j", printjson, localized("Print full JSON")); getActions->add_flag("--full", fullact, localized("Don't truncate action output")); getActions->add_flag("--pretty", prettyact, localized("Pretty print full action JSON")); getActions->add_flag("--console", printconsole, localized("Print console output generated by action ")); getActions->set_callback([&] { fc::mutable_variant_object arg; arg( "account_name", account_name ); arg( "pos", pos_seq ); arg( "offset", offset); auto result = call(get_actions_func, arg); if( printjson ) { std::cout << fc::json::to_pretty_string(result) << std::endl; } else { auto& traces = result["actions"].get_array(); uint32_t lib = result["last_irreversible_block"].as_uint64(); cout << "#" << setw(5) << "seq" << " " << setw( 24 ) << left << "when"<< " " << setw(24) << right << "contract::action" << " => " << setw(13) << left << "receiver" << " " << setw(11) << left << "trx id..." << " args\n"; cout << "================================================================================================================\n"; for( const auto& trace: traces ) { std::stringstream out; if( trace["block_num"].as_uint64() <= lib ) out << "#"; else out << "?"; out << setw(5) << trace["account_action_seq"].as_uint64() <<" "; out << setw(24) << trace["block_time"].as_string() <<" "; const auto& at = trace["action_trace"].get_object(); auto id = at["trx_id"].as_string(); const auto& receipt = at["receipt"]; auto receiver = receipt["receiver"].as_string(); const auto& act = at["act"].get_object(); auto code = act["account"].as_string(); auto func = act["name"].as_string(); string args; if( prettyact ) { args = fc::json::to_pretty_string( act["data"] ); } else { args = fc::json::to_string( act["data"], fc::time_point::maximum() ); if( !fullact ) { args = args.substr(0,60) + "..."; } } out << std::setw(24) << std::right<< (code +"::" + func) << " => " << left << std::setw(13) << receiver; out << " " << setw(11) << (id.substr(0,8) + "..."); if( fullact || prettyact ) out << "\n"; else out << " "; out << args ;//<< "\n"; if( trace["block_num"].as_uint64() <= lib ) { dlog( "\r${m}", ("m",out.str()) ); } else { wlog( "\r${m}", ("m",out.str()) ); } if( printconsole ) { auto console = at["console"].as_string(); if( console.size() ) { stringstream out; std::stringstream ss(console); string line; while( std::getline( ss, line ) ) { out << ">> " << line << "\n"; if( !fullact ) break; } cerr << out.str(); //ilog( "\r${m} ", ("m",out.str()) ); } } } } }); auto getSchedule = get_schedule_subcommand{get}; auto getTransactionId = get_transaction_id_subcommand{get}; /* auto getTransactions = get->add_subcommand("transactions", localized("Retrieve all transactions with specific account name referenced in their scope"), false); getTransactions->add_option("account_name", account_name, localized("Name of account to query on"))->required(); getTransactions->add_option("skip_seq", skip_seq_str, localized("Number of most recent transactions to skip (0 would start at most recent transaction)")); getTransactions->add_option("num_seq", num_seq_str, localized("Number of transactions to return")); getTransactions->add_flag("--json,-j", printjson, localized("Print full json")); getTransactions->set_callback([&] { fc::mutable_variant_object arg; if (skip_seq_str.empty()) { arg = fc::mutable_variant_object( "account_name", account_name); } else { uint64_t skip_seq; try { skip_seq = boost::lexical_cast<uint64_t>(skip_seq_str); } EOS_RETHROW_EXCEPTIONS(chain_type_exception, "Invalid Skip Seq: ${skip_seq}", ("skip_seq", skip_seq_str)) if (num_seq_str.empty()) { arg = fc::mutable_variant_object( "account_name", account_name)("skip_seq", skip_seq); } else { uint64_t num_seq; try { num_seq = boost::lexical_cast<uint64_t>(num_seq_str); } EOS_RETHROW_EXCEPTIONS(chain_type_exception, "Invalid Num Seq: ${num_seq}", ("num_seq", num_seq_str)) arg = fc::mutable_variant_object( "account_name", account_name)("skip_seq", skip_seq_str)("num_seq", num_seq); } } auto result = call(get_transactions_func, arg); if( printjson ) { std::cout << fc::json::to_pretty_string(result) << std::endl; } else { const auto& trxs = result.get_object()["transactions"].get_array(); for( const auto& t : trxs ) { const auto& tobj = t.get_object(); const auto& trx = tobj["transaction"].get_object(); const auto& data = trx["transaction"].get_object(); const auto& msgs = data["actions"].get_array(); for( const auto& msg : msgs ) { int64_t seq_num = tobj["seq_num"].as<int64_t>(); string id = tobj["transaction_id"].as_string(); const auto& exp = data["expiration"].as<fc::time_point_sec>(); std::cout << tobj["seq_num"].as_string() <<"] " << id.substr(0,8) << "... " << data["expiration"].as_string() << " "; auto code = msg["account"].as_string(); auto func = msg["name"].as_string(); auto args = fc::json::to_string( msg["data"] ); std::cout << setw(26) << left << (code + "::" + func) << " " << args; std::cout << std::endl; } } } }); */ // set subcommand auto setSubcommand = app.add_subcommand("set", localized("Set or update blockchain state")); setSubcommand->require_subcommand(); // set contract subcommand string account; string contractPath; string wasmPath; string abiPath; bool shouldSend = true; bool contract_clear = false; bool suppress_duplicate_check = false; auto codeSubcommand = setSubcommand->add_subcommand("code", localized("Create or update the code on an account")); codeSubcommand->add_option("account", account, localized("The account to set code for"))->required(); codeSubcommand->add_option("code-file", wasmPath, localized("The path containing the contract WASM"));//->required(); codeSubcommand->add_flag( "-c,--clear", contract_clear, localized("Remove code on an account")); codeSubcommand->add_flag( "--suppress-duplicate-check", suppress_duplicate_check, localized("Don't check for duplicate")); auto abiSubcommand = setSubcommand->add_subcommand("abi", localized("Create or update the abi on an account")); abiSubcommand->add_option("account", account, localized("The account to set the ABI for"))->required(); abiSubcommand->add_option("abi-file", abiPath, localized("The path containing the contract ABI"));//->required(); abiSubcommand->add_flag( "-c,--clear", contract_clear, localized("Remove abi on an account")); abiSubcommand->add_flag( "--suppress-duplicate-check", suppress_duplicate_check, localized("Don't check for duplicate")); auto contractSubcommand = setSubcommand->add_subcommand("contract", localized("Create or update the contract on an account")); contractSubcommand->add_option("account", account, localized("The account to publish a contract for")) ->required(); contractSubcommand->add_option("contract-dir", contractPath, localized("The path containing the .wasm and .abi")); // ->required(); contractSubcommand->add_option("wasm-file", wasmPath, localized("The file containing the contract WASM relative to contract-dir")); // ->check(CLI::ExistingFile); auto abi = contractSubcommand->add_option("abi-file,-a,--abi", abiPath, localized("The ABI for the contract relative to contract-dir")); // ->check(CLI::ExistingFile); contractSubcommand->add_flag( "-c,--clear", contract_clear, localized("Remove contract on an account")); contractSubcommand->add_flag( "--suppress-duplicate-check", suppress_duplicate_check, localized("Don't check for duplicate")); std::vector<chain::action> actions; auto set_code_callback = [&]() { std::vector<char> old_wasm; bool duplicate = false; fc::sha256 old_hash, new_hash; if (!suppress_duplicate_check) { try { const auto result = call(get_code_hash_func, fc::mutable_variant_object("account_name", account)); old_hash = fc::sha256(result["code_hash"].as_string()); } catch (...) { std::cerr << "Failed to get existing code hash, continue without duplicate check..." << std::endl; suppress_duplicate_check = true; } } bytes code_bytes; if(!contract_clear){ std::string wasm; fc::path cpath = fc::canonical(fc::path(contractPath)); if( wasmPath.empty() ) { wasmPath = (cpath / (cpath.filename().generic_string()+".wasm")).generic_string(); } else if ( boost::filesystem::path(wasmPath).is_relative() ) { wasmPath = (cpath / wasmPath).generic_string(); } std::cerr << localized(("Reading WASM from " + wasmPath + "...").c_str()) << std::endl; fc::read_file_contents(wasmPath, wasm); EOS_ASSERT( !wasm.empty(), wasm_file_not_found, "no wasm file found ${f}", ("f", wasmPath) ); const string binary_wasm_header("\x00\x61\x73\x6d\x01\x00\x00\x00", 8); if(wasm.compare(0, 8, binary_wasm_header)) std::cerr << localized("WARNING: ") << wasmPath << localized(" doesn't look like a binary WASM file. Is it something else, like WAST? Trying anyways...") << std::endl; code_bytes = bytes(wasm.begin(), wasm.end()); } else { code_bytes = bytes(); } if (!suppress_duplicate_check) { if (code_bytes.size()) { new_hash = fc::sha256::hash(&(code_bytes[0]), code_bytes.size()); } duplicate = (old_hash == new_hash); } if (!duplicate) { actions.emplace_back( create_setcode(name(account), code_bytes ) ); if ( shouldSend ) { std::cerr << localized("Setting Code...") << std::endl; send_actions(std::move(actions), signing_keys_opt.get_keys(), packed_transaction::compression_type::zlib); } } else { std::cerr << localized("Skipping set code because the new code is the same as the existing code") << std::endl; } }; auto set_abi_callback = [&]() { bytes old_abi; bool duplicate = false; if (!suppress_duplicate_check) { try { const auto result = call(get_raw_abi_func, fc::mutable_variant_object("account_name", account)); old_abi = result["abi"].as_blob().data; } catch (...) { std::cerr << "Failed to get existing raw abi, continue without duplicate check..." << std::endl; suppress_duplicate_check = true; } } bytes abi_bytes; if(!contract_clear){ fc::path cpath = fc::canonical(fc::path(contractPath)); if( abiPath.empty() ) { abiPath = (cpath / (cpath.filename().generic_string()+".abi")).generic_string(); } else if ( boost::filesystem::path(abiPath).is_relative() ) { abiPath = (cpath / abiPath).generic_string(); } EOS_ASSERT( fc::exists( abiPath ), abi_file_not_found, "no abi file found ${f}", ("f", abiPath) ); abi_bytes = fc::raw::pack(fc::json::from_file(abiPath).as<abi_def>()); } else { abi_bytes = bytes(); } if (!suppress_duplicate_check) { duplicate = (old_abi.size() == abi_bytes.size() && std::equal(old_abi.begin(), old_abi.end(), abi_bytes.begin())); } if (!duplicate) { try { actions.emplace_back( create_setabi(name(account), abi_bytes) ); } EOS_RETHROW_EXCEPTIONS(abi_type_exception, "Fail to parse ABI JSON") if ( shouldSend ) { std::cerr << localized("Setting ABI...") << std::endl; send_actions(std::move(actions), signing_keys_opt.get_keys(), packed_transaction::compression_type::zlib); } } else { std::cerr << localized("Skipping set abi because the new abi is the same as the existing abi") << std::endl; } }; add_standard_transaction_options_plus_signing(contractSubcommand, "account@active"); add_standard_transaction_options_plus_signing(codeSubcommand, "account@active"); add_standard_transaction_options_plus_signing(abiSubcommand, "account@active"); contractSubcommand->set_callback([&] { if(!contract_clear) EOS_ASSERT( !contractPath.empty(), contract_exception, " contract-dir is null ", ("f", contractPath) ); shouldSend = false; set_code_callback(); set_abi_callback(); if (actions.size()) { std::cerr << localized("Publishing contract...") << std::endl; send_actions(std::move(actions), signing_keys_opt.get_keys(), packed_transaction::compression_type::zlib); } else { std::cout << "no transaction is sent" << std::endl; } }); codeSubcommand->set_callback(set_code_callback); abiSubcommand->set_callback(set_abi_callback); // set account auto setAccount = setSubcommand->add_subcommand("account", localized("Set or update blockchain account state"))->require_subcommand(); // set account permission auto setAccountPermission = set_account_permission_subcommand(setAccount); // set action auto setAction = setSubcommand->add_subcommand("action", localized("Set or update blockchain action state"))->require_subcommand(); // set action permission auto setActionPermission = set_action_permission_subcommand(setAction); // Transfer subcommand string con = "eosio.token"; string sender; string recipient; string amount; string memo; bool pay_ram = false; auto transfer = app.add_subcommand("transfer", localized("Transfer tokens from account to account"), false); transfer->add_option("sender", sender, localized("The account sending tokens"))->required(); transfer->add_option("recipient", recipient, localized("The account receiving tokens"))->required(); transfer->add_option("amount", amount, localized("The amount of tokens to send"))->required(); transfer->add_option("memo", memo, localized("The memo for the transfer")); transfer->add_option("--contract,-c", con, localized("The contract that controls the token")); transfer->add_flag("--pay-ram-to-open", pay_ram, localized("Pay RAM to open recipient's token balance row")); add_standard_transaction_options_plus_signing(transfer, "sender@active"); transfer->set_callback([&] { if (tx_force_unique && memo.size() == 0) { // use the memo to add a nonce memo = generate_nonce_string(); tx_force_unique = false; } auto transfer_amount = to_asset(name(con), amount); auto transfer = create_transfer(con, name(sender), name(recipient), transfer_amount, memo); if (!pay_ram) { send_actions( { transfer }, signing_keys_opt.get_keys()); } else { auto open_ = create_open(con, name(recipient), transfer_amount.get_symbol(), name(sender)); send_actions( { open_, transfer }, signing_keys_opt.get_keys()); } }); // Net subcommand string new_host; auto net = app.add_subcommand( "net", localized("Interact with local p2p network connections"), false ); net->require_subcommand(); auto connect = net->add_subcommand("connect", localized("Start a new connection to a peer"), false); connect->add_option("host", new_host, localized("The hostname:port to connect to."))->required(); connect->set_callback([&] { const auto& v = call(url, net_connect, new_host); std::cout << fc::json::to_pretty_string(v) << std::endl; }); auto disconnect = net->add_subcommand("disconnect", localized("Close an existing connection"), false); disconnect->add_option("host", new_host, localized("The hostname:port to disconnect from."))->required(); disconnect->set_callback([&] { const auto& v = call(url, net_disconnect, new_host); std::cout << fc::json::to_pretty_string(v) << std::endl; }); auto status = net->add_subcommand("status", localized("Status of existing connection"), false); status->add_option("host", new_host, localized("The hostname:port to query status of connection"))->required(); status->set_callback([&] { const auto& v = call(url, net_status, new_host); std::cout << fc::json::to_pretty_string(v) << std::endl; }); auto connections = net->add_subcommand("peers", localized("Status of all existing peers"), false); connections->set_callback([&] { const auto& v = call(url, net_connections, new_host); std::cout << fc::json::to_pretty_string(v) << std::endl; }); // Wallet subcommand auto wallet = app.add_subcommand( "wallet", localized("Interact with local wallet"), false ); wallet->require_subcommand(); // create wallet string wallet_name = "default"; string password_file; auto createWallet = wallet->add_subcommand("create", localized("Create a new wallet locally"), false); createWallet->add_option("-n,--name", wallet_name, localized("The name of the new wallet"), true); createWallet->add_option("-f,--file", password_file, localized("Name of file to write wallet password output to. (Must be set, unless \"--to-console\" is passed")); createWallet->add_flag( "--to-console", print_console, localized("Print password to console.")); createWallet->set_callback([&wallet_name, &password_file, &print_console] { EOSC_ASSERT( !password_file.empty() ^ print_console, "ERROR: Either indicate a file using \"--file\" or pass \"--to-console\"" ); EOSC_ASSERT( password_file.empty() || !std::ofstream(password_file.c_str()).fail(), "ERROR: Failed to create file in specified path" ); const auto& v = call(wallet_url, wallet_create, wallet_name); std::cout << localized("Creating wallet: ${wallet_name}", ("wallet_name", wallet_name)) << std::endl; std::cout << localized("Save password to use in the future to unlock this wallet.") << std::endl; std::cout << localized("Without password imported keys will not be retrievable.") << std::endl; if (print_console) { std::cout << fc::json::to_pretty_string(v) << std::endl; } else { std::cerr << localized("saving password to ${filename}", ("filename", password_file)) << std::endl; auto password_str = fc::json::to_pretty_string(v); boost::replace_all(password_str, "\"", ""); std::ofstream out( password_file.c_str() ); out << password_str; } }); // open wallet auto openWallet = wallet->add_subcommand("open", localized("Open an existing wallet"), false); openWallet->add_option("-n,--name", wallet_name, localized("The name of the wallet to open")); openWallet->set_callback([&wallet_name] { call(wallet_url, wallet_open, wallet_name); std::cout << localized("Opened: ${wallet_name}", ("wallet_name", wallet_name)) << std::endl; }); // lock wallet auto lockWallet = wallet->add_subcommand("lock", localized("Lock wallet"), false); lockWallet->add_option("-n,--name", wallet_name, localized("The name of the wallet to lock")); lockWallet->set_callback([&wallet_name] { call(wallet_url, wallet_lock, wallet_name); std::cout << localized("Locked: ${wallet_name}", ("wallet_name", wallet_name)) << std::endl; }); // lock all wallets auto locakAllWallets = wallet->add_subcommand("lock_all", localized("Lock all unlocked wallets"), false); locakAllWallets->set_callback([] { call(wallet_url, wallet_lock_all); std::cout << localized("Locked All Wallets") << std::endl; }); // unlock wallet string wallet_pw; auto unlockWallet = wallet->add_subcommand("unlock", localized("Unlock wallet"), false); unlockWallet->add_option("-n,--name", wallet_name, localized("The name of the wallet to unlock")); unlockWallet->add_option("--password", wallet_pw, localized("The password returned by wallet create")); unlockWallet->set_callback([&wallet_name, &wallet_pw] { prompt_for_wallet_password(wallet_pw, wallet_name); fc::variants vs = {fc::variant(wallet_name), fc::variant(wallet_pw)}; call(wallet_url, wallet_unlock, vs); std::cout << localized("Unlocked: ${wallet_name}", ("wallet_name", wallet_name)) << std::endl; }); // import keys into wallet string wallet_key_str; auto importWallet = wallet->add_subcommand("import", localized("Import private key into wallet"), false); importWallet->add_option("-n,--name", wallet_name, localized("The name of the wallet to import key into")); importWallet->add_option("--private-key", wallet_key_str, localized("Private key in WIF format to import")); importWallet->set_callback([&wallet_name, &wallet_key_str] { if( wallet_key_str.size() == 0 ) { std::cout << localized("private key: "); fc::set_console_echo(false); std::getline( std::cin, wallet_key_str, '\n' ); fc::set_console_echo(true); } private_key_type wallet_key; try { wallet_key = private_key_type( wallet_key_str ); } catch (...) { EOS_THROW(private_key_type_exception, "Invalid private key") } public_key_type pubkey = wallet_key.get_public_key(); fc::variants vs = {fc::variant(wallet_name), fc::variant(wallet_key)}; call(wallet_url, wallet_import_key, vs); std::cout << localized("imported private key for: ${pubkey}", ("pubkey", pubkey.to_string())) << std::endl; }); // remove keys from wallet string wallet_rm_key_str; auto removeKeyWallet = wallet->add_subcommand("remove_key", localized("Remove key from wallet"), false); removeKeyWallet->add_option("-n,--name", wallet_name, localized("The name of the wallet to remove key from")); removeKeyWallet->add_option("key", wallet_rm_key_str, localized("Public key in WIF format to remove"))->required(); removeKeyWallet->add_option("--password", wallet_pw, localized("The password returned by wallet create")); removeKeyWallet->set_callback([&wallet_name, &wallet_pw, &wallet_rm_key_str] { prompt_for_wallet_password(wallet_pw, wallet_name); public_key_type pubkey; try { pubkey = public_key_type( wallet_rm_key_str ); } catch (...) { EOS_THROW(public_key_type_exception, "Invalid public key: ${public_key}", ("public_key", wallet_rm_key_str)) } fc::variants vs = {fc::variant(wallet_name), fc::variant(wallet_pw), fc::variant(wallet_rm_key_str)}; call(wallet_url, wallet_remove_key, vs); std::cout << localized("removed private key for: ${pubkey}", ("pubkey", wallet_rm_key_str)) << std::endl; }); // create a key within wallet string wallet_create_key_type; auto createKeyInWallet = wallet->add_subcommand("create_key", localized("Create private key within wallet"), false); createKeyInWallet->add_option("-n,--name", wallet_name, localized("The name of the wallet to create key into"), true); createKeyInWallet->add_option("key_type", wallet_create_key_type, localized("Key type to create (K1/R1)"), true)->set_type_name("K1/R1"); createKeyInWallet->set_callback([&wallet_name, &wallet_create_key_type] { //an empty key type is allowed -- it will let the underlying wallet pick which type it prefers fc::variants vs = {fc::variant(wallet_name), fc::variant(wallet_create_key_type)}; const auto& v = call(wallet_url, wallet_create_key, vs); std::cout << localized("Created new private key with a public key of: ") << fc::json::to_pretty_string(v) << std::endl; }); // list wallets auto listWallet = wallet->add_subcommand("list", localized("List opened wallets, * = unlocked"), false); listWallet->set_callback([] { std::cout << localized("Wallets:") << std::endl; const auto& v = call(wallet_url, wallet_list); std::cout << fc::json::to_pretty_string(v) << std::endl; }); // list keys auto listKeys = wallet->add_subcommand("keys", localized("List of public keys from all unlocked wallets."), false); listKeys->set_callback([] { const auto& v = call(wallet_url, wallet_public_keys); std::cout << fc::json::to_pretty_string(v) << std::endl; }); // list private keys auto listPrivKeys = wallet->add_subcommand("private_keys", localized("List of private keys from an unlocked wallet in wif or PVT_R1 format."), false); listPrivKeys->add_option("-n,--name", wallet_name, localized("The name of the wallet to list keys from"), true); listPrivKeys->add_option("--password", wallet_pw, localized("The password returned by wallet create")); listPrivKeys->set_callback([&wallet_name, &wallet_pw] { prompt_for_wallet_password(wallet_pw, wallet_name); fc::variants vs = {fc::variant(wallet_name), fc::variant(wallet_pw)}; const auto& v = call(wallet_url, wallet_list_keys, vs); std::cout << fc::json::to_pretty_string(v) << std::endl; }); auto stopKeosd = wallet->add_subcommand("stop", localized("Stop ${k}.", ("k", key_store_executable_name)), false); stopKeosd->set_callback([] { const auto& v = call(wallet_url, keosd_stop); if ( !v.is_object() || v.get_object().size() != 0 ) { //on success keosd responds with empty object std::cerr << fc::json::to_pretty_string(v) << std::endl; } else { std::cout << "OK" << std::endl; } }); // sign subcommand string trx_json_to_sign; string str_private_key; string str_chain_id; string str_private_key_file; string str_public_key; bool push_trx = false; auto sign = app.add_subcommand("sign", localized("Sign a transaction"), false); sign->add_option("transaction", trx_json_to_sign, localized("The JSON string or filename defining the transaction to sign"), true)->required(); sign->add_option("-k,--private-key", str_private_key, localized("The private key that will be used to sign the transaction")); sign->add_option("--public-key", str_public_key, localized("Ask ${exec} to sign with the corresponding private key of the given public key", ("exec", key_store_executable_name))); sign->add_option("-c,--chain-id", str_chain_id, localized("The chain id that will be used to sign the transaction")); sign->add_flag("-p,--push-transaction", push_trx, localized("Push transaction after signing")); sign->set_callback([&] { EOSC_ASSERT( str_private_key.empty() || str_public_key.empty(), "ERROR: Either -k/--private-key or --public-key or none of them can be set" ); fc::variant trx_var = json_from_file_or_string(trx_json_to_sign); signed_transaction trx; try { trx = trx_var.as<signed_transaction>(); } EOS_RETHROW_EXCEPTIONS(transaction_type_exception, "Invalid transaction format: '${data}'", ("data", fc::json::to_string(trx_var, fc::time_point::maximum()))) fc::optional<chain_id_type> chain_id; if( str_chain_id.size() == 0 ) { ilog( "grabbing chain_id from ${n}", ("n", node_executable_name) ); auto info = get_info(); chain_id = info.chain_id; } else { chain_id = chain_id_type(str_chain_id); } if( str_public_key.size() > 0 ) { public_key_type pub_key; try { pub_key = public_key_type(str_public_key); } EOS_RETHROW_EXCEPTIONS(public_key_type_exception, "Invalid public key: ${public_key}", ("public_key", str_public_key)) fc::variant keys_var(flat_set<public_key_type>{ pub_key }); sign_transaction(trx, keys_var, *chain_id); } else { if( str_private_key.size() == 0 ) { std::cerr << localized("private key: "); fc::set_console_echo(false); std::getline( std::cin, str_private_key, '\n' ); fc::set_console_echo(true); } private_key_type priv_key; try { priv_key = private_key_type(str_private_key); } EOS_RETHROW_EXCEPTIONS(private_key_type_exception, "Invalid private key") trx.sign(priv_key, *chain_id); } if(push_trx) { auto trx_result = call(push_txn_func, packed_transaction(trx, packed_transaction::compression_type::none)); std::cout << fc::json::to_pretty_string(trx_result) << std::endl; } else { std::cout << fc::json::to_pretty_string(trx) << std::endl; } }); // Push subcommand auto push = app.add_subcommand("push", localized("Push arbitrary transactions to the blockchain"), false); push->require_subcommand(); // push action string contract_account; string action; string data; vector<string> permissions; auto actionsSubcommand = push->add_subcommand("action", localized("Push a transaction with a single action")); actionsSubcommand->fallthrough(false); actionsSubcommand->add_option("account", contract_account, localized("The account providing the contract to execute"), true)->required(); actionsSubcommand->add_option("action", action, localized("A JSON string or filename defining the action to execute on the contract"), true)->required(); actionsSubcommand->add_option("data", data, localized("The arguments to the contract"))->required(); add_standard_transaction_options_plus_signing(actionsSubcommand); actionsSubcommand->set_callback([&] { fc::variant action_args_var; if( !data.empty() ) { action_args_var = json_from_file_or_string(data, fc::json::relaxed_parser); } auto accountPermissions = get_account_permissions(tx_permission); send_actions({chain::action{accountPermissions, name(contract_account), name(action), variant_to_bin( name(contract_account), name(action), action_args_var ) }}, signing_keys_opt.get_keys()); }); // push transaction string trx_to_push; auto trxSubcommand = push->add_subcommand("transaction", localized("Push an arbitrary JSON transaction")); trxSubcommand->add_option("transaction", trx_to_push, localized("The JSON string or filename defining the transaction to push"))->required(); add_standard_transaction_options_plus_signing(trxSubcommand); trxSubcommand->set_callback([&] { fc::variant trx_var = json_from_file_or_string(trx_to_push); try { signed_transaction trx = trx_var.as<signed_transaction>(); std::cout << fc::json::to_pretty_string( push_transaction( trx, signing_keys_opt.get_keys() )) << std::endl; } catch( fc::exception& ) { // unable to convert so try via abi signed_transaction trx; abi_serializer::from_variant( trx_var, trx, abi_serializer_resolver, abi_serializer_max_time ); std::cout << fc::json::to_pretty_string( push_transaction( trx, signing_keys_opt.get_keys() )) << std::endl; } }); // push transactions string trxsJson; auto trxsSubcommand = push->add_subcommand("transactions", localized("Push an array of arbitrary JSON transactions")); trxsSubcommand->add_option("transactions", trxsJson, localized("The JSON string or filename defining the array of the transactions to push"))->required(); trxsSubcommand->set_callback([&] { fc::variant trx_var = json_from_file_or_string(trxsJson); auto trxs_result = call(push_txns_func, trx_var); std::cout << fc::json::to_pretty_string(trxs_result) << std::endl; }); // multisig subcommand auto msig = app.add_subcommand("multisig", localized("Multisig contract commands"), false); msig->require_subcommand(); // multisig propose string proposal_name; string requested_perm; string transaction_perm; string proposed_transaction; string proposed_contract; string proposed_action; string proposer; unsigned int proposal_expiration_hours = 24; CLI::callback_t parse_expiration_hours = [&](CLI::results_t res) -> bool { unsigned int value_s; if (res.size() == 0 || !CLI::detail::lexical_cast(res[0], value_s)) { return false; } proposal_expiration_hours = static_cast<uint64_t>(value_s); return true; }; auto propose_action = msig->add_subcommand("propose", localized("Propose action")); add_standard_transaction_options_plus_signing(propose_action, "proposer@active"); propose_action->add_option("proposal_name", proposal_name, localized("The proposal name (string)"))->required(); propose_action->add_option("requested_permissions", requested_perm, localized("The JSON string or filename defining requested permissions"))->required(); propose_action->add_option("trx_permissions", transaction_perm, localized("The JSON string or filename defining transaction permissions"))->required(); propose_action->add_option("contract", proposed_contract, localized("The contract to which deferred transaction should be delivered"))->required(); propose_action->add_option("action", proposed_action, localized("The action of deferred transaction"))->required(); propose_action->add_option("data", proposed_transaction, localized("The JSON string or filename defining the action to propose"))->required(); propose_action->add_option("proposer", proposer, localized("Account proposing the transaction")); propose_action->add_option("proposal_expiration", parse_expiration_hours, localized("Proposal expiration interval in hours")); propose_action->set_callback([&] { fc::variant requested_perm_var = json_from_file_or_string(requested_perm); fc::variant transaction_perm_var = json_from_file_or_string(transaction_perm); fc::variant trx_var = json_from_file_or_string(proposed_transaction); transaction proposed_trx; try { proposed_trx = trx_var.as<transaction>(); } EOS_RETHROW_EXCEPTIONS(transaction_type_exception, "Invalid transaction format: '${data}'", ("data", fc::json::to_string(trx_var, fc::time_point::maximum()))) bytes proposed_trx_serialized = variant_to_bin( name(proposed_contract), name(proposed_action), trx_var ); vector<permission_level> reqperm; try { reqperm = requested_perm_var.as<vector<permission_level>>(); } EOS_RETHROW_EXCEPTIONS(transaction_type_exception, "Wrong requested permissions format: '${data}'", ("data",requested_perm_var)); vector<permission_level> trxperm; try { trxperm = transaction_perm_var.as<vector<permission_level>>(); } EOS_RETHROW_EXCEPTIONS(transaction_type_exception, "Wrong transaction permissions format: '${data}'", ("data",transaction_perm_var)); auto accountPermissions = get_account_permissions(tx_permission); if (accountPermissions.empty()) { if (!proposer.empty()) { accountPermissions = vector<permission_level>{{name(proposer), config::active_name}}; } else { EOS_THROW(missing_auth_exception, "Authority is not provided (either by multisig parameter <proposer> or -p)"); } } if (proposer.empty()) { proposer = name(accountPermissions.at(0).actor).to_string(); } transaction trx; trx.expiration = fc::time_point_sec( fc::time_point::now() + fc::hours(proposal_expiration_hours) ); trx.ref_block_num = 0; trx.ref_block_prefix = 0; trx.max_net_usage_words = 0; trx.max_cpu_usage_ms = 0; trx.delay_sec = 0; trx.actions = { chain::action(trxperm, name(proposed_contract), name(proposed_action), proposed_trx_serialized) }; fc::to_variant(trx, trx_var); auto args = fc::mutable_variant_object() ("proposer", proposer ) ("proposal_name", proposal_name) ("requested", requested_perm_var) ("trx", trx_var); send_actions({chain::action{accountPermissions, N(eosio.msig), N(propose), variant_to_bin( N(eosio.msig), N(propose), args ) }}, signing_keys_opt.get_keys()); }); //multisig propose transaction auto propose_trx = msig->add_subcommand("propose_trx", localized("Propose transaction")); add_standard_transaction_options_plus_signing(propose_trx, "proposer@active"); propose_trx->add_option("proposal_name", proposal_name, localized("The proposal name (string)"))->required(); propose_trx->add_option("requested_permissions", requested_perm, localized("The JSON string or filename defining requested permissions"))->required(); propose_trx->add_option("transaction", trx_to_push, localized("The JSON string or filename defining the transaction to push"))->required(); propose_trx->add_option("proposer", proposer, localized("Account proposing the transaction")); propose_trx->set_callback([&] { fc::variant requested_perm_var = json_from_file_or_string(requested_perm); fc::variant trx_var = json_from_file_or_string(trx_to_push); auto accountPermissions = get_account_permissions(tx_permission); if (accountPermissions.empty()) { if (!proposer.empty()) { accountPermissions = vector<permission_level>{{name(proposer), config::active_name}}; } else { EOS_THROW(missing_auth_exception, "Authority is not provided (either by multisig parameter <proposer> or -p)"); } } if (proposer.empty()) { proposer = name(accountPermissions.at(0).actor).to_string(); } auto args = fc::mutable_variant_object() ("proposer", proposer ) ("proposal_name", proposal_name) ("requested", requested_perm_var) ("trx", trx_var); send_actions({chain::action{accountPermissions, N(eosio.msig), N(propose), variant_to_bin( N(eosio.msig), N(propose), args ) }}, signing_keys_opt.get_keys()); }); // multisig review bool show_approvals_in_multisig_review = false; auto review = msig->add_subcommand("review", localized("Review transaction")); review->add_option("proposer", proposer, localized("The proposer name (string)"))->required(); review->add_option("proposal_name", proposal_name, localized("The proposal name (string)"))->required(); review->add_flag( "--show-approvals", show_approvals_in_multisig_review, localized("Show the status of the approvals requested within the proposal") ); review->set_callback([&] { const auto result1 = call(get_table_func, fc::mutable_variant_object("json", true) ("code", "eosio.msig") ("scope", proposer) ("table", "proposal") ("table_key", "") ("lower_bound", name(proposal_name).to_uint64_t()) ("upper_bound", name(proposal_name).to_uint64_t() + 1) // Less than ideal upper_bound usage preserved so cleos can still work with old buggy nodeos versions // Change to name(proposal_name).value when cleos no longer needs to support nodeos versions older than 1.5.0 ("limit", 1) ); //std::cout << fc::json::to_pretty_string(result) << std::endl; const auto& rows1 = result1.get_object()["rows"].get_array(); // Condition in if statement below can simply be rows.empty() when cleos no longer needs to support nodeos versions older than 1.5.0 if( rows1.empty() || rows1[0].get_object()["proposal_name"] != proposal_name ) { std::cerr << "Proposal not found" << std::endl; return; } const auto& proposal_object = rows1[0].get_object(); enum class approval_status { unapproved, approved, invalidated }; std::map<permission_level, std::pair<fc::time_point, approval_status>> all_approvals; std::map<eosio::account_name, std::pair<fc::time_point, vector<decltype(all_approvals)::iterator>>> provided_approvers; bool new_multisig = true; if( show_approvals_in_multisig_review ) { fc::variants rows2; try { const auto& result2 = call(get_table_func, fc::mutable_variant_object("json", true) ("code", "eosio.msig") ("scope", proposer) ("table", "approvals2") ("table_key", "") ("lower_bound", name(proposal_name).to_uint64_t()) ("upper_bound", name(proposal_name).to_uint64_t() + 1) // Less than ideal upper_bound usage preserved so cleos can still work with old buggy nodeos versions // Change to name(proposal_name).value when cleos no longer needs to support nodeos versions older than 1.5.0 ("limit", 1) ); rows2 = result2.get_object()["rows"].get_array(); } catch( ... ) { new_multisig = false; } if( !rows2.empty() && rows2[0].get_object()["proposal_name"] == proposal_name ) { const auto& approvals_object = rows2[0].get_object(); for( const auto& ra : approvals_object["requested_approvals"].get_array() ) { const auto& ra_obj = ra.get_object(); auto pl = ra["level"].as<permission_level>(); all_approvals.emplace( pl, std::make_pair(ra["time"].as<fc::time_point>(), approval_status::unapproved) ); } for( const auto& pa : approvals_object["provided_approvals"].get_array() ) { const auto& pa_obj = pa.get_object(); auto pl = pa["level"].as<permission_level>(); auto res = all_approvals.emplace( pl, std::make_pair(pa["time"].as<fc::time_point>(), approval_status::approved) ); provided_approvers[pl.actor].second.push_back( res.first ); } } else { const auto result3 = call(get_table_func, fc::mutable_variant_object("json", true) ("code", "eosio.msig") ("scope", proposer) ("table", "approvals") ("table_key", "") ("lower_bound", name(proposal_name).to_uint64_t()) ("upper_bound", name(proposal_name).to_uint64_t() + 1) // Less than ideal upper_bound usage preserved so cleos can still work with old buggy nodeos versions // Change to name(proposal_name).value when cleos no longer needs to support nodeos versions older than 1.5.0 ("limit", 1) ); const auto& rows3 = result3.get_object()["rows"].get_array(); if( rows3.empty() || rows3[0].get_object()["proposal_name"] != proposal_name ) { std::cerr << "Proposal not found" << std::endl; return; } const auto& approvals_object = rows3[0].get_object(); for( const auto& ra : approvals_object["requested_approvals"].get_array() ) { auto pl = ra.as<permission_level>(); all_approvals.emplace( pl, std::make_pair(fc::time_point{}, approval_status::unapproved) ); } for( const auto& pa : approvals_object["provided_approvals"].get_array() ) { auto pl = pa.as<permission_level>(); auto res = all_approvals.emplace( pl, std::make_pair(fc::time_point{}, approval_status::approved) ); provided_approvers[pl.actor].second.push_back( res.first ); } } if( new_multisig ) { for( auto& a : provided_approvers ) { const auto result4 = call(get_table_func, fc::mutable_variant_object("json", true) ("code", "eosio.msig") ("scope", "eosio.msig") ("table", "invals") ("table_key", "") ("lower_bound", a.first.to_uint64_t()) ("upper_bound", a.first.to_uint64_t() + 1) // Less than ideal upper_bound usage preserved so cleos can still work with old buggy nodeos versions // Change to name(proposal_name).value when cleos no longer needs to support nodeos versions older than 1.5.0 ("limit", 1) ); const auto& rows4 = result4.get_object()["rows"].get_array(); if( rows4.empty() || rows4[0].get_object()["account"].as<eosio::name>() != a.first ) { continue; } auto invalidation_time = rows4[0].get_object()["last_invalidation_time"].as<fc::time_point>(); a.second.first = invalidation_time; for( auto& itr : a.second.second ) { if( invalidation_time >= itr->second.first ) { itr->second.second = approval_status::invalidated; } } } } } auto trx_hex = proposal_object["packed_transaction"].as_string(); vector<char> trx_blob(trx_hex.size()/2); fc::from_hex(trx_hex, trx_blob.data(), trx_blob.size()); transaction trx = fc::raw::unpack<transaction>(trx_blob); fc::mutable_variant_object obj; obj["proposer"] = proposer; obj["proposal_name"] = proposal_object["proposal_name"]; obj["transaction_id"] = trx.id(); for( const auto& entry : proposal_object ) { if( entry.key() == "proposal_name" ) continue; obj.set( entry.key(), entry.value() ); } fc::variant trx_var; abi_serializer abi; abi.to_variant(trx, trx_var, abi_serializer_resolver, abi_serializer_max_time); obj["transaction"] = trx_var; if( show_approvals_in_multisig_review ) { fc::variants approvals; for( const auto& approval : all_approvals ) { fc::mutable_variant_object approval_obj; approval_obj["level"] = approval.first; switch( approval.second.second ) { case approval_status::unapproved: { approval_obj["status"] = "unapproved"; if( approval.second.first != fc::time_point{} ) { approval_obj["last_unapproval_time"] = approval.second.first; } } break; case approval_status::approved: { approval_obj["status"] = "approved"; if( new_multisig ) { approval_obj["last_approval_time"] = approval.second.first; } } break; case approval_status::invalidated: { approval_obj["status"] = "invalidated"; approval_obj["last_approval_time"] = approval.second.first; approval_obj["invalidation_time"] = provided_approvers[approval.first.actor].first; } break; } approvals.push_back( std::move(approval_obj) ); } obj["approvals"] = std::move(approvals); } std::cout << fc::json::to_pretty_string(obj) << std::endl; }); string perm; string proposal_hash; auto approve_or_unapprove = [&](const string& action) { fc::variant perm_var = json_from_file_or_string(perm); auto args = fc::mutable_variant_object() ("proposer", proposer) ("proposal_name", proposal_name) ("level", perm_var); if( proposal_hash.size() ) { args("proposal_hash", proposal_hash); } auto accountPermissions = get_account_permissions(tx_permission, {name(proposer), config::active_name}); send_actions({chain::action{accountPermissions, N(eosio.msig), name(action), variant_to_bin( N(eosio.msig), name(action), args ) }}, signing_keys_opt.get_keys()); }; // multisig approve auto approve = msig->add_subcommand("approve", localized("Approve proposed transaction")); add_standard_transaction_options_plus_signing(approve, "proposer@active"); approve->add_option("proposer", proposer, localized("The proposer name (string)"))->required(); approve->add_option("proposal_name", proposal_name, localized("The proposal name (string)"))->required(); approve->add_option("permissions", perm, localized("The JSON string of filename defining approving permissions"))->required(); approve->add_option("proposal_hash", proposal_hash, localized("Hash of proposed transaction (i.e. transaction ID) to optionally enforce as a condition of the approval")); approve->set_callback([&] { approve_or_unapprove("approve"); }); // multisig unapprove auto unapprove = msig->add_subcommand("unapprove", localized("Unapprove proposed transaction")); add_standard_transaction_options_plus_signing(unapprove, "proposer@active"); unapprove->add_option("proposer", proposer, localized("The proposer name (string)"))->required(); unapprove->add_option("proposal_name", proposal_name, localized("The proposal name (string)"))->required(); unapprove->add_option("permissions", perm, localized("The JSON string of filename defining approving permissions"))->required(); unapprove->set_callback([&] { approve_or_unapprove("unapprove"); }); // multisig invalidate string invalidator; auto invalidate = msig->add_subcommand("invalidate", localized("Invalidate all multisig approvals of an account")); add_standard_transaction_options_plus_signing(invalidate, "invalidator@active"); invalidate->add_option("invalidator", invalidator, localized("Invalidator name (string)"))->required(); invalidate->set_callback([&] { auto args = fc::mutable_variant_object() ("account", invalidator); auto accountPermissions = get_account_permissions(tx_permission, {name(invalidator), config::active_name}); send_actions({chain::action{accountPermissions, N(eosio.msig), N(invalidate), variant_to_bin( N(eosio.msig), N(invalidate), args ) }}, signing_keys_opt.get_keys()); }); // multisig cancel string canceler; auto cancel = msig->add_subcommand("cancel", localized("Cancel proposed transaction")); add_standard_transaction_options_plus_signing(cancel, "canceler@active"); cancel->add_option("proposer", proposer, localized("The proposer name (string)"))->required(); cancel->add_option("proposal_name", proposal_name, localized("The proposal name (string)"))->required(); cancel->add_option("canceler", canceler, localized("The canceler name (string)")); cancel->set_callback([&]() { auto accountPermissions = get_account_permissions(tx_permission); if (accountPermissions.empty()) { if (!canceler.empty()) { accountPermissions = vector<permission_level>{{name(canceler), config::active_name}}; } else { EOS_THROW(missing_auth_exception, "Authority is not provided (either by multisig parameter <canceler> or -p)"); } } if (canceler.empty()) { canceler = name(accountPermissions.at(0).actor).to_string(); } auto args = fc::mutable_variant_object() ("proposer", proposer) ("proposal_name", proposal_name) ("canceler", canceler); send_actions({chain::action{accountPermissions, N(eosio.msig), N(cancel), variant_to_bin( N(eosio.msig), N(cancel), args ) }}, signing_keys_opt.get_keys()); } ); // multisig exec string executer; auto exec = msig->add_subcommand("exec", localized("Execute proposed transaction")); add_standard_transaction_options_plus_signing(exec, "executer@active"); exec->add_option("proposer", proposer, localized("The proposer name (string)"))->required(); exec->add_option("proposal_name", proposal_name, localized("The proposal name (string)"))->required(); exec->add_option("executer", executer, localized("The account paying for execution (string)")); exec->set_callback([&] { auto accountPermissions = get_account_permissions(tx_permission); if (accountPermissions.empty()) { if (!executer.empty()) { accountPermissions = vector<permission_level>{{name(executer), config::active_name}}; } else { EOS_THROW(missing_auth_exception, "Authority is not provided (either by multisig parameter <executer> or -p)"); } } if (executer.empty()) { executer = name(accountPermissions.at(0).actor).to_string(); } auto args = fc::mutable_variant_object() ("proposer", proposer ) ("proposal_name", proposal_name) ("executer", executer); send_actions({chain::action{accountPermissions, N(eosio.msig), N(exec), variant_to_bin( N(eosio.msig), N(exec), args ) }}, signing_keys_opt.get_keys()); } ); // wrap subcommand auto wrap = app.add_subcommand("wrap", localized("Wrap contract commands"), false); wrap->require_subcommand(); // wrap exec string wrap_con = "eosio.wrap"; executer = ""; string trx_to_exec; auto wrap_exec = wrap->add_subcommand("exec", localized("Execute a transaction while bypassing authorization checks")); add_standard_transaction_options_plus_signing(wrap_exec, "executer@active & --contract@active"); wrap_exec->add_option("executer", executer, localized("Account executing the transaction and paying for the deferred transaction RAM"))->required(); wrap_exec->add_option("transaction", trx_to_exec, localized("The JSON string or filename defining the transaction to execute"))->required(); wrap_exec->add_option("--contract,-c", wrap_con, localized("The account which controls the wrap contract")); wrap_exec->set_callback([&] { fc::variant trx_var = json_from_file_or_string(trx_to_exec); auto accountPermissions = get_account_permissions(tx_permission); if( accountPermissions.empty() ) { accountPermissions = vector<permission_level>{{name(executer), config::active_name}, {name(wrap_con), config::active_name}}; } auto args = fc::mutable_variant_object() ("executer", executer ) ("trx", trx_var); send_actions({chain::action{accountPermissions, name(wrap_con), N(exec), variant_to_bin( name(wrap_con), N(exec), args ) }}, signing_keys_opt.get_keys()); }); // system subcommand auto system = app.add_subcommand("system", localized("Send eosio.system contract action to the blockchain."), false); system->require_subcommand(); auto createAccountSystem = create_account_subcommand( system, false /*simple*/ ); auto registerProducer = register_producer_subcommand(system); auto unregisterProducer = unregister_producer_subcommand(system); auto voteProducer = system->add_subcommand("voteproducer", localized("Vote for a producer")); voteProducer->require_subcommand(); auto voteProxy = vote_producer_proxy_subcommand(voteProducer); auto voteProducers = vote_producers_subcommand(voteProducer); auto approveProducer = approve_producer_subcommand(voteProducer); auto unapproveProducer = unapprove_producer_subcommand(voteProducer); auto listProducers = list_producers_subcommand(system); auto delegateBandWidth = delegate_bandwidth_subcommand(system); auto undelegateBandWidth = undelegate_bandwidth_subcommand(system); auto listBandWidth = list_bw_subcommand(system); auto bidname = bidname_subcommand(system); auto bidnameinfo = bidname_info_subcommand(system); auto buyram = buyram_subcommand(system); auto sellram = sellram_subcommand(system); auto claimRewards = claimrewards_subcommand(system); auto regProxy = regproxy_subcommand(system); auto unregProxy = unregproxy_subcommand(system); auto cancelDelay = canceldelay_subcommand(system); auto rex = system->add_subcommand("rex", localized("Actions related to REX (the resource exchange)")); rex->require_subcommand(); auto deposit = deposit_subcommand(rex); auto withdraw = withdraw_subcommand(rex); auto buyrex = buyrex_subcommand(rex); auto lendrex = lendrex_subcommand(rex); auto unstaketorex = unstaketorex_subcommand(rex); auto sellrex = sellrex_subcommand(rex); auto cancelrexorder = cancelrexorder_subcommand(rex); auto mvtosavings = mvtosavings_subcommand(rex); auto mvfromsavings = mvfrsavings_subcommand(rex); auto rentcpu = rentcpu_subcommand(rex); auto rentnet = rentnet_subcommand(rex); auto fundcpuloan = fundcpuloan_subcommand(rex); auto fundnetloan = fundnetloan_subcommand(rex); auto defcpuloan = defcpuloan_subcommand(rex); auto defnetloan = defnetloan_subcommand(rex); auto consolidate = consolidate_subcommand(rex); auto updaterex = updaterex_subcommand(rex); auto rexexec = rexexec_subcommand(rex); auto closerex = closerex_subcommand(rex); try { app.parse(argc, argv); } catch (const CLI::ParseError &e) { return app.exit(e); } catch (const explained_exception& e) { return 1; } catch (connection_exception& e) { if (verbose) { elog("connect error: ${e}", ("e", e.to_detail_string())); } return 1; } catch (const fc::exception& e) { // attempt to extract the error code if one is present if (!print_recognized_errors(e, verbose)) { // Error is not recognized if (!print_help_text(e) || verbose) { elog("Failed with error: ${e}", ("e", verbose ? e.to_detail_string() : e.to_string())); } } return 1; } return 0; }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ #include "core/data_render/vnode/vnode_render_manager.h" #include <chrono> #include <sstream> #include "base/make_copyable.h" #include "base/string_util.h" #include "core/bridge/platform_bridge.h" #include "core/data_render/common_error.h" #include "core/data_render/exec_state.h" #include "core/data_render/exec_state_binary.h" #include "core/data_render/string_table.h" #include "core/data_render/vnode/vnode.h" #include "core/data_render/vnode/vnode_exec_env.h" #include "core/manager/weex_core_manager.h" #include "core/network/http_module.h" #include "core/render/manager/render_manager.h" #include "core/render/node/factory/render_creator.h" #define VRENDER_LOG true #if VRENDER_LOG #include "base/LogDefines.h" #endif namespace weex { namespace core { namespace data_render { using std::map; using std::pair; using std::string; using std::vector; using WeexCore::RenderManager; void PatchVNode(const string& page_id, VNode* old_node, VNode* new_node); VNodeRenderManager* VNodeRenderManager::g_instance = nullptr; VM* VNodeRenderManager::g_vm = nullptr; // TODO establish linkages between page ref_id int ref_id = 0; WeexCore::RenderObject* ParseVNode2RenderObject(VNode* vnode, WeexCore::RenderObject* parent, bool isRoot, int index, const string& pageId) { if (vnode->IsVirtualComponent()) { VComponent* component = static_cast<VComponent*>(vnode); if (component->root_vnode() == nullptr) { component->UpdateData(); } return ParseVNode2RenderObject(component->root_vnode(), parent, isRoot, index, pageId); } std::string ref_str; if (isRoot) { ref_str = "_root"; } else { ref_str = base::to_string(ref_id++); } WeexCore::RenderObject* render_object = static_cast<WeexCore::RenderObject*>( WeexCore::RenderCreator::GetInstance()->CreateRender(vnode->tag_name(), ref_str)); // Link RenderObject and VNode vnode->set_render_object_ref(std::move(ref_str)); // style map<string, string>* style = vnode->styles(); for (auto it = style->begin(); it != style->end(); it++) { render_object->AddStyle(it->first, it->second); } // attr map<string, string>* attr = vnode->attributes(); for (auto it = attr->begin(); it != attr->end(); it++) { render_object->AddAttr(it->first, it->second); } // event std::map<std::string, void *> *events = vnode->events(); for (auto iter = events->begin(); iter != events->end(); iter++) { render_object->events()->insert(iter->first); } auto event_params_map = vnode->event_params_map(); for (auto it = event_params_map->begin(); it != event_params_map->end(); it++) { render_object->events()->insert(it->first); } // child vector<VNode*>* children = vnode->child_list(); for (int i = 0; i < children->size(); i++) { ParseVNode2RenderObject((*children)[i], render_object, false, i, pageId); } render_object->set_page_id(pageId); render_object->ApplyDefaultStyle(); render_object->ApplyDefaultAttr(); // parent if (parent != nullptr) { parent->AddRenderObject(index, render_object); } return render_object; } WeexCore::RenderObject *VNode2RenderObject(VNode *root, const string& page_id) { return ParseVNode2RenderObject(root, nullptr, true, 0, page_id); } void Patch(const string& page_id, VNode* old_root, VNode* new_root); bool VNodeRenderManager::CreatePageInternal(const string& page_id, VNode* vNode) { auto node = vnode_trees_.find(page_id); if (node != vnode_trees_.end()) { delete node->second; node->second = nullptr; } vnode_trees_[page_id] = vNode; auto render_root = VNode2RenderObject(vNode, page_id); RenderManager::GetInstance()->CreatePage(page_id, render_root); RenderManager::GetInstance()->CreateFinish(page_id); return true; } bool VNodeRenderManager::RefreshPageInternal(const string& page_id, VNode* new_node) { auto node = vnode_trees_.find(page_id); if (node == vnode_trees_.end()) { return false; } auto oldNode = node->second; Patch(page_id, oldNode, new_node); node->second = new_node; delete oldNode; return true; } bool VNodeRenderManager::ClosePageInternal(const string& page_id) { auto node = vnode_trees_.find(page_id); if (node == vnode_trees_.end()) { return false; } RenderManager::GetInstance()->ClosePage(page_id); delete node->second; vnode_trees_.erase(node); return true; } void VNodeRenderManager::InitVM() { if (g_vm == nullptr) { g_vm = new VM(); } } void VNodeRenderManager::CreatePage(const std::string &input, const std::string &page_id, const std::string &options, const std::string &init_data, std::function<void(const char*)> exec_js) { std::string err = CreatePageWithContent(input, page_id, options, init_data, exec_js); if (!err.empty()) { WeexCore::WeexCoreManager::Instance()->getPlatformBridge()->platform_side()->ReportException(page_id.c_str(), nullptr, err.c_str()); } } std::string VNodeRenderManager::CreatePageWithContent(const std::string &input, const std::string &page_id, const std::string &options, const std::string &init_data, std::function<void(const char*)> exec_js) { InitVM(); #ifdef DEBUG auto start = std::chrono::steady_clock::now(); #endif ExecState *exec_state = new ExecState(g_vm); exec_states_.insert({page_id, exec_state}); VNodeExecEnv::ImportExecEnv(exec_state); std::string err; json11::Json json = json11::Json::parse(input, err); if (!err.empty() || json.is_null()) { exec_state->context()->raw_source() = input; } else { exec_state->context()->raw_json() = json; VNodeExecEnv::ParseData(exec_state); VNodeExecEnv::ParseStyle(exec_state); VNodeExecEnv::ParseScript(exec_state); } if (init_data.length() > 0) { VNodeExecEnv::ImportExecData(exec_state, init_data); } exec_state->context()->page_id(page_id); //auto compile_start = std::chrono::steady_clock::now(); exec_state->Compile(err); if (!err.empty()) { LOGE("DATA_RENDER, compile err: %s",err.c_str()); return err; } #ifdef DEBUG auto compile_post = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - start); LOGD("[DATA_RENDER], Compile time:[%lld]\n", compile_post.count()); #endif //auto exec_start = std::chrono::steady_clock::now(); exec_state->Execute(err); if (!err.empty()) { LOGE("DATA_RENDER, exec err: %s",err.c_str()); return err; } if (exec_state->context()->root() == NULL) { return err; } CreatePageInternal(page_id, exec_state->context()->root()); #ifdef DEBUG auto duration_post = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - start); LOGD("DATA_RENDER, All time %lld\n", duration_post.count()); #endif DownloadAndExecScript(exec_state, page_id, exec_js); return err; } void VNodeRenderManager::DownloadAndExecScript( ExecState* exec_state, const std::string& page_id, std::function<void(const char*)> exec_js) { // If script exists in json, run script into js vm const json11::Json& script_array = exec_state->context()->script_json(); if (script_array.is_array()) { for (auto it = script_array.array_items().begin(); it != script_array.array_items().end(); it++) { const json11::Json& script_obj = *it; auto src = script_obj["src"]; auto content = script_obj["content"]; auto callback1 = weex::base::MakeCopyable( [page_id = page_id, exec_js = exec_js, exec_state = exec_state](const char* result) { exec_js(result); auto root = VNodeRenderManager::GetInstance()->GetRootVNode(page_id); if (root && root->IsVirtualComponent()) { static_cast<weex::core::data_render::VComponent*>(root) ->DispatchCreated(); //fire event exec_state->set_exec_js_finished(true); const std::vector<std::vector<std::string>>& event_queue = exec_state->event_queue(); for (auto args : event_queue) { VNodeRenderManager::GetInstance()->FireEvent(args[0], args[1], args[2], args[3], args[4]); } exec_state->ClearEventQueue(); } }); // callback2, a wrap for callback1, will be post to script thread to // execute callback1 auto callback2 = weex::base::MakeCopyable([callback = callback1]( const std::string& result) { #ifdef OS_ANDROID WeexCoreManager::Instance()->script_thread()->message_loop()->PostTask( weex::base::MakeCopyable([result = std::move(result), callback]() { callback(result.c_str()); })); #else callback(result.c_str()); #endif }); // If script is a url, first download the script, else run script // directly. if (content.is_string() && !content.string_value().empty()) { callback1(const_cast<char*>(content.string_value().c_str())); } else if (src.is_string()) { network::HttpModule http_module; http_module.Send(page_id.c_str(), src.string_value().c_str(), callback2); } } } } bool VNodeRenderManager::RequireModule(ExecState *exec_state, std::string &name, std::string &result) { bool finished = false; do { if (!modules_.size()) { break; } for (auto iter = modules_.begin(); iter != modules_.end(); iter++) { if ((*iter).find(name) <= 10) { result = *iter; finished = true; break; } } } while (0); return finished; } void VNodeRenderManager::ExecuteRegisterModules(ExecState *exec_state, std::vector<std::string>& registers) { do { if (!modules_.size()) { break; } const std::string func_name = "registerModule"; for (auto iter = modules_.begin(); iter != modules_.end(); iter++) { for (int j = 0; j < registers.size(); j++) { std::string prefix = registers[j]; if ((*iter).find(prefix) <= 10) { Value arg = StringToValue(exec_state, *iter); exec_state->Call(func_name, {arg}); break; } } } } while (0); } std::string VNodeRenderManager::CreatePageWithContent(const uint8_t *contents, size_t length, const std::string &page_id, const std::string &options, const std::string &init_data, std::function<void(const char*)> exec_js) { InitVM(); #ifdef DEBUG auto start = std::chrono::steady_clock::now(); #endif ExecState *exec_state = new ExecState(g_vm); exec_states_.insert({page_id, exec_state}); VNodeExecEnv::ImportExecEnv(exec_state); exec_state->context()->page_id(page_id); std::string err; if (!weex::core::data_render::WXExecDecoder(exec_state, (uint8_t *)contents, length, err)) { return err; } if (init_data.length() > 0) { VNodeExecEnv::ImportExecData(exec_state, init_data); } #ifdef DEBUG auto decoder_post = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - start); LOGD("[DATA_RENDER], Decoder time:[%lld]\n", decoder_post.count()); #endif exec_state->Execute(err); if (!err.empty()) { return err; } if (exec_state->context()->root() == NULL) { err = "Root vonde is null"; return err; } CreatePageInternal(page_id, exec_state->context()->root()); #ifdef DEBUG auto duration_post = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - start); LOGD("[DATA_RENDER], All time:[%lld]\n", duration_post.count()); #endif DownloadAndExecScript(exec_state, page_id, exec_js); return err; } void VNodeRenderManager::CreatePage(const char *contents, size_t length, const std::string& page_id, const std::string& options, const std::string& init_data, std::function<void(const char*)> exec_js) { string err = CreatePageWithContent((const uint8_t *)contents, length, page_id, options, init_data, exec_js); if (!err.empty()) { WeexCore::WeexCoreManager::Instance()->getPlatformBridge()->platform_side()->ReportException(page_id.c_str(), nullptr, err.c_str()); } } bool VNodeRenderManager::RefreshPage(const std::string& page_id, const std::string& init_data) { do { auto it = exec_states_.find(page_id); if (it == exec_states_.end()) { break; } ExecState *exec_state = it->second; // If component exsit, refresh by component auto it_vnode = vnode_trees_.find(page_id); if (it_vnode == vnode_trees_.end()) { return false; } if (it_vnode->second->IsVirtualComponent()) { auto component = static_cast<VComponent*>(it_vnode->second); Value data = StringToValue(exec_state, init_data); component->UpdateData(&data); return true; } // Otherwise re-execute VNodeExecEnv::ImportExecData(exec_state, init_data); std::string err; exec_state->context()->Reset(); exec_state->Execute(err); // refresh root if (!err.empty()) { break; } if (exec_state->context()->root() == NULL) { break; } RefreshPageInternal(page_id, exec_state->context()->root()); WeexCore::WeexCoreManager::Instance() ->getPlatformBridge() ->platform_side() ->RefreshFinish(page_id.c_str(), nullptr, ""); return true; } while (0); return false; } bool VNodeRenderManager::ClosePage(const std::string& page_id) { auto it = exec_states_.find(page_id); if (it == exec_states_.end()) { return false; } ExecState *exec_state = it->second; ClosePageInternal(page_id); delete exec_state; exec_states_.erase(it); return true; } void VNodeRenderManager::FireEvent(const std::string &page_id, const std::string &ref, const std::string &event,const std::string &args,const std::string &dom_changes) { do { auto iter = exec_states_.find(page_id); if (iter == exec_states_.end()) { break; } if (!iter->second->exec_js_finished()) { std::vector<std::string> fire_event = {page_id, ref, event, args, dom_changes}; iter->second->AddEvent(fire_event); break; } auto node = vnode_trees_.find(page_id); if (node == vnode_trees_.end()) { break; } // TODO merge two way to fire event { // First way to fire event from VNode::OnEvent auto vnode = iter->second->context()->GetVNode(ref); if (vnode) { auto hit_test = vnode->event_params_map()->find(event); if (hit_test != vnode->event_params_map()->end()) { // If vnode has eat event, return. vnode->OnEvent(event, args, dom_changes); return; } } } // Second way to fire event from call vm func auto vnode = node->second->FindNode(ref); if (vnode == nullptr) if (!vnode) { break; } auto iter_event = vnode->events()->find(event); if (iter_event == vnode->events()->end()) { break; } if (!iter_event->second) { break; } FuncState *func_state = nullptr; FuncInstance *func_inst = nullptr; ExecState *exec_state = iter->second; bool finder = false; for (auto iter : exec_state->class_factory()->stores()) { if (iter.first == iter_event->second) { if (iter.second == Value::Type::FUNC_INST) { func_inst = reinterpret_cast<FuncInstance *>(iter.first); } finder = true; } } if (!finder) { func_state = reinterpret_cast<FuncState *>(iter_event->second); } if (!func_state && !func_inst) { break; } std::vector<Value> caller_args; if (func_inst) { func_state = func_inst->func_; } if (func_state->is_class_func() && vnode->inst()) { Value inst; SetCIValue(&inst, reinterpret_cast<GCObject *>(vnode->inst())); caller_args.push_back(inst); } caller_args.push_back(StringToValue(exec_state, args)); if (func_inst) { exec_state->Call(func_inst, caller_args); } else { exec_state->Call(func_state, caller_args); } } while (0); } void VNodeRenderManager::CallNativeModule(ExecState *exec_state, const std::string& module, const std::string& method, const std::string& args, int argc) { for (auto iter = exec_states_.begin(); iter != exec_states_.end(); iter++) { if (iter->second == exec_state) { WeexCoreManager::Instance() ->getPlatformBridge() ->platform_side() ->CallNativeModule(iter->first.c_str(), module.c_str(), method.c_str(), args.length() > 0 ? args.c_str() : nullptr, static_cast<int>(args.length()), nullptr, 0); break; } } } void VNodeRenderManager::WXLogNative(ExecState *exec_state, const std::string &info) { for (auto iter = exec_states_.begin(); iter != exec_states_.end(); iter++) { if (iter->second == exec_state) { WeexCoreManager::Instance() ->getPlatformBridge() ->platform_side() ->NativeLog(info.c_str()); break; } } } void VNodeRenderManager::UpdateComponentData(const std::string& page_id, const char* cid, const std::string& json_data) { ExecState* exec_state = GetExecState(page_id); if (!exec_state) return; VComponent* component = exec_state->context()->GetComponent(atoi(cid)); if (component) { Value value(StringToValue(exec_state, json_data)); component->UpdateData(&value); } } void VNodeRenderManager::PatchVNode(ExecState *exec_state, VNode *v_node, VNode *new_node) { for (auto iter = exec_states_.begin(); iter != exec_states_.end(); iter++) { if (iter->second == exec_state) { Patch(iter->first, v_node, new_node); break; } } } bool SameNode(VNode* a, VNode* b) { if (a->IsVirtualComponent() && b->IsVirtualComponent()) { return static_cast<VComponent*>(a)->IsSameNode(static_cast<VComponent*>(b)); } else { // todo to be more accurate return a->tag_name() == b->tag_name() && a->ref() == b->ref() && a->IsVirtualComponent() == b->IsVirtualComponent(); } } inline VNode* GetOrNull(vector<VNode*>& vec, int index) { if (index < 0 || index >= vec.size()) { return nullptr; } return vec[index]; } void RemoveNodes(const string& pageId, vector<VNode*>& vec, vector<VNode*>& ref_list, unsigned int start, unsigned int end); void AddNodes(const string& pageId, vector<VNode*>& vec, vector<VNode*>& ref_list, unsigned int start, unsigned int end); inline vector<VNode*>::iterator IndexOf(vector<VNode*>& vec, const VNode* value) { return std::find(vec.begin(), vec.end(), value); } int MoveToBackOfRef(vector<VNode*>& ref_list, const VNode* move_ref, const VNode* anchor_ref); int MoveToFrontOfRef(vector<VNode*>& ref_list, const VNode* move_ref, const VNode* anchor_ref); int MoveElmToFrontOfNode(const string& page_id, vector<VNode*>& ref_list, VNode* move_node, VNode* anchor_node); int MoveElmToBackOfNode(const string& page_id, vector<VNode*>& ref_list, VNode* move_node, VNode* anchor_node); void CreateAndInsertElm(const string& page_id, VNode* node, vector<VNode*>& ref_list, const VNode* ref); void UpdateChildren(const string& page_id, VNode* old_node, VNode* new_node) { vector<VNode*>& old_children = *old_node->child_list(); vector<VNode*>& new_children = *new_node->child_list(); vector<VNode*> ref_list; map<string, unsigned int>* ref_to_index = nullptr; // ref for (auto begin = old_children.begin(); begin < old_children.end(); begin++) { ref_list.push_back((*begin)); } int old_start = 0; int old_end = static_cast<int>(old_children.size()) - 1; int new_start = 0; int new_end = static_cast<int>(new_children.size()) - 1; VNode* old_start_node = GetOrNull(old_children, old_start); VNode* old_end_node = GetOrNull(old_children, old_end); VNode* new_start_node = GetOrNull(new_children, new_start); VNode* new_end_node = GetOrNull(new_children, new_end); while (old_start <= old_end && new_start <= new_end) { if (old_start_node == nullptr) { //++oldStart might larger than children size; old_start_node = GetOrNull(old_children, ++old_start); } else if (old_end_node == nullptr) { old_end_node = GetOrNull(old_children, --old_end); } else if (new_start_node == nullptr) { new_start_node = GetOrNull(new_children, ++new_start); } else if (new_end_node == nullptr) { new_end_node = GetOrNull(new_children, --new_end); } else if (SameNode(old_start_node, new_start_node)) { PatchVNode(page_id, old_start_node, new_start_node); old_start_node = GetOrNull(old_children, ++old_start); new_start_node = GetOrNull(new_children, ++new_start); } else if (SameNode(old_end_node, new_end_node)) { PatchVNode(page_id, old_end_node, new_end_node); old_end_node = GetOrNull(old_children, --old_end); new_end_node = GetOrNull(new_children, --new_end); } else if (SameNode(old_start_node, new_end_node)) { PatchVNode(page_id, old_start_node, new_end_node); MoveElmToBackOfNode(page_id, ref_list, old_start_node, old_end_node); old_start_node = GetOrNull(old_children, ++old_start); new_end_node = GetOrNull(new_children, --new_end); } else if (SameNode(old_end_node, new_start_node)) { PatchVNode(page_id, old_end_node, new_start_node); MoveElmToFrontOfNode(page_id, ref_list, old_end_node, old_start_node); old_end_node = GetOrNull(old_children, --old_end); new_start_node = GetOrNull(new_children, ++new_start); } else { // create on first time if (ref_to_index == nullptr) { ref_to_index = new map<string, unsigned int>(); for (unsigned int i = old_start; i <= old_end; ++i) { auto vnode = GetOrNull(old_children, i); if (vnode == nullptr || vnode->ref().empty()) { continue; } ref_to_index->insert({vnode->ref(), i}); } } auto pos = ref_to_index->find(new_start_node->ref()); if (pos == ref_to_index->end()) { // no node found, create new CreateAndInsertElm(page_id, new_start_node, ref_list, old_start_node); new_start_node = GetOrNull(new_children, ++new_start); } else { auto node_to_move = GetOrNull(old_children, pos->second); if (node_to_move == nullptr) { // wtf! #if VRENDER_LOG LOGE("[VRenderManager] already moved, has duplicated ref: %s", new_start_node->ref().c_str()); #endif continue; } if (SameNode(node_to_move, new_start_node)) { PatchVNode(page_id, node_to_move, new_start_node); // delete old node. *IndexOf(ref_list, node_to_move) = new_start_node; delete old_children[pos->second]; old_children[pos->second] = nullptr; MoveElmToFrontOfNode(page_id, ref_list, new_start_node, old_start_node); new_start_node = GetOrNull(new_children, ++new_start); } else { // same ref exist, after insert there will be duplicated ref. // so must remove it in real dom first. RenderManager::GetInstance()->RemoveRenderObject( page_id, node_to_move->render_object_ref()); ref_list.erase(IndexOf(ref_list, node_to_move)); delete old_children[pos->second]; old_children[pos->second] = nullptr; // no need to remove from keyToIndex, will go into wtf above; CreateAndInsertElm(page_id, new_start_node, ref_list, old_start_node); new_start_node = GetOrNull(new_children, ++new_start); } } } } if (old_start > old_end) { AddNodes(page_id, new_children, ref_list, new_start, new_end); // end is include } else if (new_start > new_end) { RemoveNodes(page_id, old_children, ref_list, old_start, old_end); } if (ref_to_index != nullptr) { delete ref_to_index; ref_to_index = nullptr; } } void CreateAndInsertElm(const string& page_id, VNode* node, vector<VNode*>& ref_list, const VNode* ref) { auto insert_pos = IndexOf(ref_list, ref); int index = static_cast<int>(std::distance(ref_list.begin(), insert_pos)); ref_list.insert(insert_pos, node); WeexCore::RenderObject* root = ParseVNode2RenderObject(node, nullptr, false, 0, page_id); RenderManager::GetInstance()->AddRenderObject( page_id, node->parent()->render_object_ref(), index, root); } int MoveToBackOfRef(vector<VNode*>& ref_list, const VNode* move_ref, const VNode* anchor_ref) { auto move_pos = IndexOf(ref_list, move_ref); auto anchor_pos = IndexOf(ref_list, anchor_ref); if (move_pos == ref_list.end()) { #if VRENDER_LOG LOGE("[VRenderManager] moveToBackOfRef movePos == refList.end() ref: %s", move_ref->ref().c_str()); #endif return -1; // wtf! } if (anchor_pos == ref_list.end()) { #if VRENDER_LOG LOGE("[VRenderManager] moveToBackOfRef anchorPos == refList.end() ref: %s", anchor_ref->ref().c_str()); #endif return -1; // wtf } int index = static_cast<int>(std::distance(ref_list.begin(), anchor_pos)); VNode* value = *move_pos; ref_list.erase(move_pos); ref_list.insert(anchor_pos, value); return index; } int MoveToFrontOfRef(vector<VNode*>& ref_list, const VNode* move_ref, const VNode* anchor_ref) { auto move_pos = IndexOf(ref_list, move_ref); auto anchor_pos = IndexOf(ref_list, anchor_ref); if (move_pos == ref_list.end()) { #if VRENDER_LOG LOGE("[VRenderManager] moveToFrontOfRef movePos == refList.end() ref: %s", move_ref->ref().c_str()); #endif return -1; // wtf! } if (anchor_pos == ref_list.end()) { #if VRENDER_LOG LOGE("[VRenderManager] moveToFrontOfRef anchorPos == refList.end() ref: %s", anchor_ref->ref().c_str()); #endif return -1; // wtf } int index = static_cast<int>(std::distance(ref_list.begin(), anchor_pos)); VNode* value = *move_pos; ref_list.erase(move_pos); ref_list.insert(anchor_pos, value); return index; } int MoveElmToFrontOfNode(const string& page_id, vector<VNode*>& ref_list, VNode* move_node, VNode* anchor_node) { int move_to_index = MoveToFrontOfRef(ref_list, move_node, anchor_node); RenderManager::GetInstance()->MoveRenderObject( page_id, move_node->render_object_ref(), move_node->parent()->render_object_ref(), move_to_index); return move_to_index; } int MoveElmToBackOfNode(const string& page_id, vector<VNode*>& ref_list, VNode* move_node, VNode* anchor_node) { int move_to_index = MoveToBackOfRef(ref_list, move_node, anchor_node); RenderManager::GetInstance()->MoveRenderObject( page_id, move_node->render_object_ref(), move_node->parent()->render_object_ref(), move_to_index); return move_to_index; } void AddNodes(const string& pageId, vector<VNode*>& vec, vector<VNode*>& ref_list, unsigned int start, unsigned int end) { for (int i = start; i <= end; ++i) { auto p_node = vec[i]; ref_list.insert(ref_list.begin() + i, p_node); WeexCore::RenderObject *node = ParseVNode2RenderObject(p_node, nullptr, false, 0, pageId); RenderManager::GetInstance()->AddRenderObject( pageId, p_node->parent()->render_object_ref(), i, node); } } void RemoveNodes(const string& pageId, vector<VNode*>& vec, vector<VNode*>& ref_list, unsigned int start, unsigned int end) { for (int i = start; i <= end; ++i) { auto p_node = vec[i]; // some might already been used for patch, which is null. if (p_node == nullptr) { continue; } auto pos = IndexOf(ref_list, p_node); if (pos == ref_list.end()) { // wtf??? #if VRENDER_LOG LOGE("[VRenderManager] removeNodes pos == refList.end() ref: %s", p_node->ref().c_str()); #endif continue; } RenderManager::GetInstance()->RemoveRenderObject( pageId, (*pos)->render_object_ref()); } } vector<pair<string, string>>* CompareMap(const map<string, string>& oldMap, const map<string, string>& newMap) { auto p_vec = new vector<pair<string, string>>(); for (auto it = newMap.cbegin(); it != newMap.cend(); it++) { auto pos = oldMap.find(it->first); if (pos == oldMap.end() || pos->second != it->second) { // key not exist, or value not same p_vec->push_back({it->first, it->second}); } } for (auto it = oldMap.cbegin(); it != oldMap.cend(); it++) { auto pos = newMap.find(it->first); if (pos == newMap.end()) { // key not exist, remove //todo check if this is correct p_vec->push_back({it->first, ""}); } } return p_vec; }; void CompareAndApplyEvents1(const std::string& page_id, VNode* old_node, VNode* new_node) { std::map<std::string, void*> old_events = *old_node->events(); std::map<std::string, void*> new_events = *new_node->events(); for (auto it = old_events.cbegin(); it != old_events.cend(); it++) { auto pos = new_events.find(it->first); if (pos == new_events.end()) { new_events.erase(pos); } } for (auto it = new_events.cbegin(); it != new_events.cend(); it++) { auto pos = old_events.find(it->first); if (pos == old_events.end()) { old_events.erase(pos); } } for (auto it = old_events.cbegin(); it != old_events.cend(); it++) { RenderManager::GetInstance()->RemoveEvent( page_id, new_node->render_object_ref(), it->first); } for (auto it = new_events.cbegin(); it != new_events.cend(); it++) { RenderManager::GetInstance()->AddEvent( page_id, new_node->render_object_ref(), it->first); } } void CompareAndApplyEvents2(const std::string& page_id, VNode* old_node, VNode* new_node) { VNode::EventParamsMap old_events = *old_node->event_params_map(); VNode::EventParamsMap new_events = *new_node->event_params_map(); for (auto it = old_events.cbegin(); it != old_events.cend(); it++) { auto pos = new_events.find(it->first); if (pos == new_events.end()) { new_events.erase(pos); } } for (auto it = new_events.cbegin(); it != new_events.cend(); it++) { auto pos = old_events.find(it->first); if (pos == old_events.end()) { old_events.erase(pos); } } for (auto it = old_events.cbegin(); it != old_events.cend(); it++) { RenderManager::GetInstance()->RemoveEvent( page_id, new_node->render_object_ref(), it->first); } for (auto it = new_events.cbegin(); it != new_events.cend(); it++) { RenderManager::GetInstance()->AddEvent( page_id, new_node->render_object_ref(), it->first); } } void PatchVNode(const string& page_id, VNode* old_node, VNode* new_node) { if (old_node->IsVirtualComponent()) { static_cast<VComponent*>(old_node) ->MoveTo(static_cast<VComponent*>(new_node)); return; } // patch render object link new_node->set_render_object_ref(old_node->render_object_ref()); // compare attr, ptr will be delete by RenderPage auto p_vec = CompareMap(*(old_node->attributes()), *(new_node->attributes())); if (p_vec->size() > 0) { RenderManager::GetInstance()->UpdateAttr(page_id, new_node->render_object_ref(), p_vec); } else { delete p_vec; p_vec = nullptr; } // compare style, ptr will be delete by RenderPage p_vec = CompareMap(*(old_node->styles()), *(new_node->styles())); if (p_vec->size()) { RenderManager::GetInstance()->UpdateStyle(page_id, new_node->render_object_ref(), p_vec); } else { delete p_vec; p_vec = nullptr; } // compare and apply event CompareAndApplyEvents1(page_id, old_node, new_node); CompareAndApplyEvents2(page_id, old_node, new_node); // compare children if (old_node->HasChildren() && new_node->HasChildren()) { UpdateChildren(page_id, old_node, new_node); } else if (old_node->HasChildren() && !new_node->HasChildren()) { for (auto i = old_node->child_list()->cbegin(); i != old_node->child_list()->cend(); i++) { RenderManager::GetInstance()->RemoveRenderObject( page_id, (*i)->render_object_ref()); } } else if (!old_node->HasChildren() && new_node->HasChildren()) { int index = 0; for (auto it = new_node->child_list()->cbegin(); it != new_node->child_list()->cend(); it++) { WeexCore::RenderObject *child_node = ParseVNode2RenderObject(*it, nullptr, false, 0, page_id); RenderManager::GetInstance()->AddRenderObject( page_id, (*it)->parent()->render_object_ref(), index, child_node); ++index; } } } void Patch(const string& page_id, VNode *old_node, VNode *new_node) { if (!old_node) { ParseVNode2RenderObject(new_node, nullptr, false, 0, page_id); } else if (old_node->parent() == NULL || SameNode(old_node, new_node)) { // root must be the same; PatchVNode(page_id, old_node, new_node); } else { WeexCore::RenderObject *new_render_object = ParseVNode2RenderObject(new_node, nullptr, false, 0, page_id); VNode *parent = (VNode *)old_node->parent(); if (!parent && old_node->component()) { parent = const_cast<VNode*>(old_node->component()->parent()); old_node = old_node->component(); } if (parent) { vector<VNode *> &old_children = *parent->child_list(); auto pos = std::find(old_children.begin(), old_children.end(), old_node); int index = static_cast<int>(std::distance(old_children.begin(), pos)); parent->InsertChild(new_node, index); RenderManager::GetInstance()->AddRenderObject(page_id, parent->render_object_ref(), index, new_render_object); parent->RemoveChild(old_node); RenderManager::GetInstance()->RemoveRenderObject(page_id, old_node->render_object_ref()); } } } } // namespace data_render } // namespace core } // namespace weex [core] fix crash error when erase event (#1940) /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ #include "core/data_render/vnode/vnode_render_manager.h" #include <chrono> #include <sstream> #include "base/make_copyable.h" #include "base/string_util.h" #include "core/bridge/platform_bridge.h" #include "core/data_render/common_error.h" #include "core/data_render/exec_state.h" #include "core/data_render/exec_state_binary.h" #include "core/data_render/string_table.h" #include "core/data_render/vnode/vnode.h" #include "core/data_render/vnode/vnode_exec_env.h" #include "core/manager/weex_core_manager.h" #include "core/network/http_module.h" #include "core/render/manager/render_manager.h" #include "core/render/node/factory/render_creator.h" #define VRENDER_LOG true #if VRENDER_LOG #include "base/LogDefines.h" #endif namespace weex { namespace core { namespace data_render { using std::map; using std::pair; using std::string; using std::vector; using WeexCore::RenderManager; void PatchVNode(const string& page_id, VNode* old_node, VNode* new_node); VNodeRenderManager* VNodeRenderManager::g_instance = nullptr; VM* VNodeRenderManager::g_vm = nullptr; // TODO establish linkages between page ref_id int ref_id = 0; WeexCore::RenderObject* ParseVNode2RenderObject(VNode* vnode, WeexCore::RenderObject* parent, bool isRoot, int index, const string& pageId) { if (vnode->IsVirtualComponent()) { VComponent* component = static_cast<VComponent*>(vnode); if (component->root_vnode() == nullptr) { component->UpdateData(); } return ParseVNode2RenderObject(component->root_vnode(), parent, isRoot, index, pageId); } std::string ref_str; if (isRoot) { ref_str = "_root"; } else { ref_str = base::to_string(ref_id++); } WeexCore::RenderObject* render_object = static_cast<WeexCore::RenderObject*>( WeexCore::RenderCreator::GetInstance()->CreateRender(vnode->tag_name(), ref_str)); // Link RenderObject and VNode vnode->set_render_object_ref(std::move(ref_str)); // style map<string, string>* style = vnode->styles(); for (auto it = style->begin(); it != style->end(); it++) { render_object->AddStyle(it->first, it->second); } // attr map<string, string>* attr = vnode->attributes(); for (auto it = attr->begin(); it != attr->end(); it++) { render_object->AddAttr(it->first, it->second); } // event std::map<std::string, void *> *events = vnode->events(); for (auto iter = events->begin(); iter != events->end(); iter++) { render_object->events()->insert(iter->first); } auto event_params_map = vnode->event_params_map(); for (auto it = event_params_map->begin(); it != event_params_map->end(); it++) { render_object->events()->insert(it->first); } // child vector<VNode*>* children = vnode->child_list(); for (int i = 0; i < children->size(); i++) { ParseVNode2RenderObject((*children)[i], render_object, false, i, pageId); } render_object->set_page_id(pageId); render_object->ApplyDefaultStyle(); render_object->ApplyDefaultAttr(); // parent if (parent != nullptr) { parent->AddRenderObject(index, render_object); } return render_object; } WeexCore::RenderObject *VNode2RenderObject(VNode *root, const string& page_id) { return ParseVNode2RenderObject(root, nullptr, true, 0, page_id); } void Patch(const string& page_id, VNode* old_root, VNode* new_root); bool VNodeRenderManager::CreatePageInternal(const string& page_id, VNode* vNode) { auto node = vnode_trees_.find(page_id); if (node != vnode_trees_.end()) { delete node->second; node->second = nullptr; } vnode_trees_[page_id] = vNode; auto render_root = VNode2RenderObject(vNode, page_id); RenderManager::GetInstance()->CreatePage(page_id, render_root); RenderManager::GetInstance()->CreateFinish(page_id); return true; } bool VNodeRenderManager::RefreshPageInternal(const string& page_id, VNode* new_node) { auto node = vnode_trees_.find(page_id); if (node == vnode_trees_.end()) { return false; } auto oldNode = node->second; Patch(page_id, oldNode, new_node); node->second = new_node; delete oldNode; return true; } bool VNodeRenderManager::ClosePageInternal(const string& page_id) { auto node = vnode_trees_.find(page_id); if (node == vnode_trees_.end()) { return false; } RenderManager::GetInstance()->ClosePage(page_id); delete node->second; vnode_trees_.erase(node); return true; } void VNodeRenderManager::InitVM() { if (g_vm == nullptr) { g_vm = new VM(); } } void VNodeRenderManager::CreatePage(const std::string &input, const std::string &page_id, const std::string &options, const std::string &init_data, std::function<void(const char*)> exec_js) { std::string err = CreatePageWithContent(input, page_id, options, init_data, exec_js); if (!err.empty()) { WeexCore::WeexCoreManager::Instance()->getPlatformBridge()->platform_side()->ReportException(page_id.c_str(), nullptr, err.c_str()); } } std::string VNodeRenderManager::CreatePageWithContent(const std::string &input, const std::string &page_id, const std::string &options, const std::string &init_data, std::function<void(const char*)> exec_js) { InitVM(); #ifdef DEBUG auto start = std::chrono::steady_clock::now(); #endif ExecState *exec_state = new ExecState(g_vm); exec_states_.insert({page_id, exec_state}); VNodeExecEnv::ImportExecEnv(exec_state); std::string err; json11::Json json = json11::Json::parse(input, err); if (!err.empty() || json.is_null()) { exec_state->context()->raw_source() = input; } else { exec_state->context()->raw_json() = json; VNodeExecEnv::ParseData(exec_state); VNodeExecEnv::ParseStyle(exec_state); VNodeExecEnv::ParseScript(exec_state); } if (init_data.length() > 0) { VNodeExecEnv::ImportExecData(exec_state, init_data); } exec_state->context()->page_id(page_id); //auto compile_start = std::chrono::steady_clock::now(); exec_state->Compile(err); if (!err.empty()) { LOGE("DATA_RENDER, compile err: %s",err.c_str()); return err; } #ifdef DEBUG auto compile_post = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - start); LOGD("[DATA_RENDER], Compile time:[%lld]\n", compile_post.count()); #endif //auto exec_start = std::chrono::steady_clock::now(); exec_state->Execute(err); if (!err.empty()) { LOGE("DATA_RENDER, exec err: %s",err.c_str()); return err; } if (exec_state->context()->root() == NULL) { return err; } CreatePageInternal(page_id, exec_state->context()->root()); #ifdef DEBUG auto duration_post = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - start); LOGD("DATA_RENDER, All time %lld\n", duration_post.count()); #endif DownloadAndExecScript(exec_state, page_id, exec_js); return err; } void VNodeRenderManager::DownloadAndExecScript( ExecState* exec_state, const std::string& page_id, std::function<void(const char*)> exec_js) { // If script exists in json, run script into js vm const json11::Json& script_array = exec_state->context()->script_json(); if (script_array.is_array()) { for (auto it = script_array.array_items().begin(); it != script_array.array_items().end(); it++) { const json11::Json& script_obj = *it; auto src = script_obj["src"]; auto content = script_obj["content"]; auto callback1 = weex::base::MakeCopyable( [page_id = page_id, exec_js = exec_js, exec_state = exec_state](const char* result) { exec_js(result); auto root = VNodeRenderManager::GetInstance()->GetRootVNode(page_id); if (root && root->IsVirtualComponent()) { static_cast<weex::core::data_render::VComponent*>(root) ->DispatchCreated(); //fire event exec_state->set_exec_js_finished(true); const std::vector<std::vector<std::string>>& event_queue = exec_state->event_queue(); for (auto args : event_queue) { VNodeRenderManager::GetInstance()->FireEvent(args[0], args[1], args[2], args[3], args[4]); } exec_state->ClearEventQueue(); } }); // callback2, a wrap for callback1, will be post to script thread to // execute callback1 auto callback2 = weex::base::MakeCopyable([callback = callback1]( const std::string& result) { #ifdef OS_ANDROID WeexCoreManager::Instance()->script_thread()->message_loop()->PostTask( weex::base::MakeCopyable([result = std::move(result), callback]() { callback(result.c_str()); })); #else callback(result.c_str()); #endif }); // If script is a url, first download the script, else run script // directly. if (content.is_string() && !content.string_value().empty()) { callback1(const_cast<char*>(content.string_value().c_str())); } else if (src.is_string()) { network::HttpModule http_module; http_module.Send(page_id.c_str(), src.string_value().c_str(), callback2); } } } } bool VNodeRenderManager::RequireModule(ExecState *exec_state, std::string &name, std::string &result) { bool finished = false; do { if (!modules_.size()) { break; } for (auto iter = modules_.begin(); iter != modules_.end(); iter++) { if ((*iter).find(name) <= 10) { result = *iter; finished = true; break; } } } while (0); return finished; } void VNodeRenderManager::ExecuteRegisterModules(ExecState *exec_state, std::vector<std::string>& registers) { do { if (!modules_.size()) { break; } const std::string func_name = "registerModule"; for (auto iter = modules_.begin(); iter != modules_.end(); iter++) { for (int j = 0; j < registers.size(); j++) { std::string prefix = registers[j]; if ((*iter).find(prefix) <= 10) { Value arg = StringToValue(exec_state, *iter); exec_state->Call(func_name, {arg}); break; } } } } while (0); } std::string VNodeRenderManager::CreatePageWithContent(const uint8_t *contents, size_t length, const std::string &page_id, const std::string &options, const std::string &init_data, std::function<void(const char*)> exec_js) { InitVM(); #ifdef DEBUG auto start = std::chrono::steady_clock::now(); #endif ExecState *exec_state = new ExecState(g_vm); exec_states_.insert({page_id, exec_state}); VNodeExecEnv::ImportExecEnv(exec_state); exec_state->context()->page_id(page_id); std::string err; if (!weex::core::data_render::WXExecDecoder(exec_state, (uint8_t *)contents, length, err)) { return err; } if (init_data.length() > 0) { VNodeExecEnv::ImportExecData(exec_state, init_data); } #ifdef DEBUG auto decoder_post = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - start); LOGD("[DATA_RENDER], Decoder time:[%lld]\n", decoder_post.count()); #endif exec_state->Execute(err); if (!err.empty()) { return err; } if (exec_state->context()->root() == NULL) { err = "Root vonde is null"; return err; } CreatePageInternal(page_id, exec_state->context()->root()); #ifdef DEBUG auto duration_post = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - start); LOGD("[DATA_RENDER], All time:[%lld]\n", duration_post.count()); #endif DownloadAndExecScript(exec_state, page_id, exec_js); return err; } void VNodeRenderManager::CreatePage(const char *contents, size_t length, const std::string& page_id, const std::string& options, const std::string& init_data, std::function<void(const char*)> exec_js) { string err = CreatePageWithContent((const uint8_t *)contents, length, page_id, options, init_data, exec_js); if (!err.empty()) { WeexCore::WeexCoreManager::Instance()->getPlatformBridge()->platform_side()->ReportException(page_id.c_str(), nullptr, err.c_str()); } } bool VNodeRenderManager::RefreshPage(const std::string& page_id, const std::string& init_data) { do { auto it = exec_states_.find(page_id); if (it == exec_states_.end()) { break; } ExecState *exec_state = it->second; // If component exsit, refresh by component auto it_vnode = vnode_trees_.find(page_id); if (it_vnode == vnode_trees_.end()) { return false; } if (it_vnode->second->IsVirtualComponent()) { auto component = static_cast<VComponent*>(it_vnode->second); Value data = StringToValue(exec_state, init_data); component->UpdateData(&data); return true; } // Otherwise re-execute VNodeExecEnv::ImportExecData(exec_state, init_data); std::string err; exec_state->context()->Reset(); exec_state->Execute(err); // refresh root if (!err.empty()) { break; } if (exec_state->context()->root() == NULL) { break; } RefreshPageInternal(page_id, exec_state->context()->root()); WeexCore::WeexCoreManager::Instance() ->getPlatformBridge() ->platform_side() ->RefreshFinish(page_id.c_str(), nullptr, ""); return true; } while (0); return false; } bool VNodeRenderManager::ClosePage(const std::string& page_id) { auto it = exec_states_.find(page_id); if (it == exec_states_.end()) { return false; } ExecState *exec_state = it->second; ClosePageInternal(page_id); delete exec_state; exec_states_.erase(it); return true; } void VNodeRenderManager::FireEvent(const std::string &page_id, const std::string &ref, const std::string &event,const std::string &args,const std::string &dom_changes) { do { auto iter = exec_states_.find(page_id); if (iter == exec_states_.end()) { break; } if (!iter->second->exec_js_finished()) { std::vector<std::string> fire_event = {page_id, ref, event, args, dom_changes}; iter->second->AddEvent(fire_event); break; } auto node = vnode_trees_.find(page_id); if (node == vnode_trees_.end()) { break; } // TODO merge two way to fire event { // First way to fire event from VNode::OnEvent auto vnode = iter->second->context()->GetVNode(ref); if (vnode) { auto hit_test = vnode->event_params_map()->find(event); if (hit_test != vnode->event_params_map()->end()) { // If vnode has eat event, return. vnode->OnEvent(event, args, dom_changes); return; } } } // Second way to fire event from call vm func auto vnode = node->second->FindNode(ref); if (vnode == nullptr) if (!vnode) { break; } auto iter_event = vnode->events()->find(event); if (iter_event == vnode->events()->end()) { break; } if (!iter_event->second) { break; } FuncState *func_state = nullptr; FuncInstance *func_inst = nullptr; ExecState *exec_state = iter->second; bool finder = false; for (auto iter : exec_state->class_factory()->stores()) { if (iter.first == iter_event->second) { if (iter.second == Value::Type::FUNC_INST) { func_inst = reinterpret_cast<FuncInstance *>(iter.first); } finder = true; } } if (!finder) { func_state = reinterpret_cast<FuncState *>(iter_event->second); } if (!func_state && !func_inst) { break; } std::vector<Value> caller_args; if (func_inst) { func_state = func_inst->func_; } if (func_state->is_class_func() && vnode->inst()) { Value inst; SetCIValue(&inst, reinterpret_cast<GCObject *>(vnode->inst())); caller_args.push_back(inst); } caller_args.push_back(StringToValue(exec_state, args)); if (func_inst) { exec_state->Call(func_inst, caller_args); } else { exec_state->Call(func_state, caller_args); } } while (0); } void VNodeRenderManager::CallNativeModule(ExecState *exec_state, const std::string& module, const std::string& method, const std::string& args, int argc) { for (auto iter = exec_states_.begin(); iter != exec_states_.end(); iter++) { if (iter->second == exec_state) { WeexCoreManager::Instance() ->getPlatformBridge() ->platform_side() ->CallNativeModule(iter->first.c_str(), module.c_str(), method.c_str(), args.length() > 0 ? args.c_str() : nullptr, static_cast<int>(args.length()), nullptr, 0); break; } } } void VNodeRenderManager::WXLogNative(ExecState *exec_state, const std::string &info) { for (auto iter = exec_states_.begin(); iter != exec_states_.end(); iter++) { if (iter->second == exec_state) { WeexCoreManager::Instance() ->getPlatformBridge() ->platform_side() ->NativeLog(info.c_str()); break; } } } void VNodeRenderManager::UpdateComponentData(const std::string& page_id, const char* cid, const std::string& json_data) { ExecState* exec_state = GetExecState(page_id); if (!exec_state) return; VComponent* component = exec_state->context()->GetComponent(atoi(cid)); if (component) { Value value(StringToValue(exec_state, json_data)); component->UpdateData(&value); } } void VNodeRenderManager::PatchVNode(ExecState *exec_state, VNode *v_node, VNode *new_node) { for (auto iter = exec_states_.begin(); iter != exec_states_.end(); iter++) { if (iter->second == exec_state) { Patch(iter->first, v_node, new_node); break; } } } bool SameNode(VNode* a, VNode* b) { if (a->IsVirtualComponent() && b->IsVirtualComponent()) { return static_cast<VComponent*>(a)->IsSameNode(static_cast<VComponent*>(b)); } else { // todo to be more accurate return a->tag_name() == b->tag_name() && a->ref() == b->ref() && a->IsVirtualComponent() == b->IsVirtualComponent(); } } inline VNode* GetOrNull(vector<VNode*>& vec, int index) { if (index < 0 || index >= vec.size()) { return nullptr; } return vec[index]; } void RemoveNodes(const string& pageId, vector<VNode*>& vec, vector<VNode*>& ref_list, unsigned int start, unsigned int end); void AddNodes(const string& pageId, vector<VNode*>& vec, vector<VNode*>& ref_list, unsigned int start, unsigned int end); inline vector<VNode*>::iterator IndexOf(vector<VNode*>& vec, const VNode* value) { return std::find(vec.begin(), vec.end(), value); } int MoveToBackOfRef(vector<VNode*>& ref_list, const VNode* move_ref, const VNode* anchor_ref); int MoveToFrontOfRef(vector<VNode*>& ref_list, const VNode* move_ref, const VNode* anchor_ref); int MoveElmToFrontOfNode(const string& page_id, vector<VNode*>& ref_list, VNode* move_node, VNode* anchor_node); int MoveElmToBackOfNode(const string& page_id, vector<VNode*>& ref_list, VNode* move_node, VNode* anchor_node); void CreateAndInsertElm(const string& page_id, VNode* node, vector<VNode*>& ref_list, const VNode* ref); void UpdateChildren(const string& page_id, VNode* old_node, VNode* new_node) { vector<VNode*>& old_children = *old_node->child_list(); vector<VNode*>& new_children = *new_node->child_list(); vector<VNode*> ref_list; map<string, unsigned int>* ref_to_index = nullptr; // ref for (auto begin = old_children.begin(); begin < old_children.end(); begin++) { ref_list.push_back((*begin)); } int old_start = 0; int old_end = static_cast<int>(old_children.size()) - 1; int new_start = 0; int new_end = static_cast<int>(new_children.size()) - 1; VNode* old_start_node = GetOrNull(old_children, old_start); VNode* old_end_node = GetOrNull(old_children, old_end); VNode* new_start_node = GetOrNull(new_children, new_start); VNode* new_end_node = GetOrNull(new_children, new_end); while (old_start <= old_end && new_start <= new_end) { if (old_start_node == nullptr) { //++oldStart might larger than children size; old_start_node = GetOrNull(old_children, ++old_start); } else if (old_end_node == nullptr) { old_end_node = GetOrNull(old_children, --old_end); } else if (new_start_node == nullptr) { new_start_node = GetOrNull(new_children, ++new_start); } else if (new_end_node == nullptr) { new_end_node = GetOrNull(new_children, --new_end); } else if (SameNode(old_start_node, new_start_node)) { PatchVNode(page_id, old_start_node, new_start_node); old_start_node = GetOrNull(old_children, ++old_start); new_start_node = GetOrNull(new_children, ++new_start); } else if (SameNode(old_end_node, new_end_node)) { PatchVNode(page_id, old_end_node, new_end_node); old_end_node = GetOrNull(old_children, --old_end); new_end_node = GetOrNull(new_children, --new_end); } else if (SameNode(old_start_node, new_end_node)) { PatchVNode(page_id, old_start_node, new_end_node); MoveElmToBackOfNode(page_id, ref_list, old_start_node, old_end_node); old_start_node = GetOrNull(old_children, ++old_start); new_end_node = GetOrNull(new_children, --new_end); } else if (SameNode(old_end_node, new_start_node)) { PatchVNode(page_id, old_end_node, new_start_node); MoveElmToFrontOfNode(page_id, ref_list, old_end_node, old_start_node); old_end_node = GetOrNull(old_children, --old_end); new_start_node = GetOrNull(new_children, ++new_start); } else { // create on first time if (ref_to_index == nullptr) { ref_to_index = new map<string, unsigned int>(); for (unsigned int i = old_start; i <= old_end; ++i) { auto vnode = GetOrNull(old_children, i); if (vnode == nullptr || vnode->ref().empty()) { continue; } ref_to_index->insert({vnode->ref(), i}); } } auto pos = ref_to_index->find(new_start_node->ref()); if (pos == ref_to_index->end()) { // no node found, create new CreateAndInsertElm(page_id, new_start_node, ref_list, old_start_node); new_start_node = GetOrNull(new_children, ++new_start); } else { auto node_to_move = GetOrNull(old_children, pos->second); if (node_to_move == nullptr) { // wtf! #if VRENDER_LOG LOGE("[VRenderManager] already moved, has duplicated ref: %s", new_start_node->ref().c_str()); #endif continue; } if (SameNode(node_to_move, new_start_node)) { PatchVNode(page_id, node_to_move, new_start_node); // delete old node. *IndexOf(ref_list, node_to_move) = new_start_node; delete old_children[pos->second]; old_children[pos->second] = nullptr; MoveElmToFrontOfNode(page_id, ref_list, new_start_node, old_start_node); new_start_node = GetOrNull(new_children, ++new_start); } else { // same ref exist, after insert there will be duplicated ref. // so must remove it in real dom first. RenderManager::GetInstance()->RemoveRenderObject( page_id, node_to_move->render_object_ref()); ref_list.erase(IndexOf(ref_list, node_to_move)); delete old_children[pos->second]; old_children[pos->second] = nullptr; // no need to remove from keyToIndex, will go into wtf above; CreateAndInsertElm(page_id, new_start_node, ref_list, old_start_node); new_start_node = GetOrNull(new_children, ++new_start); } } } } if (old_start > old_end) { AddNodes(page_id, new_children, ref_list, new_start, new_end); // end is include } else if (new_start > new_end) { RemoveNodes(page_id, old_children, ref_list, old_start, old_end); } if (ref_to_index != nullptr) { delete ref_to_index; ref_to_index = nullptr; } } void CreateAndInsertElm(const string& page_id, VNode* node, vector<VNode*>& ref_list, const VNode* ref) { auto insert_pos = IndexOf(ref_list, ref); int index = static_cast<int>(std::distance(ref_list.begin(), insert_pos)); ref_list.insert(insert_pos, node); WeexCore::RenderObject* root = ParseVNode2RenderObject(node, nullptr, false, 0, page_id); RenderManager::GetInstance()->AddRenderObject( page_id, node->parent()->render_object_ref(), index, root); } int MoveToBackOfRef(vector<VNode*>& ref_list, const VNode* move_ref, const VNode* anchor_ref) { auto move_pos = IndexOf(ref_list, move_ref); auto anchor_pos = IndexOf(ref_list, anchor_ref); if (move_pos == ref_list.end()) { #if VRENDER_LOG LOGE("[VRenderManager] moveToBackOfRef movePos == refList.end() ref: %s", move_ref->ref().c_str()); #endif return -1; // wtf! } if (anchor_pos == ref_list.end()) { #if VRENDER_LOG LOGE("[VRenderManager] moveToBackOfRef anchorPos == refList.end() ref: %s", anchor_ref->ref().c_str()); #endif return -1; // wtf } int index = static_cast<int>(std::distance(ref_list.begin(), anchor_pos)); VNode* value = *move_pos; ref_list.erase(move_pos); ref_list.insert(anchor_pos, value); return index; } int MoveToFrontOfRef(vector<VNode*>& ref_list, const VNode* move_ref, const VNode* anchor_ref) { auto move_pos = IndexOf(ref_list, move_ref); auto anchor_pos = IndexOf(ref_list, anchor_ref); if (move_pos == ref_list.end()) { #if VRENDER_LOG LOGE("[VRenderManager] moveToFrontOfRef movePos == refList.end() ref: %s", move_ref->ref().c_str()); #endif return -1; // wtf! } if (anchor_pos == ref_list.end()) { #if VRENDER_LOG LOGE("[VRenderManager] moveToFrontOfRef anchorPos == refList.end() ref: %s", anchor_ref->ref().c_str()); #endif return -1; // wtf } int index = static_cast<int>(std::distance(ref_list.begin(), anchor_pos)); VNode* value = *move_pos; ref_list.erase(move_pos); ref_list.insert(anchor_pos, value); return index; } int MoveElmToFrontOfNode(const string& page_id, vector<VNode*>& ref_list, VNode* move_node, VNode* anchor_node) { int move_to_index = MoveToFrontOfRef(ref_list, move_node, anchor_node); RenderManager::GetInstance()->MoveRenderObject( page_id, move_node->render_object_ref(), move_node->parent()->render_object_ref(), move_to_index); return move_to_index; } int MoveElmToBackOfNode(const string& page_id, vector<VNode*>& ref_list, VNode* move_node, VNode* anchor_node) { int move_to_index = MoveToBackOfRef(ref_list, move_node, anchor_node); RenderManager::GetInstance()->MoveRenderObject( page_id, move_node->render_object_ref(), move_node->parent()->render_object_ref(), move_to_index); return move_to_index; } void AddNodes(const string& pageId, vector<VNode*>& vec, vector<VNode*>& ref_list, unsigned int start, unsigned int end) { for (int i = start; i <= end; ++i) { auto p_node = vec[i]; ref_list.insert(ref_list.begin() + i, p_node); WeexCore::RenderObject *node = ParseVNode2RenderObject(p_node, nullptr, false, 0, pageId); RenderManager::GetInstance()->AddRenderObject( pageId, p_node->parent()->render_object_ref(), i, node); } } void RemoveNodes(const string& pageId, vector<VNode*>& vec, vector<VNode*>& ref_list, unsigned int start, unsigned int end) { for (int i = start; i <= end; ++i) { auto p_node = vec[i]; // some might already been used for patch, which is null. if (p_node == nullptr) { continue; } auto pos = IndexOf(ref_list, p_node); if (pos == ref_list.end()) { // wtf??? #if VRENDER_LOG LOGE("[VRenderManager] removeNodes pos == refList.end() ref: %s", p_node->ref().c_str()); #endif continue; } RenderManager::GetInstance()->RemoveRenderObject( pageId, (*pos)->render_object_ref()); } } vector<pair<string, string>>* CompareMap(const map<string, string>& oldMap, const map<string, string>& newMap) { auto p_vec = new vector<pair<string, string>>(); for (auto it = newMap.cbegin(); it != newMap.cend(); it++) { auto pos = oldMap.find(it->first); if (pos == oldMap.end() || pos->second != it->second) { // key not exist, or value not same p_vec->push_back({it->first, it->second}); } } for (auto it = oldMap.cbegin(); it != oldMap.cend(); it++) { auto pos = newMap.find(it->first); if (pos == newMap.end()) { // key not exist, remove //todo check if this is correct p_vec->push_back({it->first, ""}); } } return p_vec; }; void CompareAndApplyEvents1(const std::string& page_id, VNode* old_node, VNode* new_node) { std::map<std::string, void*> old_events = *old_node->events(); std::map<std::string, void*> new_events = *new_node->events(); for (auto it = old_events.cbegin(); it != old_events.cend(); it++) { auto pos = new_events.find(it->first); if (pos != new_events.end()) { new_events.erase(pos); } } for (auto it = new_events.cbegin(); it != new_events.cend(); it++) { auto pos = old_events.find(it->first); if (pos != old_events.end()) { old_events.erase(pos); } } for (auto it = old_events.cbegin(); it != old_events.cend(); it++) { RenderManager::GetInstance()->RemoveEvent( page_id, new_node->render_object_ref(), it->first); } for (auto it = new_events.cbegin(); it != new_events.cend(); it++) { RenderManager::GetInstance()->AddEvent( page_id, new_node->render_object_ref(), it->first); } } void CompareAndApplyEvents2(const std::string& page_id, VNode* old_node, VNode* new_node) { VNode::EventParamsMap old_events = *old_node->event_params_map(); VNode::EventParamsMap new_events = *new_node->event_params_map(); for (auto it = old_events.cbegin(); it != old_events.cend(); it++) { auto pos = new_events.find(it->first); if (pos != new_events.end()) { new_events.erase(pos); } } for (auto it = new_events.cbegin(); it != new_events.cend(); it++) { auto pos = old_events.find(it->first); if (pos != old_events.end()) { old_events.erase(pos); } } for (auto it = old_events.cbegin(); it != old_events.cend(); it++) { RenderManager::GetInstance()->RemoveEvent( page_id, new_node->render_object_ref(), it->first); } for (auto it = new_events.cbegin(); it != new_events.cend(); it++) { RenderManager::GetInstance()->AddEvent( page_id, new_node->render_object_ref(), it->first); } } void PatchVNode(const string& page_id, VNode* old_node, VNode* new_node) { if (old_node->IsVirtualComponent()) { static_cast<VComponent*>(old_node) ->MoveTo(static_cast<VComponent*>(new_node)); return; } // patch render object link new_node->set_render_object_ref(old_node->render_object_ref()); // compare attr, ptr will be delete by RenderPage auto p_vec = CompareMap(*(old_node->attributes()), *(new_node->attributes())); if (p_vec->size() > 0) { RenderManager::GetInstance()->UpdateAttr(page_id, new_node->render_object_ref(), p_vec); } else { delete p_vec; p_vec = nullptr; } // compare style, ptr will be delete by RenderPage p_vec = CompareMap(*(old_node->styles()), *(new_node->styles())); if (p_vec->size()) { RenderManager::GetInstance()->UpdateStyle(page_id, new_node->render_object_ref(), p_vec); } else { delete p_vec; p_vec = nullptr; } // compare and apply event CompareAndApplyEvents1(page_id, old_node, new_node); CompareAndApplyEvents2(page_id, old_node, new_node); // compare children if (old_node->HasChildren() && new_node->HasChildren()) { UpdateChildren(page_id, old_node, new_node); } else if (old_node->HasChildren() && !new_node->HasChildren()) { for (auto i = old_node->child_list()->cbegin(); i != old_node->child_list()->cend(); i++) { RenderManager::GetInstance()->RemoveRenderObject( page_id, (*i)->render_object_ref()); } } else if (!old_node->HasChildren() && new_node->HasChildren()) { int index = 0; for (auto it = new_node->child_list()->cbegin(); it != new_node->child_list()->cend(); it++) { WeexCore::RenderObject *child_node = ParseVNode2RenderObject(*it, nullptr, false, 0, page_id); RenderManager::GetInstance()->AddRenderObject( page_id, (*it)->parent()->render_object_ref(), index, child_node); ++index; } } } void Patch(const string& page_id, VNode *old_node, VNode *new_node) { if (!old_node) { ParseVNode2RenderObject(new_node, nullptr, false, 0, page_id); } else if (old_node->parent() == NULL || SameNode(old_node, new_node)) { // root must be the same; PatchVNode(page_id, old_node, new_node); } else { WeexCore::RenderObject *new_render_object = ParseVNode2RenderObject(new_node, nullptr, false, 0, page_id); VNode *parent = (VNode *)old_node->parent(); if (!parent && old_node->component()) { parent = const_cast<VNode*>(old_node->component()->parent()); old_node = old_node->component(); } if (parent) { vector<VNode *> &old_children = *parent->child_list(); auto pos = std::find(old_children.begin(), old_children.end(), old_node); int index = static_cast<int>(std::distance(old_children.begin(), pos)); parent->InsertChild(new_node, index); RenderManager::GetInstance()->AddRenderObject(page_id, parent->render_object_ref(), index, new_render_object); parent->RemoveChild(old_node); RenderManager::GetInstance()->RemoveRenderObject(page_id, old_node->render_object_ref()); } } } } // namespace data_render } // namespace core } // namespace weex
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "3DChartObjects.hxx" #include <vcl/virdev.hxx> #include <vcl/svapp.hxx> #include <vcl/opengl/OpenGLHelper.hxx> namespace chart { namespace opengl3D { Renderable3DObject::Renderable3DObject(OpenGL3DRenderer* pRenderer, sal_uInt32 nId): mpRenderer(pRenderer), mnUniqueId(nId) { } void Renderable3DObject::render() { (void) mnUniqueId; } Bar::Bar(OpenGL3DRenderer* pRenderer, const glm::mat4& rPosition, sal_uInt32 aColor, sal_uInt32 nId) : Renderable3DObject(pRenderer, nId) , mbRoundedCorners(true) , maPos(rPosition) , maColor(aColor) { SAL_INFO("chart2.3dopengl", rPosition); } void Bar::render() { mpRenderer->AddShape3DExtrudeObject(mbRoundedCorners, maColor.GetColor(), 0xFFFFFF, maPos, mnUniqueId); mpRenderer->EndAddShape3DExtrudeObject(); } Line::Line(OpenGL3DRenderer* pRenderer, sal_uInt32 nId): Renderable3DObject(pRenderer, nId) { } void Line::render() { mpRenderer->AddShapePolygon3DObject(0, true, maLineColor.GetColor(), 0, 0, mnUniqueId); mpRenderer->AddPolygon3DObjectPoint(maPosBegin.x, maPosBegin.y, maPosBegin.z); mpRenderer->AddPolygon3DObjectPoint(maPosEnd.x, maPosEnd.y, maPosEnd.z); mpRenderer->EndAddPolygon3DObjectPoint(); mpRenderer->EndAddShapePolygon3DObject(); } void Line::setPosition(const glm::vec3& rBegin, const glm::vec3& rEnd) { maPosBegin = rBegin; maPosEnd = rEnd; } void Line::setLineColor(const Color& rColor) { maLineColor = rColor; } const BitmapEx& TextCache::getText(OUString rText) { TextCacheType::const_iterator itr = maTextCache.find(rText); if(itr != maTextCache.end()) return *itr->second; VirtualDevice aDevice(*Application::GetDefaultDevice(), 0, 0); Font aFont = aDevice.GetFont(); aFont.SetSize(Size(0, 96)); aFont.SetColor(COL_BLACK); ::Rectangle aRect; aDevice.SetFont(aFont); aDevice.Erase(); aDevice.GetTextBoundRect(aRect, rText); Size aSize = aRect.GetSize(); aSize.Width() += 5; aSize.Height() *= 1.6; aDevice.SetOutputSizePixel(aSize); aDevice.SetBackground(Wallpaper(COL_TRANSPARENT)); aDevice.DrawText(Point(0,0), rText); BitmapEx* pText = new BitmapEx(aDevice.GetBitmapEx(Point(0,0), aSize)); maTextCache.insert(rText, pText); return *pText; } Text::Text(OpenGL3DRenderer* pRenderer, TextCache& rTextCache, const OUString& rStr, sal_uInt32 nId): Renderable3DObject(pRenderer, nId), mrText(rTextCache.getText(rStr)) { } void Text::render() { glm::vec3 dir2 = maTopRight - maTopLeft; glm::vec3 bottomLeft = maBottomRight - dir2; mpRenderer->CreateTextTexture(mrText, maTopLeft, maTopRight, maBottomRight, bottomLeft, mnUniqueId); } Size Text::getSize() const { return mrText.GetSizePixel(); } void Text::setPosition(const glm::vec3& rTopLeft, const glm::vec3& rTopRight, const glm::vec3& rBottomRight) { maTopLeft = rTopLeft; maTopRight = rTopRight; maBottomRight = rBottomRight; } Rectangle::Rectangle(OpenGL3DRenderer* pRenderer, sal_uInt32 nId): Renderable3DObject(pRenderer, nId) { } void Rectangle::render() { glm::vec3 dir1 = maBottomRight - maTopLeft; glm::vec3 dir2 = maTopRight - maTopLeft; glm::vec3 normal = glm::normalize(glm::cross(dir1, dir2)); mpRenderer->AddShapePolygon3DObject(maColor.GetColor(), false, 0, 1, 0xFFFFFF, mnUniqueId); glm::vec3 bottomLeft = maBottomRight - dir2; //set polygon points and normals mpRenderer->AddPolygon3DObjectPoint(maBottomRight.x, maBottomRight.y, maBottomRight.z); mpRenderer->AddPolygon3DObjectNormalPoint(normal.x, normal.y, normal.z); mpRenderer->AddPolygon3DObjectPoint(maTopRight.x, maTopRight.y, maTopRight.z); mpRenderer->AddPolygon3DObjectNormalPoint(normal.x, normal.y, normal.z); mpRenderer->AddPolygon3DObjectPoint(maTopLeft.x, maTopLeft.y, maTopLeft.z); mpRenderer->AddPolygon3DObjectNormalPoint(normal.x, normal.y, normal.z); mpRenderer->AddPolygon3DObjectPoint(bottomLeft.x, bottomLeft.y, bottomLeft.z); mpRenderer->AddPolygon3DObjectNormalPoint(normal.x, normal.y, normal.z); mpRenderer->EndAddPolygon3DObjectPoint(); mpRenderer->EndAddPolygon3DObjectNormalPoint(); mpRenderer->EndAddShapePolygon3DObject(); //we should render the edge if the edge color is different from the fill color if (maColor.GetColor() != maLineColor.GetColor()) { mpRenderer->AddShapePolygon3DObject(0, true, maLineColor.GetColor(), 0, 0xFFFFFF, mnUniqueId); mpRenderer->AddPolygon3DObjectPoint(maBottomRight.x, maBottomRight.y, maBottomRight.z); mpRenderer->AddPolygon3DObjectPoint(maTopRight.x, maTopRight.y, maTopRight.z); mpRenderer->AddPolygon3DObjectPoint(maTopLeft.x, maTopLeft.y, maTopLeft.z); mpRenderer->AddPolygon3DObjectPoint(bottomLeft.x, bottomLeft.y, bottomLeft.z); mpRenderer->EndAddPolygon3DObjectPoint(); mpRenderer->EndAddShapePolygon3DObject(); } } void Rectangle::setPosition(const glm::vec3& rTopLeft, const glm::vec3& rTopRight, const glm::vec3& rBottomRight) { maTopLeft = rTopLeft; maTopRight = rTopRight; maBottomRight = rBottomRight; } void Rectangle::setFillColor(const Color& rColor) { maColor = rColor; } void Rectangle::setLineColor(const Color& rColor) { maLineColor = rColor; } Camera::Camera(OpenGL3DRenderer* pRenderer): Renderable3DObject(pRenderer, 0), maPos(10,-50,20), maUp(0, 0, 1), maDirection(glm::vec3(0,0,0)) { } void Camera::render() { mpRenderer->SetCameraInfo(maPos, maDirection, maUp); } void Camera::setPosition(const glm::vec3& rPos) { maPos = rPos; } void Camera::setDirection(const glm::vec3& rDir) { maDirection = rDir; } void Camera::zoom(sal_uInt32 /*nId*/) { // TODO here } } } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ Improve computation of the text area to make it nicer. Change-Id: I24fb1caedc55dcc297fb013acb63b3c660fcf0a2 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "3DChartObjects.hxx" #include <vcl/virdev.hxx> #include <vcl/svapp.hxx> #include <vcl/opengl/OpenGLHelper.hxx> namespace chart { namespace opengl3D { Renderable3DObject::Renderable3DObject(OpenGL3DRenderer* pRenderer, sal_uInt32 nId): mpRenderer(pRenderer), mnUniqueId(nId) { } void Renderable3DObject::render() { (void) mnUniqueId; } Bar::Bar(OpenGL3DRenderer* pRenderer, const glm::mat4& rPosition, sal_uInt32 aColor, sal_uInt32 nId) : Renderable3DObject(pRenderer, nId) , mbRoundedCorners(true) , maPos(rPosition) , maColor(aColor) { SAL_INFO("chart2.3dopengl", rPosition); } void Bar::render() { mpRenderer->AddShape3DExtrudeObject(mbRoundedCorners, maColor.GetColor(), 0xFFFFFF, maPos, mnUniqueId); mpRenderer->EndAddShape3DExtrudeObject(); } Line::Line(OpenGL3DRenderer* pRenderer, sal_uInt32 nId): Renderable3DObject(pRenderer, nId) { } void Line::render() { mpRenderer->AddShapePolygon3DObject(0, true, maLineColor.GetColor(), 0, 0, mnUniqueId); mpRenderer->AddPolygon3DObjectPoint(maPosBegin.x, maPosBegin.y, maPosBegin.z); mpRenderer->AddPolygon3DObjectPoint(maPosEnd.x, maPosEnd.y, maPosEnd.z); mpRenderer->EndAddPolygon3DObjectPoint(); mpRenderer->EndAddShapePolygon3DObject(); } void Line::setPosition(const glm::vec3& rBegin, const glm::vec3& rEnd) { maPosBegin = rBegin; maPosEnd = rEnd; } void Line::setLineColor(const Color& rColor) { maLineColor = rColor; } const BitmapEx& TextCache::getText(OUString rText) { TextCacheType::const_iterator itr = maTextCache.find(rText); if(itr != maTextCache.end()) return *itr->second; VirtualDevice aDevice(*Application::GetDefaultDevice(), 0, 0); Font aFont = aDevice.GetFont(); aFont.SetSize(Size(0, 96)); aFont.SetColor(COL_BLACK); aDevice.SetFont(aFont); aDevice.Erase(); aDevice.SetOutputSize(Size(aDevice.GetTextWidth(rText), aDevice.GetTextHeight())); aDevice.SetBackground(Wallpaper(COL_TRANSPARENT)); aDevice.DrawText(Point(0,0), rText); BitmapEx* pText = new BitmapEx(aDevice.GetBitmapEx(Point(0,0), aDevice.GetOutputSize())); maTextCache.insert(rText, pText); return *pText; } Text::Text(OpenGL3DRenderer* pRenderer, TextCache& rTextCache, const OUString& rStr, sal_uInt32 nId): Renderable3DObject(pRenderer, nId), mrText(rTextCache.getText(rStr)) { } void Text::render() { glm::vec3 dir2 = maTopRight - maTopLeft; glm::vec3 bottomLeft = maBottomRight - dir2; mpRenderer->CreateTextTexture(mrText, maTopLeft, maTopRight, maBottomRight, bottomLeft, mnUniqueId); } Size Text::getSize() const { return mrText.GetSizePixel(); } void Text::setPosition(const glm::vec3& rTopLeft, const glm::vec3& rTopRight, const glm::vec3& rBottomRight) { maTopLeft = rTopLeft; maTopRight = rTopRight; maBottomRight = rBottomRight; } Rectangle::Rectangle(OpenGL3DRenderer* pRenderer, sal_uInt32 nId): Renderable3DObject(pRenderer, nId) { } void Rectangle::render() { glm::vec3 dir1 = maBottomRight - maTopLeft; glm::vec3 dir2 = maTopRight - maTopLeft; glm::vec3 normal = glm::normalize(glm::cross(dir1, dir2)); mpRenderer->AddShapePolygon3DObject(maColor.GetColor(), false, 0, 1, 0xFFFFFF, mnUniqueId); glm::vec3 bottomLeft = maBottomRight - dir2; //set polygon points and normals mpRenderer->AddPolygon3DObjectPoint(maBottomRight.x, maBottomRight.y, maBottomRight.z); mpRenderer->AddPolygon3DObjectNormalPoint(normal.x, normal.y, normal.z); mpRenderer->AddPolygon3DObjectPoint(maTopRight.x, maTopRight.y, maTopRight.z); mpRenderer->AddPolygon3DObjectNormalPoint(normal.x, normal.y, normal.z); mpRenderer->AddPolygon3DObjectPoint(maTopLeft.x, maTopLeft.y, maTopLeft.z); mpRenderer->AddPolygon3DObjectNormalPoint(normal.x, normal.y, normal.z); mpRenderer->AddPolygon3DObjectPoint(bottomLeft.x, bottomLeft.y, bottomLeft.z); mpRenderer->AddPolygon3DObjectNormalPoint(normal.x, normal.y, normal.z); mpRenderer->EndAddPolygon3DObjectPoint(); mpRenderer->EndAddPolygon3DObjectNormalPoint(); mpRenderer->EndAddShapePolygon3DObject(); //we should render the edge if the edge color is different from the fill color if (maColor.GetColor() != maLineColor.GetColor()) { mpRenderer->AddShapePolygon3DObject(0, true, maLineColor.GetColor(), 0, 0xFFFFFF, mnUniqueId); mpRenderer->AddPolygon3DObjectPoint(maBottomRight.x, maBottomRight.y, maBottomRight.z); mpRenderer->AddPolygon3DObjectPoint(maTopRight.x, maTopRight.y, maTopRight.z); mpRenderer->AddPolygon3DObjectPoint(maTopLeft.x, maTopLeft.y, maTopLeft.z); mpRenderer->AddPolygon3DObjectPoint(bottomLeft.x, bottomLeft.y, bottomLeft.z); mpRenderer->EndAddPolygon3DObjectPoint(); mpRenderer->EndAddShapePolygon3DObject(); } } void Rectangle::setPosition(const glm::vec3& rTopLeft, const glm::vec3& rTopRight, const glm::vec3& rBottomRight) { maTopLeft = rTopLeft; maTopRight = rTopRight; maBottomRight = rBottomRight; } void Rectangle::setFillColor(const Color& rColor) { maColor = rColor; } void Rectangle::setLineColor(const Color& rColor) { maLineColor = rColor; } Camera::Camera(OpenGL3DRenderer* pRenderer): Renderable3DObject(pRenderer, 0), maPos(10,-50,20), maUp(0, 0, 1), maDirection(glm::vec3(0,0,0)) { } void Camera::render() { mpRenderer->SetCameraInfo(maPos, maDirection, maUp); } void Camera::setPosition(const glm::vec3& rPos) { maPos = rPos; } void Camera::setDirection(const glm::vec3& rDir) { maDirection = rDir; } void Camera::zoom(sal_uInt32 /*nId*/) { // TODO here } } } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */
#include "cmainwindow.h" #include "plugininterface/cpluginwindow.h" #include "progressdialogs/ccopymovedialog.h" #include "progressdialogs/cdeleteprogressdialog.h" #include "progressdialogs/cfileoperationconfirmationprompt.h" #include "settings.h" #include "settings/csettings.h" #include "shell/cshell.h" #include "settingsui/csettingsdialog.h" #include "settings/csettingspageinterface.h" #include "settings/csettingspageoperations.h" #include "settings/csettingspageedit.h" #include "settings/csettingspageother.h" #include "pluginengine/cpluginengine.h" #include "panel/filelistwidget/cfilelistview.h" #include "panel/columns.h" #include "panel/cpanelwidget.h" #include "filesystemhelperfunctions.h" #include "filessearchdialog/cfilessearchwindow.h" #include "updaterUI/cupdaterdialog.h" #include "aboutdialog/caboutdialog.h" #include "widgets/cpersistentwindow.h" #include "widgets/widgetutils.h" #include "filesystemhelpers/filesystemhelpers.hpp" #include "version.h" DISABLE_COMPILER_WARNINGS #include "ui_cmainwindow.h" #include <QCloseEvent> #include <QDesktopWidget> #include <QFileDialog> #include <QFileIconProvider> #include <QInputDialog> #include <QLineEdit> #include <QMessageBox> #include <QProcess> #include <QSortFilterProxyModel> #include <QWidgetList> RESTORE_COMPILER_WARNINGS #ifdef _WIN32 #include <Windows.h> #endif #include <memory> // Main window settings keys #define KEY_RPANEL_STATE "Ui/RPanel/State" #define KEY_LPANEL_STATE "Ui/LPanel/State" #define KEY_RPANEL_GEOMETRY "Ui/RPanel/Geometry" #define KEY_LPANEL_GEOMETRY "Ui/LPanel/Geometry" #define KEY_SPLITTER_SIZES "Ui/Splitter" #define KEY_LAST_ACTIVE_PANEL "Ui/LastActivePanel" CMainWindow * CMainWindow::_instance = nullptr; CMainWindow::CMainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::CMainWindow) { assert_r(!_instance); _instance = this; ui->setupUi(this); _leftPanelDisplayController.setPanelStackedWidget(ui->leftWidget); _leftPanelDisplayController.setPanelWidget(ui->leftPanel); _rightPanelDisplayController.setPanelStackedWidget(ui->rightWidget); _rightPanelDisplayController.setPanelWidget(ui->rightPanel); installEventFilter(new CPersistenceEnabler("UI/MainWindow", this)); QSplitterHandle * handle = ui->splitter->handle(1); handle->setContextMenuPolicy(Qt::CustomContextMenu); connect(handle, &QSplitterHandle::customContextMenuRequested, this, &CMainWindow::splitterContextMenuRequested); connect(ui->_commandLine, &CHistoryComboBox::itemActivated, this, &CMainWindow::executeCommand); _commandLineCompleter.setCaseSensitivity(Qt::CaseInsensitive); _commandLineCompleter.setCompletionMode(QCompleter::InlineCompletion); _commandLineCompleter.setCompletionColumn(NameColumn); ui->_commandLine->setCompleter(&_commandLineCompleter); ui->_commandLine->setClearEditorOnItemActivation(true); ui->_commandLine->installEventFilter(this); } CMainWindow::~CMainWindow() { _instance = nullptr; delete ui; } CMainWindow *CMainWindow::get() { return _instance; } bool CMainWindow::created() const { return _controller != nullptr; } // One-time initialization void CMainWindow::onCreate() { assert_debug_only(!created()); initCore(); // Check for updates if (CSettings().value(KEY_OTHER_CHECK_FOR_UPDATES_AUTOMATICALLY, true).toBool() && CSettings().value(KEY_LAST_UPDATE_CHECK_TIMESTAMP, QDateTime::fromTime_t(1)).toDateTime().msecsTo(QDateTime::currentDateTime()) >= 1000 * 3600 * 24) { CSettings().setValue(KEY_LAST_UPDATE_CHECK_TIMESTAMP, QDateTime::currentDateTime()); auto dlg = new CUpdaterDialog(this, "https://github.com/VioletGiraffe/file-commander", VERSION_STRING, true); connect(dlg, &QDialog::rejected, dlg, &QDialog::deleteLater); connect(dlg, &QDialog::accepted, dlg, &QDialog::deleteLater); } } void CMainWindow::updateInterface() { CSettings s; ui->splitter->restoreState(s.value(KEY_SPLITTER_SIZES).toByteArray()); ui->leftPanel->restorePanelGeometry(s.value(KEY_LPANEL_GEOMETRY).toByteArray()); ui->leftPanel->restorePanelState(s.value(KEY_LPANEL_STATE).toByteArray()); ui->rightPanel->restorePanelGeometry(s.value(KEY_RPANEL_GEOMETRY).toByteArray()); ui->rightPanel->restorePanelState(s.value(KEY_RPANEL_STATE).toByteArray()); ui->_commandLine->addItems(s.value(KEY_LAST_COMMANDS_EXECUTED).toStringList()); ui->_commandLine->lineEdit()->clear(); show(); if ((windowState() & Qt::WindowFullScreen) != 0) ui->actionFull_screen_mode->setChecked(true); const Panel lastActivePanel = (Panel)CSettings().value(KEY_LAST_ACTIVE_PANEL, LeftPanel).toInt(); if (lastActivePanel == LeftPanel) ui->leftPanel->setFocusToFileList(); else ui->rightPanel->setFocusToFileList(); } void CMainWindow::initButtons() { connect(ui->btnView, &QPushButton::clicked, this, &CMainWindow::viewFile); _shortcuts.push_back(std::make_shared<QShortcut>(QKeySequence("F3"), this, SLOT(viewFile()), nullptr, Qt::WidgetWithChildrenShortcut)); connect(ui->btnEdit, &QPushButton::clicked, this, &CMainWindow::editFile); _shortcuts.push_back(std::make_shared<QShortcut>(QKeySequence("F4"), this, SLOT(editFile()), nullptr, Qt::WidgetWithChildrenShortcut)); connect(ui->btnCopy, &QPushButton::clicked, this, &CMainWindow::copySelectedFiles); _shortcuts.push_back(std::make_shared<QShortcut>(QKeySequence("F5"), this, SLOT(copySelectedFiles()), nullptr, Qt::WidgetWithChildrenShortcut)); connect(ui->btnMove, &QPushButton::clicked, this, &CMainWindow::moveSelectedFiles); _shortcuts.push_back(std::make_shared<QShortcut>(QKeySequence("F6"), this, SLOT(moveSelectedFiles()), nullptr, Qt::WidgetWithChildrenShortcut)); connect(ui->btnNewFolder, &QPushButton::clicked, this, &CMainWindow::createFolder); _shortcuts.push_back(std::make_shared<QShortcut>(QKeySequence("F7"), this, SLOT(createFolder()), nullptr, Qt::WidgetWithChildrenShortcut)); _shortcuts.push_back(std::make_shared<QShortcut>(QKeySequence("Shift+F7"), this, SLOT(createFile()), nullptr, Qt::WidgetWithChildrenShortcut)); connect(ui->btnDelete, &QPushButton::clicked, this, &CMainWindow::deleteFiles); connect(ui->btnDelete, &QPushButton::customContextMenuRequested, this, &CMainWindow::showRecycleBInContextMenu); _shortcuts.push_back(std::make_shared<QShortcut>(QKeySequence("F8"), this, SLOT(deleteFiles()), nullptr, Qt::WidgetWithChildrenShortcut)); _shortcuts.push_back(std::make_shared<QShortcut>(QKeySequence("Delete"), this, SLOT(deleteFiles()), nullptr, Qt::WidgetWithChildrenShortcut)); #ifdef __APPLE__ _shortcuts.push_back(std::make_shared<QShortcut>(QKeySequence(Qt::CTRL + Qt::Key_Backspace), this, SLOT(deleteFiles()), nullptr, Qt::WidgetWithChildrenShortcut)); #endif _shortcuts.push_back(std::make_shared<QShortcut>(QKeySequence("Shift+F8"), this, SLOT(deleteFilesIrrevocably()), nullptr, Qt::WidgetWithChildrenShortcut)); _shortcuts.push_back(std::make_shared<QShortcut>(QKeySequence("Shift+Delete"), this, SLOT(deleteFilesIrrevocably()), nullptr, Qt::WidgetWithChildrenShortcut)); // Command line ui->_commandLine->setSelectPreviousItemShortcut(QKeySequence("Ctrl+E")); _shortcuts.push_back(std::make_shared<QShortcut>(QKeySequence("Ctrl+E"), this, SLOT(selectPreviousCommandInTheCommandLine()), nullptr, Qt::WidgetWithChildrenShortcut)); } void CMainWindow::initActions() { connect(ui->actionRefresh, &QAction::triggered, this, &CMainWindow::refresh); connect(ui->actionFind, &QAction::triggered, this, &CMainWindow::findFiles); connect(ui->actionCopy_current_item_s_path_to_clipboard, &QAction::triggered, this, [this]() { _controller->copyCurrentItemToClipboard(); }); ui->actionExit->setShortcut(QKeySequence::Quit); connect(ui->actionExit, &QAction::triggered, qApp, &QApplication::quit); connect(ui->actionOpen_Console_Here, &QAction::triggered, [this]() { _controller->openTerminal(_currentFileList->currentDir()); }); connect(ui->actionOpen_Admin_console_here, &QAction::triggered, [this]() { _controller->openTerminal(_currentFileList->currentDir(), true); }); ui->action_Show_hidden_files->setChecked(CSettings().value(KEY_INTERFACE_SHOW_HIDDEN_FILES, true).toBool()); connect(ui->action_Show_hidden_files, &QAction::triggered, this, &CMainWindow::showHiddenFiles); connect(ui->actionShowAllFiles, &QAction::triggered, this, &CMainWindow::showAllFilesFromCurrentFolderAndBelow); connect(ui->action_Settings, &QAction::triggered, this, &CMainWindow::openSettingsDialog); connect(ui->actionCalculate_occupied_space, &QAction::triggered, this, &CMainWindow::calculateOccupiedSpace); connect(ui->actionQuick_view, &QAction::triggered, this, &CMainWindow::toggleQuickView); connect(ui->action_Invert_selection, &QAction::triggered, this, &CMainWindow::invertSelection); connect(ui->actionFull_screen_mode, &QAction::toggled, this, &CMainWindow::toggleFullScreenMode); connect(ui->actionTablet_mode, &QAction::toggled, this, &CMainWindow::toggleTabletMode); connect(ui->action_Check_for_updates, &QAction::triggered, this, &CMainWindow::checkForUpdates); connect(ui->actionAbout, &QAction::triggered, this, &CMainWindow::about); } // For manual focus management void CMainWindow::tabKeyPressed() { _otherFileList->setFocusToFileList(); } bool CMainWindow::copyFiles(const std::vector<CFileSystemObject> & files, const QString & destDir) { if (files.empty() || destDir.isEmpty()) return false; // Fix for #91 raise(); activateWindow(); const QString destPath = files.size() == 1 && files.front().isFile() ? cleanPath(destDir % nativeSeparator() % files.front().fullName()) : destDir; CFileOperationConfirmationPrompt prompt(tr("Copy files"), tr("Copy %1 %2 to").arg(files.size()).arg(files.size() > 1 ? "files" : "file"), toNativeSeparators(destPath), this); if (CSettings().value(KEY_OPERATIONS_ASK_FOR_COPY_MOVE_CONFIRMATION, true).toBool()) { if (prompt.exec() != QDialog::Accepted) return false; } CCopyMoveDialog * dialog = new CCopyMoveDialog(operationCopy, files, toPosixSeparators(prompt.text()), this); connect(this, &CMainWindow::closed, dialog, &CCopyMoveDialog::deleteLater); dialog->show(); return true; } bool CMainWindow::moveFiles(const std::vector<CFileSystemObject> & files, const QString & destDir) { if (files.empty() || destDir.isEmpty()) return false; // Fix for #91 raise(); activateWindow(); CFileOperationConfirmationPrompt prompt(tr("Move files"), tr("Move %1 %2 to").arg(files.size()).arg(files.size() > 1 ? "files" : "file"), toNativeSeparators(destDir), this); if (CSettings().value(KEY_OPERATIONS_ASK_FOR_COPY_MOVE_CONFIRMATION, true).toBool()) { if (prompt.exec() != QDialog::Accepted) return false; } CCopyMoveDialog * dialog = new CCopyMoveDialog(operationMove, files, toPosixSeparators(prompt.text()), this); connect(this, &CMainWindow::closed, dialog, &CCopyMoveDialog::deleteLater); dialog->show(); return true; } void CMainWindow::closeEvent(QCloseEvent *e) { if (e->type() == QCloseEvent::Close) { CSettings s; s.setValue(KEY_SPLITTER_SIZES, ui->splitter->saveState()); s.setValue(KEY_LPANEL_GEOMETRY, ui->leftPanel->savePanelGeometry()); s.setValue(KEY_RPANEL_GEOMETRY, ui->rightPanel->savePanelGeometry()); s.setValue(KEY_LPANEL_STATE, ui->leftPanel->savePanelState()); s.setValue(KEY_RPANEL_STATE, ui->rightPanel->savePanelState()); emit closed(); // Is used to close all child windows } QMainWindow::closeEvent(e); } bool CMainWindow::eventFilter(QObject *watched, QEvent *event) { if (watched == ui->_commandLine && event->type() == QEvent::KeyPress) { auto keyEvent = static_cast<QKeyEvent*>(event); if (keyEvent->key() == Qt::Key_Escape) clearCommandLineAndRestoreFocus(); } return QMainWindow::eventFilter(watched, event); } void CMainWindow::itemActivated(qulonglong hash, CPanelWidget *panel) { const auto result = _controller->itemHashExists(panel->panelPosition(), hash) ? _controller->itemActivated(hash, panel->panelPosition()) : FileOperationResultCode::ObjectDoesntExist; switch (result) { case FileOperationResultCode::ObjectDoesntExist: QMessageBox(QMessageBox::Warning, tr("Error"), tr("The file doesn't exist.")).exec(); break; case FileOperationResultCode::Fail: QMessageBox(QMessageBox::Critical, tr("Error"), tr("Failed to launch %1").arg(_controller->itemByHash(panel->panelPosition(), hash).fullAbsolutePath())).exec(); break; case FileOperationResultCode::DirNotAccessible: QMessageBox(QMessageBox::Critical, tr("No access"), tr("This item is not accessible.")).exec(); break; default: break; } } void CMainWindow::currentPanelChanged(const Panel panel) { if (panel == RightPanel) { _currentFileList = _rightPanelDisplayController.panelWidget(); _otherFileList = _leftPanelDisplayController.panelWidget(); } else if (panel == LeftPanel) { _currentFileList = _leftPanelDisplayController.panelWidget(); _otherFileList = _rightPanelDisplayController.panelWidget(); } else assert_unconditional_r("Invalid \'panel\' argument"); if (!_currentFileList) { _commandLineCompleter.setModel(nullptr); return; } _controller->activePanelChanged(_currentFileList->panelPosition()); CSettings().setValue(KEY_LAST_ACTIVE_PANEL, _currentFileList->panelPosition()); ui->fullPath->setText(_controller->panel(_currentFileList->panelPosition()).currentDirPathNative()); CPluginEngine::get().currentPanelChanged(_currentFileList->panelPosition()); _commandLineCompleter.setModel(_currentFileList->sortModel()); } void CMainWindow::uiThreadTimerTick() { if (_controller) _controller->uiThreadTimerTick(); } // Window title management (#143) void CMainWindow::updateWindowTitleWithCurrentFolderNames() { QString leftPanelDirName = _controller->panel(LeftPanel).currentDirName(); if (leftPanelDirName.length() > 1 && leftPanelDirName.endsWith('/')) leftPanelDirName.chop(1); QString rightPanelDirName = _controller->panel(RightPanel).currentDirName(); if (rightPanelDirName.length() > 1 && rightPanelDirName.endsWith('/')) rightPanelDirName.chop(1); setWindowTitle('[' % leftPanelDirName % "] / [" % rightPanelDirName % ']'); } void CMainWindow::splitterContextMenuRequested(QPoint pos) { const QPoint globalPos = dynamic_cast<QWidget*>(sender())->mapToGlobal(pos); QMenu menu; menu.addAction("50%"); QAction * selectedItem = menu.exec(globalPos); if (selectedItem) { const int width = (ui->leftPanel->width() + ui->rightPanel->width()) / 2; QList<int> sizes; sizes.push_back(width); sizes.push_back(width); ui->splitter->setSizes(sizes); } } void CMainWindow::copySelectedFiles() { if (_currentFileList && _otherFileList) // Some algorithms rely on trailing slash for distinguishing between files and folders for non-existent items copyFiles(_controller->items(_currentFileList->panelPosition(), _currentFileList->selectedItemsHashes()), _otherFileList->currentDir()); } void CMainWindow::moveSelectedFiles() { if (_currentFileList && _otherFileList) // Some algorithms rely on trailing slash for distinguishing between files and folders for non-existent items moveFiles(_controller->items(_currentFileList->panelPosition(), _currentFileList->selectedItemsHashes()), _otherFileList->currentDir()); } void CMainWindow::deleteFiles() { if (!_currentFileList) return; #if defined _WIN32 || defined __APPLE__ auto items = _controller->items(_currentFileList->panelPosition(), _currentFileList->selectedItemsHashes()); std::vector<std::wstring> paths; paths.reserve(items.size()); for (auto& item : items) paths.emplace_back(toNativeSeparators(item.fullAbsolutePath()).toStdWString()); if (paths.empty()) return; #ifdef _WIN32 auto windowHandle = (void*)winId(); #else void* windowHandle = nullptr; #endif _controller->execOnWorkerThread([=]() { if (!OsShell::deleteItems(paths, true, windowHandle)) _controller->execOnUiThread([this]() { QMessageBox::warning(this, tr("Error deleting items"), tr("Failed to delete the selected items")); }); }); #else deleteFilesIrrevocably(); #endif } void CMainWindow::deleteFilesIrrevocably() { if (!_currentFileList) return; auto items = _controller->items(_currentFileList->panelPosition(), _currentFileList->selectedItemsHashes()); if (items.empty()) return; #ifdef _WIN32 std::vector<std::wstring> paths; paths.reserve(items.size()); for (auto& item : items) paths.emplace_back(toNativeSeparators(item.fullAbsolutePath()).toStdWString()); _controller->execOnWorkerThread([=]() { if (!OsShell::deleteItems(paths, false, (void*)winId())) _controller->execOnUiThread([this]() { QMessageBox::warning(this, tr("Error deleting items"), tr("Failed to delete the selected items")); }); }); #else if (QMessageBox::question(this, tr("Are you sure?"), tr("Do you want to delete the selected files and folders completely?"), QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) { CDeleteProgressDialog * dialog = new CDeleteProgressDialog(items, _otherFileList->currentDir(), this); connect(this, &CMainWindow::closed, dialog, &CDeleteProgressDialog::deleteLater); dialog->show(); } #endif } void CMainWindow::createFolder() { if (!_currentFileList) return; const auto currentItem = _currentFileList->currentItemHash() != 0 ? _controller->itemByHash(_currentFileList->panelPosition(), _currentFileList->currentItemHash()) : CFileSystemObject(); const QString currentItemName = !currentItem.isCdUp() ? currentItem.fullName() : QString(); QInputDialog dialog(this); dialog.setWindowIcon(QFileIconProvider().icon(QFileIconProvider::Folder)); dialog.setWindowTitle(tr("New folder")); dialog.setLabelText(tr("Enter the name for the new directory")); dialog.setTextValue(currentItemName); const QString dirName = dialog.exec() == QDialog::Accepted ? dialog.textValue() : QString();// QInputDialog::getText(this, tr("New folder"), tr("Enter the name for the new directory"), QLineEdit::Normal, currentItemName); if (dirName.isEmpty()) return; const auto result = _controller->createFolder(_currentFileList->currentDir(), toPosixSeparators(dirName)); if (result == FileOperationResultCode::TargetAlreadyExists) QMessageBox::warning(this, tr("Item already exists"), tr("The folder %1 already exists.").arg(dirName)); else if (result != FileOperationResultCode::Ok) QMessageBox::warning(this, tr("Failed to create item"), tr("Failed to create the folder %1").arg(dirName)); } void CMainWindow::createFile() { if (!_currentFileList) return; const auto currentItem = _currentFileList->currentItemHash() != 0 ? _controller->itemByHash(_currentFileList->panelPosition(), _currentFileList->currentItemHash()) : CFileSystemObject(); const QString currentItemName = !currentItem.isCdUp() ? currentItem.fullName() : QString(); QInputDialog dialog(this); dialog.setWindowIcon(QFileIconProvider().icon(QFileIconProvider::File)); dialog.setWindowTitle(tr("New file")); dialog.setLabelText(tr("Enter the name for the new file")); dialog.setTextValue(currentItemName); const QString fileName = dialog.exec() == QDialog::Accepted ? dialog.textValue() : QString(); if (fileName.isEmpty()) return; const auto result = _controller->createFile(_currentFileList->currentDir(), fileName); if (result == FileOperationResultCode::TargetAlreadyExists) QMessageBox::warning(this, tr("Item already exists"), tr("The file %1 already exists.").arg(fileName)); else if (result != FileOperationResultCode::Ok) QMessageBox::warning(this, tr("Failed to create item"), tr("Failed to create the file %1").arg(fileName)); } void CMainWindow::invertSelection() { if (_currentFileList) _currentFileList->invertSelection(); } // Other UI commands void CMainWindow::viewFile() { CPluginEngine::get().viewCurrentFile(); } void CMainWindow::editFile() { QString editorPath = CSettings().value(KEY_EDITOR_PATH).toString(); if (FileSystemHelpers::resolvePath(editorPath).isEmpty()) { if (QMessageBox::question(this, tr("Editor not configured"), tr("No editor program has been configured (or the specified path doesn't exist). Do you want to specify the editor now?")) == QMessageBox::Yes) { #ifdef _WIN32 const QString mask(tr("Executable files (*.exe *.cmd *.bat)")); #else const QString mask; #endif editorPath = QFileDialog::getOpenFileName(this, tr("Browse for editor program"), QString(), mask); if (editorPath.isEmpty()) return; CSettings().setValue(KEY_EDITOR_PATH, editorPath); } else return; } const QString currentFile = _currentFileList ? _controller->itemByHash(_currentFileList->panelPosition(), _currentFileList->currentItemHash()).fullAbsolutePath() : QString(); if (!currentFile.isEmpty()) { #ifdef __APPLE__ const bool started = std::system((QString("open -n \"") + CSettings().value(KEY_EDITOR_PATH).toString() + "\" --args \"" + currentFile + "\"").toUtf8().constData()) == 0; #else const bool started = QProcess::startDetached(editorPath, {currentFile}); #endif if (!started) QMessageBox::information(this, tr("Error"), tr("Cannot launch %1").arg(editorPath)); } } void CMainWindow::showRecycleBInContextMenu(QPoint pos) { const QPoint globalPos = ui->btnDelete->mapToGlobal(pos); OsShell::recycleBinContextMenu(globalPos.x(), globalPos.y(), (void*)winId()); } void CMainWindow::toggleQuickView() { if (!otherPanelDisplayController().quickViewActive()) quickViewCurrentFile(); else otherPanelDisplayController().endQuickView(); } void CMainWindow::currentItemChanged(Panel /*p*/, qulonglong /*itemHash*/) { if (otherPanelDisplayController().quickViewActive()) quickViewCurrentFile(); } void CMainWindow::toggleFullScreenMode(bool fullscreen) { if (fullscreen) showFullScreen(); else showNormal(); } void CMainWindow::toggleTabletMode(bool tabletMode) { static const int defaultFontSize = QApplication::font().pointSize(); ui->actionFull_screen_mode->toggle(); QFont f = QApplication::font(); f.setPointSize(tabletMode ? 24 : defaultFontSize); QApplication::setFont(f); auto widgets = QApplication::allWidgets(); for (auto widget : widgets) if (widget) widget->setFont(f); } bool CMainWindow::executeCommand(const QString& commandLineText) { if (!_currentFileList || commandLineText.isEmpty()) return false; OsShell::executeShellCommand(commandLineText, _currentFileList->currentDir()); QTimer::singleShot(0, [=]() {CSettings().setValue(KEY_LAST_COMMANDS_EXECUTED, ui->_commandLine->items()); }); // Saving the list AFTER the combobox actually accepts the newly added item clearCommandLineAndRestoreFocus(); return true; } void CMainWindow::selectPreviousCommandInTheCommandLine() { ui->_commandLine->selectPreviousItem(); ui->_commandLine->setFocus(); } void CMainWindow::clearCommandLineAndRestoreFocus() { ui->_commandLine->resetToLastSelected(true); _currentFileList->setFocusToFileList(); } void CMainWindow::pasteCurrentFileName() { if (_currentFileList && _currentFileList->currentItemHash() != 0) { QString textToAdd = _controller->itemByHash(_currentFileList->panelPosition(), _currentFileList->currentItemHash()).fullName(); if (textToAdd.contains(' ')) textToAdd = '\"' % textToAdd % '\"'; const QString newText = ui->_commandLine->lineEdit()->text().isEmpty() ? textToAdd : (ui->_commandLine->lineEdit()->text() % ' ' % textToAdd); ui->_commandLine->lineEdit()->setText(newText); } } void CMainWindow::pasteCurrentFilePath() { if (_currentFileList && _currentFileList->currentItemHash() != 0) { QString textToAdd = toNativeSeparators(_controller->itemByHash(_currentFileList->panelPosition(), _currentFileList->currentItemHash()).fullAbsolutePath()); if (textToAdd.contains(' ')) textToAdd = '\"' % textToAdd % '\"'; const QString newText = ui->_commandLine->lineEdit()->text().isEmpty() ? textToAdd : (ui->_commandLine->lineEdit()->text() % ' ' % textToAdd); ui->_commandLine->lineEdit()->setText(newText); } } void CMainWindow::refresh() { if (_currentFileList) _controller->refreshPanelContents(_currentFileList->panelPosition()); } void CMainWindow::findFiles() { if (!_currentFileList) return; auto selectedHashes = _currentFileList->selectedItemsHashes(true); std::vector<QString> selectedPaths; if (!selectedHashes.empty()) for (const auto hash : selectedHashes) selectedPaths.push_back(_controller->activePanel().itemByHash(hash).fullAbsolutePath()); else selectedPaths.push_back(_currentFileList->currentDir()); auto fileSearchUi = new CFilesSearchWindow(selectedPaths); connect(this, &CMainWindow::closed, fileSearchUi, &CFilesSearchWindow::close); fileSearchUi->show(); } void CMainWindow::showHiddenFiles() { CSettings().setValue(KEY_INTERFACE_SHOW_HIDDEN_FILES, ui->action_Show_hidden_files->isChecked()); _controller->refreshPanelContents(LeftPanel); _controller->refreshPanelContents(RightPanel); } void CMainWindow::showAllFilesFromCurrentFolderAndBelow() { if (_currentFileList) _controller->showAllFilesFromCurrentFolderAndBelow(_currentFileList->panelPosition()); } void CMainWindow::openSettingsDialog() { CSettingsDialog settings; settings.addSettingsPage(new CSettingsPageInterface); settings.addSettingsPage(new CSettingsPageOperations); settings.addSettingsPage(new CSettingsPageEdit); settings.addSettingsPage(new CSettingsPageOther); connect(&settings, &CSettingsDialog::settingsChanged, this, &CMainWindow::settingsChanged); settings.adjustSize(); settings.exec(); } void CMainWindow::calculateOccupiedSpace() { if (!_currentFileList) return; const FilesystemObjectsStatistics stats = _controller->calculateStatistics(_currentFileList->panelPosition(), _currentFileList->selectedItemsHashes()); if (stats.empty()) return; QMessageBox::information(this, tr("Occupied space"), tr("Statistics for the selected items(including subitems):\nFiles: %1\nFolders: %2\nOccupied space: %3"). arg(stats.files).arg(stats.folders).arg(fileSizeToString(stats.occupiedSpace))); } void CMainWindow::checkForUpdates() { CSettings().setValue(KEY_LAST_UPDATE_CHECK_TIMESTAMP, QDateTime::currentDateTime()); CUpdaterDialog(this, "https://github.com/VioletGiraffe/file-commander", VERSION_STRING).exec(); } void CMainWindow::about() { CAboutDialog(this).exec(); } void CMainWindow::settingsChanged() { _controller->settingsChanged(); ui->leftPanel->onSettingsChanged(); ui->rightPanel->onSettingsChanged(); } void CMainWindow::focusChanged(QWidget * /*old*/, QWidget * now) { if (!now) return; for (int i = 0; i < ui->leftWidget->count(); ++i) if (now == ui->leftWidget || WidgetUtils::widgetBelongsToHierarchy(now, ui->leftWidget->widget(i))) currentPanelChanged(LeftPanel); for (int i = 0; i < ui->rightWidget->count(); ++i) if (now == ui->rightWidget || WidgetUtils::widgetBelongsToHierarchy(now, ui->rightWidget->widget(i))) currentPanelChanged(RightPanel); } void CMainWindow::panelContentsChanged(Panel p, FileListRefreshCause /*operation*/) { if (_currentFileList && p == _currentFileList->panelPosition()) ui->fullPath->setText(_controller->panel(p).currentDirPathNative()); updateWindowTitleWithCurrentFolderNames(); } void CMainWindow::itemDiscoveryInProgress(Panel /*p*/, qulonglong /*itemHash*/, size_t /*progress*/, const QString& /*currentDir*/) { } void CMainWindow::initCore() { _controller = std::make_unique<CController>(); ui->leftPanel->init(_controller.get()); ui->rightPanel->init(_controller.get()); _controller->activePanelChanged((Panel)CSettings().value(KEY_LAST_ACTIVE_PANEL, LeftPanel).toInt()); connect(qApp, &QApplication::focusChanged, this, &CMainWindow::focusChanged); _controller->pluginProxy().setToolMenuEntryCreatorImplementation([this](const std::vector<CPluginProxy::MenuTree>& menuEntries) {createToolMenuEntries(menuEntries); }); // Need to load the plugins only after the menu creator has been set _controller->loadPlugins(); _currentFileList = ui->leftPanel; _otherFileList = ui->rightPanel; connect(ui->leftPanel->fileListView(), &CFileListView::ctrlEnterPressed, this, &CMainWindow::pasteCurrentFileName); connect(ui->rightPanel->fileListView(), &CFileListView::ctrlEnterPressed, this, &CMainWindow::pasteCurrentFileName); connect(ui->leftPanel->fileListView(), &CFileListView::ctrlShiftEnterPressed, this, &CMainWindow::pasteCurrentFilePath); connect(ui->rightPanel->fileListView(), &CFileListView::ctrlShiftEnterPressed, this, &CMainWindow::pasteCurrentFilePath); connect(ui->leftPanel, &CPanelWidget::currentItemChangedSignal, this, &CMainWindow::currentItemChanged); connect(ui->rightPanel, &CPanelWidget::currentItemChangedSignal, this, &CMainWindow::currentItemChanged); connect(ui->leftPanel, &CPanelWidget::itemActivated, this, &CMainWindow::itemActivated); connect(ui->rightPanel, &CPanelWidget::itemActivated, this, &CMainWindow::itemActivated); ui->leftPanel->fileListView()->addEventObserver(this); ui->rightPanel->fileListView()->addEventObserver(this); initButtons(); initActions(); ui->leftPanel->setPanelPosition(LeftPanel); ui->rightPanel->setPanelPosition(RightPanel); ui->fullPath->clear(); ui->leftWidget->setCurrentIndex(0); // PanelWidget ui->rightWidget->setCurrentIndex(0); // PanelWidget _controller->panel(LeftPanel).addPanelContentsChangedListener(this); _controller->panel(RightPanel).addPanelContentsChangedListener(this); connect(&_uiThreadTimer, &QTimer::timeout, this, &CMainWindow::uiThreadTimerTick); _uiThreadTimer.start(5); } void CMainWindow::createToolMenuEntries(const std::vector<CPluginProxy::MenuTree>& menuEntries) { QMenuBar * menu = menuBar(); if (!menu) return; static QMenu * toolMenu = nullptr; // Shouldn't have to be static, but 2 subsequent calls to this method result in "Tools" being added twice. QMenuBar needs event loop to update its children?.. // TODO: make it a class member for (auto topLevelMenu : menu->findChildren<QMenu*>()) { // TODO: make sure this plays nicely with localization (#145) if (topLevelMenu->title().remove('&') == "Tools") { toolMenu = topLevelMenu; break; } } if (!toolMenu) { // TODO: make sure this plays nicely with localization (#145) toolMenu = new QMenu("Tools"); menu->addMenu(toolMenu); } else toolMenu->addSeparator(); for (const auto& menuTree : menuEntries) addToolMenuEntriesRecursively(menuTree, toolMenu); toolMenu->addSeparator(); } void CMainWindow::addToolMenuEntriesRecursively(const CPluginProxy::MenuTree& entry, QMenu* toolMenu) { assert_r(toolMenu); QAction* action = toolMenu->addAction(entry.name); if (entry.children.empty()) { const auto handler = entry.handler; QObject::connect(action, &QAction::triggered, [handler](bool) {handler(); }); } else { for (const auto& childEntry : entry.children) addToolMenuEntriesRecursively(childEntry, toolMenu); } } CPanelDisplayController& CMainWindow::currentPanelDisplayController() { const auto panel = _controller->activePanelPosition(); if (panel == RightPanel) return _rightPanelDisplayController; else { assert_r(panel != UnknownPanel); return _leftPanelDisplayController; } } CPanelDisplayController& CMainWindow::otherPanelDisplayController() { const auto panel = _controller->activePanelPosition(); if (panel == RightPanel) return _leftPanelDisplayController; else { assert_r(panel != UnknownPanel); return _rightPanelDisplayController; } } bool CMainWindow::fileListReturnPressed() { return _currentFileList ? executeCommand(ui->_commandLine->currentText()) : false; } void CMainWindow::quickViewCurrentFile() { otherPanelDisplayController().startQuickView(CPluginEngine::get().createViewerWindowForCurrentFile()); } Fixed "quit" not saving window state #include "cmainwindow.h" #include "plugininterface/cpluginwindow.h" #include "progressdialogs/ccopymovedialog.h" #include "progressdialogs/cdeleteprogressdialog.h" #include "progressdialogs/cfileoperationconfirmationprompt.h" #include "settings.h" #include "settings/csettings.h" #include "shell/cshell.h" #include "settingsui/csettingsdialog.h" #include "settings/csettingspageinterface.h" #include "settings/csettingspageoperations.h" #include "settings/csettingspageedit.h" #include "settings/csettingspageother.h" #include "pluginengine/cpluginengine.h" #include "panel/filelistwidget/cfilelistview.h" #include "panel/columns.h" #include "panel/cpanelwidget.h" #include "filesystemhelperfunctions.h" #include "filessearchdialog/cfilessearchwindow.h" #include "updaterUI/cupdaterdialog.h" #include "aboutdialog/caboutdialog.h" #include "widgets/cpersistentwindow.h" #include "widgets/widgetutils.h" #include "filesystemhelpers/filesystemhelpers.hpp" #include "version.h" DISABLE_COMPILER_WARNINGS #include "ui_cmainwindow.h" #include <QCloseEvent> #include <QDesktopWidget> #include <QFileDialog> #include <QFileIconProvider> #include <QInputDialog> #include <QLineEdit> #include <QMessageBox> #include <QProcess> #include <QSortFilterProxyModel> #include <QWidgetList> RESTORE_COMPILER_WARNINGS #ifdef _WIN32 #include <Windows.h> #endif #include <memory> // Main window settings keys #define KEY_RPANEL_STATE "Ui/RPanel/State" #define KEY_LPANEL_STATE "Ui/LPanel/State" #define KEY_RPANEL_GEOMETRY "Ui/RPanel/Geometry" #define KEY_LPANEL_GEOMETRY "Ui/LPanel/Geometry" #define KEY_SPLITTER_SIZES "Ui/Splitter" #define KEY_LAST_ACTIVE_PANEL "Ui/LastActivePanel" CMainWindow * CMainWindow::_instance = nullptr; CMainWindow::CMainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::CMainWindow) { assert_r(!_instance); _instance = this; ui->setupUi(this); _leftPanelDisplayController.setPanelStackedWidget(ui->leftWidget); _leftPanelDisplayController.setPanelWidget(ui->leftPanel); _rightPanelDisplayController.setPanelStackedWidget(ui->rightWidget); _rightPanelDisplayController.setPanelWidget(ui->rightPanel); installEventFilter(new CPersistenceEnabler("UI/MainWindow", this)); QSplitterHandle * handle = ui->splitter->handle(1); handle->setContextMenuPolicy(Qt::CustomContextMenu); connect(handle, &QSplitterHandle::customContextMenuRequested, this, &CMainWindow::splitterContextMenuRequested); connect(ui->_commandLine, &CHistoryComboBox::itemActivated, this, &CMainWindow::executeCommand); _commandLineCompleter.setCaseSensitivity(Qt::CaseInsensitive); _commandLineCompleter.setCompletionMode(QCompleter::InlineCompletion); _commandLineCompleter.setCompletionColumn(NameColumn); ui->_commandLine->setCompleter(&_commandLineCompleter); ui->_commandLine->setClearEditorOnItemActivation(true); ui->_commandLine->installEventFilter(this); } CMainWindow::~CMainWindow() { _instance = nullptr; delete ui; } CMainWindow *CMainWindow::get() { return _instance; } bool CMainWindow::created() const { return _controller != nullptr; } // One-time initialization void CMainWindow::onCreate() { assert_debug_only(!created()); initCore(); CSettings s; // Check for updates if (s.value(KEY_OTHER_CHECK_FOR_UPDATES_AUTOMATICALLY, true).toBool() && s.value(KEY_LAST_UPDATE_CHECK_TIMESTAMP, QDateTime::fromTime_t(1)).toDateTime().msecsTo(QDateTime::currentDateTime()) >= 1000 * 3600 * 24) { s.setValue(KEY_LAST_UPDATE_CHECK_TIMESTAMP, QDateTime::currentDateTime()); auto dlg = new CUpdaterDialog(this, "https://github.com/VioletGiraffe/file-commander", VERSION_STRING, true); connect(dlg, &QDialog::rejected, dlg, &QDialog::deleteLater); connect(dlg, &QDialog::accepted, dlg, &QDialog::deleteLater); } } void CMainWindow::updateInterface() { CSettings s; ui->splitter->restoreState(s.value(KEY_SPLITTER_SIZES).toByteArray()); ui->leftPanel->restorePanelGeometry(s.value(KEY_LPANEL_GEOMETRY).toByteArray()); ui->leftPanel->restorePanelState(s.value(KEY_LPANEL_STATE).toByteArray()); ui->rightPanel->restorePanelGeometry(s.value(KEY_RPANEL_GEOMETRY).toByteArray()); ui->rightPanel->restorePanelState(s.value(KEY_RPANEL_STATE).toByteArray()); ui->_commandLine->addItems(s.value(KEY_LAST_COMMANDS_EXECUTED).toStringList()); ui->_commandLine->lineEdit()->clear(); show(); if ((windowState() & Qt::WindowFullScreen) != 0) ui->actionFull_screen_mode->setChecked(true); const Panel lastActivePanel = (Panel)s.value(KEY_LAST_ACTIVE_PANEL, LeftPanel).toInt(); if (lastActivePanel == LeftPanel) ui->leftPanel->setFocusToFileList(); else ui->rightPanel->setFocusToFileList(); } void CMainWindow::initButtons() { connect(ui->btnView, &QPushButton::clicked, this, &CMainWindow::viewFile); _shortcuts.push_back(std::make_shared<QShortcut>(QKeySequence("F3"), this, SLOT(viewFile()), nullptr, Qt::WidgetWithChildrenShortcut)); connect(ui->btnEdit, &QPushButton::clicked, this, &CMainWindow::editFile); _shortcuts.push_back(std::make_shared<QShortcut>(QKeySequence("F4"), this, SLOT(editFile()), nullptr, Qt::WidgetWithChildrenShortcut)); connect(ui->btnCopy, &QPushButton::clicked, this, &CMainWindow::copySelectedFiles); _shortcuts.push_back(std::make_shared<QShortcut>(QKeySequence("F5"), this, SLOT(copySelectedFiles()), nullptr, Qt::WidgetWithChildrenShortcut)); connect(ui->btnMove, &QPushButton::clicked, this, &CMainWindow::moveSelectedFiles); _shortcuts.push_back(std::make_shared<QShortcut>(QKeySequence("F6"), this, SLOT(moveSelectedFiles()), nullptr, Qt::WidgetWithChildrenShortcut)); connect(ui->btnNewFolder, &QPushButton::clicked, this, &CMainWindow::createFolder); _shortcuts.push_back(std::make_shared<QShortcut>(QKeySequence("F7"), this, SLOT(createFolder()), nullptr, Qt::WidgetWithChildrenShortcut)); _shortcuts.push_back(std::make_shared<QShortcut>(QKeySequence("Shift+F7"), this, SLOT(createFile()), nullptr, Qt::WidgetWithChildrenShortcut)); connect(ui->btnDelete, &QPushButton::clicked, this, &CMainWindow::deleteFiles); connect(ui->btnDelete, &QPushButton::customContextMenuRequested, this, &CMainWindow::showRecycleBInContextMenu); _shortcuts.push_back(std::make_shared<QShortcut>(QKeySequence("F8"), this, SLOT(deleteFiles()), nullptr, Qt::WidgetWithChildrenShortcut)); _shortcuts.push_back(std::make_shared<QShortcut>(QKeySequence("Delete"), this, SLOT(deleteFiles()), nullptr, Qt::WidgetWithChildrenShortcut)); #ifdef __APPLE__ _shortcuts.push_back(std::make_shared<QShortcut>(QKeySequence(Qt::CTRL + Qt::Key_Backspace), this, SLOT(deleteFiles()), nullptr, Qt::WidgetWithChildrenShortcut)); #endif _shortcuts.push_back(std::make_shared<QShortcut>(QKeySequence("Shift+F8"), this, SLOT(deleteFilesIrrevocably()), nullptr, Qt::WidgetWithChildrenShortcut)); _shortcuts.push_back(std::make_shared<QShortcut>(QKeySequence("Shift+Delete"), this, SLOT(deleteFilesIrrevocably()), nullptr, Qt::WidgetWithChildrenShortcut)); // Command line ui->_commandLine->setSelectPreviousItemShortcut(QKeySequence("Ctrl+E")); _shortcuts.push_back(std::make_shared<QShortcut>(QKeySequence("Ctrl+E"), this, SLOT(selectPreviousCommandInTheCommandLine()), nullptr, Qt::WidgetWithChildrenShortcut)); } void CMainWindow::initActions() { connect(ui->actionRefresh, &QAction::triggered, this, &CMainWindow::refresh); connect(ui->actionFind, &QAction::triggered, this, &CMainWindow::findFiles); connect(ui->actionCopy_current_item_s_path_to_clipboard, &QAction::triggered, this, [this]() { _controller->copyCurrentItemToClipboard(); }); ui->actionExit->setShortcut(QKeySequence::Quit); connect(ui->actionExit, &QAction::triggered, qApp, &QApplication::closeAllWindows); connect(ui->actionOpen_Console_Here, &QAction::triggered, [this]() { _controller->openTerminal(_currentFileList->currentDir()); }); connect(ui->actionOpen_Admin_console_here, &QAction::triggered, [this]() { _controller->openTerminal(_currentFileList->currentDir(), true); }); ui->action_Show_hidden_files->setChecked(CSettings().value(KEY_INTERFACE_SHOW_HIDDEN_FILES, true).toBool()); connect(ui->action_Show_hidden_files, &QAction::triggered, this, &CMainWindow::showHiddenFiles); connect(ui->actionShowAllFiles, &QAction::triggered, this, &CMainWindow::showAllFilesFromCurrentFolderAndBelow); connect(ui->action_Settings, &QAction::triggered, this, &CMainWindow::openSettingsDialog); connect(ui->actionCalculate_occupied_space, &QAction::triggered, this, &CMainWindow::calculateOccupiedSpace); connect(ui->actionQuick_view, &QAction::triggered, this, &CMainWindow::toggleQuickView); connect(ui->action_Invert_selection, &QAction::triggered, this, &CMainWindow::invertSelection); connect(ui->actionFull_screen_mode, &QAction::toggled, this, &CMainWindow::toggleFullScreenMode); connect(ui->actionTablet_mode, &QAction::toggled, this, &CMainWindow::toggleTabletMode); connect(ui->action_Check_for_updates, &QAction::triggered, this, &CMainWindow::checkForUpdates); connect(ui->actionAbout, &QAction::triggered, this, &CMainWindow::about); } // For manual focus management void CMainWindow::tabKeyPressed() { _otherFileList->setFocusToFileList(); } bool CMainWindow::copyFiles(const std::vector<CFileSystemObject> & files, const QString & destDir) { if (files.empty() || destDir.isEmpty()) return false; // Fix for #91 raise(); activateWindow(); const QString destPath = files.size() == 1 && files.front().isFile() ? cleanPath(destDir % nativeSeparator() % files.front().fullName()) : destDir; CFileOperationConfirmationPrompt prompt(tr("Copy files"), tr("Copy %1 %2 to").arg(files.size()).arg(files.size() > 1 ? "files" : "file"), toNativeSeparators(destPath), this); if (CSettings().value(KEY_OPERATIONS_ASK_FOR_COPY_MOVE_CONFIRMATION, true).toBool()) { if (prompt.exec() != QDialog::Accepted) return false; } CCopyMoveDialog * dialog = new CCopyMoveDialog(operationCopy, files, toPosixSeparators(prompt.text()), this); connect(this, &CMainWindow::closed, dialog, &CCopyMoveDialog::deleteLater); dialog->show(); return true; } bool CMainWindow::moveFiles(const std::vector<CFileSystemObject> & files, const QString & destDir) { if (files.empty() || destDir.isEmpty()) return false; // Fix for #91 raise(); activateWindow(); CFileOperationConfirmationPrompt prompt(tr("Move files"), tr("Move %1 %2 to").arg(files.size()).arg(files.size() > 1 ? "files" : "file"), toNativeSeparators(destDir), this); if (CSettings().value(KEY_OPERATIONS_ASK_FOR_COPY_MOVE_CONFIRMATION, true).toBool()) { if (prompt.exec() != QDialog::Accepted) return false; } CCopyMoveDialog * dialog = new CCopyMoveDialog(operationMove, files, toPosixSeparators(prompt.text()), this); connect(this, &CMainWindow::closed, dialog, &CCopyMoveDialog::deleteLater); dialog->show(); return true; } void CMainWindow::closeEvent(QCloseEvent *e) { if (e->type() == QCloseEvent::Close) { CSettings s; s.setValue(KEY_SPLITTER_SIZES, ui->splitter->saveState()); s.setValue(KEY_LPANEL_GEOMETRY, ui->leftPanel->savePanelGeometry()); s.setValue(KEY_RPANEL_GEOMETRY, ui->rightPanel->savePanelGeometry()); s.setValue(KEY_LPANEL_STATE, ui->leftPanel->savePanelState()); s.setValue(KEY_RPANEL_STATE, ui->rightPanel->savePanelState()); emit closed(); // Is used to close all child windows } QMainWindow::closeEvent(e); } bool CMainWindow::eventFilter(QObject *watched, QEvent *event) { if (watched == ui->_commandLine && event->type() == QEvent::KeyPress) { auto keyEvent = static_cast<QKeyEvent*>(event); if (keyEvent->key() == Qt::Key_Escape) clearCommandLineAndRestoreFocus(); } return QMainWindow::eventFilter(watched, event); } void CMainWindow::itemActivated(qulonglong hash, CPanelWidget *panel) { const auto result = _controller->itemHashExists(panel->panelPosition(), hash) ? _controller->itemActivated(hash, panel->panelPosition()) : FileOperationResultCode::ObjectDoesntExist; switch (result) { case FileOperationResultCode::ObjectDoesntExist: QMessageBox(QMessageBox::Warning, tr("Error"), tr("The file doesn't exist.")).exec(); break; case FileOperationResultCode::Fail: QMessageBox(QMessageBox::Critical, tr("Error"), tr("Failed to launch %1").arg(_controller->itemByHash(panel->panelPosition(), hash).fullAbsolutePath())).exec(); break; case FileOperationResultCode::DirNotAccessible: QMessageBox(QMessageBox::Critical, tr("No access"), tr("This item is not accessible.")).exec(); break; default: break; } } void CMainWindow::currentPanelChanged(const Panel panel) { if (panel == RightPanel) { _currentFileList = _rightPanelDisplayController.panelWidget(); _otherFileList = _leftPanelDisplayController.panelWidget(); } else if (panel == LeftPanel) { _currentFileList = _leftPanelDisplayController.panelWidget(); _otherFileList = _rightPanelDisplayController.panelWidget(); } else assert_unconditional_r("Invalid \'panel\' argument"); if (!_currentFileList) { _commandLineCompleter.setModel(nullptr); return; } _controller->activePanelChanged(_currentFileList->panelPosition()); CSettings().setValue(KEY_LAST_ACTIVE_PANEL, _currentFileList->panelPosition()); ui->fullPath->setText(_controller->panel(_currentFileList->panelPosition()).currentDirPathNative()); CPluginEngine::get().currentPanelChanged(_currentFileList->panelPosition()); _commandLineCompleter.setModel(_currentFileList->sortModel()); } void CMainWindow::uiThreadTimerTick() { if (_controller) _controller->uiThreadTimerTick(); } // Window title management (#143) void CMainWindow::updateWindowTitleWithCurrentFolderNames() { QString leftPanelDirName = _controller->panel(LeftPanel).currentDirName(); if (leftPanelDirName.length() > 1 && leftPanelDirName.endsWith('/')) leftPanelDirName.chop(1); QString rightPanelDirName = _controller->panel(RightPanel).currentDirName(); if (rightPanelDirName.length() > 1 && rightPanelDirName.endsWith('/')) rightPanelDirName.chop(1); setWindowTitle('[' % leftPanelDirName % "] / [" % rightPanelDirName % ']'); } void CMainWindow::splitterContextMenuRequested(QPoint pos) { const QPoint globalPos = dynamic_cast<QWidget*>(sender())->mapToGlobal(pos); QMenu menu; menu.addAction("50%"); QAction * selectedItem = menu.exec(globalPos); if (selectedItem) { const int width = (ui->leftPanel->width() + ui->rightPanel->width()) / 2; QList<int> sizes; sizes.push_back(width); sizes.push_back(width); ui->splitter->setSizes(sizes); } } void CMainWindow::copySelectedFiles() { if (_currentFileList && _otherFileList) // Some algorithms rely on trailing slash for distinguishing between files and folders for non-existent items copyFiles(_controller->items(_currentFileList->panelPosition(), _currentFileList->selectedItemsHashes()), _otherFileList->currentDir()); } void CMainWindow::moveSelectedFiles() { if (_currentFileList && _otherFileList) // Some algorithms rely on trailing slash for distinguishing between files and folders for non-existent items moveFiles(_controller->items(_currentFileList->panelPosition(), _currentFileList->selectedItemsHashes()), _otherFileList->currentDir()); } void CMainWindow::deleteFiles() { if (!_currentFileList) return; #if defined _WIN32 || defined __APPLE__ auto items = _controller->items(_currentFileList->panelPosition(), _currentFileList->selectedItemsHashes()); std::vector<std::wstring> paths; paths.reserve(items.size()); for (auto& item : items) paths.emplace_back(toNativeSeparators(item.fullAbsolutePath()).toStdWString()); if (paths.empty()) return; #ifdef _WIN32 auto windowHandle = (void*)winId(); #else void* windowHandle = nullptr; #endif _controller->execOnWorkerThread([=]() { if (!OsShell::deleteItems(paths, true, windowHandle)) _controller->execOnUiThread([this]() { QMessageBox::warning(this, tr("Error deleting items"), tr("Failed to delete the selected items")); }); }); #else deleteFilesIrrevocably(); #endif } void CMainWindow::deleteFilesIrrevocably() { if (!_currentFileList) return; auto items = _controller->items(_currentFileList->panelPosition(), _currentFileList->selectedItemsHashes()); if (items.empty()) return; #ifdef _WIN32 std::vector<std::wstring> paths; paths.reserve(items.size()); for (auto& item : items) paths.emplace_back(toNativeSeparators(item.fullAbsolutePath()).toStdWString()); _controller->execOnWorkerThread([=]() { if (!OsShell::deleteItems(paths, false, (void*)winId())) _controller->execOnUiThread([this]() { QMessageBox::warning(this, tr("Error deleting items"), tr("Failed to delete the selected items")); }); }); #else if (QMessageBox::question(this, tr("Are you sure?"), tr("Do you want to delete the selected files and folders completely?"), QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) { CDeleteProgressDialog * dialog = new CDeleteProgressDialog(items, _otherFileList->currentDir(), this); connect(this, &CMainWindow::closed, dialog, &CDeleteProgressDialog::deleteLater); dialog->show(); } #endif } void CMainWindow::createFolder() { if (!_currentFileList) return; const auto currentItem = _currentFileList->currentItemHash() != 0 ? _controller->itemByHash(_currentFileList->panelPosition(), _currentFileList->currentItemHash()) : CFileSystemObject(); const QString currentItemName = !currentItem.isCdUp() ? currentItem.fullName() : QString(); QInputDialog dialog(this); dialog.setWindowIcon(QFileIconProvider().icon(QFileIconProvider::Folder)); dialog.setWindowTitle(tr("New folder")); dialog.setLabelText(tr("Enter the name for the new directory")); dialog.setTextValue(currentItemName); const QString dirName = dialog.exec() == QDialog::Accepted ? dialog.textValue() : QString();// QInputDialog::getText(this, tr("New folder"), tr("Enter the name for the new directory"), QLineEdit::Normal, currentItemName); if (dirName.isEmpty()) return; const auto result = _controller->createFolder(_currentFileList->currentDir(), toPosixSeparators(dirName)); if (result == FileOperationResultCode::TargetAlreadyExists) QMessageBox::warning(this, tr("Item already exists"), tr("The folder %1 already exists.").arg(dirName)); else if (result != FileOperationResultCode::Ok) QMessageBox::warning(this, tr("Failed to create item"), tr("Failed to create the folder %1").arg(dirName)); } void CMainWindow::createFile() { if (!_currentFileList) return; const auto currentItem = _currentFileList->currentItemHash() != 0 ? _controller->itemByHash(_currentFileList->panelPosition(), _currentFileList->currentItemHash()) : CFileSystemObject(); const QString currentItemName = !currentItem.isCdUp() ? currentItem.fullName() : QString(); QInputDialog dialog(this); dialog.setWindowIcon(QFileIconProvider().icon(QFileIconProvider::File)); dialog.setWindowTitle(tr("New file")); dialog.setLabelText(tr("Enter the name for the new file")); dialog.setTextValue(currentItemName); const QString fileName = dialog.exec() == QDialog::Accepted ? dialog.textValue() : QString(); if (fileName.isEmpty()) return; const auto result = _controller->createFile(_currentFileList->currentDir(), fileName); if (result == FileOperationResultCode::TargetAlreadyExists) QMessageBox::warning(this, tr("Item already exists"), tr("The file %1 already exists.").arg(fileName)); else if (result != FileOperationResultCode::Ok) QMessageBox::warning(this, tr("Failed to create item"), tr("Failed to create the file %1").arg(fileName)); } void CMainWindow::invertSelection() { if (_currentFileList) _currentFileList->invertSelection(); } // Other UI commands void CMainWindow::viewFile() { CPluginEngine::get().viewCurrentFile(); } void CMainWindow::editFile() { QString editorPath = CSettings().value(KEY_EDITOR_PATH).toString(); if (FileSystemHelpers::resolvePath(editorPath).isEmpty()) { if (QMessageBox::question(this, tr("Editor not configured"), tr("No editor program has been configured (or the specified path doesn't exist). Do you want to specify the editor now?")) == QMessageBox::Yes) { #ifdef _WIN32 const QString mask(tr("Executable files (*.exe *.cmd *.bat)")); #else const QString mask; #endif editorPath = QFileDialog::getOpenFileName(this, tr("Browse for editor program"), QString(), mask); if (editorPath.isEmpty()) return; CSettings().setValue(KEY_EDITOR_PATH, editorPath); } else return; } const QString currentFile = _currentFileList ? _controller->itemByHash(_currentFileList->panelPosition(), _currentFileList->currentItemHash()).fullAbsolutePath() : QString(); if (!currentFile.isEmpty()) { #ifdef __APPLE__ const bool started = std::system((QString("open -n \"") + CSettings().value(KEY_EDITOR_PATH).toString() + "\" --args \"" + currentFile + "\"").toUtf8().constData()) == 0; #else const bool started = QProcess::startDetached(editorPath, {currentFile}); #endif if (!started) QMessageBox::information(this, tr("Error"), tr("Cannot launch %1").arg(editorPath)); } } void CMainWindow::showRecycleBInContextMenu(QPoint pos) { const QPoint globalPos = ui->btnDelete->mapToGlobal(pos); OsShell::recycleBinContextMenu(globalPos.x(), globalPos.y(), (void*)winId()); } void CMainWindow::toggleQuickView() { if (!otherPanelDisplayController().quickViewActive()) quickViewCurrentFile(); else otherPanelDisplayController().endQuickView(); } void CMainWindow::currentItemChanged(Panel /*p*/, qulonglong /*itemHash*/) { if (otherPanelDisplayController().quickViewActive()) quickViewCurrentFile(); } void CMainWindow::toggleFullScreenMode(bool fullscreen) { if (fullscreen) showFullScreen(); else showNormal(); } void CMainWindow::toggleTabletMode(bool tabletMode) { static const int defaultFontSize = QApplication::font().pointSize(); ui->actionFull_screen_mode->toggle(); QFont f = QApplication::font(); f.setPointSize(tabletMode ? 24 : defaultFontSize); QApplication::setFont(f); auto widgets = QApplication::allWidgets(); for (auto widget : widgets) if (widget) widget->setFont(f); } bool CMainWindow::executeCommand(const QString& commandLineText) { if (!_currentFileList || commandLineText.isEmpty()) return false; OsShell::executeShellCommand(commandLineText, _currentFileList->currentDir()); QTimer::singleShot(0, [=]() {CSettings().setValue(KEY_LAST_COMMANDS_EXECUTED, ui->_commandLine->items()); }); // Saving the list AFTER the combobox actually accepts the newly added item clearCommandLineAndRestoreFocus(); return true; } void CMainWindow::selectPreviousCommandInTheCommandLine() { ui->_commandLine->selectPreviousItem(); ui->_commandLine->setFocus(); } void CMainWindow::clearCommandLineAndRestoreFocus() { ui->_commandLine->resetToLastSelected(true); _currentFileList->setFocusToFileList(); } void CMainWindow::pasteCurrentFileName() { if (_currentFileList && _currentFileList->currentItemHash() != 0) { QString textToAdd = _controller->itemByHash(_currentFileList->panelPosition(), _currentFileList->currentItemHash()).fullName(); if (textToAdd.contains(' ')) textToAdd = '\"' % textToAdd % '\"'; const QString newText = ui->_commandLine->lineEdit()->text().isEmpty() ? textToAdd : (ui->_commandLine->lineEdit()->text() % ' ' % textToAdd); ui->_commandLine->lineEdit()->setText(newText); } } void CMainWindow::pasteCurrentFilePath() { if (_currentFileList && _currentFileList->currentItemHash() != 0) { QString textToAdd = toNativeSeparators(_controller->itemByHash(_currentFileList->panelPosition(), _currentFileList->currentItemHash()).fullAbsolutePath()); if (textToAdd.contains(' ')) textToAdd = '\"' % textToAdd % '\"'; const QString newText = ui->_commandLine->lineEdit()->text().isEmpty() ? textToAdd : (ui->_commandLine->lineEdit()->text() % ' ' % textToAdd); ui->_commandLine->lineEdit()->setText(newText); } } void CMainWindow::refresh() { if (_currentFileList) _controller->refreshPanelContents(_currentFileList->panelPosition()); } void CMainWindow::findFiles() { if (!_currentFileList) return; auto selectedHashes = _currentFileList->selectedItemsHashes(true); std::vector<QString> selectedPaths; if (!selectedHashes.empty()) for (const auto hash : selectedHashes) selectedPaths.push_back(_controller->activePanel().itemByHash(hash).fullAbsolutePath()); else selectedPaths.push_back(_currentFileList->currentDir()); auto fileSearchUi = new CFilesSearchWindow(selectedPaths); connect(this, &CMainWindow::closed, fileSearchUi, &CFilesSearchWindow::close); fileSearchUi->show(); } void CMainWindow::showHiddenFiles() { CSettings().setValue(KEY_INTERFACE_SHOW_HIDDEN_FILES, ui->action_Show_hidden_files->isChecked()); _controller->refreshPanelContents(LeftPanel); _controller->refreshPanelContents(RightPanel); } void CMainWindow::showAllFilesFromCurrentFolderAndBelow() { if (_currentFileList) _controller->showAllFilesFromCurrentFolderAndBelow(_currentFileList->panelPosition()); } void CMainWindow::openSettingsDialog() { CSettingsDialog settings; settings.addSettingsPage(new CSettingsPageInterface); settings.addSettingsPage(new CSettingsPageOperations); settings.addSettingsPage(new CSettingsPageEdit); settings.addSettingsPage(new CSettingsPageOther); connect(&settings, &CSettingsDialog::settingsChanged, this, &CMainWindow::settingsChanged); settings.adjustSize(); settings.exec(); } void CMainWindow::calculateOccupiedSpace() { if (!_currentFileList) return; const FilesystemObjectsStatistics stats = _controller->calculateStatistics(_currentFileList->panelPosition(), _currentFileList->selectedItemsHashes()); if (stats.empty()) return; QMessageBox::information(this, tr("Occupied space"), tr("Statistics for the selected items(including subitems):\nFiles: %1\nFolders: %2\nOccupied space: %3"). arg(stats.files).arg(stats.folders).arg(fileSizeToString(stats.occupiedSpace))); } void CMainWindow::checkForUpdates() { CSettings().setValue(KEY_LAST_UPDATE_CHECK_TIMESTAMP, QDateTime::currentDateTime()); CUpdaterDialog(this, "https://github.com/VioletGiraffe/file-commander", VERSION_STRING).exec(); } void CMainWindow::about() { CAboutDialog(this).exec(); } void CMainWindow::settingsChanged() { _controller->settingsChanged(); ui->leftPanel->onSettingsChanged(); ui->rightPanel->onSettingsChanged(); } void CMainWindow::focusChanged(QWidget * /*old*/, QWidget * now) { if (!now) return; for (int i = 0; i < ui->leftWidget->count(); ++i) if (now == ui->leftWidget || WidgetUtils::widgetBelongsToHierarchy(now, ui->leftWidget->widget(i))) currentPanelChanged(LeftPanel); for (int i = 0; i < ui->rightWidget->count(); ++i) if (now == ui->rightWidget || WidgetUtils::widgetBelongsToHierarchy(now, ui->rightWidget->widget(i))) currentPanelChanged(RightPanel); } void CMainWindow::panelContentsChanged(Panel p, FileListRefreshCause /*operation*/) { if (_currentFileList && p == _currentFileList->panelPosition()) ui->fullPath->setText(_controller->panel(p).currentDirPathNative()); updateWindowTitleWithCurrentFolderNames(); } void CMainWindow::itemDiscoveryInProgress(Panel /*p*/, qulonglong /*itemHash*/, size_t /*progress*/, const QString& /*currentDir*/) { } void CMainWindow::initCore() { _controller = std::make_unique<CController>(); ui->leftPanel->init(_controller.get()); ui->rightPanel->init(_controller.get()); _controller->activePanelChanged((Panel)CSettings().value(KEY_LAST_ACTIVE_PANEL, LeftPanel).toInt()); connect(qApp, &QApplication::focusChanged, this, &CMainWindow::focusChanged); _controller->pluginProxy().setToolMenuEntryCreatorImplementation([this](const std::vector<CPluginProxy::MenuTree>& menuEntries) {createToolMenuEntries(menuEntries); }); // Need to load the plugins only after the menu creator has been set _controller->loadPlugins(); _currentFileList = ui->leftPanel; _otherFileList = ui->rightPanel; connect(ui->leftPanel->fileListView(), &CFileListView::ctrlEnterPressed, this, &CMainWindow::pasteCurrentFileName); connect(ui->rightPanel->fileListView(), &CFileListView::ctrlEnterPressed, this, &CMainWindow::pasteCurrentFileName); connect(ui->leftPanel->fileListView(), &CFileListView::ctrlShiftEnterPressed, this, &CMainWindow::pasteCurrentFilePath); connect(ui->rightPanel->fileListView(), &CFileListView::ctrlShiftEnterPressed, this, &CMainWindow::pasteCurrentFilePath); connect(ui->leftPanel, &CPanelWidget::currentItemChangedSignal, this, &CMainWindow::currentItemChanged); connect(ui->rightPanel, &CPanelWidget::currentItemChangedSignal, this, &CMainWindow::currentItemChanged); connect(ui->leftPanel, &CPanelWidget::itemActivated, this, &CMainWindow::itemActivated); connect(ui->rightPanel, &CPanelWidget::itemActivated, this, &CMainWindow::itemActivated); ui->leftPanel->fileListView()->addEventObserver(this); ui->rightPanel->fileListView()->addEventObserver(this); initButtons(); initActions(); ui->leftPanel->setPanelPosition(LeftPanel); ui->rightPanel->setPanelPosition(RightPanel); ui->fullPath->clear(); ui->leftWidget->setCurrentIndex(0); // PanelWidget ui->rightWidget->setCurrentIndex(0); // PanelWidget _controller->panel(LeftPanel).addPanelContentsChangedListener(this); _controller->panel(RightPanel).addPanelContentsChangedListener(this); connect(&_uiThreadTimer, &QTimer::timeout, this, &CMainWindow::uiThreadTimerTick); _uiThreadTimer.start(5); } void CMainWindow::createToolMenuEntries(const std::vector<CPluginProxy::MenuTree>& menuEntries) { QMenuBar * menu = menuBar(); if (!menu) return; static QMenu * toolMenu = nullptr; // Shouldn't have to be static, but 2 subsequent calls to this method result in "Tools" being added twice. QMenuBar needs event loop to update its children?.. // TODO: make it a class member for (auto topLevelMenu : menu->findChildren<QMenu*>()) { // TODO: make sure this plays nicely with localization (#145) if (topLevelMenu->title().remove('&') == "Tools") { toolMenu = topLevelMenu; break; } } if (!toolMenu) { // TODO: make sure this plays nicely with localization (#145) toolMenu = new QMenu("Tools"); menu->addMenu(toolMenu); } else toolMenu->addSeparator(); for (const auto& menuTree : menuEntries) addToolMenuEntriesRecursively(menuTree, toolMenu); toolMenu->addSeparator(); } void CMainWindow::addToolMenuEntriesRecursively(const CPluginProxy::MenuTree& entry, QMenu* toolMenu) { assert_r(toolMenu); QAction* action = toolMenu->addAction(entry.name); if (entry.children.empty()) { const auto handler = entry.handler; QObject::connect(action, &QAction::triggered, [handler](bool) {handler(); }); } else { for (const auto& childEntry : entry.children) addToolMenuEntriesRecursively(childEntry, toolMenu); } } CPanelDisplayController& CMainWindow::currentPanelDisplayController() { const auto panel = _controller->activePanelPosition(); if (panel == RightPanel) return _rightPanelDisplayController; else { assert_r(panel != UnknownPanel); return _leftPanelDisplayController; } } CPanelDisplayController& CMainWindow::otherPanelDisplayController() { const auto panel = _controller->activePanelPosition(); if (panel == RightPanel) return _leftPanelDisplayController; else { assert_r(panel != UnknownPanel); return _rightPanelDisplayController; } } bool CMainWindow::fileListReturnPressed() { return _currentFileList ? executeCommand(ui->_commandLine->currentText()) : false; } void CMainWindow::quickViewCurrentFile() { otherPanelDisplayController().startQuickView(CPluginEngine::get().createViewerWindowForCurrentFile()); }
/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ftpcontentidentifier.hxx,v $ * * $Revision: 1.7 $ * * last change: $Author: hr $ $Date: 2006-06-20 05:23:36 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ /************************************************************************** TODO ************************************************************************** *************************************************************************/ #ifndef _FTP_FTPCONTENTIDENTIFIER_HXX_ #define _FTP_FTPCONTENTIDENTIFIER_HXX_ #include <vector> #include "curl.hxx" #include <curl/easy.h> #include <cppuhelper/weak.hxx> #include <cppuhelper/queryinterface.hxx> #include <com/sun/star/ucb/XContentIdentifier.hpp> #include <com/sun/star/lang/XTypeProvider.hpp> #include "ftpdirp.hxx" #include "ftpurl.hxx" namespace ftp { class FTPContentProvider; class FTPContentIdentifier : public cppu::OWeakObject, public com::sun::star::lang::XTypeProvider, public com::sun::star::ucb::XContentIdentifier { public: FTPContentIdentifier(const rtl::OUString& ident); ~FTPContentIdentifier(); // XInterface virtual com::sun::star::uno::Any SAL_CALL queryInterface( const com::sun::star::uno::Type& rType ) throw( com::sun::star::uno::RuntimeException ); virtual void SAL_CALL acquire( void ) throw(); virtual void SAL_CALL release( void ) throw(); // XTypeProvider virtual com::sun::star::uno::Sequence<com::sun::star::uno::Type> SAL_CALL getTypes( ) throw( com::sun::star::uno::RuntimeException ); virtual com::sun::star::uno::Sequence<sal_Int8> SAL_CALL getImplementationId( ) throw( com::sun::star::uno::RuntimeException ); // XContentIdentifier virtual ::rtl::OUString SAL_CALL getContentIdentifier( ) throw ( com::sun::star::uno::RuntimeException ); virtual ::rtl::OUString SAL_CALL getContentProviderScheme( ) throw ( ::com::sun::star::uno::RuntimeException ); private: rtl::OUString m_ident; }; } #endif INTEGRATION: CWS changefileheader (1.7.138); FILE MERGED 2008/03/31 15:30:19 rt 1.7.138.1: #i87441# Change license header to LPGL v3. /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ftpcontentidentifier.hxx,v $ * $Revision: 1.8 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ /************************************************************************** TODO ************************************************************************** *************************************************************************/ #ifndef _FTP_FTPCONTENTIDENTIFIER_HXX_ #define _FTP_FTPCONTENTIDENTIFIER_HXX_ #include <vector> #include "curl.hxx" #include <curl/easy.h> #include <cppuhelper/weak.hxx> #include <cppuhelper/queryinterface.hxx> #include <com/sun/star/ucb/XContentIdentifier.hpp> #include <com/sun/star/lang/XTypeProvider.hpp> #include "ftpdirp.hxx" #include "ftpurl.hxx" namespace ftp { class FTPContentProvider; class FTPContentIdentifier : public cppu::OWeakObject, public com::sun::star::lang::XTypeProvider, public com::sun::star::ucb::XContentIdentifier { public: FTPContentIdentifier(const rtl::OUString& ident); ~FTPContentIdentifier(); // XInterface virtual com::sun::star::uno::Any SAL_CALL queryInterface( const com::sun::star::uno::Type& rType ) throw( com::sun::star::uno::RuntimeException ); virtual void SAL_CALL acquire( void ) throw(); virtual void SAL_CALL release( void ) throw(); // XTypeProvider virtual com::sun::star::uno::Sequence<com::sun::star::uno::Type> SAL_CALL getTypes( ) throw( com::sun::star::uno::RuntimeException ); virtual com::sun::star::uno::Sequence<sal_Int8> SAL_CALL getImplementationId( ) throw( com::sun::star::uno::RuntimeException ); // XContentIdentifier virtual ::rtl::OUString SAL_CALL getContentIdentifier( ) throw ( com::sun::star::uno::RuntimeException ); virtual ::rtl::OUString SAL_CALL getContentProviderScheme( ) throw ( ::com::sun::star::uno::RuntimeException ); private: rtl::OUString m_ident; }; } #endif
// Copyright (C) Endpoints Server Proxy Authors // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS // OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY // OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF // SUCH DAMAGE. // //////////////////////////////////////////////////////////////////////////////// // #include "src/api_manager/auth/lib/auth_jwt_validator.h" // Implementation of JWT token verification. // Support public keys in x509 format or JWK (Json Web Keys). // -- Sample x509 keys // { // "8f3e950b309186540c314ecf348bb14f1784d79d": "-----BEGIN // CERTIFICATE-----\nMIIDHDCCAgSgAwIBAgIIYJnxRhkHEz8wDQYJKoZIhvcNAQEFBQAwMTEvMC0GA1UE\nAxMmc2VjdXJldG9rZW4uc3lzdGVtLmdzZXJ2aWNlYWNjb3VudC5jb20wHhcNMTUw\nNjE2MDEwMzQxWhcNMTUwNjE3MTQwMzQxWjAxMS8wLQYDVQQDEyZzZWN1cmV0b2tl\nbi5zeXN0ZW0uZ3NlcnZpY2VhY2NvdW50LmNvbTCCASIwDQYJKoZIhvcNAQEBBQAD\nggEPADCCAQoCggEBAMNKd/jkdD+ifIw806pawXZo656ycjL1KB/kUJbPopTzKKxZ\nR/eYJpd5BZIZPnWbXGvoY2kGne8jYJptQLLHr18u7TDVMpnh41jvLWYHXJv8Zd/W\n1HZk4t5mm4+JzZ2WUAx881aiEieO7/cMSIT3VC2I98fMFuEJ8jAWUDWY3KzHsXp0\nlj5lJknFCiESQ8s+UxFYHF/EgS8S2eJBvs2unq1a4NVan/GupA1OB5LrlFXm09Vt\na+dB4gulBrPh0/AslRd36uiXLRFnvAr+EF25WyZsUcq0ANCFx1Rd5z3Fv/5zC9hw\n3EeHEpc+NgovzPJ+IDHfqiU4BLTPgT70DYeLHUcCAwEAAaM4MDYwDAYDVR0TAQH/\nBAIwADAOBgNVHQ8BAf8EBAMCB4AwFgYDVR0lAQH/BAwwCgYIKwYBBQUHAwIwDQYJ\nKoZIhvcNAQEFBQADggEBAK2b2Mw5W0BtXS+onaKyyvC9O2Ysh7gTjjOGTVaTpYaB\nDg2vDgqFHM5xeYwMUf8O163rZz4R/DusZ5GsNav9BSsco9VsaIp5oIuy++tepnVN\niAdzK/bH/mo6w0s/+q46v3yhSE2Yd9WzKS9eSfQ6Yw/6y1rCgygTIVsdtKwN2u9L\nXj3RQGcHk7tgrICETqeMULZWMJQG2webNAu8bqkONgo+JP54QNVCzWgCznbCbmOR\nExlMusHMG60j8CxmMG/WLUhX+46m5HxVVx29AH8RhqpwmeFs17QXpGjOMW+ZL/Vf\nwmtv14KGfeX0z2A2iQAP5w6R1r6c+HWizj80mXHWI5U=\n-----END // CERTIFICATE-----\n", // "0f980915096a38d8de8d7398998c7fb9152e14fc": "-----BEGIN // CERTIFICATE-----\nMIIDHDCCAgSgAwIBAgIIVhHsCCeHFBowDQYJKoZIhvcNAQEFBQAwMTEvMC0GA1UE\nAxMmc2VjdXJldG9rZW4uc3lzdGVtLmdzZXJ2aWNlYWNjb3VudC5jb20wHhcNMTUw\nNjE3MDA0ODQxWhcNMTUwNjE4MTM0ODQxWjAxMS8wLQYDVQQDEyZzZWN1cmV0b2tl\nbi5zeXN0ZW0uZ3NlcnZpY2VhY2NvdW50LmNvbTCCASIwDQYJKoZIhvcNAQEBBQAD\nggEPADCCAQoCggEBAKbpeArSNTeYN977uD7GxgFhjghjsTFAq52IW04BdoXQmT9G\nP38s4q06UKGjaZbvEQmdxS+IX2BvswHxiOOgA210C4vRIBu6k1fAnt4JYBy1QHf8\n6C4K9cArp5Sx7/NJcTyu0cj/Ce1fi2iKcvuaQG7+e6VsERWjCFoUHbBohx9a92ch\nMVzQU3Bp8Ix6err6gsxxX8AcrgTN9Ux1Z2x6Ahd/x6Id2HkP8N4dGq72ksk1T9y6\n+Q8LmCzgILSyKvtVVW9G44neFDQvcvJyQljfM996b03yur4XRBs3dPS9AyJlGuN3\nagxBLwM2ieXyM73Za8khlR8PJMUcy4vA6zVHQeECAwEAAaM4MDYwDAYDVR0TAQH/\nBAIwADAOBgNVHQ8BAf8EBAMCB4AwFgYDVR0lAQH/BAwwCgYIKwYBBQUHAwIwDQYJ\nKoZIhvcNAQEFBQADggEBAJyWqYryl4K/DS0RCD66V4v8pZ5ja80Dr/dp8U7cH3Xi\nxHfCqtR5qmKZC48CHg4OPD9WSiVYFsDGLJn0KGU85AXghqcMSJN3ffABNMZBX5a6\nQGFjnvL4b2wZGgqXdaxstJ6pnaM6lQ5J6ZwFTMf0gaeo+jkwx9ENPRLudD5Mf91z\nLvLdp+gRWAlZ3Avo1YTG916kMnGRRwNJ7xgy1YSsEOUzzsNlQWca/XdGmj1I3BW/\nimaI/QRPePs3LlpPVtgu5jvOqyRpaNaYNQU7ki+jdEU4ZDOAvteqd5svXitfpB+a\nx5Bj4hUbZhw2U9AMMDmknhH4w3JKeKYGcdQrO/qVWFQ=\n-----END // CERTIFICATE-----\n" // } // // -- Sample JWK keys // { // "keys": [ // { // "kty": "RSA", // "alg": "RS256", // "use": "sig", // "kid": "62a93512c9ee4c7f8067b5a216dade2763d32a47", // "n": // "0YWnm_eplO9BFtXszMRQNL5UtZ8HJdTH2jK7vjs4XdLkPW7YBkkm_2xNgcaVpkW0VT2l4mU3KftR-6s3Oa5Rnz5BrWEUkCTVVolR7VYksfqIB2I_x5yZHdOiomMTcm3DheUUCgbJRv5OKRnNqszA4xHn3tA3Ry8VO3X7BgKZYAUh9fyZTFLlkeAh0-bLK5zvqCmKW5QgDIXSxUTJxPjZCgfx1vmAfGqaJb-nvmrORXQ6L284c73DUL7mnt6wj3H6tVqPKA27j56N0TB1Hfx4ja6Slr8S4EB3F1luYhATa1PKUSH8mYDW11HolzZmTQpRoLV8ZoHbHEaTfqX_aYahIw", // "e": "AQAB" // }, // { // "kty": "RSA", // "alg": "RS256", // "use": "sig", // "kid": "b3319a147514df7ee5e4bcdee51350cc890cc89e", // "n": // "qDi7Tx4DhNvPQsl1ofxxc2ePQFcs-L0mXYo6TGS64CY_2WmOtvYlcLNZjhuddZVV2X88m0MfwaSA16wE-RiKM9hqo5EY8BPXj57CMiYAyiHuQPp1yayjMgoE1P2jvp4eqF-BTillGJt5W5RuXti9uqfMtCQdagB8EC3MNRuU_KdeLgBy3lS3oo4LOYd-74kRBVZbk2wnmmb7IhP9OoLc1-7-9qU1uhpDxmE6JwBau0mDSwMnYDS4G_ML17dC-ZDtLd1i24STUw39KH0pcSdfFbL2NtEZdNeam1DDdk0iUtJSPZliUHJBI_pj8M-2Mn_oA8jBuI8YKwBqYkZCN1I95Q", // "e": "AQAB" // } // ] // } extern "C" { #include <grpc/support/alloc.h> #include <grpc/support/log.h> } #include "grpc_internals.h" #include <openssl/hmac.h> #include <openssl/pem.h> #include <cstring> #include <set> #include <string> #include "src/api_manager/auth/lib/json_util.h" using std::string; using std::chrono::system_clock; using ::google::protobuf::util::error::Code; namespace google { namespace api_manager { namespace auth { namespace { // JOSE header. see http://tools.ietf.org/html/rfc7515#section-4 struct JoseHeader { const char *alg; const char *kid; }; // An implementation of JwtValidator, hold ALL allocated memory data. class JwtValidatorImpl : public JwtValidator { public: JwtValidatorImpl(const char *jwt, size_t jwt_len); Status Parse(UserInfo *user_info); Status VerifySignature(const char *pkey, size_t pkey_len); system_clock::time_point &GetExpirationTime() { return exp_; } ~JwtValidatorImpl(); private: // Validates given JWT with pkey. grpc_jwt_verifier_status Validate(const char *jwt, size_t jwt_len, const char *pkey, size_t pkey_len, const char *aud); grpc_jwt_verifier_status ParseImpl(); grpc_jwt_verifier_status VerifySignatureImpl(const char *pkey, size_t pkey_len); // Parses the audiences and removes the audiences from the json object. void UpdateAudience(grpc_json *json); // Creates header_ from header_json_. void CreateJoseHeader(); // Checks required fields and fills User Info from claims_. // And sets expiration time to exp_. grpc_jwt_verifier_status FillUserInfoAndSetExp(UserInfo *user_info); // Finds the public key and verifies JWT signature with it. grpc_jwt_verifier_status FindAndVerifySignature(); // Extracts the public key from x509 string (key) and sets it to pkey_. // Returns true if successful. bool ExtractPubkeyFromX509(const char *key); // Extracts the public key from a jwk key (jkey) and sets it to pkey_. // Returns true if successful. bool ExtractPubkeyFromJwk(const grpc_json *jkey); // Extracts the public key from jwk key set and verifies JWT signature with // it. grpc_jwt_verifier_status ExtractAndVerifyJwkKeys(const grpc_json *jwt_keys); // Extracts the public key from pkey_json_ and verifies JWT signature with // it. grpc_jwt_verifier_status ExtractAndVerifyX509Keys(); // Verifies signature with pkey_. grpc_jwt_verifier_status VerifyPubkey(); // Verifies RS signature. grpc_jwt_verifier_status VerifyRsSignature(const char *pkey, size_t pkey_len); // Verifies HS signature. grpc_jwt_verifier_status VerifyHsSignature(const char *pkey, size_t pkey_len); // Not owned. const char *jwt; int jwt_len; JoseHeader *header_; grpc_json *header_json_; gpr_slice header_buffer_; grpc_jwt_claims *claims_; gpr_slice sig_buffer_; gpr_slice signed_buffer_; std::set<std::string> audiences_; system_clock::time_point exp_; grpc_json *pkey_json_; gpr_slice pkey_buffer_; BIO *bio_; X509 *x509_; RSA *rsa_; EVP_PKEY *pkey_; EVP_MD_CTX *md_ctx_; }; // Gets EVP_MD mapped from an alg (algorithm string). const EVP_MD *EvpMdFromAlg(const char *alg); // Gets hash size from HS algorithm string. size_t HashSizeFromAlg(const char *alg); // Parses str into grpc_json object. Does not own buffer. grpc_json *DecodeBase64AndParseJson(const char *str, size_t len, gpr_slice *buffer); // Gets BIGNUM from b64 string, used for extracting pkey from jwk. // Result owned by rsa_. BIGNUM *BigNumFromBase64String(const char *b64); } // namespace std::unique_ptr<JwtValidator> JwtValidator::Create(const char *jwt, size_t jwt_len) { return std::unique_ptr<JwtValidator>(new JwtValidatorImpl(jwt, jwt_len)); } namespace { JwtValidatorImpl::JwtValidatorImpl(const char *jwt, size_t jwt_len) : jwt(jwt), jwt_len(jwt_len), header_(nullptr), header_json_(nullptr), claims_(nullptr), pkey_json_(nullptr), bio_(nullptr), x509_(nullptr), rsa_(nullptr), pkey_(nullptr), md_ctx_(nullptr) { header_buffer_ = gpr_empty_slice(); signed_buffer_ = gpr_empty_slice(); sig_buffer_ = gpr_empty_slice(); pkey_buffer_ = gpr_empty_slice(); } // Makes sure all data are cleaned up, both success and failure case. JwtValidatorImpl::~JwtValidatorImpl() { if (header_ != nullptr) { gpr_free(header_); } if (header_json_ != nullptr) { grpc_json_destroy(header_json_); } if (pkey_json_ != nullptr) { grpc_json_destroy(pkey_json_); } if (claims_ != nullptr) { grpc_jwt_claims_destroy(claims_); } if (!GPR_SLICE_IS_EMPTY(header_buffer_)) { gpr_slice_unref(header_buffer_); } if (!GPR_SLICE_IS_EMPTY(signed_buffer_)) { gpr_slice_unref(signed_buffer_); } if (!GPR_SLICE_IS_EMPTY(sig_buffer_)) { gpr_slice_unref(sig_buffer_); } if (!GPR_SLICE_IS_EMPTY(pkey_buffer_)) { gpr_slice_unref(pkey_buffer_); } if (bio_ != nullptr) { BIO_free(bio_); } if (x509_ != nullptr) { X509_free(x509_); } if (rsa_ != nullptr) { RSA_free(rsa_); } if (pkey_ != nullptr) { EVP_PKEY_free(pkey_); } if (md_ctx_ != nullptr) { EVP_MD_CTX_destroy(md_ctx_); } } Status JwtValidatorImpl::Parse(UserInfo *user_info) { grpc_jwt_verifier_status status = ParseImpl(); if (status == GRPC_JWT_VERIFIER_OK) { status = FillUserInfoAndSetExp(user_info); if (status == GRPC_JWT_VERIFIER_OK) { return Status::OK; } } return Status(Code::UNAUTHENTICATED, grpc_jwt_verifier_status_to_string(status)); } // Extracts and removes the audiences from the token. // This is a workaround to deal with GRPC library not accepting // multiple audiences. void JwtValidatorImpl::UpdateAudience(grpc_json *json) { grpc_json *cur; for (cur = json->child; cur != nullptr; cur = cur->next) { if (strcmp(cur->key, "aud") == 0) { if (cur->type == GRPC_JSON_ARRAY) { grpc_json *aud; for (aud = cur->child; aud != nullptr; aud = aud->next) { if (aud->type == GRPC_JSON_STRING && aud->value != nullptr) { audiences_.insert(aud->value); } } // Replaces the array of audiences with an empty string. grpc_json *prev = cur->prev; grpc_json *next = cur->next; grpc_json_destroy(cur); grpc_json *fake_audience = grpc_json_create(GRPC_JSON_STRING); fake_audience->key = "aud"; fake_audience->value = ""; fake_audience->parent = json; fake_audience->prev = prev; fake_audience->next = next; if (prev) { prev->next = fake_audience; } else { json->child = fake_audience; } if (next) { next->prev = fake_audience; } } else if (cur->type == GRPC_JSON_STRING && cur->value != nullptr) { audiences_.insert(cur->value); } return; } } } grpc_jwt_verifier_status JwtValidatorImpl::ParseImpl() { // ==================== // Basic check. // ==================== if (jwt == nullptr || jwt_len <= 0) { return GRPC_JWT_VERIFIER_BAD_FORMAT; } // ==================== // Creates Jose Header. // ==================== const char *cur = jwt; const char *dot = strchr(cur, '.'); if (dot == nullptr) { return GRPC_JWT_VERIFIER_BAD_FORMAT; } header_json_ = DecodeBase64AndParseJson(cur, dot - cur, &header_buffer_); CreateJoseHeader(); if (header_ == nullptr) { return GRPC_JWT_VERIFIER_BAD_FORMAT; } // ============================= // Creates Claims/Payload. // ============================= cur = dot + 1; dot = strchr(cur, '.'); if (dot == nullptr) { return GRPC_JWT_VERIFIER_BAD_FORMAT; } // claim_buffer is the only exception that requires deallocation for failure // case, and it is owned by claims_ for successful case. gpr_slice claims_buffer = gpr_empty_slice(); grpc_json *claims_json = DecodeBase64AndParseJson(cur, dot - cur, &claims_buffer); if (claims_json == nullptr) { if (!GPR_SLICE_IS_EMPTY(claims_buffer)) { gpr_slice_unref(claims_buffer); } return GRPC_JWT_VERIFIER_BAD_FORMAT; } UpdateAudience(claims_json); // Takes ownershp of claims_json and claims_buffer. claims_ = grpc_jwt_claims_from_json(claims_json, claims_buffer); if (claims_ == nullptr) { return GRPC_JWT_VERIFIER_BAD_FORMAT; } // Check timestamp. // Passing in its own audience to skip audience check. // Audience check should be done by the caller. grpc_jwt_verifier_status status = grpc_jwt_claims_check(claims_, grpc_jwt_claims_audience(claims_)); if (status != GRPC_JWT_VERIFIER_OK) { return status; } // ============================= // Creates Buffer for signature check // ============================= size_t signed_jwt_len = (size_t)(dot - jwt); signed_buffer_ = gpr_slice_from_copied_buffer(jwt, signed_jwt_len); if (GPR_SLICE_IS_EMPTY(signed_buffer_)) { return GRPC_JWT_VERIFIER_BAD_FORMAT; } cur = dot + 1; sig_buffer_ = grpc_base64_decode_with_len(cur, jwt_len - signed_jwt_len - 1, 1); if (GPR_SLICE_IS_EMPTY(sig_buffer_)) { return GRPC_JWT_VERIFIER_BAD_FORMAT; } return GRPC_JWT_VERIFIER_OK; } Status JwtValidatorImpl::VerifySignature(const char *pkey, size_t pkey_len) { grpc_jwt_verifier_status status = VerifySignatureImpl(pkey, pkey_len); if (status == GRPC_JWT_VERIFIER_OK) { return Status::OK; } else { return Status(Code::UNAUTHENTICATED, grpc_jwt_verifier_status_to_string(status)); } } grpc_jwt_verifier_status JwtValidatorImpl::VerifySignatureImpl( const char *pkey, size_t pkey_len) { if (jwt == nullptr || pkey == nullptr || jwt_len <= 0 || pkey_len <= 0) { return GRPC_JWT_VERIFIER_BAD_FORMAT; } if (GPR_SLICE_IS_EMPTY(signed_buffer_) || GPR_SLICE_IS_EMPTY(sig_buffer_)) { return GRPC_JWT_VERIFIER_BAD_FORMAT; } if (strncmp(header_->alg, "RS", 2) == 0) { // Asymmetric keys. return VerifyRsSignature(pkey, pkey_len); } else { // Symmetric key. return VerifyHsSignature(pkey, pkey_len); } } void JwtValidatorImpl::CreateJoseHeader() { if (header_json_ == nullptr) { return; } const char *alg = GetStringValue(header_json_, "alg"); if (alg == nullptr) { gpr_log(GPR_ERROR, "Missing alg field.", alg); return; } if (EvpMdFromAlg(alg) == nullptr) { gpr_log(GPR_ERROR, "Invalid alg field [%s].", alg); return; } header_ = reinterpret_cast<JoseHeader *>(gpr_malloc(sizeof(JoseHeader))); if (header_ == nullptr) { gpr_log(GPR_ERROR, "Jose header creation failed"); } header_->alg = alg; header_->kid = GetStringValue(header_json_, "kid"); } grpc_jwt_verifier_status JwtValidatorImpl::FindAndVerifySignature() { if (pkey_json_ == nullptr) { gpr_log(GPR_ERROR, "The public keys are empty."); return GRPC_JWT_VERIFIER_KEY_RETRIEVAL_ERROR; } if (header_ == nullptr) { gpr_log(GPR_ERROR, "JWT header is empty."); return GRPC_JWT_VERIFIER_BAD_FORMAT; } // JWK set https://tools.ietf.org/html/rfc7517#section-5. const grpc_json *jwk_keys = GetProperty(pkey_json_, "keys"); if (jwk_keys == nullptr) { // Try x509 format. return ExtractAndVerifyX509Keys(); } else { // JWK format. return ExtractAndVerifyJwkKeys(jwk_keys); } } grpc_jwt_verifier_status JwtValidatorImpl::ExtractAndVerifyX509Keys() { // Precondition (checked by caller): pkey_json_ and header_ are not nullptr. if (header_->kid != nullptr) { const char *value = GetStringValue(pkey_json_, header_->kid); if (value == nullptr) { gpr_log(GPR_ERROR, "Cannot find matching key in key set for kid=%s and alg=%s", header_->kid, header_->alg); return GRPC_JWT_VERIFIER_KEY_RETRIEVAL_ERROR; } if (!ExtractPubkeyFromX509(value)) { gpr_log(GPR_ERROR, "Failed to extract public key from X509 key (%s)", header_->kid); return GRPC_JWT_VERIFIER_KEY_RETRIEVAL_ERROR; } return VerifyPubkey(); } // If kid is not specified in the header, try all keys. If the JWT can be // validated with any of the keys, the request is successful. const grpc_json *cur; for (cur = pkey_json_->child; cur != nullptr; cur = cur->next) { if (cur->value == nullptr || !ExtractPubkeyFromX509(cur->value)) { // Failed to extract public key from X509 key. continue; } if (VerifyPubkey() == GRPC_JWT_VERIFIER_OK) { return GRPC_JWT_VERIFIER_OK; } } // header_->kid is nullptr. The JWT cannot be validated with any of the keys. // Return error. gpr_log(GPR_ERROR, "The JWT cannot be validated with any of the public keys."); return GRPC_JWT_VERIFIER_BAD_SIGNATURE; } bool JwtValidatorImpl::ExtractPubkeyFromX509(const char *key) { if (bio_ != nullptr) { BIO_free(bio_); } bio_ = BIO_new(BIO_s_mem()); if (bio_ == nullptr) { gpr_log(GPR_ERROR, "Unable to allocate a BIO object."); return false; } if (BIO_write(bio_, key, strlen(key)) <= 0) { gpr_log(GPR_ERROR, "BIO write error for key (%s).", key); return false; } if (x509_ != nullptr) { X509_free(x509_); } x509_ = PEM_read_bio_X509(bio_, nullptr, nullptr, nullptr); if (x509_ == nullptr) { gpr_log(GPR_ERROR, "Unable to parse x509 cert for key (%s).", key); return false; } if (pkey_ != nullptr) { EVP_PKEY_free(pkey_); } pkey_ = X509_get_pubkey(x509_); if (pkey_ == nullptr) { gpr_log(GPR_ERROR, "X509_get_pubkey failed"); return false; } return true; } grpc_jwt_verifier_status JwtValidatorImpl::ExtractAndVerifyJwkKeys( const grpc_json *jwk_keys) { // Precondition (checked by caller): jwk_keys and header_ are not nullptr. if (jwk_keys->type != GRPC_JSON_ARRAY) { gpr_log(GPR_ERROR, "Unexpected value type of keys property in jwks key set."); return GRPC_JWT_VERIFIER_KEY_RETRIEVAL_ERROR; } const grpc_json *jkey = nullptr; // JWK format from https://tools.ietf.org/html/rfc7518#section-6. for (jkey = jwk_keys->child; jkey != nullptr; jkey = jkey->next) { if (jkey->type != GRPC_JSON_OBJECT) continue; const char *alg = GetStringValue(jkey, "alg"); if (alg == nullptr || strcmp(alg, header_->alg) != 0) { continue; } const char *kid = GetStringValue(jkey, "kid"); if (kid == nullptr || (header_->kid != nullptr && strcmp(kid, header_->kid) != 0)) { continue; } const char *kty = GetStringValue(jkey, "kty"); if (kty == nullptr || strcmp(kty, "RSA") != 0) { gpr_log(GPR_ERROR, "Missing or unsupported key type %s.", kty); continue; } if (!ExtractPubkeyFromJwk(jkey)) { // Failed to extract public key from this Jwk key. continue; } if (header_->kid != nullptr) { return VerifyPubkey(); } else { // If kid is not specified in the header, try all keys. If the JWT can be // validated with any of the keys, the request is successful. if (VerifyPubkey() == GRPC_JWT_VERIFIER_OK) { return GRPC_JWT_VERIFIER_OK; } } } if (header_->kid != nullptr) { gpr_log(GPR_ERROR, "Cannot find matching key in key set for kid=%s and alg=%s", header_->kid, header_->alg); return GRPC_JWT_VERIFIER_KEY_RETRIEVAL_ERROR; } // header_->kid is nullptr. The JWT cannot be validated with any of the keys. // Return error. gpr_log(GPR_ERROR, "The JWT cannot be validated with any of the public keys."); return GRPC_JWT_VERIFIER_BAD_SIGNATURE; } bool JwtValidatorImpl::ExtractPubkeyFromJwk(const grpc_json *jkey) { if (rsa_ != nullptr) { RSA_free(rsa_); } rsa_ = RSA_new(); if (rsa_ == nullptr) { gpr_log(GPR_ERROR, "Could not create rsa key."); return false; } const char *rsa_n = GetStringValue(jkey, "n"); rsa_->n = rsa_n == nullptr ? nullptr : BigNumFromBase64String(rsa_n); const char *rsa_e = GetStringValue(jkey, "e"); rsa_->e = rsa_e == nullptr ? nullptr : BigNumFromBase64String(rsa_e); if (rsa_->e == nullptr || rsa_->n == nullptr) { gpr_log(GPR_ERROR, "Missing RSA public key field."); return false; } if (pkey_ != nullptr) { EVP_PKEY_free(pkey_); } pkey_ = EVP_PKEY_new(); if (EVP_PKEY_set1_RSA(pkey_, rsa_) == 0) { gpr_log(GPR_ERROR, "EVP_PKEY_ste1_RSA failed"); return false; } return true; } grpc_jwt_verifier_status JwtValidatorImpl::VerifyRsSignature(const char *pkey, size_t pkey_len) { pkey_buffer_ = gpr_slice_from_copied_buffer(pkey, pkey_len); if (GPR_SLICE_IS_EMPTY(pkey_buffer_)) { return GRPC_JWT_VERIFIER_KEY_RETRIEVAL_ERROR; } pkey_json_ = grpc_json_parse_string_with_len( reinterpret_cast<char *>(GPR_SLICE_START_PTR(pkey_buffer_)), GPR_SLICE_LENGTH(pkey_buffer_)); if (pkey_json_ == nullptr) { return GRPC_JWT_VERIFIER_KEY_RETRIEVAL_ERROR; } return FindAndVerifySignature(); } grpc_jwt_verifier_status JwtValidatorImpl::VerifyPubkey() { if (pkey_ == nullptr) { gpr_log(GPR_ERROR, "Cannot find public key."); return GRPC_JWT_VERIFIER_KEY_RETRIEVAL_ERROR; } if (md_ctx_ != nullptr) { EVP_MD_CTX_destroy(md_ctx_); } md_ctx_ = EVP_MD_CTX_create(); if (md_ctx_ == nullptr) { gpr_log(GPR_ERROR, "Could not create EVP_MD_CTX."); return GRPC_JWT_VERIFIER_BAD_SIGNATURE; } const EVP_MD *md = EvpMdFromAlg(header_->alg); GPR_ASSERT(md != nullptr); // Checked before. if (EVP_DigestVerifyInit(md_ctx_, nullptr, md, nullptr, pkey_) != 1) { gpr_log(GPR_ERROR, "EVP_DigestVerifyInit failed."); return GRPC_JWT_VERIFIER_BAD_SIGNATURE; } if (EVP_DigestVerifyUpdate(md_ctx_, GPR_SLICE_START_PTR(signed_buffer_), GPR_SLICE_LENGTH(signed_buffer_)) != 1) { gpr_log(GPR_ERROR, "EVP_DigestVerifyUpdate failed."); return GRPC_JWT_VERIFIER_BAD_SIGNATURE; } if (EVP_DigestVerifyFinal(md_ctx_, GPR_SLICE_START_PTR(sig_buffer_), GPR_SLICE_LENGTH(sig_buffer_)) != 1) { gpr_log(GPR_ERROR, "JWT signature verification failed."); return GRPC_JWT_VERIFIER_BAD_SIGNATURE; } return GRPC_JWT_VERIFIER_OK; } grpc_jwt_verifier_status JwtValidatorImpl::VerifyHsSignature(const char *pkey, size_t pkey_len) { const EVP_MD *md = EvpMdFromAlg(header_->alg); GPR_ASSERT(md != nullptr); // Checked before. pkey_buffer_ = grpc_base64_decode_with_len(pkey, pkey_len, 1); if (GPR_SLICE_IS_EMPTY(pkey_buffer_)) { gpr_log(GPR_ERROR, "Unable to decode base64 of secret"); return GRPC_JWT_VERIFIER_KEY_RETRIEVAL_ERROR; } unsigned char res[HashSizeFromAlg(header_->alg)]; unsigned int res_len = 0; HMAC(md, GPR_SLICE_START_PTR(pkey_buffer_), GPR_SLICE_LENGTH(pkey_buffer_), GPR_SLICE_START_PTR(signed_buffer_), GPR_SLICE_LENGTH(signed_buffer_), res, &res_len); if (res_len == 0) { gpr_log(GPR_ERROR, "Cannot compute HMAC from secret."); return GRPC_JWT_VERIFIER_BAD_SIGNATURE; } if (res_len != GPR_SLICE_LENGTH(sig_buffer_) || strncmp(reinterpret_cast<char *>(GPR_SLICE_START_PTR(sig_buffer_)), reinterpret_cast<char *>(res), res_len) != 0) { gpr_log(GPR_ERROR, "JWT signature verification failed."); return GRPC_JWT_VERIFIER_BAD_SIGNATURE; } return GRPC_JWT_VERIFIER_OK; } grpc_jwt_verifier_status JwtValidatorImpl::FillUserInfoAndSetExp( UserInfo *user_info) { // Required fields. const char *issuer = grpc_jwt_claims_issuer(claims_); if (issuer == nullptr) { gpr_log(GPR_ERROR, "Missing issuer field."); return GRPC_JWT_VERIFIER_BAD_FORMAT; } if (audiences_.empty()) { gpr_log(GPR_ERROR, "Missing audience field."); return GRPC_JWT_VERIFIER_BAD_FORMAT; } const char *subject = grpc_jwt_claims_subject(claims_); if (subject == nullptr) { gpr_log(GPR_ERROR, "Missing subject field."); return GRPC_JWT_VERIFIER_BAD_FORMAT; } user_info->issuer = issuer; user_info->audiences = audiences_; user_info->id = subject; // Optional field. const char *email = GetStringValue(grpc_jwt_claims_json(claims_), "email"); user_info->email = email == nullptr ? "" : email; exp_ = system_clock::from_time_t(grpc_jwt_claims_expires_at(claims_).tv_sec); return GRPC_JWT_VERIFIER_OK; } const EVP_MD *EvpMdFromAlg(const char *alg) { if (strcmp(alg, "RS256") == 0 || strcmp(alg, "HS256") == 0) { return EVP_sha256(); } else if (strcmp(alg, "RS384") == 0 || strcmp(alg, "HS384") == 0) { return EVP_sha384(); } else if (strcmp(alg, "RS512") == 0 || strcmp(alg, "HS512") == 0) { return EVP_sha512(); } else { return nullptr; } } // Gets hash byte size from HS algorithm string. size_t HashSizeFromAlg(const char *alg) { if (strcmp(alg, "HS256") == 0) { return 32; } else if (strcmp(alg, "HS384") == 0) { return 48; } else if (strcmp(alg, "HS512") == 0) { return 64; } else { return 0; } } grpc_json *DecodeBase64AndParseJson(const char *str, size_t len, gpr_slice *buffer) { grpc_json *json; *buffer = grpc_base64_decode_with_len(str, len, 1); if (GPR_SLICE_IS_EMPTY(*buffer)) { gpr_log(GPR_ERROR, "Invalid base64."); return nullptr; } json = grpc_json_parse_string_with_len( reinterpret_cast<char *>(GPR_SLICE_START_PTR(*buffer)), GPR_SLICE_LENGTH(*buffer)); if (json == nullptr) { gpr_log(GPR_ERROR, "JSON parsing error."); } return json; } BIGNUM *BigNumFromBase64String(const char *b64) { BIGNUM *result = nullptr; gpr_slice bin; if (b64 == nullptr) return nullptr; bin = grpc_base64_decode(b64, 1); if (GPR_SLICE_IS_EMPTY(bin)) { gpr_log(GPR_ERROR, "Invalid base64 for big num."); return nullptr; } result = BN_bin2bn(GPR_SLICE_START_PTR(bin), GPR_SLICE_LENGTH(bin), nullptr); gpr_slice_unref(bin); return result; } } // namespace } // namespace auth } // namespace api_manager } // namespace google Use CRYPTO_memcmp for hash comparisons. Change-Id: I3096195ab88aac9fb23942035a0b0b9c00974d0c // Copyright (C) Endpoints Server Proxy Authors // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS // OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY // OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF // SUCH DAMAGE. // //////////////////////////////////////////////////////////////////////////////// // #include "src/api_manager/auth/lib/auth_jwt_validator.h" // Implementation of JWT token verification. // Support public keys in x509 format or JWK (Json Web Keys). // -- Sample x509 keys // { // "8f3e950b309186540c314ecf348bb14f1784d79d": "-----BEGIN // CERTIFICATE-----\nMIIDHDCCAgSgAwIBAgIIYJnxRhkHEz8wDQYJKoZIhvcNAQEFBQAwMTEvMC0GA1UE\nAxMmc2VjdXJldG9rZW4uc3lzdGVtLmdzZXJ2aWNlYWNjb3VudC5jb20wHhcNMTUw\nNjE2MDEwMzQxWhcNMTUwNjE3MTQwMzQxWjAxMS8wLQYDVQQDEyZzZWN1cmV0b2tl\nbi5zeXN0ZW0uZ3NlcnZpY2VhY2NvdW50LmNvbTCCASIwDQYJKoZIhvcNAQEBBQAD\nggEPADCCAQoCggEBAMNKd/jkdD+ifIw806pawXZo656ycjL1KB/kUJbPopTzKKxZ\nR/eYJpd5BZIZPnWbXGvoY2kGne8jYJptQLLHr18u7TDVMpnh41jvLWYHXJv8Zd/W\n1HZk4t5mm4+JzZ2WUAx881aiEieO7/cMSIT3VC2I98fMFuEJ8jAWUDWY3KzHsXp0\nlj5lJknFCiESQ8s+UxFYHF/EgS8S2eJBvs2unq1a4NVan/GupA1OB5LrlFXm09Vt\na+dB4gulBrPh0/AslRd36uiXLRFnvAr+EF25WyZsUcq0ANCFx1Rd5z3Fv/5zC9hw\n3EeHEpc+NgovzPJ+IDHfqiU4BLTPgT70DYeLHUcCAwEAAaM4MDYwDAYDVR0TAQH/\nBAIwADAOBgNVHQ8BAf8EBAMCB4AwFgYDVR0lAQH/BAwwCgYIKwYBBQUHAwIwDQYJ\nKoZIhvcNAQEFBQADggEBAK2b2Mw5W0BtXS+onaKyyvC9O2Ysh7gTjjOGTVaTpYaB\nDg2vDgqFHM5xeYwMUf8O163rZz4R/DusZ5GsNav9BSsco9VsaIp5oIuy++tepnVN\niAdzK/bH/mo6w0s/+q46v3yhSE2Yd9WzKS9eSfQ6Yw/6y1rCgygTIVsdtKwN2u9L\nXj3RQGcHk7tgrICETqeMULZWMJQG2webNAu8bqkONgo+JP54QNVCzWgCznbCbmOR\nExlMusHMG60j8CxmMG/WLUhX+46m5HxVVx29AH8RhqpwmeFs17QXpGjOMW+ZL/Vf\nwmtv14KGfeX0z2A2iQAP5w6R1r6c+HWizj80mXHWI5U=\n-----END // CERTIFICATE-----\n", // "0f980915096a38d8de8d7398998c7fb9152e14fc": "-----BEGIN // CERTIFICATE-----\nMIIDHDCCAgSgAwIBAgIIVhHsCCeHFBowDQYJKoZIhvcNAQEFBQAwMTEvMC0GA1UE\nAxMmc2VjdXJldG9rZW4uc3lzdGVtLmdzZXJ2aWNlYWNjb3VudC5jb20wHhcNMTUw\nNjE3MDA0ODQxWhcNMTUwNjE4MTM0ODQxWjAxMS8wLQYDVQQDEyZzZWN1cmV0b2tl\nbi5zeXN0ZW0uZ3NlcnZpY2VhY2NvdW50LmNvbTCCASIwDQYJKoZIhvcNAQEBBQAD\nggEPADCCAQoCggEBAKbpeArSNTeYN977uD7GxgFhjghjsTFAq52IW04BdoXQmT9G\nP38s4q06UKGjaZbvEQmdxS+IX2BvswHxiOOgA210C4vRIBu6k1fAnt4JYBy1QHf8\n6C4K9cArp5Sx7/NJcTyu0cj/Ce1fi2iKcvuaQG7+e6VsERWjCFoUHbBohx9a92ch\nMVzQU3Bp8Ix6err6gsxxX8AcrgTN9Ux1Z2x6Ahd/x6Id2HkP8N4dGq72ksk1T9y6\n+Q8LmCzgILSyKvtVVW9G44neFDQvcvJyQljfM996b03yur4XRBs3dPS9AyJlGuN3\nagxBLwM2ieXyM73Za8khlR8PJMUcy4vA6zVHQeECAwEAAaM4MDYwDAYDVR0TAQH/\nBAIwADAOBgNVHQ8BAf8EBAMCB4AwFgYDVR0lAQH/BAwwCgYIKwYBBQUHAwIwDQYJ\nKoZIhvcNAQEFBQADggEBAJyWqYryl4K/DS0RCD66V4v8pZ5ja80Dr/dp8U7cH3Xi\nxHfCqtR5qmKZC48CHg4OPD9WSiVYFsDGLJn0KGU85AXghqcMSJN3ffABNMZBX5a6\nQGFjnvL4b2wZGgqXdaxstJ6pnaM6lQ5J6ZwFTMf0gaeo+jkwx9ENPRLudD5Mf91z\nLvLdp+gRWAlZ3Avo1YTG916kMnGRRwNJ7xgy1YSsEOUzzsNlQWca/XdGmj1I3BW/\nimaI/QRPePs3LlpPVtgu5jvOqyRpaNaYNQU7ki+jdEU4ZDOAvteqd5svXitfpB+a\nx5Bj4hUbZhw2U9AMMDmknhH4w3JKeKYGcdQrO/qVWFQ=\n-----END // CERTIFICATE-----\n" // } // // -- Sample JWK keys // { // "keys": [ // { // "kty": "RSA", // "alg": "RS256", // "use": "sig", // "kid": "62a93512c9ee4c7f8067b5a216dade2763d32a47", // "n": // "0YWnm_eplO9BFtXszMRQNL5UtZ8HJdTH2jK7vjs4XdLkPW7YBkkm_2xNgcaVpkW0VT2l4mU3KftR-6s3Oa5Rnz5BrWEUkCTVVolR7VYksfqIB2I_x5yZHdOiomMTcm3DheUUCgbJRv5OKRnNqszA4xHn3tA3Ry8VO3X7BgKZYAUh9fyZTFLlkeAh0-bLK5zvqCmKW5QgDIXSxUTJxPjZCgfx1vmAfGqaJb-nvmrORXQ6L284c73DUL7mnt6wj3H6tVqPKA27j56N0TB1Hfx4ja6Slr8S4EB3F1luYhATa1PKUSH8mYDW11HolzZmTQpRoLV8ZoHbHEaTfqX_aYahIw", // "e": "AQAB" // }, // { // "kty": "RSA", // "alg": "RS256", // "use": "sig", // "kid": "b3319a147514df7ee5e4bcdee51350cc890cc89e", // "n": // "qDi7Tx4DhNvPQsl1ofxxc2ePQFcs-L0mXYo6TGS64CY_2WmOtvYlcLNZjhuddZVV2X88m0MfwaSA16wE-RiKM9hqo5EY8BPXj57CMiYAyiHuQPp1yayjMgoE1P2jvp4eqF-BTillGJt5W5RuXti9uqfMtCQdagB8EC3MNRuU_KdeLgBy3lS3oo4LOYd-74kRBVZbk2wnmmb7IhP9OoLc1-7-9qU1uhpDxmE6JwBau0mDSwMnYDS4G_ML17dC-ZDtLd1i24STUw39KH0pcSdfFbL2NtEZdNeam1DDdk0iUtJSPZliUHJBI_pj8M-2Mn_oA8jBuI8YKwBqYkZCN1I95Q", // "e": "AQAB" // } // ] // } extern "C" { #include <grpc/support/alloc.h> #include <grpc/support/log.h> } #include "grpc_internals.h" #include <openssl/hmac.h> #include <openssl/pem.h> #include <cstring> #include <set> #include <string> #include "src/api_manager/auth/lib/json_util.h" using std::string; using std::chrono::system_clock; using ::google::protobuf::util::error::Code; namespace google { namespace api_manager { namespace auth { namespace { // JOSE header. see http://tools.ietf.org/html/rfc7515#section-4 struct JoseHeader { const char *alg; const char *kid; }; // An implementation of JwtValidator, hold ALL allocated memory data. class JwtValidatorImpl : public JwtValidator { public: JwtValidatorImpl(const char *jwt, size_t jwt_len); Status Parse(UserInfo *user_info); Status VerifySignature(const char *pkey, size_t pkey_len); system_clock::time_point &GetExpirationTime() { return exp_; } ~JwtValidatorImpl(); private: // Validates given JWT with pkey. grpc_jwt_verifier_status Validate(const char *jwt, size_t jwt_len, const char *pkey, size_t pkey_len, const char *aud); grpc_jwt_verifier_status ParseImpl(); grpc_jwt_verifier_status VerifySignatureImpl(const char *pkey, size_t pkey_len); // Parses the audiences and removes the audiences from the json object. void UpdateAudience(grpc_json *json); // Creates header_ from header_json_. void CreateJoseHeader(); // Checks required fields and fills User Info from claims_. // And sets expiration time to exp_. grpc_jwt_verifier_status FillUserInfoAndSetExp(UserInfo *user_info); // Finds the public key and verifies JWT signature with it. grpc_jwt_verifier_status FindAndVerifySignature(); // Extracts the public key from x509 string (key) and sets it to pkey_. // Returns true if successful. bool ExtractPubkeyFromX509(const char *key); // Extracts the public key from a jwk key (jkey) and sets it to pkey_. // Returns true if successful. bool ExtractPubkeyFromJwk(const grpc_json *jkey); // Extracts the public key from jwk key set and verifies JWT signature with // it. grpc_jwt_verifier_status ExtractAndVerifyJwkKeys(const grpc_json *jwt_keys); // Extracts the public key from pkey_json_ and verifies JWT signature with // it. grpc_jwt_verifier_status ExtractAndVerifyX509Keys(); // Verifies signature with pkey_. grpc_jwt_verifier_status VerifyPubkey(); // Verifies RS signature. grpc_jwt_verifier_status VerifyRsSignature(const char *pkey, size_t pkey_len); // Verifies HS signature. grpc_jwt_verifier_status VerifyHsSignature(const char *pkey, size_t pkey_len); // Not owned. const char *jwt; int jwt_len; JoseHeader *header_; grpc_json *header_json_; gpr_slice header_buffer_; grpc_jwt_claims *claims_; gpr_slice sig_buffer_; gpr_slice signed_buffer_; std::set<std::string> audiences_; system_clock::time_point exp_; grpc_json *pkey_json_; gpr_slice pkey_buffer_; BIO *bio_; X509 *x509_; RSA *rsa_; EVP_PKEY *pkey_; EVP_MD_CTX *md_ctx_; }; // Gets EVP_MD mapped from an alg (algorithm string). const EVP_MD *EvpMdFromAlg(const char *alg); // Gets hash size from HS algorithm string. size_t HashSizeFromAlg(const char *alg); // Parses str into grpc_json object. Does not own buffer. grpc_json *DecodeBase64AndParseJson(const char *str, size_t len, gpr_slice *buffer); // Gets BIGNUM from b64 string, used for extracting pkey from jwk. // Result owned by rsa_. BIGNUM *BigNumFromBase64String(const char *b64); } // namespace std::unique_ptr<JwtValidator> JwtValidator::Create(const char *jwt, size_t jwt_len) { return std::unique_ptr<JwtValidator>(new JwtValidatorImpl(jwt, jwt_len)); } namespace { JwtValidatorImpl::JwtValidatorImpl(const char *jwt, size_t jwt_len) : jwt(jwt), jwt_len(jwt_len), header_(nullptr), header_json_(nullptr), claims_(nullptr), pkey_json_(nullptr), bio_(nullptr), x509_(nullptr), rsa_(nullptr), pkey_(nullptr), md_ctx_(nullptr) { header_buffer_ = gpr_empty_slice(); signed_buffer_ = gpr_empty_slice(); sig_buffer_ = gpr_empty_slice(); pkey_buffer_ = gpr_empty_slice(); } // Makes sure all data are cleaned up, both success and failure case. JwtValidatorImpl::~JwtValidatorImpl() { if (header_ != nullptr) { gpr_free(header_); } if (header_json_ != nullptr) { grpc_json_destroy(header_json_); } if (pkey_json_ != nullptr) { grpc_json_destroy(pkey_json_); } if (claims_ != nullptr) { grpc_jwt_claims_destroy(claims_); } if (!GPR_SLICE_IS_EMPTY(header_buffer_)) { gpr_slice_unref(header_buffer_); } if (!GPR_SLICE_IS_EMPTY(signed_buffer_)) { gpr_slice_unref(signed_buffer_); } if (!GPR_SLICE_IS_EMPTY(sig_buffer_)) { gpr_slice_unref(sig_buffer_); } if (!GPR_SLICE_IS_EMPTY(pkey_buffer_)) { gpr_slice_unref(pkey_buffer_); } if (bio_ != nullptr) { BIO_free(bio_); } if (x509_ != nullptr) { X509_free(x509_); } if (rsa_ != nullptr) { RSA_free(rsa_); } if (pkey_ != nullptr) { EVP_PKEY_free(pkey_); } if (md_ctx_ != nullptr) { EVP_MD_CTX_destroy(md_ctx_); } } Status JwtValidatorImpl::Parse(UserInfo *user_info) { grpc_jwt_verifier_status status = ParseImpl(); if (status == GRPC_JWT_VERIFIER_OK) { status = FillUserInfoAndSetExp(user_info); if (status == GRPC_JWT_VERIFIER_OK) { return Status::OK; } } return Status(Code::UNAUTHENTICATED, grpc_jwt_verifier_status_to_string(status)); } // Extracts and removes the audiences from the token. // This is a workaround to deal with GRPC library not accepting // multiple audiences. void JwtValidatorImpl::UpdateAudience(grpc_json *json) { grpc_json *cur; for (cur = json->child; cur != nullptr; cur = cur->next) { if (strcmp(cur->key, "aud") == 0) { if (cur->type == GRPC_JSON_ARRAY) { grpc_json *aud; for (aud = cur->child; aud != nullptr; aud = aud->next) { if (aud->type == GRPC_JSON_STRING && aud->value != nullptr) { audiences_.insert(aud->value); } } // Replaces the array of audiences with an empty string. grpc_json *prev = cur->prev; grpc_json *next = cur->next; grpc_json_destroy(cur); grpc_json *fake_audience = grpc_json_create(GRPC_JSON_STRING); fake_audience->key = "aud"; fake_audience->value = ""; fake_audience->parent = json; fake_audience->prev = prev; fake_audience->next = next; if (prev) { prev->next = fake_audience; } else { json->child = fake_audience; } if (next) { next->prev = fake_audience; } } else if (cur->type == GRPC_JSON_STRING && cur->value != nullptr) { audiences_.insert(cur->value); } return; } } } grpc_jwt_verifier_status JwtValidatorImpl::ParseImpl() { // ==================== // Basic check. // ==================== if (jwt == nullptr || jwt_len <= 0) { return GRPC_JWT_VERIFIER_BAD_FORMAT; } // ==================== // Creates Jose Header. // ==================== const char *cur = jwt; const char *dot = strchr(cur, '.'); if (dot == nullptr) { return GRPC_JWT_VERIFIER_BAD_FORMAT; } header_json_ = DecodeBase64AndParseJson(cur, dot - cur, &header_buffer_); CreateJoseHeader(); if (header_ == nullptr) { return GRPC_JWT_VERIFIER_BAD_FORMAT; } // ============================= // Creates Claims/Payload. // ============================= cur = dot + 1; dot = strchr(cur, '.'); if (dot == nullptr) { return GRPC_JWT_VERIFIER_BAD_FORMAT; } // claim_buffer is the only exception that requires deallocation for failure // case, and it is owned by claims_ for successful case. gpr_slice claims_buffer = gpr_empty_slice(); grpc_json *claims_json = DecodeBase64AndParseJson(cur, dot - cur, &claims_buffer); if (claims_json == nullptr) { if (!GPR_SLICE_IS_EMPTY(claims_buffer)) { gpr_slice_unref(claims_buffer); } return GRPC_JWT_VERIFIER_BAD_FORMAT; } UpdateAudience(claims_json); // Takes ownershp of claims_json and claims_buffer. claims_ = grpc_jwt_claims_from_json(claims_json, claims_buffer); if (claims_ == nullptr) { return GRPC_JWT_VERIFIER_BAD_FORMAT; } // Check timestamp. // Passing in its own audience to skip audience check. // Audience check should be done by the caller. grpc_jwt_verifier_status status = grpc_jwt_claims_check(claims_, grpc_jwt_claims_audience(claims_)); if (status != GRPC_JWT_VERIFIER_OK) { return status; } // ============================= // Creates Buffer for signature check // ============================= size_t signed_jwt_len = (size_t)(dot - jwt); signed_buffer_ = gpr_slice_from_copied_buffer(jwt, signed_jwt_len); if (GPR_SLICE_IS_EMPTY(signed_buffer_)) { return GRPC_JWT_VERIFIER_BAD_FORMAT; } cur = dot + 1; sig_buffer_ = grpc_base64_decode_with_len(cur, jwt_len - signed_jwt_len - 1, 1); if (GPR_SLICE_IS_EMPTY(sig_buffer_)) { return GRPC_JWT_VERIFIER_BAD_FORMAT; } return GRPC_JWT_VERIFIER_OK; } Status JwtValidatorImpl::VerifySignature(const char *pkey, size_t pkey_len) { grpc_jwt_verifier_status status = VerifySignatureImpl(pkey, pkey_len); if (status == GRPC_JWT_VERIFIER_OK) { return Status::OK; } else { return Status(Code::UNAUTHENTICATED, grpc_jwt_verifier_status_to_string(status)); } } grpc_jwt_verifier_status JwtValidatorImpl::VerifySignatureImpl( const char *pkey, size_t pkey_len) { if (jwt == nullptr || pkey == nullptr || jwt_len <= 0 || pkey_len <= 0) { return GRPC_JWT_VERIFIER_BAD_FORMAT; } if (GPR_SLICE_IS_EMPTY(signed_buffer_) || GPR_SLICE_IS_EMPTY(sig_buffer_)) { return GRPC_JWT_VERIFIER_BAD_FORMAT; } if (strncmp(header_->alg, "RS", 2) == 0) { // Asymmetric keys. return VerifyRsSignature(pkey, pkey_len); } else { // Symmetric key. return VerifyHsSignature(pkey, pkey_len); } } void JwtValidatorImpl::CreateJoseHeader() { if (header_json_ == nullptr) { return; } const char *alg = GetStringValue(header_json_, "alg"); if (alg == nullptr) { gpr_log(GPR_ERROR, "Missing alg field.", alg); return; } if (EvpMdFromAlg(alg) == nullptr) { gpr_log(GPR_ERROR, "Invalid alg field [%s].", alg); return; } header_ = reinterpret_cast<JoseHeader *>(gpr_malloc(sizeof(JoseHeader))); if (header_ == nullptr) { gpr_log(GPR_ERROR, "Jose header creation failed"); } header_->alg = alg; header_->kid = GetStringValue(header_json_, "kid"); } grpc_jwt_verifier_status JwtValidatorImpl::FindAndVerifySignature() { if (pkey_json_ == nullptr) { gpr_log(GPR_ERROR, "The public keys are empty."); return GRPC_JWT_VERIFIER_KEY_RETRIEVAL_ERROR; } if (header_ == nullptr) { gpr_log(GPR_ERROR, "JWT header is empty."); return GRPC_JWT_VERIFIER_BAD_FORMAT; } // JWK set https://tools.ietf.org/html/rfc7517#section-5. const grpc_json *jwk_keys = GetProperty(pkey_json_, "keys"); if (jwk_keys == nullptr) { // Try x509 format. return ExtractAndVerifyX509Keys(); } else { // JWK format. return ExtractAndVerifyJwkKeys(jwk_keys); } } grpc_jwt_verifier_status JwtValidatorImpl::ExtractAndVerifyX509Keys() { // Precondition (checked by caller): pkey_json_ and header_ are not nullptr. if (header_->kid != nullptr) { const char *value = GetStringValue(pkey_json_, header_->kid); if (value == nullptr) { gpr_log(GPR_ERROR, "Cannot find matching key in key set for kid=%s and alg=%s", header_->kid, header_->alg); return GRPC_JWT_VERIFIER_KEY_RETRIEVAL_ERROR; } if (!ExtractPubkeyFromX509(value)) { gpr_log(GPR_ERROR, "Failed to extract public key from X509 key (%s)", header_->kid); return GRPC_JWT_VERIFIER_KEY_RETRIEVAL_ERROR; } return VerifyPubkey(); } // If kid is not specified in the header, try all keys. If the JWT can be // validated with any of the keys, the request is successful. const grpc_json *cur; for (cur = pkey_json_->child; cur != nullptr; cur = cur->next) { if (cur->value == nullptr || !ExtractPubkeyFromX509(cur->value)) { // Failed to extract public key from X509 key. continue; } if (VerifyPubkey() == GRPC_JWT_VERIFIER_OK) { return GRPC_JWT_VERIFIER_OK; } } // header_->kid is nullptr. The JWT cannot be validated with any of the keys. // Return error. gpr_log(GPR_ERROR, "The JWT cannot be validated with any of the public keys."); return GRPC_JWT_VERIFIER_BAD_SIGNATURE; } bool JwtValidatorImpl::ExtractPubkeyFromX509(const char *key) { if (bio_ != nullptr) { BIO_free(bio_); } bio_ = BIO_new(BIO_s_mem()); if (bio_ == nullptr) { gpr_log(GPR_ERROR, "Unable to allocate a BIO object."); return false; } if (BIO_write(bio_, key, strlen(key)) <= 0) { gpr_log(GPR_ERROR, "BIO write error for key (%s).", key); return false; } if (x509_ != nullptr) { X509_free(x509_); } x509_ = PEM_read_bio_X509(bio_, nullptr, nullptr, nullptr); if (x509_ == nullptr) { gpr_log(GPR_ERROR, "Unable to parse x509 cert for key (%s).", key); return false; } if (pkey_ != nullptr) { EVP_PKEY_free(pkey_); } pkey_ = X509_get_pubkey(x509_); if (pkey_ == nullptr) { gpr_log(GPR_ERROR, "X509_get_pubkey failed"); return false; } return true; } grpc_jwt_verifier_status JwtValidatorImpl::ExtractAndVerifyJwkKeys( const grpc_json *jwk_keys) { // Precondition (checked by caller): jwk_keys and header_ are not nullptr. if (jwk_keys->type != GRPC_JSON_ARRAY) { gpr_log(GPR_ERROR, "Unexpected value type of keys property in jwks key set."); return GRPC_JWT_VERIFIER_KEY_RETRIEVAL_ERROR; } const grpc_json *jkey = nullptr; // JWK format from https://tools.ietf.org/html/rfc7518#section-6. for (jkey = jwk_keys->child; jkey != nullptr; jkey = jkey->next) { if (jkey->type != GRPC_JSON_OBJECT) continue; const char *alg = GetStringValue(jkey, "alg"); if (alg == nullptr || strcmp(alg, header_->alg) != 0) { continue; } const char *kid = GetStringValue(jkey, "kid"); if (kid == nullptr || (header_->kid != nullptr && strcmp(kid, header_->kid) != 0)) { continue; } const char *kty = GetStringValue(jkey, "kty"); if (kty == nullptr || strcmp(kty, "RSA") != 0) { gpr_log(GPR_ERROR, "Missing or unsupported key type %s.", kty); continue; } if (!ExtractPubkeyFromJwk(jkey)) { // Failed to extract public key from this Jwk key. continue; } if (header_->kid != nullptr) { return VerifyPubkey(); } else { // If kid is not specified in the header, try all keys. If the JWT can be // validated with any of the keys, the request is successful. if (VerifyPubkey() == GRPC_JWT_VERIFIER_OK) { return GRPC_JWT_VERIFIER_OK; } } } if (header_->kid != nullptr) { gpr_log(GPR_ERROR, "Cannot find matching key in key set for kid=%s and alg=%s", header_->kid, header_->alg); return GRPC_JWT_VERIFIER_KEY_RETRIEVAL_ERROR; } // header_->kid is nullptr. The JWT cannot be validated with any of the keys. // Return error. gpr_log(GPR_ERROR, "The JWT cannot be validated with any of the public keys."); return GRPC_JWT_VERIFIER_BAD_SIGNATURE; } bool JwtValidatorImpl::ExtractPubkeyFromJwk(const grpc_json *jkey) { if (rsa_ != nullptr) { RSA_free(rsa_); } rsa_ = RSA_new(); if (rsa_ == nullptr) { gpr_log(GPR_ERROR, "Could not create rsa key."); return false; } const char *rsa_n = GetStringValue(jkey, "n"); rsa_->n = rsa_n == nullptr ? nullptr : BigNumFromBase64String(rsa_n); const char *rsa_e = GetStringValue(jkey, "e"); rsa_->e = rsa_e == nullptr ? nullptr : BigNumFromBase64String(rsa_e); if (rsa_->e == nullptr || rsa_->n == nullptr) { gpr_log(GPR_ERROR, "Missing RSA public key field."); return false; } if (pkey_ != nullptr) { EVP_PKEY_free(pkey_); } pkey_ = EVP_PKEY_new(); if (EVP_PKEY_set1_RSA(pkey_, rsa_) == 0) { gpr_log(GPR_ERROR, "EVP_PKEY_ste1_RSA failed"); return false; } return true; } grpc_jwt_verifier_status JwtValidatorImpl::VerifyRsSignature(const char *pkey, size_t pkey_len) { pkey_buffer_ = gpr_slice_from_copied_buffer(pkey, pkey_len); if (GPR_SLICE_IS_EMPTY(pkey_buffer_)) { return GRPC_JWT_VERIFIER_KEY_RETRIEVAL_ERROR; } pkey_json_ = grpc_json_parse_string_with_len( reinterpret_cast<char *>(GPR_SLICE_START_PTR(pkey_buffer_)), GPR_SLICE_LENGTH(pkey_buffer_)); if (pkey_json_ == nullptr) { return GRPC_JWT_VERIFIER_KEY_RETRIEVAL_ERROR; } return FindAndVerifySignature(); } grpc_jwt_verifier_status JwtValidatorImpl::VerifyPubkey() { if (pkey_ == nullptr) { gpr_log(GPR_ERROR, "Cannot find public key."); return GRPC_JWT_VERIFIER_KEY_RETRIEVAL_ERROR; } if (md_ctx_ != nullptr) { EVP_MD_CTX_destroy(md_ctx_); } md_ctx_ = EVP_MD_CTX_create(); if (md_ctx_ == nullptr) { gpr_log(GPR_ERROR, "Could not create EVP_MD_CTX."); return GRPC_JWT_VERIFIER_BAD_SIGNATURE; } const EVP_MD *md = EvpMdFromAlg(header_->alg); GPR_ASSERT(md != nullptr); // Checked before. if (EVP_DigestVerifyInit(md_ctx_, nullptr, md, nullptr, pkey_) != 1) { gpr_log(GPR_ERROR, "EVP_DigestVerifyInit failed."); return GRPC_JWT_VERIFIER_BAD_SIGNATURE; } if (EVP_DigestVerifyUpdate(md_ctx_, GPR_SLICE_START_PTR(signed_buffer_), GPR_SLICE_LENGTH(signed_buffer_)) != 1) { gpr_log(GPR_ERROR, "EVP_DigestVerifyUpdate failed."); return GRPC_JWT_VERIFIER_BAD_SIGNATURE; } if (EVP_DigestVerifyFinal(md_ctx_, GPR_SLICE_START_PTR(sig_buffer_), GPR_SLICE_LENGTH(sig_buffer_)) != 1) { gpr_log(GPR_ERROR, "JWT signature verification failed."); return GRPC_JWT_VERIFIER_BAD_SIGNATURE; } return GRPC_JWT_VERIFIER_OK; } grpc_jwt_verifier_status JwtValidatorImpl::VerifyHsSignature(const char *pkey, size_t pkey_len) { const EVP_MD *md = EvpMdFromAlg(header_->alg); GPR_ASSERT(md != nullptr); // Checked before. pkey_buffer_ = grpc_base64_decode_with_len(pkey, pkey_len, 1); if (GPR_SLICE_IS_EMPTY(pkey_buffer_)) { gpr_log(GPR_ERROR, "Unable to decode base64 of secret"); return GRPC_JWT_VERIFIER_KEY_RETRIEVAL_ERROR; } unsigned char res[HashSizeFromAlg(header_->alg)]; unsigned int res_len = 0; HMAC(md, GPR_SLICE_START_PTR(pkey_buffer_), GPR_SLICE_LENGTH(pkey_buffer_), GPR_SLICE_START_PTR(signed_buffer_), GPR_SLICE_LENGTH(signed_buffer_), res, &res_len); if (res_len == 0) { gpr_log(GPR_ERROR, "Cannot compute HMAC from secret."); return GRPC_JWT_VERIFIER_BAD_SIGNATURE; } if (res_len != GPR_SLICE_LENGTH(sig_buffer_) || CRYPTO_memcmp(reinterpret_cast<void *>(GPR_SLICE_START_PTR(sig_buffer_)), reinterpret_cast<void *>(res), res_len) != 0) { gpr_log(GPR_ERROR, "JWT signature verification failed."); return GRPC_JWT_VERIFIER_BAD_SIGNATURE; } return GRPC_JWT_VERIFIER_OK; } grpc_jwt_verifier_status JwtValidatorImpl::FillUserInfoAndSetExp( UserInfo *user_info) { // Required fields. const char *issuer = grpc_jwt_claims_issuer(claims_); if (issuer == nullptr) { gpr_log(GPR_ERROR, "Missing issuer field."); return GRPC_JWT_VERIFIER_BAD_FORMAT; } if (audiences_.empty()) { gpr_log(GPR_ERROR, "Missing audience field."); return GRPC_JWT_VERIFIER_BAD_FORMAT; } const char *subject = grpc_jwt_claims_subject(claims_); if (subject == nullptr) { gpr_log(GPR_ERROR, "Missing subject field."); return GRPC_JWT_VERIFIER_BAD_FORMAT; } user_info->issuer = issuer; user_info->audiences = audiences_; user_info->id = subject; // Optional field. const char *email = GetStringValue(grpc_jwt_claims_json(claims_), "email"); user_info->email = email == nullptr ? "" : email; exp_ = system_clock::from_time_t(grpc_jwt_claims_expires_at(claims_).tv_sec); return GRPC_JWT_VERIFIER_OK; } const EVP_MD *EvpMdFromAlg(const char *alg) { if (strcmp(alg, "RS256") == 0 || strcmp(alg, "HS256") == 0) { return EVP_sha256(); } else if (strcmp(alg, "RS384") == 0 || strcmp(alg, "HS384") == 0) { return EVP_sha384(); } else if (strcmp(alg, "RS512") == 0 || strcmp(alg, "HS512") == 0) { return EVP_sha512(); } else { return nullptr; } } // Gets hash byte size from HS algorithm string. size_t HashSizeFromAlg(const char *alg) { if (strcmp(alg, "HS256") == 0) { return 32; } else if (strcmp(alg, "HS384") == 0) { return 48; } else if (strcmp(alg, "HS512") == 0) { return 64; } else { return 0; } } grpc_json *DecodeBase64AndParseJson(const char *str, size_t len, gpr_slice *buffer) { grpc_json *json; *buffer = grpc_base64_decode_with_len(str, len, 1); if (GPR_SLICE_IS_EMPTY(*buffer)) { gpr_log(GPR_ERROR, "Invalid base64."); return nullptr; } json = grpc_json_parse_string_with_len( reinterpret_cast<char *>(GPR_SLICE_START_PTR(*buffer)), GPR_SLICE_LENGTH(*buffer)); if (json == nullptr) { gpr_log(GPR_ERROR, "JSON parsing error."); } return json; } BIGNUM *BigNumFromBase64String(const char *b64) { BIGNUM *result = nullptr; gpr_slice bin; if (b64 == nullptr) return nullptr; bin = grpc_base64_decode(b64, 1); if (GPR_SLICE_IS_EMPTY(bin)) { gpr_log(GPR_ERROR, "Invalid base64 for big num."); return nullptr; } result = BN_bin2bn(GPR_SLICE_START_PTR(bin), GPR_SLICE_LENGTH(bin), nullptr); gpr_slice_unref(bin); return result; } } // namespace } // namespace auth } // namespace api_manager } // namespace google
/* Copyright (C) 2005-2010, Thorvald Natvig <thorvald@natvig.com> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of the Mumble Developers nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "AudioInput.h" #include "AudioOutput.h" #include "ServerHandler.h" #include "MainWindow.h" #include "User.h" #include "Plugins.h" #include "Message.h" #include "Global.h" #include "NetworkConfig.h" #include "VoiceRecorder.h" #include "wavlog.h" #include <sys/time.h> // Remember that we cannot use static member classes that are not pointers, as the constructor // for AudioInputRegistrar() might be called before they are initialized, as the constructor // is called from global initialization. // Hence, we allocate upon first call. #ifdef CIRCULAR_BUFFER CircularBuffer *micBuf; CircularBuffer *speakerBuf; CircularBuffer *cleanBuf; CircularBuffer *eventBuf; static long addEchoNum = 0; static long addMicNum = 0; static long takeNum = 0; static long appendNum = 0; void *CircularBufferIO(void *threadid) { while(true) { micBuf->readToFile(); speakerBuf->readToFile(); cleanBuf->readToFile(); eventBuf->readToFile(); usleep(20000); } } #endif QMap<QString, AudioInputRegistrar *> *AudioInputRegistrar::qmNew; QString AudioInputRegistrar::current = QString(); AudioInputRegistrar::AudioInputRegistrar(const QString &n, int p) : name(n), priority(p) { if (! qmNew) qmNew = new QMap<QString, AudioInputRegistrar *>(); qmNew->insert(name,this); } AudioInputRegistrar::~AudioInputRegistrar() { qmNew->remove(name); } AudioInputPtr AudioInputRegistrar::newFromChoice(QString choice) { if (! qmNew) return AudioInputPtr(); if (!choice.isEmpty() && qmNew->contains(choice)) { g.s.qsAudioInput = choice; current = choice; return AudioInputPtr(qmNew->value(current)->create()); } choice = g.s.qsAudioInput; if (qmNew->contains(choice)) { current = choice; return AudioInputPtr(qmNew->value(choice)->create()); } AudioInputRegistrar *r = NULL; foreach(AudioInputRegistrar *air, *qmNew) if (!r || (air->priority > r->priority)) r = air; if (r) { current = r->name; return AudioInputPtr(r->create()); } return AudioInputPtr(); } bool AudioInputRegistrar::canExclusive() const { return false; } AudioInput::AudioInput() { #ifdef CIRCULAR_BUFFER micBuf = new CircularBuffer("/tmp/psMic"); speakerBuf = new CircularBuffer("/tmp/psSpeaker"); cleanBuf = new CircularBuffer("/tmp/psClean"); eventBuf = new CircularBuffer("/tmp/eventLog"); pthread_t logThread; int rc = pthread_create(&logThread, NULL, CircularBufferIO, NULL); if (rc) { fprintf(stderr, "Logging thread failed to start\n"); abort(); } #endif adjustBandwidth(g.iMaxBandwidth, iAudioQuality, iAudioFrames); g.iAudioBandwidth = getNetworkBandwidth(iAudioQuality, iAudioFrames); if (preferCELT(iAudioQuality, iAudioFrames)) umtType = MessageHandler::UDPVoiceCELTAlpha; else umtType = MessageHandler::UDPVoiceSpeex; cCodec = NULL; ceEncoder = NULL; if (umtType != MessageHandler::UDPVoiceSpeex) { iSampleRate = SAMPLE_RATE; iFrameSize = SAMPLE_RATE / 100; esSpeex = NULL; qWarning("AudioInput: %d bits/s, %d hz, %d sample CELT", iAudioQuality, iSampleRate, iFrameSize); } else { iAudioFrames /= 2; speex_bits_init(&sbBits); speex_bits_reset(&sbBits); esSpeex = speex_encoder_init(speex_lib_get_mode(SPEEX_MODEID_UWB)); speex_encoder_ctl(esSpeex,SPEEX_GET_FRAME_SIZE,&iFrameSize); speex_encoder_ctl(esSpeex,SPEEX_GET_SAMPLING_RATE,&iSampleRate); int iArg=1; speex_encoder_ctl(esSpeex,SPEEX_SET_VBR, &iArg); iArg = 0; speex_encoder_ctl(esSpeex,SPEEX_SET_VAD, &iArg); speex_encoder_ctl(esSpeex,SPEEX_SET_DTX, &iArg); float fArg=8.0; speex_encoder_ctl(esSpeex,SPEEX_SET_VBR_QUALITY, &fArg); iArg = iAudioQuality; speex_encoder_ctl(esSpeex, SPEEX_SET_VBR_MAX_BITRATE, &iArg); iArg = 5; speex_encoder_ctl(esSpeex,SPEEX_SET_COMPLEXITY, &iArg); qWarning("AudioInput: %d bits/s, %d hz, %d sample Speex-UWB", iAudioQuality, iSampleRate, iFrameSize); } iMicFreq = iSampleRate; iFrameCounter = 0; iSilentFrames = 0; iHoldFrames = 0; bResetProcessor = true; bEchoMulti = false; sppPreprocess = NULL; sesEcho = NULL; srsMic = srsEcho = NULL; iJitterSeq = 0; iMinBuffered = 1000; psMic = new short[iFrameSize]; psClean = new short[iFrameSize]; psSpeaker = NULL; iEchoChannels = iMicChannels = 0; AudioOutputPtr ao = g.ao; if (ao) { iEchoChannels = ao->getChannels(); iEchoFreq = ao->getMixerFreq(); } else { fprintf(stderr, "AudioOutput has not been initialized\n"); std::exit(1); } iEchoFilled = iMicFilled = 0; eMicFormat = eEchoFormat = SampleFloat; iMicSampleSize = iEchoSampleSize = 0; bPreviousVoice = false; pfMicInput = pfEchoInput = pfOutput = NULL; iBitrate = 0; dPeakSignal = dPeakSpeaker = dPeakMic = dPeakCleanMic = 0.0; if (g.uiSession) { // no bandwidth limit for us //setMaxBandwidth(g.iMaxBandwidth); } // hard code quality and audio frames iAudioQuality = 31900; iAudioFrames = 2; bRunning = true; connect(this, SIGNAL(doDeaf()), g.mw->qaAudioDeaf, SLOT(trigger()), Qt::QueuedConnection); } AudioInput::~AudioInput() { bRunning = false; wait(); if (ceEncoder) { cCodec->celt_encoder_destroy(ceEncoder); } else if (esSpeex) { speex_bits_destroy(&sbBits); speex_encoder_destroy(esSpeex); } foreach(short *buf, qlEchoFrames) delete [] buf; if (sppPreprocess) speex_preprocess_state_destroy(sppPreprocess); if (sesEcho) speex_echo_state_destroy(sesEcho); if (srsMic) speex_resampler_destroy(srsMic); if (srsEcho) speex_resampler_destroy(srsEcho); appendWavHeader("psMic", 1, iSampleRate); appendWavHeader("psSpeaker", 1, iSampleRate); appendWavHeader("psClean", 1, iSampleRate); delete [] psMic; delete [] psClean; delete [] psSpeaker; delete [] pfMicInput; delete [] pfEchoInput; delete [] pfOutput; } bool AudioInput::isTransmitting() const { return bPreviousVoice; }; #define IN_MIXER_FLOAT(channels) \ static void inMixerFloat##channels ( float * RESTRICT buffer, const void * RESTRICT ipt, unsigned int nsamp, unsigned int N) { \ const float * RESTRICT input = reinterpret_cast<const float *>(ipt); \ register const float m = 1.0f / static_cast<float>(channels); \ Q_UNUSED(N); \ for(unsigned int i=0;i<nsamp;++i) {\ register float v= 0.0f; \ for(unsigned int j=0;j<channels;++j) \ v += input[i*channels+j]; \ buffer[i] = v * m; \ } \ } #define IN_MIXER_SHORT(channels) \ static void inMixerShort##channels ( float * RESTRICT buffer, const void * RESTRICT ipt, unsigned int nsamp, unsigned int N) { \ const short * RESTRICT input = reinterpret_cast<const short *>(ipt); \ register const float m = 1.0f / (32768.f * static_cast<float>(channels)); \ Q_UNUSED(N); \ for(unsigned int i=0;i<nsamp;++i) {\ register float v= 0.0f; \ for(unsigned int j=0;j<channels;++j) \ v += static_cast<float>(input[i*channels+j]); \ buffer[i] = v * m; \ } \ } IN_MIXER_FLOAT(1) IN_MIXER_FLOAT(2) IN_MIXER_FLOAT(3) IN_MIXER_FLOAT(4) IN_MIXER_FLOAT(5) IN_MIXER_FLOAT(6) IN_MIXER_FLOAT(7) IN_MIXER_FLOAT(8) IN_MIXER_FLOAT(N) IN_MIXER_SHORT(1) IN_MIXER_SHORT(2) IN_MIXER_SHORT(3) IN_MIXER_SHORT(4) IN_MIXER_SHORT(5) IN_MIXER_SHORT(6) IN_MIXER_SHORT(7) IN_MIXER_SHORT(8) IN_MIXER_SHORT(N) AudioInput::inMixerFunc AudioInput::chooseMixer(const unsigned int nchan, SampleFormat sf) { inMixerFunc r = NULL; if (sf == SampleFloat) { switch (nchan) { case 1: r = inMixerFloat1; break; case 2: r = inMixerFloat2; break; case 3: r = inMixerFloat3; break; case 4: r = inMixerFloat4; break; case 5: r = inMixerFloat5; break; case 6: r = inMixerFloat6; break; case 7: r = inMixerFloat7; break; case 8: r = inMixerFloat8; break; default: r = inMixerFloatN; break; } } else { switch (nchan) { case 1: r = inMixerShort1; break; case 2: r = inMixerShort2; break; case 3: r = inMixerShort3; break; case 4: r = inMixerShort4; break; case 5: r = inMixerShort5; break; case 6: r = inMixerShort6; break; case 7: r = inMixerShort7; break; case 8: r = inMixerShort8; break; default: r = inMixerShortN; break; } } return r; } void AudioInput::initializeMixer() { int err; if (srsMic) speex_resampler_destroy(srsMic); if (srsEcho) speex_resampler_destroy(srsEcho); delete [] pfMicInput; delete [] pfEchoInput; delete [] pfOutput; if (iMicFreq != iSampleRate) srsMic = speex_resampler_init(1, iMicFreq, iSampleRate, 3, &err); iMicLength = (iFrameSize * iMicFreq) / iSampleRate; pfMicInput = new float[iMicLength]; pfOutput = new float[iFrameSize * qMax(1U,iEchoChannels)]; if (iEchoChannels > 0) { bEchoMulti = g.s.bEchoMulti; if (iEchoFreq != iSampleRate) srsEcho = speex_resampler_init(bEchoMulti ? iEchoChannels : 1, iEchoFreq, iSampleRate, 3, &err); iEchoLength = (iFrameSize * iEchoFreq) / iSampleRate; iEchoMCLength = bEchoMulti ? iEchoLength * iEchoChannels : iEchoLength; iEchoFrameSize = bEchoMulti ? iFrameSize * iEchoChannels : iFrameSize; pfEchoInput = new float[iEchoMCLength]; } else { srsEcho = NULL; pfEchoInput = NULL; } imfMic = chooseMixer(iMicChannels, eMicFormat); imfEcho = chooseMixer(iEchoChannels, eEchoFormat); iMicSampleSize = static_cast<int>(iMicChannels * ((eMicFormat == SampleFloat) ? sizeof(float) : sizeof(short))); iEchoSampleSize = static_cast<int>(iEchoChannels * ((eEchoFormat == SampleFloat) ? sizeof(float) : sizeof(short))); bResetProcessor = true; qWarning("AudioInput: Initialized mixer for %d channel %d hz mic and %d channel %d hz echo", iMicChannels, iMicFreq, iEchoChannels, iEchoFreq); } void AudioInput::addMic(const void *data, unsigned int nsamp) { #ifdef CIRCULAR_BUFFER char addBuf[200]; sprintf(addBuf, "Func: addMic, times: %ld\n", ++addMicNum); eventBuf->log(addBuf); #endif while (nsamp > 0) { unsigned int left = qMin(nsamp, iMicLength - iMicFilled); imfMic(pfMicInput + iMicFilled, data, left, iMicChannels); iMicFilled += left; nsamp -= left; if (nsamp > 0) { if (eMicFormat == SampleFloat) data = reinterpret_cast<const float *>(data) + left * iMicChannels; else data = reinterpret_cast<const short *>(data) + left * iMicChannels; } if (iMicFilled == iMicLength) { iMicFilled = 0; float *ptr = srsMic ? pfOutput : pfMicInput; if (srsMic) { spx_uint32_t inlen = iMicLength; spx_uint32_t outlen = iFrameSize; speex_resampler_process_float(srsMic, 0, pfMicInput, &inlen, pfOutput, &outlen); } const float mul = 32768.f; for (int j=0;j<iFrameSize;++j) psMic[j] = static_cast<short>(ptr[j] * mul); if (iEchoChannels > 0) { short *echo = NULL; { QMutexLocker l(&qmEcho); if (qlEchoFrames.isEmpty()) { iJitterSeq = 0; iMinBuffered = 1000; } else { #ifdef CIRCULAR_BUFFER char pbuf[200]; sprintf(pbuf, "Func: take first, list size: %d, times: %ld\n", qlEchoFrames.count(), ++takeNum); eventBuf->log(pbuf); #endif iMinBuffered = qMin(iMinBuffered, qlEchoFrames.count()); if ((iJitterSeq > 100) && (iMinBuffered > 1)) { iJitterSeq = 0; iMinBuffered = 1000; delete [] qlEchoFrames.takeFirst(); } echo = qlEchoFrames.takeFirst(); } } if (echo) { delete [] psSpeaker; psSpeaker = echo; } } encodeAudioFrame(); } } } void AudioInput::addInternalEcho(const void *data, unsigned int nsamp) { addEcho(data, nsamp); } void AudioInput::addEcho(const void *data, unsigned int nsamp) { #ifdef CIRCULAR_BUFFER char addBuf[200]; sprintf(addBuf, "Func: addEcho, times: %ld\n", ++addEchoNum); eventBuf->log(addBuf); #endif while (nsamp > 0) { unsigned int left = qMin(nsamp, iEchoLength - iEchoFilled); if (bEchoMulti) { const unsigned int samples = left * iEchoChannels; if (eEchoFormat == SampleFloat) for (unsigned int i=0;i<samples;++i) pfEchoInput[i] = reinterpret_cast<const float *>(data)[i]; else for (unsigned int i=0;i<samples;++i) pfEchoInput[i] = static_cast<float>(reinterpret_cast<const short *>(data)[i]) * (1.0f / 32768.f); } else { imfEcho(pfEchoInput + iEchoFilled, data, left, iEchoChannels); } iEchoFilled += left; nsamp -= left; if (nsamp > 0) { if (eEchoFormat == SampleFloat) data = reinterpret_cast<const float *>(data) + left * iEchoChannels; else data = reinterpret_cast<const short *>(data) + left * iEchoChannels; } if (iEchoFilled == iEchoLength) { iEchoFilled = 0; float *ptr = srsEcho ? pfOutput : pfEchoInput; if (srsEcho) { spx_uint32_t inlen = iEchoLength; spx_uint32_t outlen = iFrameSize; speex_resampler_process_interleaved_float(srsEcho, pfEchoInput, &inlen, pfOutput, &outlen); } short *outbuff = new short[iEchoFrameSize]; const float mul = 32768.f; for (unsigned int j=0;j<iEchoFrameSize;++j) outbuff[j] = static_cast<short>(ptr[j] * mul); iJitterSeq = qMin(iJitterSeq+1,10000U); QMutexLocker l(&qmEcho); if (qlEchoFrames.isEmpty()) { /* do nothing short *echo_delay = new short[iEchoFrameSize]; for (int k = 0; k < iEchoFrameSize; k++) echo_delay[k] = 0; qlEchoFrames.append(echo_delay); echo_delay = new short[iEchoFrameSize]; for (int k = 0; k < iEchoFrameSize; k++) echo_delay[k] = 0; qlEchoFrames.append(echo_delay); echo_delay = new short[iEchoFrameSize]; for (int k = 0; k < iEchoFrameSize; k++) echo_delay[k] = 0; qlEchoFrames.append(echo_delay); */ } qlEchoFrames.append(outbuff); #ifdef CIRCULAR_BUFFER char pbuf[200]; sprintf(pbuf, "Func: append frame, list size: %d, times: %ld\n", qlEchoFrames.size(), ++appendNum); eventBuf->log(pbuf); #endif } } } bool AudioInput::preferCELT(int bitrate, int frames) { return ((bitrate >= 32000) || (frames == 1)); } void AudioInput::adjustBandwidth(int bitspersec, int &bitrate, int &frames) { frames = g.s.iFramesPerPacket; bitrate = g.s.iQuality; if (bitspersec == -1) { // No limit } else { if (getNetworkBandwidth(bitrate, frames) > bitspersec) { if ((frames <= 4) && (bitspersec <= 32000)) frames = 4; else if ((frames == 1) && (bitspersec <= 64000)) frames = 2; else if ((frames == 2) && (bitspersec <= 48000)) frames = 4; if (getNetworkBandwidth(bitrate, frames) > bitspersec) { do { bitrate -= 1000; } while ((bitrate > 8000) && (getNetworkBandwidth(bitrate, frames) > bitspersec)); } } } if (bitrate <= 8000) bitrate = 8000; } void AudioInput::setMaxBandwidth(int bitspersec) { if (bitspersec == g.iMaxBandwidth) return; int frames; int bitrate; adjustBandwidth(bitspersec, bitrate, frames); g.iMaxBandwidth = bitspersec; if (bitspersec != -1) { if ((bitrate != g.s.iQuality) || (frames != g.s.iFramesPerPacket)) g.mw->msgBox(tr("Server maximum network bandwidth is only %1 kbit/s. Audio quality auto-adjusted to %2 kbit/s (%3ms)").arg(bitspersec / 1000).arg(bitrate / 1000).arg(frames*10)); } AudioInputPtr ai = g.ai; if (ai && (preferCELT(bitrate, frames) == (ai->umtType != MessageHandler::UDPVoiceSpeex))) { g.iAudioBandwidth = getNetworkBandwidth(bitrate, frames); ai->iAudioQuality = bitrate; ai->iAudioFrames = frames; return; } ai.reset(); Audio::stopInput(); Audio::startInput(); } int AudioInput::getNetworkBandwidth(int bitrate, int frames) { int overhead = 20 + 8 + 4 + 1 + 2 + (g.s.bTransmitPosition ? 12 : 0) + (NetworkConfig::TcpModeEnabled() ? 12 : 0) + frames; overhead *= (800 / frames); int bw = overhead + bitrate; return bw; } /* * FIXME: Experimental zero-latency callback-based preprocessing. extern "C" { int speex_preprocess_run_cb(SpeexPreprocessState *st, float *ft); SpeexPreprocessState *speex_preprocess_callback_init(int frame_size, int sampling_rate); }; celt_int32_t celtBack(CELTEncoder *enc, void *rawdata, celt_int32_t format, celt_int32_t bits, celt_int32_t num, void *data) { qWarning() << "CB" << enc << rawdata << format << bits << num << data; static SpeexPreprocessState *st = NULL; if (! st) { int samp = 480; int freq = 48000; celt_encoder_ctl(enc, CELT_GET_SAMPLE_RATE, &freq); celt_encoder_ctl(enc, CELT_GET_FRAME_SIZE, &samp); qWarning() << "Init" << samp << freq; st= speex_preprocess_callback_init(samp, freq); int iArg; iArg = 1; speex_preprocess_ctl(st, SPEEX_PREPROCESS_SET_VAD, &iArg); speex_preprocess_ctl(st, SPEEX_PREPROCESS_SET_AGC, &iArg); speex_preprocess_ctl(st, SPEEX_PREPROCESS_SET_DENOISE, &iArg); speex_preprocess_ctl(st, SPEEX_PREPROCESS_SET_DEREVERB, &iArg); iArg = 30000; speex_preprocess_ctl(st, SPEEX_PREPROCESS_SET_AGC_TARGET, &iArg); iArg = 30000; speex_preprocess_ctl(st, SPEEX_PREPROCESS_SET_AGC_TARGET, &iArg); float v = 30000.0f / static_cast<float>(g.s.iMinLoudness); iArg = iroundf(floorf(20.0f * log10f(v))); speex_preprocess_ctl(st, SPEEX_PREPROCESS_SET_AGC_MAX_GAIN, &iArg); iArg = g.s.iNoiseSuppress; speex_preprocess_ctl(st, SPEEX_PREPROCESS_SET_NOISE_SUPPRESS, &iArg); } qWarning() << "Call"; // int res = 1; int res = speex_preprocess_run_cb(st, (float *) rawdata); qWarning() << "Result" << res; return 1; } */ void AudioInput::encodeAudioFrame() { int iArg; ClientUser *p=ClientUser::get(g.uiSession); int i; float sum; short max; short *psSource; iFrameCounter++; if (! bRunning) return; sum=1.0f; for (i=0;i<iFrameSize;i++) sum += static_cast<float>(psMic[i] * psMic[i]); dPeakMic = qMax(20.0f*log10f(sqrtf(sum / static_cast<float>(iFrameSize)) / 32768.0f), -96.0f); max = 1; for (i=0;i<iFrameSize;i++) max = static_cast<short>(abs(psMic[i]) > max ? abs(psMic[i]) : max); dMaxMic = max; if (psSpeaker && (iEchoChannels > 0)) { sum=1.0f; for (i=0;i<iFrameSize;i++) sum += static_cast<float>(psSpeaker[i] * psSpeaker[i]); dPeakSpeaker = qMax(20.0f*log10f(sqrtf(sum / static_cast<float>(iFrameSize)) / 32768.0f), -96.0f); } else { dPeakSpeaker = 0.0; } QMutexLocker l(&qmSpeex); if (bResetProcessor) { if (sppPreprocess) speex_preprocess_state_destroy(sppPreprocess); if (sesEcho) speex_echo_state_destroy(sesEcho); sppPreprocess = speex_preprocess_state_init(iFrameSize, iSampleRate); iArg = 1; speex_preprocess_ctl(sppPreprocess, SPEEX_PREPROCESS_SET_VAD, &iArg); speex_preprocess_ctl(sppPreprocess, SPEEX_PREPROCESS_SET_AGC, &iArg); speex_preprocess_ctl(sppPreprocess, SPEEX_PREPROCESS_SET_DENOISE, &iArg); speex_preprocess_ctl(sppPreprocess, SPEEX_PREPROCESS_SET_DEREVERB, &iArg); iArg = 30000; speex_preprocess_ctl(sppPreprocess, SPEEX_PREPROCESS_SET_AGC_TARGET, &iArg); float v = 30000.0f / static_cast<float>(g.s.iMinLoudness); iArg = iroundf(floorf(20.0f * log10f(v))); speex_preprocess_ctl(sppPreprocess, SPEEX_PREPROCESS_SET_AGC_MAX_GAIN, &iArg); iArg = -60; speex_preprocess_ctl(sppPreprocess, SPEEX_PREPROCESS_SET_AGC_DECREMENT, &iArg); iArg = g.s.iNoiseSuppress; speex_preprocess_ctl(sppPreprocess, SPEEX_PREPROCESS_SET_NOISE_SUPPRESS, &iArg); if (iEchoChannels > 0) { sesEcho = speex_echo_state_init_mc(iFrameSize, iFrameSize*10, 1, bEchoMulti ? iEchoChannels : 1); iArg = iSampleRate; speex_echo_ctl(sesEcho, SPEEX_ECHO_SET_SAMPLING_RATE, &iArg); speex_preprocess_ctl(sppPreprocess, SPEEX_PREPROCESS_SET_ECHO_STATE, sesEcho); qWarning("AudioInput: ECHO CANCELLER ACTIVE"); } else { sesEcho = NULL; } bResetProcessor = false; } speex_preprocess_ctl(sppPreprocess, SPEEX_PREPROCESS_GET_AGC_GAIN, &iArg); float gainValue = static_cast<float>(iArg); iArg = g.s.iNoiseSuppress - iArg; speex_preprocess_ctl(sppPreprocess, SPEEX_PREPROCESS_SET_NOISE_SUPPRESS, &iArg); if (sesEcho && psSpeaker) { speex_echo_cancellation(sesEcho, psMic, psSpeaker, psClean); speex_preprocess_run(sppPreprocess, psClean); psSource = psClean; #ifdef CIRCULAR_BUFFER micBuf->writeToBuffer((char *)psMic, iFrameSize * sizeof(short)); speakerBuf->writeToBuffer((char *)psSpeaker, iFrameSize * sizeof(short)); cleanBuf->writeToBuffer((char *)psClean, iFrameSize * sizeof(short)); #endif } else { speex_preprocess_run(sppPreprocess, psMic); psSource = psMic; #ifdef CIRCULAR_BUFFER eventBuf->log("echoAudioFrame called without echo\n"); #endif } sum=1.0f; for (i=0;i<iFrameSize;i++) sum += static_cast<float>(psSource[i] * psSource[i]); float micLevel = sqrtf(sum / static_cast<float>(iFrameSize)); dPeakSignal = qMax(20.0f*log10f(micLevel / 32768.0f), -96.0f); spx_int32_t prob = 0; speex_preprocess_ctl(sppPreprocess, SPEEX_PREPROCESS_GET_PROB, &prob); fSpeechProb = static_cast<float>(prob) / 100.0f; // clean microphone level: peak of filtered signal attenuated by AGC gain dPeakCleanMic = qMax(dPeakSignal - gainValue, -96.0f); float level = (g.s.vsVAD == Settings::SignalToNoise) ? fSpeechProb : (1.0f + dPeakCleanMic / 96.0f); bool bIsSpeech = false; if (level > g.s.fVADmax) bIsSpeech = true; else if (level > g.s.fVADmin && bPreviousVoice) bIsSpeech = true; if (! bIsSpeech) { iHoldFrames++; if (iHoldFrames < g.s.iVoiceHold) bIsSpeech = true; } else { iHoldFrames = 0; } if (g.s.atTransmit == Settings::Continous) bIsSpeech = true; else if (g.s.atTransmit == Settings::PushToTalk) bIsSpeech = g.s.uiDoublePush && ((g.uiDoublePush < g.s.uiDoublePush) || (g.tDoublePush.elapsed() < g.s.uiDoublePush)); bIsSpeech = bIsSpeech || (g.iPushToTalk > 0); if (g.s.bMute || ((g.s.lmLoopMode != Settings::Local) && p && (p->bMute || p->bSuppress)) || g.bPushToMute || (g.iTarget < 0)) { bIsSpeech = false; } if (bIsSpeech) { iSilentFrames = 0; } else { iSilentFrames++; if (iSilentFrames > 500) iFrameCounter = 0; } if (p) { if (! bIsSpeech) p->setTalking(Settings::Passive); else if (g.iTarget == 0) p->setTalking(Settings::Talking); else p->setTalking(Settings::Shouting); } if (g.s.bPushClick && (g.s.atTransmit == Settings::PushToTalk)) { AudioOutputPtr ao = g.ao; if (bIsSpeech && ! bPreviousVoice && ao) ao->playSample(g.s.qsPushClickOn); else if (ao && !bIsSpeech && bPreviousVoice && ao) ao->playSample(g.s.qsPushClickOff); } if (! bIsSpeech && ! bPreviousVoice) { iBitrate = 0; if (g.s.iIdleTime && ! g.s.bDeaf && ((tIdle.elapsed() / 1000000ULL) > g.s.iIdleTime)) { emit doDeaf(); tIdle.restart(); } spx_int32_t increment = 0; speex_preprocess_ctl(sppPreprocess, SPEEX_PREPROCESS_SET_AGC_INCREMENT, &increment); return; } else { spx_int32_t increment = 12; speex_preprocess_ctl(sppPreprocess, SPEEX_PREPROCESS_SET_AGC_INCREMENT, &increment); } tIdle.restart(); /* int r = celt_encoder_ctl(ceEncoder, CELT_SET_POST_MDCT_CALLBACK(celtBack, NULL)); qWarning() << "Set Callback" << r; */ unsigned char buffer[512]; int len; if (umtType != MessageHandler::UDPVoiceSpeex) { CELTCodec *switchto = NULL; if ((! g.uiSession || (g.s.lmLoopMode == Settings::Local)) && (! g.qmCodecs.isEmpty())) { // Use latest for local loopback QMap<int, CELTCodec *>::const_iterator i = g.qmCodecs.constEnd(); --i; switchto = i.value(); } else { if (cCodec && bPreviousVoice) { // Currently talking, don't switch unless you must. int v = cCodec->bitstreamVersion(); if ((v == g.iCodecAlpha) || (v == g.iCodecBeta)) switchto = cCodec; } } if (! switchto) { switchto = g.qmCodecs.value(g.bPreferAlpha ? g.iCodecAlpha : g.iCodecBeta); if (! switchto) { switchto = g.qmCodecs.value(g.bPreferAlpha ? g.iCodecBeta : g.iCodecAlpha); } } if (switchto != cCodec) { if (cCodec && ceEncoder) { cCodec->celt_encoder_destroy(ceEncoder); ceEncoder = NULL; } cCodec = switchto; if (cCodec) { ceEncoder = cCodec->encoderCreate(); } } else if (cCodec && ! bPreviousVoice) { cCodec->celt_encoder_ctl(ceEncoder, CELT_RESET_STATE); } if (! cCodec) return; if (g.uiSession && g.s.lmLoopMode != Settings::Local) { int v = cCodec->bitstreamVersion(); if (v == g.iCodecAlpha) umtType = MessageHandler::UDPVoiceCELTAlpha; else if (v == g.iCodecBeta) umtType = MessageHandler::UDPVoiceCELTBeta; else { qWarning() << "Couldn't find message type for codec version" << v; return; } } cCodec->celt_encoder_ctl(ceEncoder, CELT_SET_PREDICTION(0)); cCodec->celt_encoder_ctl(ceEncoder,CELT_SET_VBR_RATE(iAudioQuality)); len = cCodec->encode(ceEncoder, psSource, buffer, qMin(iAudioQuality / 800, 127)); iBitrate = len * 100 * 8; } else { int vbr = 0; speex_encoder_ctl(esSpeex, SPEEX_GET_VBR_MAX_BITRATE, &vbr); if (vbr != iAudioQuality) { vbr = iAudioQuality; speex_encoder_ctl(esSpeex, SPEEX_SET_VBR_MAX_BITRATE, &vbr); } if (! bPreviousVoice) speex_encoder_ctl(esSpeex, SPEEX_RESET_STATE, NULL); speex_encode_int(esSpeex, psSource, &sbBits); len = speex_bits_write(&sbBits, reinterpret_cast<char *>(buffer), 127); iBitrate = len * 50 * 8; speex_bits_reset(&sbBits); } flushCheck(QByteArray(reinterpret_cast<const char *>(buffer), len), ! bIsSpeech); if (! bIsSpeech) iBitrate = 0; bPreviousVoice = bIsSpeech; } void AudioInput::flushCheck(const QByteArray &frame, bool terminator) { qlFrames << frame; if (! terminator && qlFrames.count() < iAudioFrames) return; int flags = g.iTarget; if (terminator) flags = g.iPrevTarget; if (g.s.lmLoopMode == Settings::Server) flags = 0x1f; // Server loopback flags |= (umtType << 5); char data[1024]; data[0] = static_cast<unsigned char>(flags); PacketDataStream pds(data + 1, 1023); pds << iFrameCounter - qlFrames.count(); if (terminator) qlFrames << QByteArray(); for (int i=0;i<qlFrames.count(); ++i) { const QByteArray &qba = qlFrames.at(i); unsigned char head = static_cast<unsigned char>(qba.size()); if (i < qlFrames.count() - 1) head |= 0x80; pds.append(head); pds.append(qba.constData(), qba.size()); } if (g.s.bTransmitPosition && g.p && ! g.bCenterPosition && g.p->fetch()) { pds << g.p->fPosition[0]; pds << g.p->fPosition[1]; pds << g.p->fPosition[2]; } ServerHandlerPtr sh = g.sh; if (sh) { VoiceRecorderPtr recorder(sh->recorder); if (recorder) recorder->getRecordUser().addFrame(QByteArray(data, pds.size() + 1)); } if (g.s.lmLoopMode == Settings::Local) LoopUser::lpLoopy.addFrame(QByteArray(data, pds.size() + 1)); else if (sh) sh->sendMessage(data, pds.size() + 1); qlFrames.clear(); } bool AudioInput::isAlive() const { return isRunning(); } noise suppress = 50 /* Copyright (C) 2005-2010, Thorvald Natvig <thorvald@natvig.com> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of the Mumble Developers nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "AudioInput.h" #include "AudioOutput.h" #include "ServerHandler.h" #include "MainWindow.h" #include "User.h" #include "Plugins.h" #include "Message.h" #include "Global.h" #include "NetworkConfig.h" #include "VoiceRecorder.h" #include "wavlog.h" #include <sys/time.h> // Remember that we cannot use static member classes that are not pointers, as the constructor // for AudioInputRegistrar() might be called before they are initialized, as the constructor // is called from global initialization. // Hence, we allocate upon first call. #ifdef CIRCULAR_BUFFER CircularBuffer *micBuf; CircularBuffer *speakerBuf; CircularBuffer *cleanBuf; CircularBuffer *eventBuf; static long addEchoNum = 0; static long addMicNum = 0; static long takeNum = 0; static long appendNum = 0; void *CircularBufferIO(void *threadid) { while(true) { micBuf->readToFile(); speakerBuf->readToFile(); cleanBuf->readToFile(); eventBuf->readToFile(); usleep(20000); } } #endif QMap<QString, AudioInputRegistrar *> *AudioInputRegistrar::qmNew; QString AudioInputRegistrar::current = QString(); AudioInputRegistrar::AudioInputRegistrar(const QString &n, int p) : name(n), priority(p) { if (! qmNew) qmNew = new QMap<QString, AudioInputRegistrar *>(); qmNew->insert(name,this); } AudioInputRegistrar::~AudioInputRegistrar() { qmNew->remove(name); } AudioInputPtr AudioInputRegistrar::newFromChoice(QString choice) { if (! qmNew) return AudioInputPtr(); if (!choice.isEmpty() && qmNew->contains(choice)) { g.s.qsAudioInput = choice; current = choice; return AudioInputPtr(qmNew->value(current)->create()); } choice = g.s.qsAudioInput; if (qmNew->contains(choice)) { current = choice; return AudioInputPtr(qmNew->value(choice)->create()); } AudioInputRegistrar *r = NULL; foreach(AudioInputRegistrar *air, *qmNew) if (!r || (air->priority > r->priority)) r = air; if (r) { current = r->name; return AudioInputPtr(r->create()); } return AudioInputPtr(); } bool AudioInputRegistrar::canExclusive() const { return false; } AudioInput::AudioInput() { #ifdef CIRCULAR_BUFFER micBuf = new CircularBuffer("/tmp/psMic"); speakerBuf = new CircularBuffer("/tmp/psSpeaker"); cleanBuf = new CircularBuffer("/tmp/psClean"); eventBuf = new CircularBuffer("/tmp/eventLog"); pthread_t logThread; int rc = pthread_create(&logThread, NULL, CircularBufferIO, NULL); if (rc) { fprintf(stderr, "Logging thread failed to start\n"); abort(); } #endif adjustBandwidth(g.iMaxBandwidth, iAudioQuality, iAudioFrames); g.iAudioBandwidth = getNetworkBandwidth(iAudioQuality, iAudioFrames); if (preferCELT(iAudioQuality, iAudioFrames)) umtType = MessageHandler::UDPVoiceCELTAlpha; else umtType = MessageHandler::UDPVoiceSpeex; cCodec = NULL; ceEncoder = NULL; if (umtType != MessageHandler::UDPVoiceSpeex) { iSampleRate = SAMPLE_RATE; iFrameSize = SAMPLE_RATE / 100; esSpeex = NULL; qWarning("AudioInput: %d bits/s, %d hz, %d sample CELT", iAudioQuality, iSampleRate, iFrameSize); } else { iAudioFrames /= 2; speex_bits_init(&sbBits); speex_bits_reset(&sbBits); esSpeex = speex_encoder_init(speex_lib_get_mode(SPEEX_MODEID_UWB)); speex_encoder_ctl(esSpeex,SPEEX_GET_FRAME_SIZE,&iFrameSize); speex_encoder_ctl(esSpeex,SPEEX_GET_SAMPLING_RATE,&iSampleRate); int iArg=1; speex_encoder_ctl(esSpeex,SPEEX_SET_VBR, &iArg); iArg = 0; speex_encoder_ctl(esSpeex,SPEEX_SET_VAD, &iArg); speex_encoder_ctl(esSpeex,SPEEX_SET_DTX, &iArg); float fArg=8.0; speex_encoder_ctl(esSpeex,SPEEX_SET_VBR_QUALITY, &fArg); iArg = iAudioQuality; speex_encoder_ctl(esSpeex, SPEEX_SET_VBR_MAX_BITRATE, &iArg); iArg = 5; speex_encoder_ctl(esSpeex,SPEEX_SET_COMPLEXITY, &iArg); qWarning("AudioInput: %d bits/s, %d hz, %d sample Speex-UWB", iAudioQuality, iSampleRate, iFrameSize); } iMicFreq = iSampleRate; iFrameCounter = 0; iSilentFrames = 0; iHoldFrames = 0; bResetProcessor = true; bEchoMulti = false; sppPreprocess = NULL; sesEcho = NULL; srsMic = srsEcho = NULL; iJitterSeq = 0; iMinBuffered = 1000; psMic = new short[iFrameSize]; psClean = new short[iFrameSize]; psSpeaker = NULL; iEchoChannels = iMicChannels = 0; AudioOutputPtr ao = g.ao; if (ao) { iEchoChannels = ao->getChannels(); iEchoFreq = ao->getMixerFreq(); } else { fprintf(stderr, "AudioOutput has not been initialized\n"); std::exit(1); } iEchoFilled = iMicFilled = 0; eMicFormat = eEchoFormat = SampleFloat; iMicSampleSize = iEchoSampleSize = 0; bPreviousVoice = false; pfMicInput = pfEchoInput = pfOutput = NULL; iBitrate = 0; dPeakSignal = dPeakSpeaker = dPeakMic = dPeakCleanMic = 0.0; if (g.uiSession) { // no bandwidth limit for us //setMaxBandwidth(g.iMaxBandwidth); } // hard code quality and audio frames iAudioQuality = 31900; iAudioFrames = 2; bRunning = true; connect(this, SIGNAL(doDeaf()), g.mw->qaAudioDeaf, SLOT(trigger()), Qt::QueuedConnection); } AudioInput::~AudioInput() { bRunning = false; wait(); if (ceEncoder) { cCodec->celt_encoder_destroy(ceEncoder); } else if (esSpeex) { speex_bits_destroy(&sbBits); speex_encoder_destroy(esSpeex); } foreach(short *buf, qlEchoFrames) delete [] buf; if (sppPreprocess) speex_preprocess_state_destroy(sppPreprocess); if (sesEcho) speex_echo_state_destroy(sesEcho); if (srsMic) speex_resampler_destroy(srsMic); if (srsEcho) speex_resampler_destroy(srsEcho); appendWavHeader("psMic", 1, iSampleRate); appendWavHeader("psSpeaker", 1, iSampleRate); appendWavHeader("psClean", 1, iSampleRate); delete [] psMic; delete [] psClean; delete [] psSpeaker; delete [] pfMicInput; delete [] pfEchoInput; delete [] pfOutput; } bool AudioInput::isTransmitting() const { return bPreviousVoice; }; #define IN_MIXER_FLOAT(channels) \ static void inMixerFloat##channels ( float * RESTRICT buffer, const void * RESTRICT ipt, unsigned int nsamp, unsigned int N) { \ const float * RESTRICT input = reinterpret_cast<const float *>(ipt); \ register const float m = 1.0f / static_cast<float>(channels); \ Q_UNUSED(N); \ for(unsigned int i=0;i<nsamp;++i) {\ register float v= 0.0f; \ for(unsigned int j=0;j<channels;++j) \ v += input[i*channels+j]; \ buffer[i] = v * m; \ } \ } #define IN_MIXER_SHORT(channels) \ static void inMixerShort##channels ( float * RESTRICT buffer, const void * RESTRICT ipt, unsigned int nsamp, unsigned int N) { \ const short * RESTRICT input = reinterpret_cast<const short *>(ipt); \ register const float m = 1.0f / (32768.f * static_cast<float>(channels)); \ Q_UNUSED(N); \ for(unsigned int i=0;i<nsamp;++i) {\ register float v= 0.0f; \ for(unsigned int j=0;j<channels;++j) \ v += static_cast<float>(input[i*channels+j]); \ buffer[i] = v * m; \ } \ } IN_MIXER_FLOAT(1) IN_MIXER_FLOAT(2) IN_MIXER_FLOAT(3) IN_MIXER_FLOAT(4) IN_MIXER_FLOAT(5) IN_MIXER_FLOAT(6) IN_MIXER_FLOAT(7) IN_MIXER_FLOAT(8) IN_MIXER_FLOAT(N) IN_MIXER_SHORT(1) IN_MIXER_SHORT(2) IN_MIXER_SHORT(3) IN_MIXER_SHORT(4) IN_MIXER_SHORT(5) IN_MIXER_SHORT(6) IN_MIXER_SHORT(7) IN_MIXER_SHORT(8) IN_MIXER_SHORT(N) AudioInput::inMixerFunc AudioInput::chooseMixer(const unsigned int nchan, SampleFormat sf) { inMixerFunc r = NULL; if (sf == SampleFloat) { switch (nchan) { case 1: r = inMixerFloat1; break; case 2: r = inMixerFloat2; break; case 3: r = inMixerFloat3; break; case 4: r = inMixerFloat4; break; case 5: r = inMixerFloat5; break; case 6: r = inMixerFloat6; break; case 7: r = inMixerFloat7; break; case 8: r = inMixerFloat8; break; default: r = inMixerFloatN; break; } } else { switch (nchan) { case 1: r = inMixerShort1; break; case 2: r = inMixerShort2; break; case 3: r = inMixerShort3; break; case 4: r = inMixerShort4; break; case 5: r = inMixerShort5; break; case 6: r = inMixerShort6; break; case 7: r = inMixerShort7; break; case 8: r = inMixerShort8; break; default: r = inMixerShortN; break; } } return r; } void AudioInput::initializeMixer() { int err; if (srsMic) speex_resampler_destroy(srsMic); if (srsEcho) speex_resampler_destroy(srsEcho); delete [] pfMicInput; delete [] pfEchoInput; delete [] pfOutput; if (iMicFreq != iSampleRate) srsMic = speex_resampler_init(1, iMicFreq, iSampleRate, 3, &err); iMicLength = (iFrameSize * iMicFreq) / iSampleRate; pfMicInput = new float[iMicLength]; pfOutput = new float[iFrameSize * qMax(1U,iEchoChannels)]; if (iEchoChannels > 0) { bEchoMulti = g.s.bEchoMulti; if (iEchoFreq != iSampleRate) srsEcho = speex_resampler_init(bEchoMulti ? iEchoChannels : 1, iEchoFreq, iSampleRate, 3, &err); iEchoLength = (iFrameSize * iEchoFreq) / iSampleRate; iEchoMCLength = bEchoMulti ? iEchoLength * iEchoChannels : iEchoLength; iEchoFrameSize = bEchoMulti ? iFrameSize * iEchoChannels : iFrameSize; pfEchoInput = new float[iEchoMCLength]; } else { srsEcho = NULL; pfEchoInput = NULL; } imfMic = chooseMixer(iMicChannels, eMicFormat); imfEcho = chooseMixer(iEchoChannels, eEchoFormat); iMicSampleSize = static_cast<int>(iMicChannels * ((eMicFormat == SampleFloat) ? sizeof(float) : sizeof(short))); iEchoSampleSize = static_cast<int>(iEchoChannels * ((eEchoFormat == SampleFloat) ? sizeof(float) : sizeof(short))); bResetProcessor = true; qWarning("AudioInput: Initialized mixer for %d channel %d hz mic and %d channel %d hz echo", iMicChannels, iMicFreq, iEchoChannels, iEchoFreq); } void AudioInput::addMic(const void *data, unsigned int nsamp) { #ifdef CIRCULAR_BUFFER char addBuf[200]; sprintf(addBuf, "Func: addMic, times: %ld\n", ++addMicNum); eventBuf->log(addBuf); #endif while (nsamp > 0) { unsigned int left = qMin(nsamp, iMicLength - iMicFilled); imfMic(pfMicInput + iMicFilled, data, left, iMicChannels); iMicFilled += left; nsamp -= left; if (nsamp > 0) { if (eMicFormat == SampleFloat) data = reinterpret_cast<const float *>(data) + left * iMicChannels; else data = reinterpret_cast<const short *>(data) + left * iMicChannels; } if (iMicFilled == iMicLength) { iMicFilled = 0; float *ptr = srsMic ? pfOutput : pfMicInput; if (srsMic) { spx_uint32_t inlen = iMicLength; spx_uint32_t outlen = iFrameSize; speex_resampler_process_float(srsMic, 0, pfMicInput, &inlen, pfOutput, &outlen); } const float mul = 32768.f; for (int j=0;j<iFrameSize;++j) psMic[j] = static_cast<short>(ptr[j] * mul); if (iEchoChannels > 0) { short *echo = NULL; { QMutexLocker l(&qmEcho); if (qlEchoFrames.isEmpty()) { iJitterSeq = 0; iMinBuffered = 1000; } else { #ifdef CIRCULAR_BUFFER char pbuf[200]; sprintf(pbuf, "Func: take first, list size: %d, times: %ld\n", qlEchoFrames.count(), ++takeNum); eventBuf->log(pbuf); #endif iMinBuffered = qMin(iMinBuffered, qlEchoFrames.count()); if ((iJitterSeq > 100) && (iMinBuffered > 1)) { iJitterSeq = 0; iMinBuffered = 1000; delete [] qlEchoFrames.takeFirst(); } echo = qlEchoFrames.takeFirst(); } } if (echo) { delete [] psSpeaker; psSpeaker = echo; } } encodeAudioFrame(); } } } void AudioInput::addInternalEcho(const void *data, unsigned int nsamp) { addEcho(data, nsamp); } void AudioInput::addEcho(const void *data, unsigned int nsamp) { #ifdef CIRCULAR_BUFFER char addBuf[200]; sprintf(addBuf, "Func: addEcho, times: %ld\n", ++addEchoNum); eventBuf->log(addBuf); #endif while (nsamp > 0) { unsigned int left = qMin(nsamp, iEchoLength - iEchoFilled); if (bEchoMulti) { const unsigned int samples = left * iEchoChannels; if (eEchoFormat == SampleFloat) for (unsigned int i=0;i<samples;++i) pfEchoInput[i] = reinterpret_cast<const float *>(data)[i]; else for (unsigned int i=0;i<samples;++i) pfEchoInput[i] = static_cast<float>(reinterpret_cast<const short *>(data)[i]) * (1.0f / 32768.f); } else { imfEcho(pfEchoInput + iEchoFilled, data, left, iEchoChannels); } iEchoFilled += left; nsamp -= left; if (nsamp > 0) { if (eEchoFormat == SampleFloat) data = reinterpret_cast<const float *>(data) + left * iEchoChannels; else data = reinterpret_cast<const short *>(data) + left * iEchoChannels; } if (iEchoFilled == iEchoLength) { iEchoFilled = 0; float *ptr = srsEcho ? pfOutput : pfEchoInput; if (srsEcho) { spx_uint32_t inlen = iEchoLength; spx_uint32_t outlen = iFrameSize; speex_resampler_process_interleaved_float(srsEcho, pfEchoInput, &inlen, pfOutput, &outlen); } short *outbuff = new short[iEchoFrameSize]; const float mul = 32768.f; for (unsigned int j=0;j<iEchoFrameSize;++j) outbuff[j] = static_cast<short>(ptr[j] * mul); iJitterSeq = qMin(iJitterSeq+1,10000U); QMutexLocker l(&qmEcho); if (qlEchoFrames.isEmpty()) { /* do nothing short *echo_delay = new short[iEchoFrameSize]; for (int k = 0; k < iEchoFrameSize; k++) echo_delay[k] = 0; qlEchoFrames.append(echo_delay); echo_delay = new short[iEchoFrameSize]; for (int k = 0; k < iEchoFrameSize; k++) echo_delay[k] = 0; qlEchoFrames.append(echo_delay); echo_delay = new short[iEchoFrameSize]; for (int k = 0; k < iEchoFrameSize; k++) echo_delay[k] = 0; qlEchoFrames.append(echo_delay); */ } qlEchoFrames.append(outbuff); #ifdef CIRCULAR_BUFFER char pbuf[200]; sprintf(pbuf, "Func: append frame, list size: %d, times: %ld\n", qlEchoFrames.size(), ++appendNum); eventBuf->log(pbuf); #endif } } } bool AudioInput::preferCELT(int bitrate, int frames) { return ((bitrate >= 32000) || (frames == 1)); } void AudioInput::adjustBandwidth(int bitspersec, int &bitrate, int &frames) { frames = g.s.iFramesPerPacket; bitrate = g.s.iQuality; if (bitspersec == -1) { // No limit } else { if (getNetworkBandwidth(bitrate, frames) > bitspersec) { if ((frames <= 4) && (bitspersec <= 32000)) frames = 4; else if ((frames == 1) && (bitspersec <= 64000)) frames = 2; else if ((frames == 2) && (bitspersec <= 48000)) frames = 4; if (getNetworkBandwidth(bitrate, frames) > bitspersec) { do { bitrate -= 1000; } while ((bitrate > 8000) && (getNetworkBandwidth(bitrate, frames) > bitspersec)); } } } if (bitrate <= 8000) bitrate = 8000; } void AudioInput::setMaxBandwidth(int bitspersec) { if (bitspersec == g.iMaxBandwidth) return; int frames; int bitrate; adjustBandwidth(bitspersec, bitrate, frames); g.iMaxBandwidth = bitspersec; if (bitspersec != -1) { if ((bitrate != g.s.iQuality) || (frames != g.s.iFramesPerPacket)) g.mw->msgBox(tr("Server maximum network bandwidth is only %1 kbit/s. Audio quality auto-adjusted to %2 kbit/s (%3ms)").arg(bitspersec / 1000).arg(bitrate / 1000).arg(frames*10)); } AudioInputPtr ai = g.ai; if (ai && (preferCELT(bitrate, frames) == (ai->umtType != MessageHandler::UDPVoiceSpeex))) { g.iAudioBandwidth = getNetworkBandwidth(bitrate, frames); ai->iAudioQuality = bitrate; ai->iAudioFrames = frames; return; } ai.reset(); Audio::stopInput(); Audio::startInput(); } int AudioInput::getNetworkBandwidth(int bitrate, int frames) { int overhead = 20 + 8 + 4 + 1 + 2 + (g.s.bTransmitPosition ? 12 : 0) + (NetworkConfig::TcpModeEnabled() ? 12 : 0) + frames; overhead *= (800 / frames); int bw = overhead + bitrate; return bw; } /* * FIXME: Experimental zero-latency callback-based preprocessing. extern "C" { int speex_preprocess_run_cb(SpeexPreprocessState *st, float *ft); SpeexPreprocessState *speex_preprocess_callback_init(int frame_size, int sampling_rate); }; celt_int32_t celtBack(CELTEncoder *enc, void *rawdata, celt_int32_t format, celt_int32_t bits, celt_int32_t num, void *data) { qWarning() << "CB" << enc << rawdata << format << bits << num << data; static SpeexPreprocessState *st = NULL; if (! st) { int samp = 480; int freq = 48000; celt_encoder_ctl(enc, CELT_GET_SAMPLE_RATE, &freq); celt_encoder_ctl(enc, CELT_GET_FRAME_SIZE, &samp); qWarning() << "Init" << samp << freq; st= speex_preprocess_callback_init(samp, freq); int iArg; iArg = 1; speex_preprocess_ctl(st, SPEEX_PREPROCESS_SET_VAD, &iArg); speex_preprocess_ctl(st, SPEEX_PREPROCESS_SET_AGC, &iArg); speex_preprocess_ctl(st, SPEEX_PREPROCESS_SET_DENOISE, &iArg); speex_preprocess_ctl(st, SPEEX_PREPROCESS_SET_DEREVERB, &iArg); iArg = 30000; speex_preprocess_ctl(st, SPEEX_PREPROCESS_SET_AGC_TARGET, &iArg); iArg = 30000; speex_preprocess_ctl(st, SPEEX_PREPROCESS_SET_AGC_TARGET, &iArg); float v = 30000.0f / static_cast<float>(g.s.iMinLoudness); iArg = iroundf(floorf(20.0f * log10f(v))); speex_preprocess_ctl(st, SPEEX_PREPROCESS_SET_AGC_MAX_GAIN, &iArg); iArg = g.s.iNoiseSuppress; speex_preprocess_ctl(st, SPEEX_PREPROCESS_SET_NOISE_SUPPRESS, &iArg); } qWarning() << "Call"; // int res = 1; int res = speex_preprocess_run_cb(st, (float *) rawdata); qWarning() << "Result" << res; return 1; } */ void AudioInput::encodeAudioFrame() { int iArg; ClientUser *p=ClientUser::get(g.uiSession); int i; float sum; short max; short *psSource; iFrameCounter++; if (! bRunning) return; sum=1.0f; for (i=0;i<iFrameSize;i++) sum += static_cast<float>(psMic[i] * psMic[i]); dPeakMic = qMax(20.0f*log10f(sqrtf(sum / static_cast<float>(iFrameSize)) / 32768.0f), -96.0f); max = 1; for (i=0;i<iFrameSize;i++) max = static_cast<short>(abs(psMic[i]) > max ? abs(psMic[i]) : max); dMaxMic = max; if (psSpeaker && (iEchoChannels > 0)) { sum=1.0f; for (i=0;i<iFrameSize;i++) sum += static_cast<float>(psSpeaker[i] * psSpeaker[i]); dPeakSpeaker = qMax(20.0f*log10f(sqrtf(sum / static_cast<float>(iFrameSize)) / 32768.0f), -96.0f); } else { dPeakSpeaker = 0.0; } QMutexLocker l(&qmSpeex); if (bResetProcessor) { if (sppPreprocess) speex_preprocess_state_destroy(sppPreprocess); if (sesEcho) speex_echo_state_destroy(sesEcho); sppPreprocess = speex_preprocess_state_init(iFrameSize, iSampleRate); iArg = 1; speex_preprocess_ctl(sppPreprocess, SPEEX_PREPROCESS_SET_VAD, &iArg); speex_preprocess_ctl(sppPreprocess, SPEEX_PREPROCESS_SET_AGC, &iArg); speex_preprocess_ctl(sppPreprocess, SPEEX_PREPROCESS_SET_DENOISE, &iArg); speex_preprocess_ctl(sppPreprocess, SPEEX_PREPROCESS_SET_DEREVERB, &iArg); iArg = 30000; speex_preprocess_ctl(sppPreprocess, SPEEX_PREPROCESS_SET_AGC_TARGET, &iArg); float v = 30000.0f / static_cast<float>(g.s.iMinLoudness); iArg = iroundf(floorf(20.0f * log10f(v))); speex_preprocess_ctl(sppPreprocess, SPEEX_PREPROCESS_SET_AGC_MAX_GAIN, &iArg); iArg = -60; speex_preprocess_ctl(sppPreprocess, SPEEX_PREPROCESS_SET_AGC_DECREMENT, &iArg); iArg = g.s.iNoiseSuppress; if (iArg >= -30) iArg = 50; speex_preprocess_ctl(sppPreprocess, SPEEX_PREPROCESS_SET_NOISE_SUPPRESS, &iArg); if (iEchoChannels > 0) { sesEcho = speex_echo_state_init_mc(iFrameSize, iFrameSize*10, 1, bEchoMulti ? iEchoChannels : 1); iArg = iSampleRate; speex_echo_ctl(sesEcho, SPEEX_ECHO_SET_SAMPLING_RATE, &iArg); speex_preprocess_ctl(sppPreprocess, SPEEX_PREPROCESS_SET_ECHO_STATE, sesEcho); qWarning("AudioInput: ECHO CANCELLER ACTIVE"); } else { sesEcho = NULL; } bResetProcessor = false; } speex_preprocess_ctl(sppPreprocess, SPEEX_PREPROCESS_GET_AGC_GAIN, &iArg); float gainValue = static_cast<float>(iArg); iArg = g.s.iNoiseSuppress - iArg; speex_preprocess_ctl(sppPreprocess, SPEEX_PREPROCESS_SET_NOISE_SUPPRESS, &iArg); if (sesEcho && psSpeaker) { speex_echo_cancellation(sesEcho, psMic, psSpeaker, psClean); speex_preprocess_run(sppPreprocess, psClean); psSource = psClean; #ifdef CIRCULAR_BUFFER micBuf->writeToBuffer((char *)psMic, iFrameSize * sizeof(short)); speakerBuf->writeToBuffer((char *)psSpeaker, iFrameSize * sizeof(short)); cleanBuf->writeToBuffer((char *)psClean, iFrameSize * sizeof(short)); #endif } else { speex_preprocess_run(sppPreprocess, psMic); psSource = psMic; #ifdef CIRCULAR_BUFFER eventBuf->log("echoAudioFrame called without echo\n"); #endif } sum=1.0f; for (i=0;i<iFrameSize;i++) sum += static_cast<float>(psSource[i] * psSource[i]); float micLevel = sqrtf(sum / static_cast<float>(iFrameSize)); dPeakSignal = qMax(20.0f*log10f(micLevel / 32768.0f), -96.0f); spx_int32_t prob = 0; speex_preprocess_ctl(sppPreprocess, SPEEX_PREPROCESS_GET_PROB, &prob); fSpeechProb = static_cast<float>(prob) / 100.0f; // clean microphone level: peak of filtered signal attenuated by AGC gain dPeakCleanMic = qMax(dPeakSignal - gainValue, -96.0f); float level = (g.s.vsVAD == Settings::SignalToNoise) ? fSpeechProb : (1.0f + dPeakCleanMic / 96.0f); bool bIsSpeech = false; if (level > g.s.fVADmax) bIsSpeech = true; else if (level > g.s.fVADmin && bPreviousVoice) bIsSpeech = true; if (! bIsSpeech) { iHoldFrames++; if (iHoldFrames < g.s.iVoiceHold) bIsSpeech = true; } else { iHoldFrames = 0; } if (g.s.atTransmit == Settings::Continous) bIsSpeech = true; else if (g.s.atTransmit == Settings::PushToTalk) bIsSpeech = g.s.uiDoublePush && ((g.uiDoublePush < g.s.uiDoublePush) || (g.tDoublePush.elapsed() < g.s.uiDoublePush)); bIsSpeech = bIsSpeech || (g.iPushToTalk > 0); if (g.s.bMute || ((g.s.lmLoopMode != Settings::Local) && p && (p->bMute || p->bSuppress)) || g.bPushToMute || (g.iTarget < 0)) { bIsSpeech = false; } if (bIsSpeech) { iSilentFrames = 0; } else { iSilentFrames++; if (iSilentFrames > 500) iFrameCounter = 0; } if (p) { if (! bIsSpeech) p->setTalking(Settings::Passive); else if (g.iTarget == 0) p->setTalking(Settings::Talking); else p->setTalking(Settings::Shouting); } if (g.s.bPushClick && (g.s.atTransmit == Settings::PushToTalk)) { AudioOutputPtr ao = g.ao; if (bIsSpeech && ! bPreviousVoice && ao) ao->playSample(g.s.qsPushClickOn); else if (ao && !bIsSpeech && bPreviousVoice && ao) ao->playSample(g.s.qsPushClickOff); } if (! bIsSpeech && ! bPreviousVoice) { iBitrate = 0; if (g.s.iIdleTime && ! g.s.bDeaf && ((tIdle.elapsed() / 1000000ULL) > g.s.iIdleTime)) { emit doDeaf(); tIdle.restart(); } spx_int32_t increment = 0; speex_preprocess_ctl(sppPreprocess, SPEEX_PREPROCESS_SET_AGC_INCREMENT, &increment); return; } else { spx_int32_t increment = 12; speex_preprocess_ctl(sppPreprocess, SPEEX_PREPROCESS_SET_AGC_INCREMENT, &increment); } tIdle.restart(); /* int r = celt_encoder_ctl(ceEncoder, CELT_SET_POST_MDCT_CALLBACK(celtBack, NULL)); qWarning() << "Set Callback" << r; */ unsigned char buffer[512]; int len; if (umtType != MessageHandler::UDPVoiceSpeex) { CELTCodec *switchto = NULL; if ((! g.uiSession || (g.s.lmLoopMode == Settings::Local)) && (! g.qmCodecs.isEmpty())) { // Use latest for local loopback QMap<int, CELTCodec *>::const_iterator i = g.qmCodecs.constEnd(); --i; switchto = i.value(); } else { if (cCodec && bPreviousVoice) { // Currently talking, don't switch unless you must. int v = cCodec->bitstreamVersion(); if ((v == g.iCodecAlpha) || (v == g.iCodecBeta)) switchto = cCodec; } } if (! switchto) { switchto = g.qmCodecs.value(g.bPreferAlpha ? g.iCodecAlpha : g.iCodecBeta); if (! switchto) { switchto = g.qmCodecs.value(g.bPreferAlpha ? g.iCodecBeta : g.iCodecAlpha); } } if (switchto != cCodec) { if (cCodec && ceEncoder) { cCodec->celt_encoder_destroy(ceEncoder); ceEncoder = NULL; } cCodec = switchto; if (cCodec) { ceEncoder = cCodec->encoderCreate(); } } else if (cCodec && ! bPreviousVoice) { cCodec->celt_encoder_ctl(ceEncoder, CELT_RESET_STATE); } if (! cCodec) return; if (g.uiSession && g.s.lmLoopMode != Settings::Local) { int v = cCodec->bitstreamVersion(); if (v == g.iCodecAlpha) umtType = MessageHandler::UDPVoiceCELTAlpha; else if (v == g.iCodecBeta) umtType = MessageHandler::UDPVoiceCELTBeta; else { qWarning() << "Couldn't find message type for codec version" << v; return; } } cCodec->celt_encoder_ctl(ceEncoder, CELT_SET_PREDICTION(0)); cCodec->celt_encoder_ctl(ceEncoder,CELT_SET_VBR_RATE(iAudioQuality)); len = cCodec->encode(ceEncoder, psSource, buffer, qMin(iAudioQuality / 800, 127)); iBitrate = len * 100 * 8; } else { int vbr = 0; speex_encoder_ctl(esSpeex, SPEEX_GET_VBR_MAX_BITRATE, &vbr); if (vbr != iAudioQuality) { vbr = iAudioQuality; speex_encoder_ctl(esSpeex, SPEEX_SET_VBR_MAX_BITRATE, &vbr); } if (! bPreviousVoice) speex_encoder_ctl(esSpeex, SPEEX_RESET_STATE, NULL); speex_encode_int(esSpeex, psSource, &sbBits); len = speex_bits_write(&sbBits, reinterpret_cast<char *>(buffer), 127); iBitrate = len * 50 * 8; speex_bits_reset(&sbBits); } flushCheck(QByteArray(reinterpret_cast<const char *>(buffer), len), ! bIsSpeech); if (! bIsSpeech) iBitrate = 0; bPreviousVoice = bIsSpeech; } void AudioInput::flushCheck(const QByteArray &frame, bool terminator) { qlFrames << frame; if (! terminator && qlFrames.count() < iAudioFrames) return; int flags = g.iTarget; if (terminator) flags = g.iPrevTarget; if (g.s.lmLoopMode == Settings::Server) flags = 0x1f; // Server loopback flags |= (umtType << 5); char data[1024]; data[0] = static_cast<unsigned char>(flags); PacketDataStream pds(data + 1, 1023); pds << iFrameCounter - qlFrames.count(); if (terminator) qlFrames << QByteArray(); for (int i=0;i<qlFrames.count(); ++i) { const QByteArray &qba = qlFrames.at(i); unsigned char head = static_cast<unsigned char>(qba.size()); if (i < qlFrames.count() - 1) head |= 0x80; pds.append(head); pds.append(qba.constData(), qba.size()); } if (g.s.bTransmitPosition && g.p && ! g.bCenterPosition && g.p->fetch()) { pds << g.p->fPosition[0]; pds << g.p->fPosition[1]; pds << g.p->fPosition[2]; } ServerHandlerPtr sh = g.sh; if (sh) { VoiceRecorderPtr recorder(sh->recorder); if (recorder) recorder->getRecordUser().addFrame(QByteArray(data, pds.size() + 1)); } if (g.s.lmLoopMode == Settings::Local) LoopUser::lpLoopy.addFrame(QByteArray(data, pds.size() + 1)); else if (sh) sh->sendMessage(data, pds.size() + 1); qlFrames.clear(); } bool AudioInput::isAlive() const { return isRunning(); }
/* * Copyright 2014 Kamil Michalak <kmichalak8@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifndef ASSERT_HPP #define ASSERT_HPP #include <gtest/gtest.h> void EXPECT_SEME_ORDER(std::vector<std::string> vec, std::string *strings) { int counter = 0; for (std::vector<std::string>::iterator it = vec.begin(); it != vec.end(); ++it) { EXPECT_EQ(0, strings[counter++].compare(*it)); } } #endif // ASSERT_H Define assertions in assert.hpp as an inlined functions /* * Copyright 2014 Kamil Michalak <kmichalak8@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifndef ASSERT_HPP #define ASSERT_HPP #include <gtest/gtest.h> inline void EXPECT_SEME_ORDER(std::vector<std::string> vec, std::string *strings) { int counter = 0; for (std::vector<std::string>::iterator it = vec.begin(); it != vec.end(); ++it) { EXPECT_EQ(0, strings[counter++].compare(*it)); } } inline void EXPECT_STR_CONTAINS(std::string stringValue, std::string stringToSearch) { std::size_t foundPos = stringValue.find(stringToSearch); EXPECT_NE(std::string::npos, foundPos); } #endif // ASSERT_H
/*====================================================================== This file is part of the elastix software. Copyright (c) University Medical Center Utrecht. All rights reserved. See src/CopyrightElastix.txt or http://elastix.isi.uu.nl/legal.php for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. ======================================================================*/ #ifndef __itkAdvancedCombinationTransform_hxx #define __itkAdvancedCombinationTransform_hxx #include "itkAdvancedCombinationTransform.h" namespace itk { /** * ************************ Constructor ************************* */ template <typename TScalarType, unsigned int NDimensions> AdvancedCombinationTransform<TScalarType, NDimensions> ::AdvancedCombinationTransform() : Superclass(NDimensions,1) { /** Initialize. */ this->m_InitialTransform = 0; this->m_CurrentTransform = 0; /** Set composition by default.*/ this->m_UseAddition = false; this->m_UseComposition = true; /** Set everything to have no current transform. */ this->m_SelectedTransformPointFunction = &Self::TransformPointNoCurrentTransform; this->m_SelectedGetJacobianFunction = &Self::GetJacobianNoCurrentTransform; this->m_SelectedGetSparseJacobianFunction = &Self::GetJacobianNoCurrentTransform; this->m_SelectedGetSpatialJacobianFunction = &Self::GetSpatialJacobianNoCurrentTransform; this->m_SelectedGetSpatialHessianFunction = &Self::GetSpatialHessianNoCurrentTransform; this->m_SelectedGetJacobianOfSpatialJacobianFunction = &Self::GetJacobianOfSpatialJacobianNoCurrentTransform; this->m_SelectedGetJacobianOfSpatialJacobianFunction2 = &Self::GetJacobianOfSpatialJacobianNoCurrentTransform; this->m_SelectedGetJacobianOfSpatialHessianFunction = &Self::GetJacobianOfSpatialHessianNoCurrentTransform; this->m_SelectedGetJacobianOfSpatialHessianFunction2 = &Self::GetJacobianOfSpatialHessianNoCurrentTransform; } // end Constructor /** * * *********************************************************** * ***** Override functions to aid for combining transformations. * * *********************************************************** * */ /** * ***************** GetNumberOfParameters ************************** */ template <typename TScalarType, unsigned int NDimensions> unsigned int AdvancedCombinationTransform<TScalarType, NDimensions> ::GetNumberOfParameters( void ) const { /** Return the number of parameters that completely define * the m_CurrentTransform. */ if ( this->m_CurrentTransform.IsNotNull() ) { return this->m_CurrentTransform->GetNumberOfParameters(); } else { /** Throw an exception. */ this->NoCurrentTransformSet(); /** dummy return. */ return this->m_Parameters.GetSize(); } } // end GetNumberOfParameters() /** * ***************** GetNumberOfNonZeroJacobianIndices ************************** */ template <typename TScalarType, unsigned int NDimensions> unsigned long AdvancedCombinationTransform<TScalarType, NDimensions> ::GetNumberOfNonZeroJacobianIndices( void ) const { /** Return the number of parameters that completely define * the m_CurrentTransform. */ if ( this->m_CurrentTransform.IsNotNull() ) { return this->m_CurrentTransform->GetNumberOfNonZeroJacobianIndices(); } else { /** Throw an exception. */ this->NoCurrentTransformSet(); /** dummy return. */ return this->m_Parameters.GetSize(); } } // end GetNumberOfNonZeroJacobianIndices() /** * ***************** IsLinear ************************** */ template <typename TScalarType, unsigned int NDimensions> bool AdvancedCombinationTransform<TScalarType, NDimensions> ::IsLinear( void ) const { bool currentLinear = true; if ( this->m_CurrentTransform.IsNotNull() ) { currentLinear = this->m_CurrentTransform->IsLinear(); } bool initialLinear = true; if ( this->m_InitialTransform.IsNotNull() ) { initialLinear = this->m_InitialTransform->IsLinear(); } return ( currentLinear && initialLinear ); } // end IsLinear() /** * ***************** GetParameters ************************** */ template <typename TScalarType, unsigned int NDimensions> const typename AdvancedCombinationTransform<TScalarType, NDimensions>::ParametersType & AdvancedCombinationTransform<TScalarType, NDimensions> ::GetParameters( void ) const { /** Return the parameters that completely define the m_CurrentTransform. */ if ( this->m_CurrentTransform.IsNotNull() ) { return this->m_CurrentTransform->GetParameters(); } else { /** Throw an exception. */ this->NoCurrentTransformSet(); /** dummy return. */ return this->m_Parameters; } } // end GetParameters() /** * ***************** SetParameters ************************** */ template <typename TScalarType, unsigned int NDimensions> void AdvancedCombinationTransform<TScalarType, NDimensions> ::SetParameters( const ParametersType & param ) { /** Set the parameters in the m_CurrentTransform. */ if ( this->m_CurrentTransform.IsNotNull() ) { this->Modified(); this->m_CurrentTransform->SetParameters( param ); } else { /** Throw an exception. */ this->NoCurrentTransformSet(); } } // end SetParameters() /** * ***************** SetParametersByValue ************************** */ template <typename TScalarType, unsigned int NDimensions> void AdvancedCombinationTransform<TScalarType, NDimensions> ::SetParametersByValue( const ParametersType & param ) { /** Set the parameters in the m_CurrentTransfom. */ if ( this->m_CurrentTransform.IsNotNull() ) { this->Modified(); this->m_CurrentTransform->SetParametersByValue( param ); } else { /** Throw an exception. */ this->NoCurrentTransformSet(); } } // end SetParametersByValue() /** * ***************** GetInverse ************************** */ template <typename TScalarType, unsigned int NDimensions> bool AdvancedCombinationTransform<TScalarType, NDimensions> ::GetInverse( Self * inverse ) const { if( !inverse ) { /** Inverse transformation cannot be returned into nothingness. */ return false; } else if ( this->m_CurrentTransform.IsNull() ) { /** No current transform has been set. Throw an exception. */ this->NoCurrentTransformSet(); return false; } else if ( this->m_InitialTransform.IsNull() ) { /** No Initial transform, so call the CurrentTransform's implementation. */ return this->m_CurrentTransform->GetInverse( inverse ); } else if ( this->m_UseAddition ) { /** No generic expression exists for the inverse of (T0+T1)(x). */ return false; } else // UseComposition { /** The initial transform and the current transform have been set * and UseComposition is set to true. * The inverse transform IT is defined by: * IT ( T1(T0(x) ) = x * So: * IT(y) = T0^{-1} ( T1^{-1} (y) ), * which is of course only defined when the inverses of both * the initial and the current transforms are defined. */ /** Try create the inverse of the initial transform. */ InitialTransformPointer inverseT0 = InitialTransformType::New(); bool T0invertable = this->m_InitialTransform->GetInverse( inverseT0 ); if ( T0invertable ) { /** Try to create the inverse of the current transform. */ CurrentTransformPointer inverseT1 = CurrentTransformType::New(); bool T1invertable = this->m_CurrentTransform->GetInverse( inverseT1 ); if ( T1invertable ) { /** The transform can be inverted! */ inverse->SetUseComposition( true ); inverse->SetInitialTransform( inverseT1 ); inverse->SetCurrentTransform( inverseT0 ); return true; } else { /** The initial transform is invertible, but the current one not. */ return false; } } else { /** The initial transform is not invertible. */ return false; } } // end else: UseComposition } // end GetInverse() /** * ***************** GetHasNonZeroSpatialHessian ************************** */ template <typename TScalarType, unsigned int NDimensions> bool AdvancedCombinationTransform<TScalarType, NDimensions> ::GetHasNonZeroSpatialHessian( void ) const { /** Set the parameters in the m_CurrentTransfom. */ if ( this->m_CurrentTransform.IsNull() ) { /** No current transform has been set. Throw an exception. */ this->NoCurrentTransformSet(); return false; } else if ( this->m_InitialTransform.IsNull() ) { /** No Initial transform, so call the CurrentTransform's implementation. */ return this->m_CurrentTransform->GetHasNonZeroSpatialHessian(); } else { bool dummy = this->m_InitialTransform->GetHasNonZeroSpatialHessian() || this->m_CurrentTransform->GetHasNonZeroSpatialHessian(); return dummy; } } // end GetHasNonZeroSpatialHessian() /** * ***************** HasNonZeroJacobianOfSpatialHessian ************************** */ template <typename TScalarType, unsigned int NDimensions> bool AdvancedCombinationTransform<TScalarType, NDimensions> ::HasNonZeroJacobianOfSpatialHessian( void ) const { /** Set the parameters in the m_CurrentTransfom. */ if ( this->m_CurrentTransform.IsNull() ) { /** No current transform has been set. Throw an exception. */ this->NoCurrentTransformSet(); return false; } else if ( this->m_InitialTransform.IsNull() ) { /** No Initial transform, so call the CurrentTransform's implementation. */ return this->m_CurrentTransform->GetHasNonZeroJacobianOfSpatialHessian(); } else { bool dummy = this->m_InitialTransform->GetHasNonZeroJacobianOfSpatialHessian() || this->m_CurrentTransform->GetHasNonZeroJacobianOfSpatialHessian(); return dummy; } } // end HasNonZeroJacobianOfSpatialHessian() /** * * *********************************************************** * ***** Functions to set the transformations and choose the * ***** combination method. * * *********************************************************** * */ /** * ******************* SetInitialTransform ********************** */ template <typename TScalarType, unsigned int NDimensions> void AdvancedCombinationTransform<TScalarType, NDimensions> ::SetInitialTransform( const InitialTransformType * _arg ) { /** Set the the initial transform and call the UpdateCombinationMethod. */ if ( this->m_InitialTransform != _arg ) { this->m_InitialTransform = _arg; this->Modified(); this->UpdateCombinationMethod(); } } // end SetInitialTransform() /** * ******************* SetCurrentTransform ********************** */ template <typename TScalarType, unsigned int NDimensions> void AdvancedCombinationTransform<TScalarType, NDimensions> ::SetCurrentTransform( CurrentTransformType * _arg ) { /** Set the the current transform and call the UpdateCombinationMethod. */ if ( this->m_CurrentTransform != _arg ) { this->m_CurrentTransform = _arg; this->Modified(); this->UpdateCombinationMethod(); } } // end SetCurrentTransform() /** * ********************** SetUseAddition ********************** */ template <typename TScalarType, unsigned int NDimensions> void AdvancedCombinationTransform<TScalarType, NDimensions> ::SetUseAddition( bool _arg ) { /** Set the UseAddition and UseComposition bools and call the UpdateCombinationMethod. */ if ( this->m_UseAddition != _arg ) { this->m_UseAddition = _arg; this->m_UseComposition = !_arg; this->Modified(); this->UpdateCombinationMethod(); } } // end SetUseAddition() /** * ********************** SetUseComposition ******************* */ template <typename TScalarType, unsigned int NDimensions> void AdvancedCombinationTransform<TScalarType, NDimensions> ::SetUseComposition( bool _arg ) { /** Set the UseAddition and UseComposition bools and call the UpdateCombinationMethod. */ if ( this->m_UseComposition != _arg ) { this->m_UseComposition = _arg; this->m_UseAddition = !_arg; this->Modified(); this->UpdateCombinationMethod(); } } // end SetUseComposition() /** * ****************** UpdateCombinationMethod ******************** */ template <typename TScalarType, unsigned int NDimensions> void AdvancedCombinationTransform<TScalarType, NDimensions> ::UpdateCombinationMethod( void ) { /** Update the m_SelectedTransformPointFunction and * the m_SelectedGetJacobianFunction */ if ( this->m_CurrentTransform.IsNull() ) { this->m_SelectedTransformPointFunction = &Self::TransformPointNoCurrentTransform; this->m_SelectedGetJacobianFunction = &Self::GetJacobianNoCurrentTransform; this->m_SelectedGetSparseJacobianFunction = &Self::GetJacobianNoCurrentTransform; this->m_SelectedGetSpatialJacobianFunction = &Self::GetSpatialJacobianNoCurrentTransform; this->m_SelectedGetSpatialHessianFunction = &Self::GetSpatialHessianNoCurrentTransform; this->m_SelectedGetJacobianOfSpatialJacobianFunction = &Self::GetJacobianOfSpatialJacobianNoCurrentTransform; this->m_SelectedGetJacobianOfSpatialJacobianFunction2 = &Self::GetJacobianOfSpatialJacobianNoCurrentTransform; this->m_SelectedGetJacobianOfSpatialHessianFunction = &Self::GetJacobianOfSpatialHessianNoCurrentTransform; this->m_SelectedGetJacobianOfSpatialHessianFunction2 = &Self::GetJacobianOfSpatialHessianNoCurrentTransform; } else if ( this->m_InitialTransform.IsNull() ) { this->m_SelectedTransformPointFunction = &Self::TransformPointNoInitialTransform; this->m_SelectedGetJacobianFunction = &Self::GetJacobianNoInitialTransform; this->m_SelectedGetSparseJacobianFunction = &Self::GetJacobianNoInitialTransform; this->m_SelectedGetSpatialJacobianFunction = &Self::GetSpatialJacobianNoInitialTransform; this->m_SelectedGetSpatialHessianFunction = &Self::GetSpatialHessianNoInitialTransform; this->m_SelectedGetJacobianOfSpatialJacobianFunction = &Self::GetJacobianOfSpatialJacobianNoInitialTransform; this->m_SelectedGetJacobianOfSpatialJacobianFunction2 = &Self::GetJacobianOfSpatialJacobianNoInitialTransform; this->m_SelectedGetJacobianOfSpatialHessianFunction = &Self::GetJacobianOfSpatialHessianNoInitialTransform; this->m_SelectedGetJacobianOfSpatialHessianFunction2 = &Self::GetJacobianOfSpatialHessianNoInitialTransform; } else if ( this->m_UseAddition ) { this->m_SelectedTransformPointFunction = &Self::TransformPointUseAddition; this->m_SelectedGetJacobianFunction = &Self::GetJacobianUseAddition; this->m_SelectedGetSparseJacobianFunction = &Self::GetJacobianUseAddition; this->m_SelectedGetSpatialJacobianFunction = &Self::GetSpatialJacobianUseAddition; this->m_SelectedGetSpatialHessianFunction = &Self::GetSpatialHessianUseAddition; this->m_SelectedGetJacobianOfSpatialJacobianFunction = &Self::GetJacobianOfSpatialJacobianUseAddition; this->m_SelectedGetJacobianOfSpatialJacobianFunction2 = &Self::GetJacobianOfSpatialJacobianUseAddition; this->m_SelectedGetJacobianOfSpatialHessianFunction = &Self::GetJacobianOfSpatialHessianUseAddition; this->m_SelectedGetJacobianOfSpatialHessianFunction2 = &Self::GetJacobianOfSpatialHessianUseAddition; } else { this->m_SelectedTransformPointFunction = &Self::TransformPointUseComposition; this->m_SelectedGetJacobianFunction = &Self::GetJacobianUseComposition; this->m_SelectedGetSparseJacobianFunction = &Self::GetJacobianUseComposition; this->m_SelectedGetSpatialJacobianFunction = &Self::GetSpatialJacobianUseComposition; this->m_SelectedGetSpatialHessianFunction = &Self::GetSpatialHessianUseComposition; this->m_SelectedGetJacobianOfSpatialJacobianFunction = &Self::GetJacobianOfSpatialJacobianUseComposition; this->m_SelectedGetJacobianOfSpatialJacobianFunction2 = &Self::GetJacobianOfSpatialJacobianUseComposition; this->m_SelectedGetJacobianOfSpatialHessianFunction = &Self::GetJacobianOfSpatialHessianUseComposition; this->m_SelectedGetJacobianOfSpatialHessianFunction2 = &Self::GetJacobianOfSpatialHessianUseComposition; } } // end UpdateCombinationMethod() /** * ************* NoCurrentTransformSet ********************** */ template <typename TScalarType, unsigned int NDimensions> void AdvancedCombinationTransform<TScalarType, NDimensions> ::NoCurrentTransformSet( void ) const throw (ExceptionObject) { itkExceptionMacro( << "No current transform set in the AdvancedCombinationTransform" ); } // end NoCurrentTransformSet() /** * * *********************************************************** * ***** Functions that implement the: * ***** - TransformPoint() * ***** - GetJacobian() * ***** - GetSpatialJacobian() * ***** - GetSpatialHessian() * ***** - GetJacobianOfSpatialJacobian() * ***** - GetJacobianOfSpatialHessian() * ***** for the four possible cases: * ***** - no initial transform: this is the same as using only one transform * ***** - no current transform: error, it should be set * ***** - use addition to combine transformations * ***** - use composition to combine transformations * * *********************************************************** * */ /** * ************* TransformPointUseAddition ********************** */ template <typename TScalarType, unsigned int NDimensions> typename AdvancedCombinationTransform<TScalarType, NDimensions>::OutputPointType AdvancedCombinationTransform<TScalarType, NDimensions> ::TransformPointUseAddition( const InputPointType & point ) const { /** The Initial transform. */ OutputPointType out0 = this->m_InitialTransform->TransformPoint( point ); /** The Current transform. */ OutputPointType out = this->m_CurrentTransform->TransformPoint( point ); /** Add them. */ for ( unsigned int i=0; i < SpaceDimension; i++ ) { out[ i ] += ( out0[ i ] - point[ i ] ); } return out; } // end TransformPointUseAddition() /** * **************** TransformPointUseComposition ************* */ template <typename TScalarType, unsigned int NDimensions> typename AdvancedCombinationTransform<TScalarType, NDimensions>::OutputPointType AdvancedCombinationTransform<TScalarType, NDimensions> ::TransformPointUseComposition( const InputPointType & point ) const { return this->m_CurrentTransform->TransformPoint( this->m_InitialTransform->TransformPoint( point ) ); } // end TransformPointUseComposition() /** * **************** TransformPointNoInitialTransform ****************** */ template <typename TScalarType, unsigned int NDimensions> typename AdvancedCombinationTransform<TScalarType, NDimensions>::OutputPointType AdvancedCombinationTransform<TScalarType, NDimensions> ::TransformPointNoInitialTransform( const InputPointType & point ) const { return this->m_CurrentTransform->TransformPoint( point ); } // end TransformPointNoInitialTransform() /** * ******** TransformPointNoCurrentTransform ****************** */ template <typename TScalarType, unsigned int NDimensions> typename AdvancedCombinationTransform<TScalarType, NDimensions>::OutputPointType AdvancedCombinationTransform<TScalarType, NDimensions> ::TransformPointNoCurrentTransform( const InputPointType & point ) const { /** Throw an exception. */ this->NoCurrentTransformSet(); /** dummy return. */ return point; } // end TransformPointNoCurrentTransform() /** * ************* GetJacobianUseAddition *************************** */ template <typename TScalarType, unsigned int NDimensions> const typename AdvancedCombinationTransform<TScalarType, NDimensions>::JacobianType & AdvancedCombinationTransform<TScalarType, NDimensions> ::GetJacobianUseAddition( const InputPointType & point ) const { return this->m_CurrentTransform->GetJacobian( point ); } // end GetJacobianUseAddition() /** * **************** GetJacobianUseComposition ************* */ template <typename TScalarType, unsigned int NDimensions> const typename AdvancedCombinationTransform<TScalarType, NDimensions>::JacobianType & AdvancedCombinationTransform<TScalarType, NDimensions> ::GetJacobianUseComposition( const InputPointType & point ) const { return this->m_CurrentTransform->GetJacobian( this->m_InitialTransform->TransformPoint( point ) ); } // end GetJacobianUseComposition() /** * **************** GetJacobianNoInitialTransform ****************** */ template <typename TScalarType, unsigned int NDimensions> const typename AdvancedCombinationTransform<TScalarType, NDimensions>::JacobianType & AdvancedCombinationTransform<TScalarType, NDimensions> ::GetJacobianNoInitialTransform( const InputPointType & point ) const { return this->m_CurrentTransform->GetJacobian( point ); } // end GetJacobianNoInitialTransform() /** * ******** GetJacobianNoCurrentTransform ****************** */ template <typename TScalarType, unsigned int NDimensions> const typename AdvancedCombinationTransform<TScalarType, NDimensions>::JacobianType & AdvancedCombinationTransform<TScalarType, NDimensions> ::GetJacobianNoCurrentTransform( const InputPointType & point ) const { /** Throw an exception. */ this->NoCurrentTransformSet(); /** dummy return. */ return this->m_Jacobian; } // end GetJacobianNoCurrentTransform() /** * ************* GetJacobianUseAddition *************************** */ template <typename TScalarType, unsigned int NDimensions> void AdvancedCombinationTransform<TScalarType, NDimensions> ::GetJacobianUseAddition( const InputPointType & ipp, JacobianType & j, NonZeroJacobianIndicesType & nonZeroJacobianIndices ) const { this->m_CurrentTransform->GetJacobian( ipp, j, nonZeroJacobianIndices ); } // end GetJacobianUseAddition() /** * **************** GetJacobianUseComposition ************* */ template <typename TScalarType, unsigned int NDimensions> void AdvancedCombinationTransform<TScalarType, NDimensions> ::GetJacobianUseComposition( const InputPointType & ipp, JacobianType & j, NonZeroJacobianIndicesType & nonZeroJacobianIndices ) const { this->m_CurrentTransform->GetJacobian( this->m_InitialTransform->TransformPoint( ipp ), j, nonZeroJacobianIndices ); } // end GetJacobianUseComposition() /** * **************** GetJacobianNoInitialTransform ****************** */ template <typename TScalarType, unsigned int NDimensions> void AdvancedCombinationTransform<TScalarType, NDimensions> ::GetJacobianNoInitialTransform( const InputPointType & ipp, JacobianType & j, NonZeroJacobianIndicesType & nonZeroJacobianIndices ) const { this->m_CurrentTransform->GetJacobian( ipp, j, nonZeroJacobianIndices ); } // end GetJacobianNoInitialTransform() /** * ******** GetJacobianNoCurrentTransform ****************** */ template <typename TScalarType, unsigned int NDimensions> void AdvancedCombinationTransform<TScalarType, NDimensions> ::GetJacobianNoCurrentTransform( const InputPointType & ipp, JacobianType & j, NonZeroJacobianIndicesType & nonZeroJacobianIndices ) const { /** Throw an exception. */ this->NoCurrentTransformSet(); } // end GetJacobianNoCurrentTransform() /** * ************* GetSpatialJacobianUseAddition *************************** */ template <typename TScalarType, unsigned int NDimensions> void AdvancedCombinationTransform<TScalarType, NDimensions> ::GetSpatialJacobianUseAddition( const InputPointType & ipp, SpatialJacobianType & sj ) const { SpatialJacobianType sj0, sj1, identity; this->m_InitialTransform->GetSpatialJacobian( ipp, sj0 ); this->m_CurrentTransform->GetSpatialJacobian( ipp, sj1 ); identity.SetIdentity(); sj = sj0 + sj1 - identity; } // end GetSpatialJacobianUseAddition() /** * **************** GetSpatialJacobianUseComposition ************* */ template <typename TScalarType, unsigned int NDimensions> void AdvancedCombinationTransform<TScalarType, NDimensions> ::GetSpatialJacobianUseComposition( const InputPointType & ipp, SpatialJacobianType & sj ) const { SpatialJacobianType sj0, sj1; this->m_InitialTransform->GetSpatialJacobian( ipp, sj0 ); this->m_CurrentTransform->GetSpatialJacobian( this->m_InitialTransform->TransformPoint( ipp ), sj1 ); sj = sj1 * sj0; } // end GetSpatialJacobianUseComposition() /** * **************** GetSpatialJacobianNoInitialTransform ****************** */ template <typename TScalarType, unsigned int NDimensions> void AdvancedCombinationTransform<TScalarType, NDimensions> ::GetSpatialJacobianNoInitialTransform( const InputPointType & ipp, SpatialJacobianType & sj ) const { this->m_CurrentTransform->GetSpatialJacobian( ipp, sj ); } // end GetSpatialJacobianNoInitialTransform() /** * ******** GetSpatialJacobianNoCurrentTransform ****************** */ template <typename TScalarType, unsigned int NDimensions> void AdvancedCombinationTransform<TScalarType, NDimensions> ::GetSpatialJacobianNoCurrentTransform( const InputPointType & ipp, SpatialJacobianType & sj ) const { /** Throw an exception. */ this->NoCurrentTransformSet(); } // end GetSpatialJacobianNoCurrentTransform() /** * ******** GetSpatialHessianUseAddition ****************** */ template <typename TScalarType, unsigned int NDimensions> void AdvancedCombinationTransform<TScalarType, NDimensions> ::GetSpatialHessianUseAddition( const InputPointType & ipp, SpatialHessianType & sh ) const { SpatialHessianType sh0, sh1; this->m_InitialTransform->GetSpatialHessian( ipp, sh0 ); this->m_CurrentTransform->GetSpatialHessian( ipp, sh1 ); for ( unsigned int i = 0; i < SpaceDimension; ++i ) { sh[ i ] = sh0[ i ] + sh1[ i ]; } } // end GetSpatialHessianUseAddition() /** * ******** GetSpatialHessianUseComposition ****************** */ template <typename TScalarType, unsigned int NDimensions> void AdvancedCombinationTransform<TScalarType, NDimensions> ::GetSpatialHessianUseComposition( const InputPointType & ipp, SpatialHessianType & sh ) const { /** Create intermediary variables for the internal transforms. */ SpatialJacobianType sj0, sj1; SpatialHessianType sh0, sh1; /** Transform the input point. */ // \todo this has already been computed and it is expensive. InputPointType transformedPoint = this->m_InitialTransform->TransformPoint( ipp ); /** Compute the (Jacobian of the) spatial Jacobian / Hessian of the * internal transforms. */ this->m_InitialTransform->GetSpatialJacobian( ipp, sj0 ); this->m_CurrentTransform->GetSpatialJacobian( transformedPoint, sj1 ); this->m_InitialTransform->GetSpatialHessian( ipp, sh0 ); this->m_CurrentTransform->GetSpatialHessian( transformedPoint, sh1 ); typename SpatialJacobianType::InternalMatrixType sj0tvnl = sj0.GetTranspose(); SpatialJacobianType sj0t( sj0tvnl ); /** Combine them in one overall spatial Hessian. */ for ( unsigned int dim = 0; dim < SpaceDimension; ++dim ) { sh[dim] = sj0t * ( sh1[dim] * sj0 ); for ( unsigned int p = 0; p < SpaceDimension; ++p ) { sh[dim] += ( sh0[p] * sj1(dim,p) ); } } } // end GetSpatialHessianUseComposition() /** * ******** GetSpatialHessianNoInitialTransform ****************** */ template <typename TScalarType, unsigned int NDimensions> void AdvancedCombinationTransform<TScalarType, NDimensions> ::GetSpatialHessianNoInitialTransform( const InputPointType & ipp, SpatialHessianType & sh ) const { this->m_CurrentTransform->GetSpatialHessian( ipp, sh ); } // end GetSpatialHessianNoInitialTransform() /** * ******** GetSpatialHessianNoCurrentTransform ****************** */ template <typename TScalarType, unsigned int NDimensions> void AdvancedCombinationTransform<TScalarType, NDimensions> ::GetSpatialHessianNoCurrentTransform( const InputPointType & ipp, SpatialHessianType & sh ) const { /** Throw an exception. */ this->NoCurrentTransformSet(); } // end GetSpatialHessianNoCurrentTransform() /** * ******** GetJacobianOfSpatialJacobianUseAddition ****************** */ template <typename TScalarType, unsigned int NDimensions> void AdvancedCombinationTransform<TScalarType, NDimensions> ::GetJacobianOfSpatialJacobianUseAddition( const InputPointType & ipp, JacobianOfSpatialJacobianType & jsj, NonZeroJacobianIndicesType & nonZeroJacobianIndices ) const { this->m_CurrentTransform->GetJacobianOfSpatialJacobian( ipp, jsj, nonZeroJacobianIndices ); } // end GetJacobianOfSpatialJacobianUseAddition() /** * ******** GetJacobianOfSpatialJacobianUseAddition ****************** */ template <typename TScalarType, unsigned int NDimensions> void AdvancedCombinationTransform<TScalarType, NDimensions> ::GetJacobianOfSpatialJacobianUseAddition( const InputPointType & ipp, SpatialJacobianType & sj, JacobianOfSpatialJacobianType & jsj, NonZeroJacobianIndicesType & nonZeroJacobianIndices ) const { this->m_CurrentTransform->GetJacobianOfSpatialJacobian( ipp, sj, jsj, nonZeroJacobianIndices ); } // end GetJacobianOfSpatialJacobianUseAddition() /** * ******** GetJacobianOfSpatialJacobianUseComposition ****************** */ template <typename TScalarType, unsigned int NDimensions> void AdvancedCombinationTransform<TScalarType, NDimensions> ::GetJacobianOfSpatialJacobianUseComposition( const InputPointType & ipp, JacobianOfSpatialJacobianType & jsj, NonZeroJacobianIndicesType & nonZeroJacobianIndices ) const { SpatialJacobianType sj0; JacobianOfSpatialJacobianType jsj1; this->m_InitialTransform->GetSpatialJacobian( ipp, sj0 ); this->m_CurrentTransform->GetJacobianOfSpatialJacobian( this->m_InitialTransform->TransformPoint( ipp ), jsj1, nonZeroJacobianIndices ); jsj.resize( nonZeroJacobianIndices.size() ); for ( unsigned int mu = 0; mu < nonZeroJacobianIndices.size(); ++mu ) { jsj[ mu ] = jsj1[ mu ] * sj0; } } // end GetJacobianOfSpatialJacobianUseComposition() /** * ******** GetJacobianOfSpatialJacobianUseComposition ****************** */ template <typename TScalarType, unsigned int NDimensions> void AdvancedCombinationTransform<TScalarType, NDimensions> ::GetJacobianOfSpatialJacobianUseComposition( const InputPointType & ipp, SpatialJacobianType & sj, JacobianOfSpatialJacobianType & jsj, NonZeroJacobianIndicesType & nonZeroJacobianIndices ) const { SpatialJacobianType sj0, sj1; JacobianOfSpatialJacobianType jsj1; this->m_InitialTransform->GetSpatialJacobian( ipp, sj0 ); this->m_CurrentTransform->GetJacobianOfSpatialJacobian( this->m_InitialTransform->TransformPoint( ipp ), sj1, jsj1, nonZeroJacobianIndices ); sj = sj1 * sj0; jsj.resize( nonZeroJacobianIndices.size() ); for ( unsigned int mu = 0; mu < nonZeroJacobianIndices.size(); ++mu ) { jsj[ mu ] = jsj1[ mu ] * sj0; } } // end GetJacobianOfSpatialJacobianUseComposition() /** * ******** GetJacobianOfSpatialJacobianNoInitialTransform ****************** */ template <typename TScalarType, unsigned int NDimensions> void AdvancedCombinationTransform<TScalarType, NDimensions> ::GetJacobianOfSpatialJacobianNoInitialTransform( const InputPointType & ipp, JacobianOfSpatialJacobianType & jsj, NonZeroJacobianIndicesType & nonZeroJacobianIndices ) const { this->m_CurrentTransform->GetJacobianOfSpatialJacobian( ipp, jsj, nonZeroJacobianIndices ); } // end GetJacobianOfSpatialJacobianNoInitialTransform() /** * ******** GetJacobianOfSpatialJacobianNoInitialTransform ****************** */ template <typename TScalarType, unsigned int NDimensions> void AdvancedCombinationTransform<TScalarType, NDimensions> ::GetJacobianOfSpatialJacobianNoInitialTransform( const InputPointType & ipp, SpatialJacobianType & sj, JacobianOfSpatialJacobianType & jsj, NonZeroJacobianIndicesType & nonZeroJacobianIndices ) const { this->m_CurrentTransform->GetJacobianOfSpatialJacobian( ipp, sj, jsj, nonZeroJacobianIndices ); } // end GetJacobianOfSpatialJacobianNoInitialTransform() /** * ******** GetJacobianOfSpatialJacobianNoCurrentTransform ****************** */ template <typename TScalarType, unsigned int NDimensions> void AdvancedCombinationTransform<TScalarType, NDimensions> ::GetJacobianOfSpatialJacobianNoCurrentTransform( const InputPointType & ipp, JacobianOfSpatialJacobianType & jsj, NonZeroJacobianIndicesType & nonZeroJacobianIndices ) const { /** Throw an exception. */ this->NoCurrentTransformSet(); } // end GetJacobianOfSpatialJacobianNoCurrentTransform() /** * ******** GetJacobianOfSpatialJacobianNoCurrentTransform ****************** */ template <typename TScalarType, unsigned int NDimensions> void AdvancedCombinationTransform<TScalarType, NDimensions> ::GetJacobianOfSpatialJacobianNoCurrentTransform( const InputPointType & ipp, SpatialJacobianType & sj, JacobianOfSpatialJacobianType & jsj, NonZeroJacobianIndicesType & nonZeroJacobianIndices ) const { /** Throw an exception. */ this->NoCurrentTransformSet(); } // end GetJacobianOfSpatialJacobianNoCurrentTransform() /** * ******** GetJacobianOfSpatialHessianUseAddition ****************** */ template <typename TScalarType, unsigned int NDimensions> void AdvancedCombinationTransform<TScalarType, NDimensions> ::GetJacobianOfSpatialHessianUseAddition( const InputPointType & ipp, JacobianOfSpatialHessianType & jsh, NonZeroJacobianIndicesType & nonZeroJacobianIndices ) const { this->m_CurrentTransform->GetJacobianOfSpatialHessian( ipp, jsh, nonZeroJacobianIndices ); } // end GetJacobianOfSpatialHessianUseAddition() /** * ******** GetJacobianOfSpatialHessianUseAddition ****************** */ template <typename TScalarType, unsigned int NDimensions> void AdvancedCombinationTransform<TScalarType, NDimensions> ::GetJacobianOfSpatialHessianUseAddition( const InputPointType & ipp, SpatialHessianType & sh, JacobianOfSpatialHessianType & jsh, NonZeroJacobianIndicesType & nonZeroJacobianIndices ) const { this->m_CurrentTransform->GetJacobianOfSpatialHessian( ipp, sh, jsh, nonZeroJacobianIndices ); } // end GetJacobianOfSpatialHessianUseAddition() /** * ******** GetJacobianOfSpatialHessianUseComposition ****************** */ template <typename TScalarType, unsigned int NDimensions> void AdvancedCombinationTransform<TScalarType, NDimensions> ::GetJacobianOfSpatialHessianUseComposition( const InputPointType & ipp, JacobianOfSpatialHessianType & jsh, NonZeroJacobianIndicesType & nonZeroJacobianIndices ) const { /** Create intermediary variables for the internal transforms. */ SpatialJacobianType sj0; SpatialHessianType sh0; JacobianOfSpatialJacobianType jsj1; JacobianOfSpatialHessianType jsh1; /** Transform the input point. */ // \todo: this has already been computed and it is expensive. InputPointType transformedPoint = this->m_InitialTransform->TransformPoint( ipp ); /** Compute the (Jacobian of the) spatial Jacobian / Hessian of the * internal transforms. */ this->m_InitialTransform->GetSpatialJacobian( ipp, sj0 ); this->m_InitialTransform->GetSpatialHessian( ipp, sh0 ); /** Assume/demand that GetJacobianOfSpatialJacobian returns * the same nonZeroJacobianIndices as the GetJacobianOfSpatialHessian. */ this->m_CurrentTransform->GetJacobianOfSpatialJacobian( transformedPoint, jsj1, nonZeroJacobianIndices ); this->m_CurrentTransform->GetJacobianOfSpatialHessian( transformedPoint, jsh1, nonZeroJacobianIndices ); typename SpatialJacobianType::InternalMatrixType sj0tvnl = sj0.GetTranspose(); SpatialJacobianType sj0t( sj0tvnl ); jsh.resize( nonZeroJacobianIndices.size() ); /** Combine them in one overall Jacobian of spatial Hessian. */ for ( unsigned int mu = 0; mu < nonZeroJacobianIndices.size(); ++mu ) { for ( unsigned int dim = 0; dim < SpaceDimension; ++dim ) { jsh[mu][dim] = sj0t * ( jsh1[mu][dim] * sj0 ); for ( unsigned int p = 0; p < SpaceDimension; ++p ) { jsh[mu][dim] += ( sh0[p] * jsj1[mu](dim,p) ); } } } } // end GetJacobianOfSpatialHessianUseComposition() /** * ******** GetJacobianOfSpatialHessianUseComposition ****************** */ template <typename TScalarType, unsigned int NDimensions> void AdvancedCombinationTransform<TScalarType, NDimensions> ::GetJacobianOfSpatialHessianUseComposition( const InputPointType & ipp, SpatialHessianType & sh, JacobianOfSpatialHessianType & jsh, NonZeroJacobianIndicesType & nonZeroJacobianIndices ) const { /** Create intermediary variables for the internal transforms. */ SpatialJacobianType sj0, sj1; SpatialHessianType sh0, sh1; JacobianOfSpatialJacobianType jsj1; JacobianOfSpatialHessianType jsh1; /** Transform the input point. */ // \todo this has already been computed and it is expensive. InputPointType transformedPoint = this->m_InitialTransform->TransformPoint( ipp ); /** Compute the (Jacobian of the) spatial Jacobian / Hessian of the * internal transforms. */ this->m_InitialTransform->GetSpatialJacobian( ipp, sj0 ); this->m_InitialTransform->GetSpatialHessian( ipp, sh0 ); /** Assume/demand that GetJacobianOfSpatialJacobian returns * the same nonZeroJacobianIndices as the GetJacobianOfSpatialHessian. */ this->m_CurrentTransform->GetJacobianOfSpatialJacobian( transformedPoint, sj1, jsj1, nonZeroJacobianIndices ); this->m_CurrentTransform->GetJacobianOfSpatialHessian( transformedPoint, sh1, jsh1, nonZeroJacobianIndices ); SpatialJacobianType sj0t = sj0.GetTranspose(); jsh.resize( nonZeroJacobianIndices.size() ); /** Combine them in one overall Jacobian of spatial Hessian. */ for ( unsigned int mu = 0; mu < nonZeroJacobianIndices.size(); ++mu ) { for ( unsigned int dim = 0; dim < SpaceDimension; ++dim ) { jsh[mu][dim] = sj0t * ( jsh1[mu][dim] * sj0 ); for ( unsigned int p = 0; p < SpaceDimension; ++p ) { jsh[mu][dim] += ( sh0[p] * jsj1[mu](dim,p) ); } } } /** Combine them in one overall spatial Hessian. */ for ( unsigned int dim = 0; dim < SpaceDimension; ++dim ) { sh[dim] = sj0t * ( sh1[dim] * sj0 ); for ( unsigned int p = 0; p < SpaceDimension; ++p ) { sh[dim] += ( sh0[p] * sj1(dim,p) ); } } } // end GetJacobianOfSpatialHessianUseComposition() /** * ******** GetJacobianOfSpatialHessianNoInitialTransform ****************** */ template <typename TScalarType, unsigned int NDimensions> void AdvancedCombinationTransform<TScalarType, NDimensions> ::GetJacobianOfSpatialHessianNoInitialTransform( const InputPointType & ipp, JacobianOfSpatialHessianType & jsh, NonZeroJacobianIndicesType & nonZeroJacobianIndices ) const { this->m_CurrentTransform->GetJacobianOfSpatialHessian( ipp, jsh, nonZeroJacobianIndices ); } // end GetJacobianOfSpatialHessianNoInitialTransform() /** * ******** GetJacobianOfSpatialHessianNoInitialTransform ****************** */ template <typename TScalarType, unsigned int NDimensions> void AdvancedCombinationTransform<TScalarType, NDimensions> ::GetJacobianOfSpatialHessianNoInitialTransform( const InputPointType & ipp, SpatialHessianType & sh, JacobianOfSpatialHessianType & jsh, NonZeroJacobianIndicesType & nonZeroJacobianIndices ) const { this->m_CurrentTransform->GetJacobianOfSpatialHessian( ipp, sh, jsh, nonZeroJacobianIndices ); } // end GetJacobianOfSpatialHessianNoInitialTransform() /** * ******** GetJacobianOfSpatialHessianNoCurrentTransform ****************** */ template <typename TScalarType, unsigned int NDimensions> void AdvancedCombinationTransform<TScalarType, NDimensions> ::GetJacobianOfSpatialHessianNoCurrentTransform( const InputPointType & ipp, JacobianOfSpatialHessianType & jsh, NonZeroJacobianIndicesType & nonZeroJacobianIndices ) const { /** Throw an exception. */ this->NoCurrentTransformSet(); } // end GetJacobianOfSpatialHessianNoCurrentTransform() /** * ******** GetJacobianOfSpatialHessianNoCurrentTransform ****************** */ template <typename TScalarType, unsigned int NDimensions> void AdvancedCombinationTransform<TScalarType, NDimensions> ::GetJacobianOfSpatialHessianNoCurrentTransform( const InputPointType & ipp, SpatialHessianType & sh, JacobianOfSpatialHessianType & jsh, NonZeroJacobianIndicesType & nonZeroJacobianIndices ) const { /** Throw an exception. */ this->NoCurrentTransformSet(); } // end GetJacobianOfSpatialHessianNoCurrentTransform() /** * * *********************************************************** * ***** Functions that point to the selected implementation. * * *********************************************************** * */ /** * ****************** TransformPoint **************************** */ template <typename TScalarType, unsigned int NDimensions> typename AdvancedCombinationTransform<TScalarType, NDimensions>::OutputPointType AdvancedCombinationTransform<TScalarType, NDimensions> ::TransformPoint( const InputPointType & point ) const { /** Call the selected TransformPointFunction. */ return ((*this).*m_SelectedTransformPointFunction)( point ); } // end TransformPoint() /** * ****************** GetJacobian **************************** */ template <typename TScalarType, unsigned int NDimensions> const typename AdvancedCombinationTransform<TScalarType, NDimensions>::JacobianType & AdvancedCombinationTransform<TScalarType, NDimensions> ::GetJacobian( const InputPointType & point ) const { /** Call the selected GetJacobian. */ return ((*this).*m_SelectedGetJacobianFunction)( point ); } // end GetJacobian() /** * ****************** GetJacobian **************************** */ template <typename TScalarType, unsigned int NDimensions> void AdvancedCombinationTransform<TScalarType, NDimensions> ::GetJacobian( const InputPointType & ipp, JacobianType & j, NonZeroJacobianIndicesType & nonZeroJacobianIndices ) const { /** Call the selected GetJacobian. */ return ((*this).*m_SelectedGetSparseJacobianFunction)( ipp, j, nonZeroJacobianIndices ); } // end GetJacobian() /** * ****************** GetSpatialJacobian **************************** */ template <typename TScalarType, unsigned int NDimensions> void AdvancedCombinationTransform<TScalarType, NDimensions> ::GetSpatialJacobian( const InputPointType & ipp, SpatialJacobianType & sj ) const { /** Call the selected GetJacobian. */ return ((*this).*m_SelectedGetSpatialJacobianFunction)( ipp, sj ); } // end GetSpatialJacobian() /** * ****************** GetSpatialHessian **************************** */ template <typename TScalarType, unsigned int NDimensions> void AdvancedCombinationTransform<TScalarType, NDimensions> ::GetSpatialHessian( const InputPointType & ipp, SpatialHessianType & sh ) const { /** Call the selected GetJacobian. */ return ((*this).*m_SelectedGetSpatialHessianFunction)( ipp, sh ); } // end GetSpatialHessian() /** * ****************** GetJacobianOfSpatialJacobian **************************** */ template <typename TScalarType, unsigned int NDimensions> void AdvancedCombinationTransform<TScalarType, NDimensions> ::GetJacobianOfSpatialJacobian( const InputPointType & ipp, JacobianOfSpatialJacobianType & jsj, NonZeroJacobianIndicesType & nonZeroJacobianIndices ) const { /** Call the selected GetJacobian. */ return ((*this).*m_SelectedGetJacobianOfSpatialJacobianFunction)( ipp, jsj, nonZeroJacobianIndices ); } // end GetJacobianOfSpatialJacobian() /** * ****************** GetJacobianOfSpatialJacobian **************************** */ template <typename TScalarType, unsigned int NDimensions> void AdvancedCombinationTransform<TScalarType, NDimensions> ::GetJacobianOfSpatialJacobian( const InputPointType & ipp, SpatialJacobianType & sj, JacobianOfSpatialJacobianType & jsj, NonZeroJacobianIndicesType & nonZeroJacobianIndices ) const { /** Call the selected GetJacobian. */ return ((*this).*m_SelectedGetJacobianOfSpatialJacobianFunction2)( ipp, sj, jsj, nonZeroJacobianIndices ); } // end GetJacobianOfSpatialJacobian() /** * ****************** GetJacobianOfSpatialHessian **************************** */ template <typename TScalarType, unsigned int NDimensions> void AdvancedCombinationTransform<TScalarType, NDimensions> ::GetJacobianOfSpatialHessian( const InputPointType & ipp, JacobianOfSpatialHessianType & jsh, NonZeroJacobianIndicesType & nonZeroJacobianIndices ) const { /** Call the selected GetJacobian. */ return ((*this).*m_SelectedGetJacobianOfSpatialHessianFunction)( ipp, jsh, nonZeroJacobianIndices ); } // end GetJacobianOfSpatialHessian() /** * ****************** GetJacobianOfSpatialHessian **************************** */ template <typename TScalarType, unsigned int NDimensions> void AdvancedCombinationTransform<TScalarType, NDimensions> ::GetJacobianOfSpatialHessian( const InputPointType & ipp, SpatialHessianType & sh, JacobianOfSpatialHessianType & jsh, NonZeroJacobianIndicesType & nonZeroJacobianIndices ) const { /** Call the selected GetJacobian. */ return ((*this).*m_SelectedGetJacobianOfSpatialHessianFunction2)( ipp, sh, jsh, nonZeroJacobianIndices ); } // end GetJacobianOfSpatialHessian() } // end namespace itk #endif // end #ifndef __itkAdvancedCombinationTransform_hxx SK: -BUG: the fix seemed to work, but was required at another place /*====================================================================== This file is part of the elastix software. Copyright (c) University Medical Center Utrecht. All rights reserved. See src/CopyrightElastix.txt or http://elastix.isi.uu.nl/legal.php for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. ======================================================================*/ #ifndef __itkAdvancedCombinationTransform_hxx #define __itkAdvancedCombinationTransform_hxx #include "itkAdvancedCombinationTransform.h" namespace itk { /** * ************************ Constructor ************************* */ template <typename TScalarType, unsigned int NDimensions> AdvancedCombinationTransform<TScalarType, NDimensions> ::AdvancedCombinationTransform() : Superclass(NDimensions,1) { /** Initialize. */ this->m_InitialTransform = 0; this->m_CurrentTransform = 0; /** Set composition by default.*/ this->m_UseAddition = false; this->m_UseComposition = true; /** Set everything to have no current transform. */ this->m_SelectedTransformPointFunction = &Self::TransformPointNoCurrentTransform; this->m_SelectedGetJacobianFunction = &Self::GetJacobianNoCurrentTransform; this->m_SelectedGetSparseJacobianFunction = &Self::GetJacobianNoCurrentTransform; this->m_SelectedGetSpatialJacobianFunction = &Self::GetSpatialJacobianNoCurrentTransform; this->m_SelectedGetSpatialHessianFunction = &Self::GetSpatialHessianNoCurrentTransform; this->m_SelectedGetJacobianOfSpatialJacobianFunction = &Self::GetJacobianOfSpatialJacobianNoCurrentTransform; this->m_SelectedGetJacobianOfSpatialJacobianFunction2 = &Self::GetJacobianOfSpatialJacobianNoCurrentTransform; this->m_SelectedGetJacobianOfSpatialHessianFunction = &Self::GetJacobianOfSpatialHessianNoCurrentTransform; this->m_SelectedGetJacobianOfSpatialHessianFunction2 = &Self::GetJacobianOfSpatialHessianNoCurrentTransform; } // end Constructor /** * * *********************************************************** * ***** Override functions to aid for combining transformations. * * *********************************************************** * */ /** * ***************** GetNumberOfParameters ************************** */ template <typename TScalarType, unsigned int NDimensions> unsigned int AdvancedCombinationTransform<TScalarType, NDimensions> ::GetNumberOfParameters( void ) const { /** Return the number of parameters that completely define * the m_CurrentTransform. */ if ( this->m_CurrentTransform.IsNotNull() ) { return this->m_CurrentTransform->GetNumberOfParameters(); } else { /** Throw an exception. */ this->NoCurrentTransformSet(); /** dummy return. */ return this->m_Parameters.GetSize(); } } // end GetNumberOfParameters() /** * ***************** GetNumberOfNonZeroJacobianIndices ************************** */ template <typename TScalarType, unsigned int NDimensions> unsigned long AdvancedCombinationTransform<TScalarType, NDimensions> ::GetNumberOfNonZeroJacobianIndices( void ) const { /** Return the number of parameters that completely define * the m_CurrentTransform. */ if ( this->m_CurrentTransform.IsNotNull() ) { return this->m_CurrentTransform->GetNumberOfNonZeroJacobianIndices(); } else { /** Throw an exception. */ this->NoCurrentTransformSet(); /** dummy return. */ return this->m_Parameters.GetSize(); } } // end GetNumberOfNonZeroJacobianIndices() /** * ***************** IsLinear ************************** */ template <typename TScalarType, unsigned int NDimensions> bool AdvancedCombinationTransform<TScalarType, NDimensions> ::IsLinear( void ) const { bool currentLinear = true; if ( this->m_CurrentTransform.IsNotNull() ) { currentLinear = this->m_CurrentTransform->IsLinear(); } bool initialLinear = true; if ( this->m_InitialTransform.IsNotNull() ) { initialLinear = this->m_InitialTransform->IsLinear(); } return ( currentLinear && initialLinear ); } // end IsLinear() /** * ***************** GetParameters ************************** */ template <typename TScalarType, unsigned int NDimensions> const typename AdvancedCombinationTransform<TScalarType, NDimensions>::ParametersType & AdvancedCombinationTransform<TScalarType, NDimensions> ::GetParameters( void ) const { /** Return the parameters that completely define the m_CurrentTransform. */ if ( this->m_CurrentTransform.IsNotNull() ) { return this->m_CurrentTransform->GetParameters(); } else { /** Throw an exception. */ this->NoCurrentTransformSet(); /** dummy return. */ return this->m_Parameters; } } // end GetParameters() /** * ***************** SetParameters ************************** */ template <typename TScalarType, unsigned int NDimensions> void AdvancedCombinationTransform<TScalarType, NDimensions> ::SetParameters( const ParametersType & param ) { /** Set the parameters in the m_CurrentTransform. */ if ( this->m_CurrentTransform.IsNotNull() ) { this->Modified(); this->m_CurrentTransform->SetParameters( param ); } else { /** Throw an exception. */ this->NoCurrentTransformSet(); } } // end SetParameters() /** * ***************** SetParametersByValue ************************** */ template <typename TScalarType, unsigned int NDimensions> void AdvancedCombinationTransform<TScalarType, NDimensions> ::SetParametersByValue( const ParametersType & param ) { /** Set the parameters in the m_CurrentTransfom. */ if ( this->m_CurrentTransform.IsNotNull() ) { this->Modified(); this->m_CurrentTransform->SetParametersByValue( param ); } else { /** Throw an exception. */ this->NoCurrentTransformSet(); } } // end SetParametersByValue() /** * ***************** GetInverse ************************** */ template <typename TScalarType, unsigned int NDimensions> bool AdvancedCombinationTransform<TScalarType, NDimensions> ::GetInverse( Self * inverse ) const { if( !inverse ) { /** Inverse transformation cannot be returned into nothingness. */ return false; } else if ( this->m_CurrentTransform.IsNull() ) { /** No current transform has been set. Throw an exception. */ this->NoCurrentTransformSet(); return false; } else if ( this->m_InitialTransform.IsNull() ) { /** No Initial transform, so call the CurrentTransform's implementation. */ return this->m_CurrentTransform->GetInverse( inverse ); } else if ( this->m_UseAddition ) { /** No generic expression exists for the inverse of (T0+T1)(x). */ return false; } else // UseComposition { /** The initial transform and the current transform have been set * and UseComposition is set to true. * The inverse transform IT is defined by: * IT ( T1(T0(x) ) = x * So: * IT(y) = T0^{-1} ( T1^{-1} (y) ), * which is of course only defined when the inverses of both * the initial and the current transforms are defined. */ /** Try create the inverse of the initial transform. */ InitialTransformPointer inverseT0 = InitialTransformType::New(); bool T0invertable = this->m_InitialTransform->GetInverse( inverseT0 ); if ( T0invertable ) { /** Try to create the inverse of the current transform. */ CurrentTransformPointer inverseT1 = CurrentTransformType::New(); bool T1invertable = this->m_CurrentTransform->GetInverse( inverseT1 ); if ( T1invertable ) { /** The transform can be inverted! */ inverse->SetUseComposition( true ); inverse->SetInitialTransform( inverseT1 ); inverse->SetCurrentTransform( inverseT0 ); return true; } else { /** The initial transform is invertible, but the current one not. */ return false; } } else { /** The initial transform is not invertible. */ return false; } } // end else: UseComposition } // end GetInverse() /** * ***************** GetHasNonZeroSpatialHessian ************************** */ template <typename TScalarType, unsigned int NDimensions> bool AdvancedCombinationTransform<TScalarType, NDimensions> ::GetHasNonZeroSpatialHessian( void ) const { /** Set the parameters in the m_CurrentTransfom. */ if ( this->m_CurrentTransform.IsNull() ) { /** No current transform has been set. Throw an exception. */ this->NoCurrentTransformSet(); return false; } else if ( this->m_InitialTransform.IsNull() ) { /** No Initial transform, so call the CurrentTransform's implementation. */ return this->m_CurrentTransform->GetHasNonZeroSpatialHessian(); } else { bool dummy = this->m_InitialTransform->GetHasNonZeroSpatialHessian() || this->m_CurrentTransform->GetHasNonZeroSpatialHessian(); return dummy; } } // end GetHasNonZeroSpatialHessian() /** * ***************** HasNonZeroJacobianOfSpatialHessian ************************** */ template <typename TScalarType, unsigned int NDimensions> bool AdvancedCombinationTransform<TScalarType, NDimensions> ::HasNonZeroJacobianOfSpatialHessian( void ) const { /** Set the parameters in the m_CurrentTransfom. */ if ( this->m_CurrentTransform.IsNull() ) { /** No current transform has been set. Throw an exception. */ this->NoCurrentTransformSet(); return false; } else if ( this->m_InitialTransform.IsNull() ) { /** No Initial transform, so call the CurrentTransform's implementation. */ return this->m_CurrentTransform->GetHasNonZeroJacobianOfSpatialHessian(); } else { bool dummy = this->m_InitialTransform->GetHasNonZeroJacobianOfSpatialHessian() || this->m_CurrentTransform->GetHasNonZeroJacobianOfSpatialHessian(); return dummy; } } // end HasNonZeroJacobianOfSpatialHessian() /** * * *********************************************************** * ***** Functions to set the transformations and choose the * ***** combination method. * * *********************************************************** * */ /** * ******************* SetInitialTransform ********************** */ template <typename TScalarType, unsigned int NDimensions> void AdvancedCombinationTransform<TScalarType, NDimensions> ::SetInitialTransform( const InitialTransformType * _arg ) { /** Set the the initial transform and call the UpdateCombinationMethod. */ if ( this->m_InitialTransform != _arg ) { this->m_InitialTransform = _arg; this->Modified(); this->UpdateCombinationMethod(); } } // end SetInitialTransform() /** * ******************* SetCurrentTransform ********************** */ template <typename TScalarType, unsigned int NDimensions> void AdvancedCombinationTransform<TScalarType, NDimensions> ::SetCurrentTransform( CurrentTransformType * _arg ) { /** Set the the current transform and call the UpdateCombinationMethod. */ if ( this->m_CurrentTransform != _arg ) { this->m_CurrentTransform = _arg; this->Modified(); this->UpdateCombinationMethod(); } } // end SetCurrentTransform() /** * ********************** SetUseAddition ********************** */ template <typename TScalarType, unsigned int NDimensions> void AdvancedCombinationTransform<TScalarType, NDimensions> ::SetUseAddition( bool _arg ) { /** Set the UseAddition and UseComposition bools and call the UpdateCombinationMethod. */ if ( this->m_UseAddition != _arg ) { this->m_UseAddition = _arg; this->m_UseComposition = !_arg; this->Modified(); this->UpdateCombinationMethod(); } } // end SetUseAddition() /** * ********************** SetUseComposition ******************* */ template <typename TScalarType, unsigned int NDimensions> void AdvancedCombinationTransform<TScalarType, NDimensions> ::SetUseComposition( bool _arg ) { /** Set the UseAddition and UseComposition bools and call the UpdateCombinationMethod. */ if ( this->m_UseComposition != _arg ) { this->m_UseComposition = _arg; this->m_UseAddition = !_arg; this->Modified(); this->UpdateCombinationMethod(); } } // end SetUseComposition() /** * ****************** UpdateCombinationMethod ******************** */ template <typename TScalarType, unsigned int NDimensions> void AdvancedCombinationTransform<TScalarType, NDimensions> ::UpdateCombinationMethod( void ) { /** Update the m_SelectedTransformPointFunction and * the m_SelectedGetJacobianFunction */ if ( this->m_CurrentTransform.IsNull() ) { this->m_SelectedTransformPointFunction = &Self::TransformPointNoCurrentTransform; this->m_SelectedGetJacobianFunction = &Self::GetJacobianNoCurrentTransform; this->m_SelectedGetSparseJacobianFunction = &Self::GetJacobianNoCurrentTransform; this->m_SelectedGetSpatialJacobianFunction = &Self::GetSpatialJacobianNoCurrentTransform; this->m_SelectedGetSpatialHessianFunction = &Self::GetSpatialHessianNoCurrentTransform; this->m_SelectedGetJacobianOfSpatialJacobianFunction = &Self::GetJacobianOfSpatialJacobianNoCurrentTransform; this->m_SelectedGetJacobianOfSpatialJacobianFunction2 = &Self::GetJacobianOfSpatialJacobianNoCurrentTransform; this->m_SelectedGetJacobianOfSpatialHessianFunction = &Self::GetJacobianOfSpatialHessianNoCurrentTransform; this->m_SelectedGetJacobianOfSpatialHessianFunction2 = &Self::GetJacobianOfSpatialHessianNoCurrentTransform; } else if ( this->m_InitialTransform.IsNull() ) { this->m_SelectedTransformPointFunction = &Self::TransformPointNoInitialTransform; this->m_SelectedGetJacobianFunction = &Self::GetJacobianNoInitialTransform; this->m_SelectedGetSparseJacobianFunction = &Self::GetJacobianNoInitialTransform; this->m_SelectedGetSpatialJacobianFunction = &Self::GetSpatialJacobianNoInitialTransform; this->m_SelectedGetSpatialHessianFunction = &Self::GetSpatialHessianNoInitialTransform; this->m_SelectedGetJacobianOfSpatialJacobianFunction = &Self::GetJacobianOfSpatialJacobianNoInitialTransform; this->m_SelectedGetJacobianOfSpatialJacobianFunction2 = &Self::GetJacobianOfSpatialJacobianNoInitialTransform; this->m_SelectedGetJacobianOfSpatialHessianFunction = &Self::GetJacobianOfSpatialHessianNoInitialTransform; this->m_SelectedGetJacobianOfSpatialHessianFunction2 = &Self::GetJacobianOfSpatialHessianNoInitialTransform; } else if ( this->m_UseAddition ) { this->m_SelectedTransformPointFunction = &Self::TransformPointUseAddition; this->m_SelectedGetJacobianFunction = &Self::GetJacobianUseAddition; this->m_SelectedGetSparseJacobianFunction = &Self::GetJacobianUseAddition; this->m_SelectedGetSpatialJacobianFunction = &Self::GetSpatialJacobianUseAddition; this->m_SelectedGetSpatialHessianFunction = &Self::GetSpatialHessianUseAddition; this->m_SelectedGetJacobianOfSpatialJacobianFunction = &Self::GetJacobianOfSpatialJacobianUseAddition; this->m_SelectedGetJacobianOfSpatialJacobianFunction2 = &Self::GetJacobianOfSpatialJacobianUseAddition; this->m_SelectedGetJacobianOfSpatialHessianFunction = &Self::GetJacobianOfSpatialHessianUseAddition; this->m_SelectedGetJacobianOfSpatialHessianFunction2 = &Self::GetJacobianOfSpatialHessianUseAddition; } else { this->m_SelectedTransformPointFunction = &Self::TransformPointUseComposition; this->m_SelectedGetJacobianFunction = &Self::GetJacobianUseComposition; this->m_SelectedGetSparseJacobianFunction = &Self::GetJacobianUseComposition; this->m_SelectedGetSpatialJacobianFunction = &Self::GetSpatialJacobianUseComposition; this->m_SelectedGetSpatialHessianFunction = &Self::GetSpatialHessianUseComposition; this->m_SelectedGetJacobianOfSpatialJacobianFunction = &Self::GetJacobianOfSpatialJacobianUseComposition; this->m_SelectedGetJacobianOfSpatialJacobianFunction2 = &Self::GetJacobianOfSpatialJacobianUseComposition; this->m_SelectedGetJacobianOfSpatialHessianFunction = &Self::GetJacobianOfSpatialHessianUseComposition; this->m_SelectedGetJacobianOfSpatialHessianFunction2 = &Self::GetJacobianOfSpatialHessianUseComposition; } } // end UpdateCombinationMethod() /** * ************* NoCurrentTransformSet ********************** */ template <typename TScalarType, unsigned int NDimensions> void AdvancedCombinationTransform<TScalarType, NDimensions> ::NoCurrentTransformSet( void ) const throw (ExceptionObject) { itkExceptionMacro( << "No current transform set in the AdvancedCombinationTransform" ); } // end NoCurrentTransformSet() /** * * *********************************************************** * ***** Functions that implement the: * ***** - TransformPoint() * ***** - GetJacobian() * ***** - GetSpatialJacobian() * ***** - GetSpatialHessian() * ***** - GetJacobianOfSpatialJacobian() * ***** - GetJacobianOfSpatialHessian() * ***** for the four possible cases: * ***** - no initial transform: this is the same as using only one transform * ***** - no current transform: error, it should be set * ***** - use addition to combine transformations * ***** - use composition to combine transformations * * *********************************************************** * */ /** * ************* TransformPointUseAddition ********************** */ template <typename TScalarType, unsigned int NDimensions> typename AdvancedCombinationTransform<TScalarType, NDimensions>::OutputPointType AdvancedCombinationTransform<TScalarType, NDimensions> ::TransformPointUseAddition( const InputPointType & point ) const { /** The Initial transform. */ OutputPointType out0 = this->m_InitialTransform->TransformPoint( point ); /** The Current transform. */ OutputPointType out = this->m_CurrentTransform->TransformPoint( point ); /** Add them. */ for ( unsigned int i=0; i < SpaceDimension; i++ ) { out[ i ] += ( out0[ i ] - point[ i ] ); } return out; } // end TransformPointUseAddition() /** * **************** TransformPointUseComposition ************* */ template <typename TScalarType, unsigned int NDimensions> typename AdvancedCombinationTransform<TScalarType, NDimensions>::OutputPointType AdvancedCombinationTransform<TScalarType, NDimensions> ::TransformPointUseComposition( const InputPointType & point ) const { return this->m_CurrentTransform->TransformPoint( this->m_InitialTransform->TransformPoint( point ) ); } // end TransformPointUseComposition() /** * **************** TransformPointNoInitialTransform ****************** */ template <typename TScalarType, unsigned int NDimensions> typename AdvancedCombinationTransform<TScalarType, NDimensions>::OutputPointType AdvancedCombinationTransform<TScalarType, NDimensions> ::TransformPointNoInitialTransform( const InputPointType & point ) const { return this->m_CurrentTransform->TransformPoint( point ); } // end TransformPointNoInitialTransform() /** * ******** TransformPointNoCurrentTransform ****************** */ template <typename TScalarType, unsigned int NDimensions> typename AdvancedCombinationTransform<TScalarType, NDimensions>::OutputPointType AdvancedCombinationTransform<TScalarType, NDimensions> ::TransformPointNoCurrentTransform( const InputPointType & point ) const { /** Throw an exception. */ this->NoCurrentTransformSet(); /** dummy return. */ return point; } // end TransformPointNoCurrentTransform() /** * ************* GetJacobianUseAddition *************************** */ template <typename TScalarType, unsigned int NDimensions> const typename AdvancedCombinationTransform<TScalarType, NDimensions>::JacobianType & AdvancedCombinationTransform<TScalarType, NDimensions> ::GetJacobianUseAddition( const InputPointType & point ) const { return this->m_CurrentTransform->GetJacobian( point ); } // end GetJacobianUseAddition() /** * **************** GetJacobianUseComposition ************* */ template <typename TScalarType, unsigned int NDimensions> const typename AdvancedCombinationTransform<TScalarType, NDimensions>::JacobianType & AdvancedCombinationTransform<TScalarType, NDimensions> ::GetJacobianUseComposition( const InputPointType & point ) const { return this->m_CurrentTransform->GetJacobian( this->m_InitialTransform->TransformPoint( point ) ); } // end GetJacobianUseComposition() /** * **************** GetJacobianNoInitialTransform ****************** */ template <typename TScalarType, unsigned int NDimensions> const typename AdvancedCombinationTransform<TScalarType, NDimensions>::JacobianType & AdvancedCombinationTransform<TScalarType, NDimensions> ::GetJacobianNoInitialTransform( const InputPointType & point ) const { return this->m_CurrentTransform->GetJacobian( point ); } // end GetJacobianNoInitialTransform() /** * ******** GetJacobianNoCurrentTransform ****************** */ template <typename TScalarType, unsigned int NDimensions> const typename AdvancedCombinationTransform<TScalarType, NDimensions>::JacobianType & AdvancedCombinationTransform<TScalarType, NDimensions> ::GetJacobianNoCurrentTransform( const InputPointType & point ) const { /** Throw an exception. */ this->NoCurrentTransformSet(); /** dummy return. */ return this->m_Jacobian; } // end GetJacobianNoCurrentTransform() /** * ************* GetJacobianUseAddition *************************** */ template <typename TScalarType, unsigned int NDimensions> void AdvancedCombinationTransform<TScalarType, NDimensions> ::GetJacobianUseAddition( const InputPointType & ipp, JacobianType & j, NonZeroJacobianIndicesType & nonZeroJacobianIndices ) const { this->m_CurrentTransform->GetJacobian( ipp, j, nonZeroJacobianIndices ); } // end GetJacobianUseAddition() /** * **************** GetJacobianUseComposition ************* */ template <typename TScalarType, unsigned int NDimensions> void AdvancedCombinationTransform<TScalarType, NDimensions> ::GetJacobianUseComposition( const InputPointType & ipp, JacobianType & j, NonZeroJacobianIndicesType & nonZeroJacobianIndices ) const { this->m_CurrentTransform->GetJacobian( this->m_InitialTransform->TransformPoint( ipp ), j, nonZeroJacobianIndices ); } // end GetJacobianUseComposition() /** * **************** GetJacobianNoInitialTransform ****************** */ template <typename TScalarType, unsigned int NDimensions> void AdvancedCombinationTransform<TScalarType, NDimensions> ::GetJacobianNoInitialTransform( const InputPointType & ipp, JacobianType & j, NonZeroJacobianIndicesType & nonZeroJacobianIndices ) const { this->m_CurrentTransform->GetJacobian( ipp, j, nonZeroJacobianIndices ); } // end GetJacobianNoInitialTransform() /** * ******** GetJacobianNoCurrentTransform ****************** */ template <typename TScalarType, unsigned int NDimensions> void AdvancedCombinationTransform<TScalarType, NDimensions> ::GetJacobianNoCurrentTransform( const InputPointType & ipp, JacobianType & j, NonZeroJacobianIndicesType & nonZeroJacobianIndices ) const { /** Throw an exception. */ this->NoCurrentTransformSet(); } // end GetJacobianNoCurrentTransform() /** * ************* GetSpatialJacobianUseAddition *************************** */ template <typename TScalarType, unsigned int NDimensions> void AdvancedCombinationTransform<TScalarType, NDimensions> ::GetSpatialJacobianUseAddition( const InputPointType & ipp, SpatialJacobianType & sj ) const { SpatialJacobianType sj0, sj1, identity; this->m_InitialTransform->GetSpatialJacobian( ipp, sj0 ); this->m_CurrentTransform->GetSpatialJacobian( ipp, sj1 ); identity.SetIdentity(); sj = sj0 + sj1 - identity; } // end GetSpatialJacobianUseAddition() /** * **************** GetSpatialJacobianUseComposition ************* */ template <typename TScalarType, unsigned int NDimensions> void AdvancedCombinationTransform<TScalarType, NDimensions> ::GetSpatialJacobianUseComposition( const InputPointType & ipp, SpatialJacobianType & sj ) const { SpatialJacobianType sj0, sj1; this->m_InitialTransform->GetSpatialJacobian( ipp, sj0 ); this->m_CurrentTransform->GetSpatialJacobian( this->m_InitialTransform->TransformPoint( ipp ), sj1 ); sj = sj1 * sj0; } // end GetSpatialJacobianUseComposition() /** * **************** GetSpatialJacobianNoInitialTransform ****************** */ template <typename TScalarType, unsigned int NDimensions> void AdvancedCombinationTransform<TScalarType, NDimensions> ::GetSpatialJacobianNoInitialTransform( const InputPointType & ipp, SpatialJacobianType & sj ) const { this->m_CurrentTransform->GetSpatialJacobian( ipp, sj ); } // end GetSpatialJacobianNoInitialTransform() /** * ******** GetSpatialJacobianNoCurrentTransform ****************** */ template <typename TScalarType, unsigned int NDimensions> void AdvancedCombinationTransform<TScalarType, NDimensions> ::GetSpatialJacobianNoCurrentTransform( const InputPointType & ipp, SpatialJacobianType & sj ) const { /** Throw an exception. */ this->NoCurrentTransformSet(); } // end GetSpatialJacobianNoCurrentTransform() /** * ******** GetSpatialHessianUseAddition ****************** */ template <typename TScalarType, unsigned int NDimensions> void AdvancedCombinationTransform<TScalarType, NDimensions> ::GetSpatialHessianUseAddition( const InputPointType & ipp, SpatialHessianType & sh ) const { SpatialHessianType sh0, sh1; this->m_InitialTransform->GetSpatialHessian( ipp, sh0 ); this->m_CurrentTransform->GetSpatialHessian( ipp, sh1 ); for ( unsigned int i = 0; i < SpaceDimension; ++i ) { sh[ i ] = sh0[ i ] + sh1[ i ]; } } // end GetSpatialHessianUseAddition() /** * ******** GetSpatialHessianUseComposition ****************** */ template <typename TScalarType, unsigned int NDimensions> void AdvancedCombinationTransform<TScalarType, NDimensions> ::GetSpatialHessianUseComposition( const InputPointType & ipp, SpatialHessianType & sh ) const { /** Create intermediary variables for the internal transforms. */ SpatialJacobianType sj0, sj1; SpatialHessianType sh0, sh1; /** Transform the input point. */ // \todo this has already been computed and it is expensive. InputPointType transformedPoint = this->m_InitialTransform->TransformPoint( ipp ); /** Compute the (Jacobian of the) spatial Jacobian / Hessian of the * internal transforms. */ this->m_InitialTransform->GetSpatialJacobian( ipp, sj0 ); this->m_CurrentTransform->GetSpatialJacobian( transformedPoint, sj1 ); this->m_InitialTransform->GetSpatialHessian( ipp, sh0 ); this->m_CurrentTransform->GetSpatialHessian( transformedPoint, sh1 ); typename SpatialJacobianType::InternalMatrixType sj0tvnl = sj0.GetTranspose(); SpatialJacobianType sj0t( sj0tvnl ); /** Combine them in one overall spatial Hessian. */ for ( unsigned int dim = 0; dim < SpaceDimension; ++dim ) { sh[dim] = sj0t * ( sh1[dim] * sj0 ); for ( unsigned int p = 0; p < SpaceDimension; ++p ) { sh[dim] += ( sh0[p] * sj1(dim,p) ); } } } // end GetSpatialHessianUseComposition() /** * ******** GetSpatialHessianNoInitialTransform ****************** */ template <typename TScalarType, unsigned int NDimensions> void AdvancedCombinationTransform<TScalarType, NDimensions> ::GetSpatialHessianNoInitialTransform( const InputPointType & ipp, SpatialHessianType & sh ) const { this->m_CurrentTransform->GetSpatialHessian( ipp, sh ); } // end GetSpatialHessianNoInitialTransform() /** * ******** GetSpatialHessianNoCurrentTransform ****************** */ template <typename TScalarType, unsigned int NDimensions> void AdvancedCombinationTransform<TScalarType, NDimensions> ::GetSpatialHessianNoCurrentTransform( const InputPointType & ipp, SpatialHessianType & sh ) const { /** Throw an exception. */ this->NoCurrentTransformSet(); } // end GetSpatialHessianNoCurrentTransform() /** * ******** GetJacobianOfSpatialJacobianUseAddition ****************** */ template <typename TScalarType, unsigned int NDimensions> void AdvancedCombinationTransform<TScalarType, NDimensions> ::GetJacobianOfSpatialJacobianUseAddition( const InputPointType & ipp, JacobianOfSpatialJacobianType & jsj, NonZeroJacobianIndicesType & nonZeroJacobianIndices ) const { this->m_CurrentTransform->GetJacobianOfSpatialJacobian( ipp, jsj, nonZeroJacobianIndices ); } // end GetJacobianOfSpatialJacobianUseAddition() /** * ******** GetJacobianOfSpatialJacobianUseAddition ****************** */ template <typename TScalarType, unsigned int NDimensions> void AdvancedCombinationTransform<TScalarType, NDimensions> ::GetJacobianOfSpatialJacobianUseAddition( const InputPointType & ipp, SpatialJacobianType & sj, JacobianOfSpatialJacobianType & jsj, NonZeroJacobianIndicesType & nonZeroJacobianIndices ) const { this->m_CurrentTransform->GetJacobianOfSpatialJacobian( ipp, sj, jsj, nonZeroJacobianIndices ); } // end GetJacobianOfSpatialJacobianUseAddition() /** * ******** GetJacobianOfSpatialJacobianUseComposition ****************** */ template <typename TScalarType, unsigned int NDimensions> void AdvancedCombinationTransform<TScalarType, NDimensions> ::GetJacobianOfSpatialJacobianUseComposition( const InputPointType & ipp, JacobianOfSpatialJacobianType & jsj, NonZeroJacobianIndicesType & nonZeroJacobianIndices ) const { SpatialJacobianType sj0; JacobianOfSpatialJacobianType jsj1; this->m_InitialTransform->GetSpatialJacobian( ipp, sj0 ); this->m_CurrentTransform->GetJacobianOfSpatialJacobian( this->m_InitialTransform->TransformPoint( ipp ), jsj1, nonZeroJacobianIndices ); jsj.resize( nonZeroJacobianIndices.size() ); for ( unsigned int mu = 0; mu < nonZeroJacobianIndices.size(); ++mu ) { jsj[ mu ] = jsj1[ mu ] * sj0; } } // end GetJacobianOfSpatialJacobianUseComposition() /** * ******** GetJacobianOfSpatialJacobianUseComposition ****************** */ template <typename TScalarType, unsigned int NDimensions> void AdvancedCombinationTransform<TScalarType, NDimensions> ::GetJacobianOfSpatialJacobianUseComposition( const InputPointType & ipp, SpatialJacobianType & sj, JacobianOfSpatialJacobianType & jsj, NonZeroJacobianIndicesType & nonZeroJacobianIndices ) const { SpatialJacobianType sj0, sj1; JacobianOfSpatialJacobianType jsj1; this->m_InitialTransform->GetSpatialJacobian( ipp, sj0 ); this->m_CurrentTransform->GetJacobianOfSpatialJacobian( this->m_InitialTransform->TransformPoint( ipp ), sj1, jsj1, nonZeroJacobianIndices ); sj = sj1 * sj0; jsj.resize( nonZeroJacobianIndices.size() ); for ( unsigned int mu = 0; mu < nonZeroJacobianIndices.size(); ++mu ) { jsj[ mu ] = jsj1[ mu ] * sj0; } } // end GetJacobianOfSpatialJacobianUseComposition() /** * ******** GetJacobianOfSpatialJacobianNoInitialTransform ****************** */ template <typename TScalarType, unsigned int NDimensions> void AdvancedCombinationTransform<TScalarType, NDimensions> ::GetJacobianOfSpatialJacobianNoInitialTransform( const InputPointType & ipp, JacobianOfSpatialJacobianType & jsj, NonZeroJacobianIndicesType & nonZeroJacobianIndices ) const { this->m_CurrentTransform->GetJacobianOfSpatialJacobian( ipp, jsj, nonZeroJacobianIndices ); } // end GetJacobianOfSpatialJacobianNoInitialTransform() /** * ******** GetJacobianOfSpatialJacobianNoInitialTransform ****************** */ template <typename TScalarType, unsigned int NDimensions> void AdvancedCombinationTransform<TScalarType, NDimensions> ::GetJacobianOfSpatialJacobianNoInitialTransform( const InputPointType & ipp, SpatialJacobianType & sj, JacobianOfSpatialJacobianType & jsj, NonZeroJacobianIndicesType & nonZeroJacobianIndices ) const { this->m_CurrentTransform->GetJacobianOfSpatialJacobian( ipp, sj, jsj, nonZeroJacobianIndices ); } // end GetJacobianOfSpatialJacobianNoInitialTransform() /** * ******** GetJacobianOfSpatialJacobianNoCurrentTransform ****************** */ template <typename TScalarType, unsigned int NDimensions> void AdvancedCombinationTransform<TScalarType, NDimensions> ::GetJacobianOfSpatialJacobianNoCurrentTransform( const InputPointType & ipp, JacobianOfSpatialJacobianType & jsj, NonZeroJacobianIndicesType & nonZeroJacobianIndices ) const { /** Throw an exception. */ this->NoCurrentTransformSet(); } // end GetJacobianOfSpatialJacobianNoCurrentTransform() /** * ******** GetJacobianOfSpatialJacobianNoCurrentTransform ****************** */ template <typename TScalarType, unsigned int NDimensions> void AdvancedCombinationTransform<TScalarType, NDimensions> ::GetJacobianOfSpatialJacobianNoCurrentTransform( const InputPointType & ipp, SpatialJacobianType & sj, JacobianOfSpatialJacobianType & jsj, NonZeroJacobianIndicesType & nonZeroJacobianIndices ) const { /** Throw an exception. */ this->NoCurrentTransformSet(); } // end GetJacobianOfSpatialJacobianNoCurrentTransform() /** * ******** GetJacobianOfSpatialHessianUseAddition ****************** */ template <typename TScalarType, unsigned int NDimensions> void AdvancedCombinationTransform<TScalarType, NDimensions> ::GetJacobianOfSpatialHessianUseAddition( const InputPointType & ipp, JacobianOfSpatialHessianType & jsh, NonZeroJacobianIndicesType & nonZeroJacobianIndices ) const { this->m_CurrentTransform->GetJacobianOfSpatialHessian( ipp, jsh, nonZeroJacobianIndices ); } // end GetJacobianOfSpatialHessianUseAddition() /** * ******** GetJacobianOfSpatialHessianUseAddition ****************** */ template <typename TScalarType, unsigned int NDimensions> void AdvancedCombinationTransform<TScalarType, NDimensions> ::GetJacobianOfSpatialHessianUseAddition( const InputPointType & ipp, SpatialHessianType & sh, JacobianOfSpatialHessianType & jsh, NonZeroJacobianIndicesType & nonZeroJacobianIndices ) const { this->m_CurrentTransform->GetJacobianOfSpatialHessian( ipp, sh, jsh, nonZeroJacobianIndices ); } // end GetJacobianOfSpatialHessianUseAddition() /** * ******** GetJacobianOfSpatialHessianUseComposition ****************** */ template <typename TScalarType, unsigned int NDimensions> void AdvancedCombinationTransform<TScalarType, NDimensions> ::GetJacobianOfSpatialHessianUseComposition( const InputPointType & ipp, JacobianOfSpatialHessianType & jsh, NonZeroJacobianIndicesType & nonZeroJacobianIndices ) const { /** Create intermediary variables for the internal transforms. */ SpatialJacobianType sj0; SpatialHessianType sh0; JacobianOfSpatialJacobianType jsj1; JacobianOfSpatialHessianType jsh1; /** Transform the input point. */ // \todo: this has already been computed and it is expensive. InputPointType transformedPoint = this->m_InitialTransform->TransformPoint( ipp ); /** Compute the (Jacobian of the) spatial Jacobian / Hessian of the * internal transforms. */ this->m_InitialTransform->GetSpatialJacobian( ipp, sj0 ); this->m_InitialTransform->GetSpatialHessian( ipp, sh0 ); /** Assume/demand that GetJacobianOfSpatialJacobian returns * the same nonZeroJacobianIndices as the GetJacobianOfSpatialHessian. */ this->m_CurrentTransform->GetJacobianOfSpatialJacobian( transformedPoint, jsj1, nonZeroJacobianIndices ); this->m_CurrentTransform->GetJacobianOfSpatialHessian( transformedPoint, jsh1, nonZeroJacobianIndices ); typename SpatialJacobianType::InternalMatrixType sj0tvnl = sj0.GetTranspose(); SpatialJacobianType sj0t( sj0tvnl ); jsh.resize( nonZeroJacobianIndices.size() ); /** Combine them in one overall Jacobian of spatial Hessian. */ for ( unsigned int mu = 0; mu < nonZeroJacobianIndices.size(); ++mu ) { for ( unsigned int dim = 0; dim < SpaceDimension; ++dim ) { jsh[mu][dim] = sj0t * ( jsh1[mu][dim] * sj0 ); for ( unsigned int p = 0; p < SpaceDimension; ++p ) { jsh[mu][dim] += ( sh0[p] * jsj1[mu](dim,p) ); } } } } // end GetJacobianOfSpatialHessianUseComposition() /** * ******** GetJacobianOfSpatialHessianUseComposition ****************** */ template <typename TScalarType, unsigned int NDimensions> void AdvancedCombinationTransform<TScalarType, NDimensions> ::GetJacobianOfSpatialHessianUseComposition( const InputPointType & ipp, SpatialHessianType & sh, JacobianOfSpatialHessianType & jsh, NonZeroJacobianIndicesType & nonZeroJacobianIndices ) const { /** Create intermediary variables for the internal transforms. */ SpatialJacobianType sj0, sj1; SpatialHessianType sh0, sh1; JacobianOfSpatialJacobianType jsj1; JacobianOfSpatialHessianType jsh1; /** Transform the input point. */ // \todo this has already been computed and it is expensive. InputPointType transformedPoint = this->m_InitialTransform->TransformPoint( ipp ); /** Compute the (Jacobian of the) spatial Jacobian / Hessian of the * internal transforms. */ this->m_InitialTransform->GetSpatialJacobian( ipp, sj0 ); this->m_InitialTransform->GetSpatialHessian( ipp, sh0 ); /** Assume/demand that GetJacobianOfSpatialJacobian returns * the same nonZeroJacobianIndices as the GetJacobianOfSpatialHessian. */ this->m_CurrentTransform->GetJacobianOfSpatialJacobian( transformedPoint, sj1, jsj1, nonZeroJacobianIndices ); this->m_CurrentTransform->GetJacobianOfSpatialHessian( transformedPoint, sh1, jsh1, nonZeroJacobianIndices ); typename SpatialJacobianType::InternalMatrixType sj0tvnl = sj0.GetTranspose(); SpatialJacobianType sj0t( sj0tvnl ); jsh.resize( nonZeroJacobianIndices.size() ); /** Combine them in one overall Jacobian of spatial Hessian. */ for ( unsigned int mu = 0; mu < nonZeroJacobianIndices.size(); ++mu ) { for ( unsigned int dim = 0; dim < SpaceDimension; ++dim ) { jsh[mu][dim] = sj0t * ( jsh1[mu][dim] * sj0 ); for ( unsigned int p = 0; p < SpaceDimension; ++p ) { jsh[mu][dim] += ( sh0[p] * jsj1[mu](dim,p) ); } } } /** Combine them in one overall spatial Hessian. */ for ( unsigned int dim = 0; dim < SpaceDimension; ++dim ) { sh[dim] = sj0t * ( sh1[dim] * sj0 ); for ( unsigned int p = 0; p < SpaceDimension; ++p ) { sh[dim] += ( sh0[p] * sj1(dim,p) ); } } } // end GetJacobianOfSpatialHessianUseComposition() /** * ******** GetJacobianOfSpatialHessianNoInitialTransform ****************** */ template <typename TScalarType, unsigned int NDimensions> void AdvancedCombinationTransform<TScalarType, NDimensions> ::GetJacobianOfSpatialHessianNoInitialTransform( const InputPointType & ipp, JacobianOfSpatialHessianType & jsh, NonZeroJacobianIndicesType & nonZeroJacobianIndices ) const { this->m_CurrentTransform->GetJacobianOfSpatialHessian( ipp, jsh, nonZeroJacobianIndices ); } // end GetJacobianOfSpatialHessianNoInitialTransform() /** * ******** GetJacobianOfSpatialHessianNoInitialTransform ****************** */ template <typename TScalarType, unsigned int NDimensions> void AdvancedCombinationTransform<TScalarType, NDimensions> ::GetJacobianOfSpatialHessianNoInitialTransform( const InputPointType & ipp, SpatialHessianType & sh, JacobianOfSpatialHessianType & jsh, NonZeroJacobianIndicesType & nonZeroJacobianIndices ) const { this->m_CurrentTransform->GetJacobianOfSpatialHessian( ipp, sh, jsh, nonZeroJacobianIndices ); } // end GetJacobianOfSpatialHessianNoInitialTransform() /** * ******** GetJacobianOfSpatialHessianNoCurrentTransform ****************** */ template <typename TScalarType, unsigned int NDimensions> void AdvancedCombinationTransform<TScalarType, NDimensions> ::GetJacobianOfSpatialHessianNoCurrentTransform( const InputPointType & ipp, JacobianOfSpatialHessianType & jsh, NonZeroJacobianIndicesType & nonZeroJacobianIndices ) const { /** Throw an exception. */ this->NoCurrentTransformSet(); } // end GetJacobianOfSpatialHessianNoCurrentTransform() /** * ******** GetJacobianOfSpatialHessianNoCurrentTransform ****************** */ template <typename TScalarType, unsigned int NDimensions> void AdvancedCombinationTransform<TScalarType, NDimensions> ::GetJacobianOfSpatialHessianNoCurrentTransform( const InputPointType & ipp, SpatialHessianType & sh, JacobianOfSpatialHessianType & jsh, NonZeroJacobianIndicesType & nonZeroJacobianIndices ) const { /** Throw an exception. */ this->NoCurrentTransformSet(); } // end GetJacobianOfSpatialHessianNoCurrentTransform() /** * * *********************************************************** * ***** Functions that point to the selected implementation. * * *********************************************************** * */ /** * ****************** TransformPoint **************************** */ template <typename TScalarType, unsigned int NDimensions> typename AdvancedCombinationTransform<TScalarType, NDimensions>::OutputPointType AdvancedCombinationTransform<TScalarType, NDimensions> ::TransformPoint( const InputPointType & point ) const { /** Call the selected TransformPointFunction. */ return ((*this).*m_SelectedTransformPointFunction)( point ); } // end TransformPoint() /** * ****************** GetJacobian **************************** */ template <typename TScalarType, unsigned int NDimensions> const typename AdvancedCombinationTransform<TScalarType, NDimensions>::JacobianType & AdvancedCombinationTransform<TScalarType, NDimensions> ::GetJacobian( const InputPointType & point ) const { /** Call the selected GetJacobian. */ return ((*this).*m_SelectedGetJacobianFunction)( point ); } // end GetJacobian() /** * ****************** GetJacobian **************************** */ template <typename TScalarType, unsigned int NDimensions> void AdvancedCombinationTransform<TScalarType, NDimensions> ::GetJacobian( const InputPointType & ipp, JacobianType & j, NonZeroJacobianIndicesType & nonZeroJacobianIndices ) const { /** Call the selected GetJacobian. */ return ((*this).*m_SelectedGetSparseJacobianFunction)( ipp, j, nonZeroJacobianIndices ); } // end GetJacobian() /** * ****************** GetSpatialJacobian **************************** */ template <typename TScalarType, unsigned int NDimensions> void AdvancedCombinationTransform<TScalarType, NDimensions> ::GetSpatialJacobian( const InputPointType & ipp, SpatialJacobianType & sj ) const { /** Call the selected GetJacobian. */ return ((*this).*m_SelectedGetSpatialJacobianFunction)( ipp, sj ); } // end GetSpatialJacobian() /** * ****************** GetSpatialHessian **************************** */ template <typename TScalarType, unsigned int NDimensions> void AdvancedCombinationTransform<TScalarType, NDimensions> ::GetSpatialHessian( const InputPointType & ipp, SpatialHessianType & sh ) const { /** Call the selected GetJacobian. */ return ((*this).*m_SelectedGetSpatialHessianFunction)( ipp, sh ); } // end GetSpatialHessian() /** * ****************** GetJacobianOfSpatialJacobian **************************** */ template <typename TScalarType, unsigned int NDimensions> void AdvancedCombinationTransform<TScalarType, NDimensions> ::GetJacobianOfSpatialJacobian( const InputPointType & ipp, JacobianOfSpatialJacobianType & jsj, NonZeroJacobianIndicesType & nonZeroJacobianIndices ) const { /** Call the selected GetJacobian. */ return ((*this).*m_SelectedGetJacobianOfSpatialJacobianFunction)( ipp, jsj, nonZeroJacobianIndices ); } // end GetJacobianOfSpatialJacobian() /** * ****************** GetJacobianOfSpatialJacobian **************************** */ template <typename TScalarType, unsigned int NDimensions> void AdvancedCombinationTransform<TScalarType, NDimensions> ::GetJacobianOfSpatialJacobian( const InputPointType & ipp, SpatialJacobianType & sj, JacobianOfSpatialJacobianType & jsj, NonZeroJacobianIndicesType & nonZeroJacobianIndices ) const { /** Call the selected GetJacobian. */ return ((*this).*m_SelectedGetJacobianOfSpatialJacobianFunction2)( ipp, sj, jsj, nonZeroJacobianIndices ); } // end GetJacobianOfSpatialJacobian() /** * ****************** GetJacobianOfSpatialHessian **************************** */ template <typename TScalarType, unsigned int NDimensions> void AdvancedCombinationTransform<TScalarType, NDimensions> ::GetJacobianOfSpatialHessian( const InputPointType & ipp, JacobianOfSpatialHessianType & jsh, NonZeroJacobianIndicesType & nonZeroJacobianIndices ) const { /** Call the selected GetJacobian. */ return ((*this).*m_SelectedGetJacobianOfSpatialHessianFunction)( ipp, jsh, nonZeroJacobianIndices ); } // end GetJacobianOfSpatialHessian() /** * ****************** GetJacobianOfSpatialHessian **************************** */ template <typename TScalarType, unsigned int NDimensions> void AdvancedCombinationTransform<TScalarType, NDimensions> ::GetJacobianOfSpatialHessian( const InputPointType & ipp, SpatialHessianType & sh, JacobianOfSpatialHessianType & jsh, NonZeroJacobianIndicesType & nonZeroJacobianIndices ) const { /** Call the selected GetJacobian. */ return ((*this).*m_SelectedGetJacobianOfSpatialHessianFunction2)( ipp, sh, jsh, nonZeroJacobianIndices ); } // end GetJacobianOfSpatialHessian() } // end namespace itk #endif // end #ifndef __itkAdvancedCombinationTransform_hxx
// (c) 2015, dividiti // BSD license #ifndef CL_STATE_HPP #define CL_STATE_HPP #include "cl_dataset.hpp" #include <iostream> #include <fstream> #include <sstream> #include <cstdlib> #include <cassert> #include <CL/cl.h> #include <xopenme.h> #include <cJSON.h> namespace gemmbench { template<typename T> class dataset; class file { public: struct buffer { char * data; size_t size; // Default constructor. buffer() : data(NULL), size(0) { } // Initializing constructor. buffer(char * _data, size_t _size) : data(_data), size(_size) { } // Initializing constructor with pointer cast. buffer(const char * _data, size_t _size) : data((char*) _data), size(_size) { } // Destructor. ~buffer() { delete [] data; } }; // END OF buffer struct // Read file into buffer. Return true on success. static bool read(const std::string & path, buffer & buff); // Write file from buffer. Return true on success. static bool write(const std::string & path, const buffer & buff); // Prevent instantiating this class. virtual ~file(); }; // END OF file class class xopenme { private: static const int max_str_len = 1000; static const int max_var_count = 50; static const int max_tmr_count = 2; static const int max_work_dims = 3; public: char str[max_str_len]; int var_count; cl_uint tmp_uint; cl_ulong tmp_ulong; size_t tmp_size_t; size_t tmp_size_t_dims[max_work_dims]; xopenme() : var_count(0), tmp_uint(0), tmp_ulong(0), tmp_size_t(0), tmp_size_t_dims() // C++11: {0, ..., 0} { assert(3 == max_work_dims); xopenme_init(max_tmr_count, max_var_count); } ~xopenme() { xopenme_dump_state(); } bool var_count_below_max() { return var_count < max_var_count; } }; // END OF gemmbench::xopenme class class arguments { private: void print_usage(const char * cmd) { // Print on one line. std::cout << "Usage: " << cmd ; std::cout << " -f <file name>"; std::cout << " -n <matrix order>"; std::cout << " -p <platform index>"; std::cout << " -d <device index>"; std::cout << " -lws <lws_j,lws_i>"; std::cout << std::endl; exit(EXIT_SUCCESS); } public: std::string file_name; cl_uint platform_idx; cl_uint device_idx; cl_uint matrix_order; cl_uint lws_j, lws_i; cl_double eps; arguments() : file_name(""), platform_idx(0), device_idx(0), matrix_order(256), lws_j(0), lws_i(0), eps(1e-5) { } void parse(int argc, char* argv[]) { if (1 == argc) { print_usage(argv[0]); } for (int i = 1; i < argc-1; ++i) { std::string this_arg(argv[i]); std::string next_arg(argv[++i]); if ("-f" == this_arg) { file_name = next_arg; } else if ("-n" == this_arg) { std::istringstream ss(next_arg); ss >> matrix_order; } else if ("-p" == this_arg) { std::istringstream ss(next_arg); ss >> platform_idx; } else if ("-d" == this_arg) { std::istringstream ss(next_arg); ss >> device_idx; } else if ("-lws" == this_arg) { const std::string::size_type pos = next_arg.find(','); assert(std::string::npos != pos); std::istringstream lws_j_ss(next_arg.substr(0, pos)); lws_j_ss >> lws_j; std::istringstream lws_i_ss(next_arg.substr(pos+1)); lws_i_ss >> lws_i; } else if ("-eps" == this_arg) { std::istringstream ss(next_arg); ss >> eps; } else { std::cerr << "Unhandled argument: " << this_arg << std::endl; --i; // skip only one argument } } // END OF for each argument } // END OF parse() }; // END OF gemmbench::arguments class class metadata { public: // Program name. std::string name; // Program file name. std::string file; // Program build options. std::string opts; // Single precision real ("S") and complex ("C"). // Double precision real ("G") and complex ("Z"). std::string type; // Transposed ('T'), if true; non-transposed ('N'), if false. bool transA; bool transB; // Coarsening factors along rows ("di") and columns ("dj"). cl_uint di; cl_uint dj; // Constructor. metadata() : name(""), file(""), opts(""), type(""), transA(false), transB(false), di(1), dj(1) { } // Destructor. ~metadata() { } // Parse the metadata file specified with the "-f" command line argument. // Example file: // { // "name" : "DGEMM_NT_1x1", // "file" : "DGEMM_NT_1x1.cl", // "type" : "D", // "transA" : "N", // "transB" : "T", // "dj" : 1, // "di" : 1 // } void parse(const std::string & path) { #if (1 == TEST_METADATA) std::cout << "Reading OpenCL kernel metadata from string:" << std::endl; const char *raw_meta = "{\n" " \"name\" : \"DGEMM_NT_1x1\",\n" " \"file\" : \"DGEMM_NT_1x1.cl\",\n" " \"type\" : \"D\",\n" " \"transB\" : \"T\"\n" "}\n"; #else std::cout << "Reading OpenCL kernel metadata from \'" << path << "\'..." << std::endl; file::buffer buffer; bool read_success = file::read(path, buffer); assert(read_success && "file::read() failed."); assert(buffer.data && buffer.size > 0 && "No metadata."); buffer.data[buffer.size-1] = '\0'; // null-terminate const char * raw_meta = buffer.data; #endif std::cout << raw_meta << std::endl; cJSON* meta = cJSON_Parse(raw_meta); for (int i = 0; i < cJSON_GetArraySize(meta); ++i) { const cJSON *meta_i = cJSON_GetArrayItem(meta, i); const int value_type = meta_i->type; const std::string key(meta_i->string); if ("name" == key) { assert(cJSON_String == value_type && "Unexpected value type."); name = std::string(meta_i->valuestring); } else if ("file" == key) { assert(cJSON_String == value_type && "Unexpected value type."); file = std::string(meta_i->valuestring); } else if ("opts" == key) { assert(cJSON_String == value_type && "Unexpected value type."); opts = std::string(meta_i->valuestring); } else if ("type" == key) { assert(cJSON_String == value_type && "Unexpected value type."); type = std::string(meta_i->valuestring); assert(type == "S" || type == "C" || type == "D" || type == "Z"); } else if ("transA" == key) { assert(cJSON_String == value_type && "Unexpected value type."); transA = std::string(meta_i->valuestring) == "T" ? true : false; } else if ("transB" == key) { assert(cJSON_String == value_type && "Unexpected value type."); transB = std::string(meta_i->valuestring) == "T" ? true : false; } else if ("di" == key) { assert(cJSON_Number == value_type && "Unexpected value type."); di = meta_i->valueint; } else if ("dj" == key) { assert(cJSON_Number == value_type && "Unexpected value type."); dj = meta_i->valueint; } else { std::cerr << "Unhandled key: " << key << std::endl; } } // END OF for each key:value pair cJSON_Delete(meta); } // END OF parse() }; // END OF gemmbench::metadata class class state { public: // Command line arguments (with defaults). arguments args; // Kernel metadata (with defaults). metadata meta; // xOpenME state. xopenme openme; // OpenCL objects. cl_platform_id platform; cl_device_id device; cl_context context; cl_command_queue queue; cl_program program; cl_kernel kernel; cl_mem buffer_A; cl_mem buffer_B; cl_mem buffer_C; cl_event enqueue; // Constructor. state() : platform(NULL), device(NULL), context(NULL), queue(NULL), program(NULL), kernel(NULL), buffer_A(NULL), buffer_B(NULL), buffer_C(NULL), enqueue(NULL) { } // Destructor. Release in reverse order. ~state() { cl_int err = CL_SUCCESS; err = clReleaseEvent(enqueue); assert(CL_SUCCESS == err && "clReleaseEvent() failed."); err = clReleaseMemObject(buffer_C); assert(CL_SUCCESS == err && "clReleaseMemObject() failed."); err = clReleaseMemObject(buffer_B); assert(CL_SUCCESS == err && "clReleaseMemObject() failed."); err = clReleaseMemObject(buffer_A); assert(CL_SUCCESS == err && "clReleaseMemObject() failed."); err = clReleaseKernel(kernel); assert(CL_SUCCESS == err && "clReleaseKernel() failed."); err = clReleaseProgram(program); assert(CL_SUCCESS == err && "clReleaseProgram() failed."); err = clReleaseCommandQueue(queue); assert(CL_SUCCESS == err && "clReleaseCommandQueue() failed."); err = clReleaseContext(context); assert(CL_SUCCESS == err && "clReleaseContext() failed."); } void init(int argc, char* argv[]) { // Parse command line arguments. args.parse(argc, argv); #if (1 == XOPENME) xopenme_add_var_s(openme.var_count++, (char*) " \"CMD_LINE_ARGS#file_name\":\"%s\"", (char*) args.file_name.c_str()); assert(openme.var_count_below_max() && "xOpenME max var count reached."); xopenme_add_var_i(openme.var_count++, (char*) " \"CMD_LINE_ARGS#platform_idx\":%u", args.platform_idx); assert(openme.var_count_below_max() && "xOpenME max var count reached."); xopenme_add_var_i(openme.var_count++, (char*) " \"CMD_LINE_ARGS#device_idx\":%u", args.device_idx); assert(openme.var_count_below_max() && "xOpenME max var count reached."); xopenme_add_var_i(openme.var_count++, (char*) " \"CMD_LINE_ARGS#matrix_order\":%u", args.matrix_order); assert(openme.var_count_below_max() && "xOpenME max var count reached."); xopenme_add_var_d(openme.var_count++, (char*) " \"CMD_LINE_ARGS#eps\":%.8lf", args.eps); assert(openme.var_count_below_max() && "xOpenME max var count reached."); #endif // Parse kernel metadata. meta.parse(args.file_name); #if (1 == XOPENME) xopenme_add_var_s(openme.var_count++, (char*) " \"METADATA#name\":\"%s\"", (char*) meta.name.c_str()); assert(openme.var_count_below_max() && "xOpenME max var count reached."); xopenme_add_var_s(openme.var_count++, (char*) " \"METADATA#file\":\"%s\"", (char*) meta.file.c_str()); assert(openme.var_count_below_max() && "xOpenME max var count reached."); xopenme_add_var_s(openme.var_count++, (char*) " \"METADATA#opts\":\"%s\"", (char*) meta.opts.c_str()); assert(openme.var_count_below_max() && "xOpenME max var count reached."); xopenme_add_var_s(openme.var_count++, (char*) " \"METADATA#type\":\"%s\"", (char*) meta.type.c_str()); assert(openme.var_count_below_max() && "xOpenME max var count reached."); xopenme_add_var_i(openme.var_count++, (char*) " \"METADATA#transA\":%u", (int) meta.transA); assert(openme.var_count_below_max() && "xOpenME max var count reached."); xopenme_add_var_i(openme.var_count++, (char*) " \"METADATA#transB\":%u", (int) meta.transB); assert(openme.var_count_below_max() && "xOpenME max var count reached."); xopenme_add_var_i(openme.var_count++, (char*) " \"METADATA#di\":%u", (int) meta.di); assert(openme.var_count_below_max() && "xOpenME max var count reached."); xopenme_add_var_i(openme.var_count++, (char*) " \"METADATA#dj\":%u", (int) meta.dj); assert(openme.var_count_below_max() && "xOpenME max var count reached."); #endif } // END OF parse_arguments() // Get OpenCL platform specified with the "-p" command line argument. void get_platform() { cl_int err = CL_SUCCESS; cl_uint platform_idx = args.platform_idx; cl_uint num_entries = platform_idx+1; cl_platform_id * platforms = new cl_platform_id[num_entries]; cl_uint num_platforms; err = clGetPlatformIDs(num_entries, platforms, &num_platforms); assert(CL_SUCCESS == err && "clGetPlatformIDs() failed."); assert(platform_idx < num_platforms && "Platform not available."); this->platform = platforms[platform_idx]; delete [] platforms; #if (1 == XOPENME) err = clGetPlatformInfo(platform, CL_PLATFORM_NAME, sizeof(openme.str), &openme.str, NULL); assert(CL_SUCCESS == err && "clGetPlatformInfo() failed."); xopenme_add_var_s(openme.var_count++, (char*) " \"CL_PLATFORM_NAME\":\"%s\"", openme.str); assert(openme.var_count_below_max() && "xOpenME max var count reached."); err = clGetPlatformInfo(platform, CL_PLATFORM_VENDOR, sizeof(openme.str), &openme.str, NULL); assert(CL_SUCCESS == err && "clGetPlatformInfo() failed."); xopenme_add_var_s(openme.var_count++, (char*) " \"CL_PLATFORM_VENDOR\":\"%s\"", openme.str); assert(openme.var_count_below_max() && "xOpenME max var count reached."); err = clGetPlatformInfo(platform, CL_PLATFORM_VERSION, sizeof(openme.str), &openme.str, NULL); assert(CL_SUCCESS == err && "clGetPlatformInfo() failed."); xopenme_add_var_s(openme.var_count++, (char*) " \"CL_PLATFORM_VERSION\":\"%s\"", openme.str); assert(openme.var_count_below_max() && "xOpenME max var count reached."); #endif } // END OF get_platform() // Get OpenCL device specified with the "-d" command line argument. void get_device() { cl_int err = CL_SUCCESS; cl_uint device_idx = args.device_idx; cl_uint num_entries = device_idx+1; cl_device_id * devices = new cl_device_id[num_entries]; cl_uint num_devices; err = clGetDeviceIDs(platform, CL_DEVICE_TYPE_ALL, num_entries, devices, &num_devices); assert(CL_SUCCESS == err && "clGetDeviceIDs() failed."); assert(device_idx < num_devices && "No device."); this->device = devices[device_idx]; delete [] devices; #if (1 == XOPENME) err = clGetDeviceInfo(device, CL_DEVICE_NAME, sizeof(openme.str), &openme.str, NULL); assert(CL_SUCCESS == err && "clGetDeviceInfo() failed."); xopenme_add_var_s(openme.var_count++, (char*) " \"CL_DEVICE_NAME\":\"%s\"", openme.str); assert(openme.var_count_below_max() && "xOpenME max var count reached."); err = clGetDeviceInfo(device, CL_DEVICE_VENDOR, sizeof(openme.str), &openme.str, NULL); assert(CL_SUCCESS == err && "clGetDeviceInfo() failed."); xopenme_add_var_s(openme.var_count++, (char*) " \"CL_DEVICE_VENDOR\":\"%s\"", openme.str); assert(openme.var_count_below_max() && "xOpenME max var count reached."); err = clGetDeviceInfo(device, CL_DEVICE_VERSION, sizeof(openme.str), &openme.str, NULL); assert(CL_SUCCESS == err && "clGetDeviceInfo() failed."); xopenme_add_var_s(openme.var_count++, (char*) " \"CL_DEVICE_VERSION\":\"%s\"", openme.str); assert(openme.var_count_below_max() && "xOpenME max var count reached."); err = clGetDeviceInfo(device, CL_DRIVER_VERSION, sizeof(openme.str), &openme.str, NULL); assert(CL_SUCCESS == err && "clGetDeviceInfo() failed."); xopenme_add_var_s(openme.var_count++, (char*) " \"CL_DRIVER_VERSION\":\"%s\"", openme.str); assert(openme.var_count_below_max() && "xOpenME max var count reached."); err = clGetDeviceInfo(device, CL_DEVICE_MAX_COMPUTE_UNITS, sizeof(cl_uint), &openme.tmp_uint, NULL); assert(CL_SUCCESS == err && "clGetDeviceInfo() failed."); xopenme_add_var_i(openme.var_count++, (char*) " \"CL_DEVICE_MAX_COMPUTE_UNITS\":%u", openme.tmp_uint); assert(openme.var_count_below_max() && "xOpenME max var count reached."); err = clGetDeviceInfo(device, CL_DEVICE_MAX_CLOCK_FREQUENCY, sizeof(cl_uint), &openme.tmp_uint, NULL); assert(CL_SUCCESS == err && "clGetDeviceInfo() failed."); xopenme_add_var_i(openme.var_count++, (char*) " \"CL_DEVICE_MAX_CLOCK_FREQUENCY\":%u", openme.tmp_uint); assert(openme.var_count_below_max() && "xOpenME max var count reached."); err = clGetDeviceInfo(device, CL_DEVICE_GLOBAL_MEM_SIZE, sizeof(cl_ulong), &openme.tmp_ulong, NULL); assert(CL_SUCCESS == err && "clGetDeviceInfo() failed."); xopenme_add_var_i(openme.var_count++, (char*) " \"CL_DEVICE_GLOBAL_MEM_SIZE\":%u", openme.tmp_ulong); assert(openme.var_count_below_max() && "xOpenME max var count reached."); err = clGetDeviceInfo(device, CL_DEVICE_LOCAL_MEM_SIZE, sizeof(cl_ulong), &openme.tmp_ulong, NULL); assert(CL_SUCCESS == err && "clGetDeviceInfo() failed."); xopenme_add_var_i(openme.var_count++, (char*) " \"CL_DEVICE_LOCAL_MEM_SIZE\":%u", openme.tmp_ulong); assert(openme.var_count_below_max() && "xOpenME max var count reached."); err = clGetDeviceInfo(device, CL_DEVICE_MAX_WORK_GROUP_SIZE, sizeof(size_t), &openme.tmp_size_t, NULL); assert(CL_SUCCESS == err && "clGetDeviceInfo() failed."); xopenme_add_var_i(openme.var_count++, (char*) " \"CL_DEVICE_MAX_WORK_GROUP_SIZE\":%u", openme.tmp_size_t); assert(openme.var_count_below_max() && "xOpenME max var count reached."); err = clGetDeviceInfo(device, CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS, sizeof(size_t), &openme.tmp_size_t, NULL); assert(CL_SUCCESS == err && "clGetDeviceInfo() failed."); xopenme_add_var_i(openme.var_count++, (char*) " \"CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS\":%u", openme.tmp_size_t); assert(openme.tmp_size_t == 3 && "CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS != 3"); assert(openme.var_count_below_max() && "xOpenME max var count reached."); err = clGetDeviceInfo(device, CL_DEVICE_MAX_WORK_ITEM_SIZES, sizeof(openme.tmp_size_t_dims), openme.tmp_size_t_dims, NULL); assert(CL_SUCCESS == err && "clGetDeviceInfo() failed."); xopenme_add_var_i(openme.var_count++, (char*) " \"CL_DEVICE_MAX_WORK_ITEM_SIZES_0\":%u", openme.tmp_size_t_dims[0]); xopenme_add_var_i(openme.var_count++, (char*) " \"CL_DEVICE_MAX_WORK_ITEM_SIZES_1\":%u", openme.tmp_size_t_dims[1]); xopenme_add_var_i(openme.var_count++, (char*) " \"CL_DEVICE_MAX_WORK_ITEM_SIZES_2\":%u", openme.tmp_size_t_dims[2]); #endif } // END OF get_device() // Create OpenCL context for platform and device. void create_context() { cl_context_properties properties[3] = { CL_CONTEXT_PLATFORM, (cl_context_properties) platform, 0 }; cl_int err = CL_SUCCESS; context = clCreateContext(properties, /* number of devices */ 1, &device, /* callback fn */ NULL, /* callback data */ NULL, &err); assert(CL_SUCCESS == err && "clCreateContext() failed."); } // END OF create_context() // Create OpenCL queue for context and device with profiling enabled. void create_queue() { cl_command_queue_properties properties = CL_QUEUE_PROFILING_ENABLE; cl_int err = CL_SUCCESS; queue = clCreateCommandQueue(context, device, properties, &err); assert(CL_SUCCESS == err && "clCreateCommandQueue() failed."); } // END OF create_queue() // Create OpenCL program from file specified in the metadata supplied with the "-f" command line argument. void create_program() { //TODO: Read the name of the file containing an OpenCL program from the metadata file. //FIXME: For now, just assume the OpenCL file thas the same base name and the ".cl" extension. const size_t index_of_last_dot = args.file_name.find_last_of("."); const std::string file_name = args.file_name.substr(0, index_of_last_dot).append(".cl"); std::cout << "Reading an OpenCL kernel from \'" << file_name << "\'..." << std::endl; // Open file for reading. Close file on function exit. file::buffer buffer; bool read_success = file::read(file_name, buffer); assert(read_success && "file::read() failed."); // Create program from source. cl_int err = CL_SUCCESS; program = clCreateProgramWithSource(context, /* num_strings */ 1, /* strings */ (const char**) &buffer.data, /* lengths */ &buffer.size, &err); assert(CL_SUCCESS == err && "clCreateProgramWithSource() failed."); } // END OF create_program() // Build program with options specified with the "-b" command line argument. void build_program() { cl_int err = CL_SUCCESS; const char * build_options = meta.opts.c_str(); err = clBuildProgram(program, /* num_devices */ 1, /* device_list */ &device, /* options */ build_options, /* callback fn */ NULL, /* callback data */ NULL); assert(CL_SUCCESS == err && "clBuildProgram() failed."); } // END OF build_program() // Create kernel called "gemm". void create_kernel() { cl_int err = CL_SUCCESS; const char * kernel_name = "gemm"; kernel = clCreateKernel(program, kernel_name, &err); assert(CL_SUCCESS == err && "clCreateKernel() failed."); } // END OF create_kernel() private: // Create buffers and set kernel arguments. template<typename T> void set_kernel_args(const dataset<T>& data) { cl_int err = CL_SUCCESS; // Create buffers. buffer_A = clCreateBuffer(context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, data.n * data.n * sizeof(T), (T*) data.matrix_A, &err); assert(CL_SUCCESS == err && "clCreateBuffer() failed."); buffer_B = clCreateBuffer(context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, data.n * data.n * sizeof(T), (T*) data.matrix_B, &err); assert(CL_SUCCESS == err && "clCreateBuffer() failed."); buffer_C = clCreateBuffer(context, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, data.n * data.n * sizeof(T), (T*) data.matrix_C, &err); assert(CL_SUCCESS == err && "clCreateBuffer() failed."); // Set kernel arguments. cl_uint arg_count = 0; err = clSetKernelArg(kernel, arg_count++, sizeof(cl_mem), &buffer_A); assert(CL_SUCCESS == err && "clSetKernelArg() failed."); err = clSetKernelArg(kernel, arg_count++, sizeof(cl_mem), &buffer_B); assert(CL_SUCCESS == err && "clSetKernelArg() failed."); err = clSetKernelArg(kernel, arg_count++, sizeof(cl_mem), &buffer_C); assert(CL_SUCCESS == err && "clSetKernelArg() failed."); err = clSetKernelArg(kernel, arg_count++, sizeof(T), &data.alpha); assert(CL_SUCCESS == err && "clSetKernelArg() failed."); err = clSetKernelArg(kernel, arg_count++, sizeof(T), &data.beta); assert(CL_SUCCESS == err && "clSetKernelArg() failed."); err = clSetKernelArg(kernel, arg_count++, sizeof(cl_uint), &data.n); assert(CL_SUCCESS == err && "clSetKernelArg() failed."); } void enqueue_kernel() { cl_int err = CL_SUCCESS; // Enqueue kernel. { const size_t n = (size_t) args.matrix_order; const size_t work_dim = 2; assert(0 < work_dim && work_dim <= 3); const size_t global_work_offset[work_dim] = { 0, 0 }; // Global work size. const size_t global_work_size[work_dim] = { n / meta.dj, n / meta.di }; assert((n % meta.dj == 0) && (n % meta.di == 0) && "Matrix order not divisible by coarsening factors."); #if (1 == XOPENME) xopenme_add_var_i(openme.var_count++, (char*) " \"EXECUTION#gws_j\":%u", global_work_size[0]); assert(openme.var_count_below_max() && "xOpenME max var count reached."); xopenme_add_var_i(openme.var_count++, (char*) " \"EXECUTION#gws_i\":%u", global_work_size[1]); assert(openme.var_count_below_max() && "xOpenME max var count reached."); #endif // Local work size. const size_t * local_work_size; size_t max_lws; err = clGetKernelWorkGroupInfo(kernel, device, CL_KERNEL_WORK_GROUP_SIZE, sizeof(max_lws), &max_lws, NULL); assert(CL_SUCCESS == err && "clGetKernelWorkGroupInfo() failed."); #if (1 == XOPENME) xopenme_add_var_i(openme.var_count++, (char*) " \"CL_KERNEL_WORK_GROUP_SIZE\":%u", max_lws); assert(openme.var_count_below_max() && "xOpenME max var count reached."); #endif const size_t _local_work_size[work_dim] = { args.lws_j, args.lws_i }; const size_t lws = _local_work_size[0] * _local_work_size[1]; if ((0 < lws) && (lws <= max_lws) && (global_work_size[0] % _local_work_size[0] == 0) && (global_work_size[1] % _local_work_size[1] == 0)) { local_work_size = _local_work_size; assert((n % (local_work_size[0] * meta.dj) == 0) && (n % (local_work_size[1] * meta.di) == 0) && "Matrix order not divisible by product of local work size and coarsening factor"); #if (1 == XOPENME) xopenme_add_var_i(openme.var_count++, (char*) " \"EXECUTION#lws_j\":%u", local_work_size[0]); assert(openme.var_count_below_max() && "xOpenME max var count reached."); xopenme_add_var_i(openme.var_count++, (char*) " \"EXECUTION#lws_i\":%u", local_work_size[1]); assert(openme.var_count_below_max() && "xOpenME max var count reached."); #endif } else { local_work_size = NULL; #if (1 == XOPENME) xopenme_add_var_i(openme.var_count++, (char*) " \"EXECUTION#lws_j\":%u", 0); assert(openme.var_count_below_max() && "xOpenME max var count reached."); xopenme_add_var_i(openme.var_count++, (char*) " \"EXECUTION#lws_i\":%u", 0); assert(openme.var_count_below_max() && "xOpenME max var count reached."); #endif } cl_uint num_events_in_wait_list = 0; const cl_event *event_wait_list = NULL; err = clEnqueueNDRangeKernel(queue, kernel, work_dim, global_work_offset, global_work_size, local_work_size, num_events_in_wait_list, event_wait_list, &enqueue); assert(CL_SUCCESS == err && "clEnqueueNDRangeKernel() failed."); } // Wait for kernel completion. { const cl_uint num_events = 1; const cl_event event_list[num_events] = { enqueue }; err = clWaitForEvents(num_events, event_list); assert(CL_SUCCESS == err && "clWaitForEvents() failed."); } } // END OF enqueue_kernel() // Calculate nanoseconds, flops, Gflops/s (flops/ns), etc. void profile_execution() { cl_int err = CL_SUCCESS; cl_ulong end = 0; err = clGetEventProfilingInfo(enqueue, CL_PROFILING_COMMAND_END, sizeof(cl_ulong), &end, 0); assert(CL_SUCCESS == err && "clGetEventProfilingInfo() failed."); cl_ulong start = 0; err = clGetEventProfilingInfo(enqueue, CL_PROFILING_COMMAND_START, sizeof(cl_ulong), &start, 0); assert(CL_SUCCESS == err && "clGetEventProfilingInfo() failed."); const cl_ulong ns = end - start; const cl_ulong n = (cl_ulong) args.matrix_order; const cl_ulong flops = 2 * (n + 1) * (n * n); const cl_double gflops_per_s = (cl_double) flops / (cl_double) ns; std::cout << "Calculating performance... " << gflops_per_s << " Gflops/s"; std::cout << " (performed " << flops << " flops in " << ns << " ns)." << std::endl; #if (1 == XOPENME) xopenme_add_var_i(openme.var_count++, (char*) " \"EXECUTION#ns\":%u", ns); assert(openme.var_count_below_max() && "xOpenME max var count reached."); xopenme_add_var_f(openme.var_count++, (char*) " \"EXECUTION#us\":%.3f", ns * 1e-3); assert(openme.var_count_below_max() && "xOpenME max var count reached."); xopenme_add_var_f(openme.var_count++, (char*) " \"EXECUTION#ms\":%.3f", ns * 1e-6); assert(openme.var_count_below_max() && "xOpenME max var count reached."); xopenme_add_var_f(openme.var_count++, (char*) " \"EXECUTION#s\":%.3f", ns * 1e-9); assert(openme.var_count_below_max() && "xOpenME max var count reached."); xopenme_add_var_i(openme.var_count++, (char*) " \"EXECUTION#flops\":%u", flops); assert(openme.var_count_below_max() && "xOpenME max var count reached."); xopenme_add_var_f(openme.var_count++, (char*) " \"EXECUTION#Gflops\":%.3f", flops * 1e-9); assert(openme.var_count_below_max() && "xOpenME max var count reached."); xopenme_add_var_d(openme.var_count++, (char*) " \"EXECUTION#Gflops/s\":%.3lf", gflops_per_s); assert(openme.var_count_below_max() && "xOpenME max var count reached."); #endif } // END OF profile_execution() template<typename T> void _execute_kernel() { gemmbench::dataset<T> data(args.matrix_order); assert(data.matrix_A && "No data."); assert(data.matrix_B && "No data."); assert(data.matrix_C && "No data."); data.init_random(); set_kernel_args<T>(data); assert(buffer_A && "No buffer."); assert(buffer_B && "No buffer."); assert(buffer_C && "No buffer."); #if (1 == XOPENME) xopenme_clock_start(0); #endif enqueue_kernel(); #if (1 == XOPENME) xopenme_clock_end(0); #endif profile_execution(); data.verify_results(*this); } // END OF _execute_kernel() public: // Run the kernel on random data, profile and verify. void execute_kernel() { if (meta.type == "S") { _execute_kernel<cl_float>(); } else if (meta.type == "D") { _execute_kernel<cl_double>(); } else { assert(false && "Unsupported data type."); } } // END OF execute_kernel() }; // END OF gemmbench::state class } // END OF gemmbench namespace #endif // CL_STATE_HPP * adding building log (if error) * support for Android // (c) 2015, dividiti // BSD license #ifndef CL_STATE_HPP #define CL_STATE_HPP #include "cl_dataset.hpp" #include <iostream> #include <fstream> #include <sstream> #include <cstdlib> #include <cassert> #include <CL/cl.h> #include <xopenme.h> #include <cJSON.h> namespace gemmbench { template<typename T> class dataset; class file { public: struct buffer { char * data; size_t size; // Default constructor. buffer() : data(NULL), size(0) { } // Initializing constructor. buffer(char * _data, size_t _size) : data(_data), size(_size) { } // Initializing constructor with pointer cast. buffer(const char * _data, size_t _size) : data((char*) _data), size(_size) { } // Destructor. ~buffer() { delete [] data; } }; // END OF buffer struct // Read file into buffer. Return true on success. static bool read(const std::string & path, buffer & buff); // Write file from buffer. Return true on success. static bool write(const std::string & path, const buffer & buff); // Prevent instantiating this class. virtual ~file(); }; // END OF file class class xopenme { private: static const int max_str_len = 1000; static const int max_var_count = 50; static const int max_tmr_count = 2; static const int max_work_dims = 3; public: char str[max_str_len]; int var_count; cl_uint tmp_uint; cl_ulong tmp_ulong; size_t tmp_size_t; size_t tmp_size_t_dims[max_work_dims]; xopenme() : var_count(0), tmp_uint(0), tmp_ulong(0), tmp_size_t(0), tmp_size_t_dims() // C++11: {0, ..., 0} { assert(3 == max_work_dims); xopenme_init(max_tmr_count, max_var_count); } ~xopenme() { xopenme_dump_state(); } bool var_count_below_max() { return var_count < max_var_count; } }; // END OF gemmbench::xopenme class class arguments { private: void print_usage(const char * cmd) { // Print on one line. std::cout << "Usage: " << cmd ; std::cout << " -f <file name>"; std::cout << " -n <matrix order>"; std::cout << " -p <platform index>"; std::cout << " -d <device index>"; std::cout << " -lws <lws_j,lws_i>"; std::cout << std::endl; exit(EXIT_SUCCESS); } public: std::string file_name; cl_uint platform_idx; cl_uint device_idx; cl_uint matrix_order; cl_uint lws_j, lws_i; cl_double eps; arguments() : file_name(""), platform_idx(0), device_idx(0), matrix_order(256), lws_j(0), lws_i(0), eps(1e-5) { } void parse(int argc, char* argv[]) { if (1 == argc) { print_usage(argv[0]); } for (int i = 1; i < argc-1; ++i) { std::string this_arg(argv[i]); std::string next_arg(argv[++i]); if ("-f" == this_arg) { file_name = next_arg; } else if ("-n" == this_arg) { std::istringstream ss(next_arg); ss >> matrix_order; } else if ("-p" == this_arg) { std::istringstream ss(next_arg); ss >> platform_idx; } else if ("-d" == this_arg) { std::istringstream ss(next_arg); ss >> device_idx; } else if ("-lws" == this_arg) { const std::string::size_type pos = next_arg.find(','); assert(std::string::npos != pos); std::istringstream lws_j_ss(next_arg.substr(0, pos)); lws_j_ss >> lws_j; std::istringstream lws_i_ss(next_arg.substr(pos+1)); lws_i_ss >> lws_i; } else if ("-eps" == this_arg) { std::istringstream ss(next_arg); ss >> eps; } else { std::cerr << "Unhandled argument: " << this_arg << std::endl; --i; // skip only one argument } } // END OF for each argument } // END OF parse() }; // END OF gemmbench::arguments class class metadata { public: // Program name. std::string name; // Program file name. std::string file; // Program build options. std::string opts; // Single precision real ("S") and complex ("C"). // Double precision real ("G") and complex ("Z"). std::string type; // Transposed ('T'), if true; non-transposed ('N'), if false. bool transA; bool transB; // Coarsening factors along rows ("di") and columns ("dj"). cl_uint di; cl_uint dj; // Constructor. metadata() : name(""), file(""), opts(""), type(""), transA(false), transB(false), di(1), dj(1) { } // Destructor. ~metadata() { } // Parse the metadata file specified with the "-f" command line argument. // Example file: // { // "name" : "DGEMM_NT_1x1", // "file" : "DGEMM_NT_1x1.cl", // "type" : "D", // "transA" : "N", // "transB" : "T", // "dj" : 1, // "di" : 1 // } void parse(const std::string & path) { #if (1 == TEST_METADATA) std::cout << "Reading OpenCL kernel metadata from string:" << std::endl; const char *raw_meta = "{\n" " \"name\" : \"DGEMM_NT_1x1\",\n" " \"file\" : \"DGEMM_NT_1x1.cl\",\n" " \"type\" : \"D\",\n" " \"transB\" : \"T\"\n" "}\n"; #else std::cout << "Reading OpenCL kernel metadata from \'" << path << "\'..." << std::endl; file::buffer buffer; bool read_success = file::read(path, buffer); assert(read_success && "file::read() failed."); assert(buffer.data && buffer.size > 0 && "No metadata."); buffer.data[buffer.size-1] = '\0'; // null-terminate const char * raw_meta = buffer.data; #endif std::cout << raw_meta << std::endl; cJSON* meta = cJSON_Parse(raw_meta); for (int i = 0; i < cJSON_GetArraySize(meta); ++i) { const cJSON *meta_i = cJSON_GetArrayItem(meta, i); const int value_type = meta_i->type; const std::string key(meta_i->string); if ("name" == key) { assert(cJSON_String == value_type && "Unexpected value type."); name = std::string(meta_i->valuestring); } else if ("file" == key) { assert(cJSON_String == value_type && "Unexpected value type."); file = std::string(meta_i->valuestring); } else if ("opts" == key) { assert(cJSON_String == value_type && "Unexpected value type."); opts = std::string(meta_i->valuestring); } else if ("type" == key) { assert(cJSON_String == value_type && "Unexpected value type."); type = std::string(meta_i->valuestring); assert(type == "S" || type == "C" || type == "D" || type == "Z"); } else if ("transA" == key) { assert(cJSON_String == value_type && "Unexpected value type."); transA = std::string(meta_i->valuestring) == "T" ? true : false; } else if ("transB" == key) { assert(cJSON_String == value_type && "Unexpected value type."); transB = std::string(meta_i->valuestring) == "T" ? true : false; } else if ("di" == key) { assert(cJSON_Number == value_type && "Unexpected value type."); di = meta_i->valueint; } else if ("dj" == key) { assert(cJSON_Number == value_type && "Unexpected value type."); dj = meta_i->valueint; } else { std::cerr << "Unhandled key: " << key << std::endl; } } // END OF for each key:value pair cJSON_Delete(meta); } // END OF parse() }; // END OF gemmbench::metadata class class state { public: // Command line arguments (with defaults). arguments args; // Kernel metadata (with defaults). metadata meta; // xOpenME state. xopenme openme; // OpenCL objects. cl_platform_id platform; cl_device_id device; cl_context context; cl_command_queue queue; cl_program program; cl_kernel kernel; cl_mem buffer_A; cl_mem buffer_B; cl_mem buffer_C; cl_event enqueue; // Constructor. state() : platform(NULL), device(NULL), context(NULL), queue(NULL), program(NULL), kernel(NULL), buffer_A(NULL), buffer_B(NULL), buffer_C(NULL), enqueue(NULL) { } // Destructor. Release in reverse order. ~state() { cl_int err = CL_SUCCESS; err = clReleaseEvent(enqueue); assert(CL_SUCCESS == err && "clReleaseEvent() failed."); err = clReleaseMemObject(buffer_C); assert(CL_SUCCESS == err && "clReleaseMemObject() failed."); err = clReleaseMemObject(buffer_B); assert(CL_SUCCESS == err && "clReleaseMemObject() failed."); err = clReleaseMemObject(buffer_A); assert(CL_SUCCESS == err && "clReleaseMemObject() failed."); err = clReleaseKernel(kernel); assert(CL_SUCCESS == err && "clReleaseKernel() failed."); err = clReleaseProgram(program); assert(CL_SUCCESS == err && "clReleaseProgram() failed."); err = clReleaseCommandQueue(queue); assert(CL_SUCCESS == err && "clReleaseCommandQueue() failed."); err = clReleaseContext(context); assert(CL_SUCCESS == err && "clReleaseContext() failed."); } void init(int argc, char* argv[]) { // Parse command line arguments. args.parse(argc, argv); #if (1 == XOPENME) xopenme_add_var_s(openme.var_count++, (char*) " \"CMD_LINE_ARGS#file_name\":\"%s\"", (char*) args.file_name.c_str()); assert(openme.var_count_below_max() && "xOpenME max var count reached."); xopenme_add_var_i(openme.var_count++, (char*) " \"CMD_LINE_ARGS#platform_idx\":%u", args.platform_idx); assert(openme.var_count_below_max() && "xOpenME max var count reached."); xopenme_add_var_i(openme.var_count++, (char*) " \"CMD_LINE_ARGS#device_idx\":%u", args.device_idx); assert(openme.var_count_below_max() && "xOpenME max var count reached."); xopenme_add_var_i(openme.var_count++, (char*) " \"CMD_LINE_ARGS#matrix_order\":%u", args.matrix_order); assert(openme.var_count_below_max() && "xOpenME max var count reached."); xopenme_add_var_d(openme.var_count++, (char*) " \"CMD_LINE_ARGS#eps\":%.8lf", args.eps); assert(openme.var_count_below_max() && "xOpenME max var count reached."); #endif // Parse kernel metadata. meta.parse(args.file_name); #if (1 == XOPENME) xopenme_add_var_s(openme.var_count++, (char*) " \"METADATA#name\":\"%s\"", (char*) meta.name.c_str()); assert(openme.var_count_below_max() && "xOpenME max var count reached."); xopenme_add_var_s(openme.var_count++, (char*) " \"METADATA#file\":\"%s\"", (char*) meta.file.c_str()); assert(openme.var_count_below_max() && "xOpenME max var count reached."); xopenme_add_var_s(openme.var_count++, (char*) " \"METADATA#opts\":\"%s\"", (char*) meta.opts.c_str()); assert(openme.var_count_below_max() && "xOpenME max var count reached."); xopenme_add_var_s(openme.var_count++, (char*) " \"METADATA#type\":\"%s\"", (char*) meta.type.c_str()); assert(openme.var_count_below_max() && "xOpenME max var count reached."); xopenme_add_var_i(openme.var_count++, (char*) " \"METADATA#transA\":%u", (int) meta.transA); assert(openme.var_count_below_max() && "xOpenME max var count reached."); xopenme_add_var_i(openme.var_count++, (char*) " \"METADATA#transB\":%u", (int) meta.transB); assert(openme.var_count_below_max() && "xOpenME max var count reached."); xopenme_add_var_i(openme.var_count++, (char*) " \"METADATA#di\":%u", (int) meta.di); assert(openme.var_count_below_max() && "xOpenME max var count reached."); xopenme_add_var_i(openme.var_count++, (char*) " \"METADATA#dj\":%u", (int) meta.dj); assert(openme.var_count_below_max() && "xOpenME max var count reached."); #endif } // END OF parse_arguments() // Get OpenCL platform specified with the "-p" command line argument. void get_platform() { cl_int err = CL_SUCCESS; cl_uint platform_idx = args.platform_idx; cl_uint num_entries = platform_idx+1; cl_platform_id * platforms = new cl_platform_id[num_entries]; cl_uint num_platforms; err = clGetPlatformIDs(num_entries, platforms, &num_platforms); assert(CL_SUCCESS == err && "clGetPlatformIDs() failed."); assert(platform_idx < num_platforms && "Platform not available."); this->platform = platforms[platform_idx]; delete [] platforms; #if (1 == XOPENME) err = clGetPlatformInfo(platform, CL_PLATFORM_NAME, sizeof(openme.str), &openme.str, NULL); assert(CL_SUCCESS == err && "clGetPlatformInfo() failed."); xopenme_add_var_s(openme.var_count++, (char*) " \"CL_PLATFORM_NAME\":\"%s\"", openme.str); assert(openme.var_count_below_max() && "xOpenME max var count reached."); err = clGetPlatformInfo(platform, CL_PLATFORM_VENDOR, sizeof(openme.str), &openme.str, NULL); assert(CL_SUCCESS == err && "clGetPlatformInfo() failed."); xopenme_add_var_s(openme.var_count++, (char*) " \"CL_PLATFORM_VENDOR\":\"%s\"", openme.str); assert(openme.var_count_below_max() && "xOpenME max var count reached."); err = clGetPlatformInfo(platform, CL_PLATFORM_VERSION, sizeof(openme.str), &openme.str, NULL); assert(CL_SUCCESS == err && "clGetPlatformInfo() failed."); xopenme_add_var_s(openme.var_count++, (char*) " \"CL_PLATFORM_VERSION\":\"%s\"", openme.str); assert(openme.var_count_below_max() && "xOpenME max var count reached."); #endif } // END OF get_platform() // Get OpenCL device specified with the "-d" command line argument. void get_device() { cl_int err = CL_SUCCESS; cl_uint device_idx = args.device_idx; cl_uint num_entries = device_idx+1; cl_device_id * devices = new cl_device_id[num_entries]; cl_uint num_devices; err = clGetDeviceIDs(platform, CL_DEVICE_TYPE_ALL, num_entries, devices, &num_devices); assert(CL_SUCCESS == err && "clGetDeviceIDs() failed."); assert(device_idx < num_devices && "No device."); this->device = devices[device_idx]; delete [] devices; #if (1 == XOPENME) err = clGetDeviceInfo(device, CL_DEVICE_NAME, sizeof(openme.str), &openme.str, NULL); assert(CL_SUCCESS == err && "clGetDeviceInfo() failed."); xopenme_add_var_s(openme.var_count++, (char*) " \"CL_DEVICE_NAME\":\"%s\"", openme.str); assert(openme.var_count_below_max() && "xOpenME max var count reached."); err = clGetDeviceInfo(device, CL_DEVICE_VENDOR, sizeof(openme.str), &openme.str, NULL); assert(CL_SUCCESS == err && "clGetDeviceInfo() failed."); xopenme_add_var_s(openme.var_count++, (char*) " \"CL_DEVICE_VENDOR\":\"%s\"", openme.str); assert(openme.var_count_below_max() && "xOpenME max var count reached."); err = clGetDeviceInfo(device, CL_DEVICE_VERSION, sizeof(openme.str), &openme.str, NULL); assert(CL_SUCCESS == err && "clGetDeviceInfo() failed."); xopenme_add_var_s(openme.var_count++, (char*) " \"CL_DEVICE_VERSION\":\"%s\"", openme.str); assert(openme.var_count_below_max() && "xOpenME max var count reached."); err = clGetDeviceInfo(device, CL_DRIVER_VERSION, sizeof(openme.str), &openme.str, NULL); assert(CL_SUCCESS == err && "clGetDeviceInfo() failed."); xopenme_add_var_s(openme.var_count++, (char*) " \"CL_DRIVER_VERSION\":\"%s\"", openme.str); assert(openme.var_count_below_max() && "xOpenME max var count reached."); err = clGetDeviceInfo(device, CL_DEVICE_MAX_COMPUTE_UNITS, sizeof(cl_uint), &openme.tmp_uint, NULL); assert(CL_SUCCESS == err && "clGetDeviceInfo() failed."); xopenme_add_var_i(openme.var_count++, (char*) " \"CL_DEVICE_MAX_COMPUTE_UNITS\":%u", openme.tmp_uint); assert(openme.var_count_below_max() && "xOpenME max var count reached."); err = clGetDeviceInfo(device, CL_DEVICE_MAX_CLOCK_FREQUENCY, sizeof(cl_uint), &openme.tmp_uint, NULL); assert(CL_SUCCESS == err && "clGetDeviceInfo() failed."); xopenme_add_var_i(openme.var_count++, (char*) " \"CL_DEVICE_MAX_CLOCK_FREQUENCY\":%u", openme.tmp_uint); assert(openme.var_count_below_max() && "xOpenME max var count reached."); err = clGetDeviceInfo(device, CL_DEVICE_GLOBAL_MEM_SIZE, sizeof(cl_ulong), &openme.tmp_ulong, NULL); assert(CL_SUCCESS == err && "clGetDeviceInfo() failed."); xopenme_add_var_i(openme.var_count++, (char*) " \"CL_DEVICE_GLOBAL_MEM_SIZE\":%u", openme.tmp_ulong); assert(openme.var_count_below_max() && "xOpenME max var count reached."); err = clGetDeviceInfo(device, CL_DEVICE_LOCAL_MEM_SIZE, sizeof(cl_ulong), &openme.tmp_ulong, NULL); assert(CL_SUCCESS == err && "clGetDeviceInfo() failed."); xopenme_add_var_i(openme.var_count++, (char*) " \"CL_DEVICE_LOCAL_MEM_SIZE\":%u", openme.tmp_ulong); assert(openme.var_count_below_max() && "xOpenME max var count reached."); err = clGetDeviceInfo(device, CL_DEVICE_MAX_WORK_GROUP_SIZE, sizeof(size_t), &openme.tmp_size_t, NULL); assert(CL_SUCCESS == err && "clGetDeviceInfo() failed."); xopenme_add_var_i(openme.var_count++, (char*) " \"CL_DEVICE_MAX_WORK_GROUP_SIZE\":%u", openme.tmp_size_t); assert(openme.var_count_below_max() && "xOpenME max var count reached."); err = clGetDeviceInfo(device, CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS, sizeof(size_t), &openme.tmp_size_t, NULL); assert(CL_SUCCESS == err && "clGetDeviceInfo() failed."); xopenme_add_var_i(openme.var_count++, (char*) " \"CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS\":%u", openme.tmp_size_t); assert(openme.tmp_size_t == 3 && "CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS != 3"); assert(openme.var_count_below_max() && "xOpenME max var count reached."); err = clGetDeviceInfo(device, CL_DEVICE_MAX_WORK_ITEM_SIZES, sizeof(openme.tmp_size_t_dims), openme.tmp_size_t_dims, NULL); assert(CL_SUCCESS == err && "clGetDeviceInfo() failed."); xopenme_add_var_i(openme.var_count++, (char*) " \"CL_DEVICE_MAX_WORK_ITEM_SIZES_0\":%u", openme.tmp_size_t_dims[0]); xopenme_add_var_i(openme.var_count++, (char*) " \"CL_DEVICE_MAX_WORK_ITEM_SIZES_1\":%u", openme.tmp_size_t_dims[1]); xopenme_add_var_i(openme.var_count++, (char*) " \"CL_DEVICE_MAX_WORK_ITEM_SIZES_2\":%u", openme.tmp_size_t_dims[2]); #endif } // END OF get_device() // Create OpenCL context for platform and device. void create_context() { cl_context_properties properties[3] = { CL_CONTEXT_PLATFORM, (cl_context_properties) platform, 0 }; cl_int err = CL_SUCCESS; context = clCreateContext(properties, /* number of devices */ 1, &device, /* callback fn */ NULL, /* callback data */ NULL, &err); assert(CL_SUCCESS == err && "clCreateContext() failed."); } // END OF create_context() // Create OpenCL queue for context and device with profiling enabled. void create_queue() { cl_command_queue_properties properties = CL_QUEUE_PROFILING_ENABLE; cl_int err = CL_SUCCESS; queue = clCreateCommandQueue(context, device, properties, &err); assert(CL_SUCCESS == err && "clCreateCommandQueue() failed."); } // END OF create_queue() // Create OpenCL program from file specified in the metadata supplied with the "-f" command line argument. void create_program() { //TODO: Read the name of the file containing an OpenCL program from the metadata file. //FIXME: For now, just assume the OpenCL file thas the same base name and the ".cl" extension. const size_t index_of_last_dot = args.file_name.find_last_of("."); const std::string file_name = args.file_name.substr(0, index_of_last_dot).append(".cl"); std::cout << "Reading an OpenCL kernel from \'" << file_name << "\'..." << std::endl; // Open file for reading. Close file on function exit. file::buffer buffer; bool read_success = file::read(file_name, buffer); assert(read_success && "file::read() failed."); // Create program from source. cl_int err = CL_SUCCESS; program = clCreateProgramWithSource(context, /* num_strings */ 1, /* strings */ (const char**) &buffer.data, /* lengths */ &buffer.size, &err); assert(CL_SUCCESS == err && "clCreateProgramWithSource() failed."); } // END OF create_program() // Build program with options specified with the "-b" command line argument. void build_program() { cl_int err = CL_SUCCESS; const char * build_options = meta.opts.c_str(); std::cout << "Building program (" << build_options << ") ... " << std::endl; err = clBuildProgram(program, /* num_devices */ 1, /* device_list */ &device, /* options */ build_options, /* callback fn */ NULL, /* callback data */ NULL); size_t ls = 0; clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG, 0, NULL, &ls); if (CL_SUCCESS!=err) { if (ls>0) { std::cerr << "Build problem: " << std::endl; char* lg = new char[1024]; clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG, ls, lg, NULL); std::cerr << lg << std::endl; delete[] lg; } } assert(CL_SUCCESS == err && "clBuildProgram() failed."); } // END OF build_program() // Create kernel called "gemm". void create_kernel() { std::cout << "Creating kernel ... " << std::endl; cl_int err = CL_SUCCESS; const char * kernel_name = "gemm"; kernel = clCreateKernel(program, kernel_name, &err); assert(CL_SUCCESS == err && "clCreateKernel() failed."); } // END OF create_kernel() private: // Create buffers and set kernel arguments. template<typename T> void set_kernel_args(const dataset<T>& data) { cl_int err = CL_SUCCESS; // Create buffers. buffer_A = clCreateBuffer(context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, data.n * data.n * sizeof(T), (T*) data.matrix_A, &err); assert(CL_SUCCESS == err && "clCreateBuffer() failed."); buffer_B = clCreateBuffer(context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, data.n * data.n * sizeof(T), (T*) data.matrix_B, &err); assert(CL_SUCCESS == err && "clCreateBuffer() failed."); buffer_C = clCreateBuffer(context, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, data.n * data.n * sizeof(T), (T*) data.matrix_C, &err); assert(CL_SUCCESS == err && "clCreateBuffer() failed."); // Set kernel arguments. cl_uint arg_count = 0; err = clSetKernelArg(kernel, arg_count++, sizeof(cl_mem), &buffer_A); assert(CL_SUCCESS == err && "clSetKernelArg() failed."); err = clSetKernelArg(kernel, arg_count++, sizeof(cl_mem), &buffer_B); assert(CL_SUCCESS == err && "clSetKernelArg() failed."); err = clSetKernelArg(kernel, arg_count++, sizeof(cl_mem), &buffer_C); assert(CL_SUCCESS == err && "clSetKernelArg() failed."); err = clSetKernelArg(kernel, arg_count++, sizeof(T), &data.alpha); assert(CL_SUCCESS == err && "clSetKernelArg() failed."); err = clSetKernelArg(kernel, arg_count++, sizeof(T), &data.beta); assert(CL_SUCCESS == err && "clSetKernelArg() failed."); err = clSetKernelArg(kernel, arg_count++, sizeof(cl_uint), &data.n); assert(CL_SUCCESS == err && "clSetKernelArg() failed."); } void enqueue_kernel() { std::cout << "Enqueuing kernel ... " << std::endl; cl_int err = CL_SUCCESS; // Enqueue kernel. { const size_t n = (size_t) args.matrix_order; const size_t work_dim = 2; assert(0 < work_dim && work_dim <= 3); const size_t global_work_offset[work_dim] = { 0, 0 }; // Global work size. const size_t global_work_size[work_dim] = { n / meta.dj, n / meta.di }; assert((n % meta.dj == 0) && (n % meta.di == 0) && "Matrix order not divisible by coarsening factors."); #if (1 == XOPENME) xopenme_add_var_i(openme.var_count++, (char*) " \"EXECUTION#gws_j\":%u", global_work_size[0]); assert(openme.var_count_below_max() && "xOpenME max var count reached."); xopenme_add_var_i(openme.var_count++, (char*) " \"EXECUTION#gws_i\":%u", global_work_size[1]); assert(openme.var_count_below_max() && "xOpenME max var count reached."); #endif // Local work size. const size_t * local_work_size; size_t max_lws; err = clGetKernelWorkGroupInfo(kernel, device, CL_KERNEL_WORK_GROUP_SIZE, sizeof(max_lws), &max_lws, NULL); assert(CL_SUCCESS == err && "clGetKernelWorkGroupInfo() failed."); #if (1 == XOPENME) xopenme_add_var_i(openme.var_count++, (char*) " \"CL_KERNEL_WORK_GROUP_SIZE\":%u", max_lws); assert(openme.var_count_below_max() && "xOpenME max var count reached."); #endif const size_t _local_work_size[work_dim] = { args.lws_j, args.lws_i }; const size_t lws = _local_work_size[0] * _local_work_size[1]; if ((0 < lws) && (lws <= max_lws) && (global_work_size[0] % _local_work_size[0] == 0) && (global_work_size[1] % _local_work_size[1] == 0)) { local_work_size = _local_work_size; assert((n % (local_work_size[0] * meta.dj) == 0) && (n % (local_work_size[1] * meta.di) == 0) && "Matrix order not divisible by product of local work size and coarsening factor"); #if (1 == XOPENME) xopenme_add_var_i(openme.var_count++, (char*) " \"EXECUTION#lws_j\":%u", local_work_size[0]); assert(openme.var_count_below_max() && "xOpenME max var count reached."); xopenme_add_var_i(openme.var_count++, (char*) " \"EXECUTION#lws_i\":%u", local_work_size[1]); assert(openme.var_count_below_max() && "xOpenME max var count reached."); #endif } else { local_work_size = NULL; #if (1 == XOPENME) xopenme_add_var_i(openme.var_count++, (char*) " \"EXECUTION#lws_j\":%u", 0); assert(openme.var_count_below_max() && "xOpenME max var count reached."); xopenme_add_var_i(openme.var_count++, (char*) " \"EXECUTION#lws_i\":%u", 0); assert(openme.var_count_below_max() && "xOpenME max var count reached."); #endif } cl_uint num_events_in_wait_list = 0; const cl_event *event_wait_list = NULL; err = clEnqueueNDRangeKernel(queue, kernel, work_dim, global_work_offset, global_work_size, local_work_size, num_events_in_wait_list, event_wait_list, &enqueue); assert(CL_SUCCESS == err && "clEnqueueNDRangeKernel() failed."); } // Wait for kernel completion. { const cl_uint num_events = 1; const cl_event event_list[num_events] = { enqueue }; err = clWaitForEvents(num_events, event_list); assert(CL_SUCCESS == err && "clWaitForEvents() failed."); } } // END OF enqueue_kernel() // Calculate nanoseconds, flops, Gflops/s (flops/ns), etc. void profile_execution() { std::cout << "Profiling kernel ... " << std::endl; cl_int err = CL_SUCCESS; cl_ulong end = 0; err = clGetEventProfilingInfo(enqueue, CL_PROFILING_COMMAND_END, sizeof(cl_ulong), &end, 0); assert(CL_SUCCESS == err && "clGetEventProfilingInfo() failed."); cl_ulong start = 0; err = clGetEventProfilingInfo(enqueue, CL_PROFILING_COMMAND_START, sizeof(cl_ulong), &start, 0); assert(CL_SUCCESS == err && "clGetEventProfilingInfo() failed."); const cl_ulong ns = end - start; const cl_ulong n = (cl_ulong) args.matrix_order; const cl_ulong flops = 2 * (n + 1) * (n * n); const cl_double gflops_per_s = (cl_double) flops / (cl_double) ns; std::cout << "Calculating performance... " << gflops_per_s << " Gflops/s"; std::cout << " (performed " << flops << " flops in " << ns << " ns)." << std::endl; #if (1 == XOPENME) xopenme_add_var_i(openme.var_count++, (char*) " \"EXECUTION#ns\":%u", ns); assert(openme.var_count_below_max() && "xOpenME max var count reached."); xopenme_add_var_f(openme.var_count++, (char*) " \"EXECUTION#us\":%.3f", ns * 1e-3); assert(openme.var_count_below_max() && "xOpenME max var count reached."); xopenme_add_var_f(openme.var_count++, (char*) " \"EXECUTION#ms\":%.3f", ns * 1e-6); assert(openme.var_count_below_max() && "xOpenME max var count reached."); xopenme_add_var_f(openme.var_count++, (char*) " \"EXECUTION#s\":%.3f", ns * 1e-9); assert(openme.var_count_below_max() && "xOpenME max var count reached."); xopenme_add_var_i(openme.var_count++, (char*) " \"EXECUTION#flops\":%u", flops); assert(openme.var_count_below_max() && "xOpenME max var count reached."); xopenme_add_var_f(openme.var_count++, (char*) " \"EXECUTION#Gflops\":%.3f", flops * 1e-9); assert(openme.var_count_below_max() && "xOpenME max var count reached."); xopenme_add_var_d(openme.var_count++, (char*) " \"EXECUTION#Gflops/s\":%.3lf", gflops_per_s); assert(openme.var_count_below_max() && "xOpenME max var count reached."); #endif } // END OF profile_execution() template<typename T> void _execute_kernel() { gemmbench::dataset<T> data(args.matrix_order); assert(data.matrix_A && "No data."); assert(data.matrix_B && "No data."); assert(data.matrix_C && "No data."); data.init_random(); set_kernel_args<T>(data); assert(buffer_A && "No buffer."); assert(buffer_B && "No buffer."); assert(buffer_C && "No buffer."); #if (1 == XOPENME) xopenme_clock_start(0); #endif enqueue_kernel(); #if (1 == XOPENME) xopenme_clock_end(0); #endif profile_execution(); data.verify_results(*this); } // END OF _execute_kernel() public: // Run the kernel on random data, profile and verify. void execute_kernel() { if (meta.type == "S") { _execute_kernel<cl_float>(); } else if (meta.type == "D") { _execute_kernel<cl_double>(); } else { assert(false && "Unsupported data type."); } } // END OF execute_kernel() }; // END OF gemmbench::state class } // END OF gemmbench namespace #endif // CL_STATE_HPP
#include "ride/finddlg.h" #include "ride/wx.h" #include "ride/generated/ui.h" #include "ride/wxutils.h" #include "wx/stc/stc.h" #include "ride/settings.h" #include <wx/dir.h> #include "ride/mainwindow.h" #include "ride/fileedit.h" class FindDlg : public ui::Find { public: FindDlg(wxWindow* parent, const wxString& find, const ride::FindDlg& data, FindAction find_action, FindScope find_scope); const wxString GetText() const { return uiFindText->GetValue(); } const int GetFlags(); void ToData(ride::FindDlg& data) const; wxStyledTextCtrl* GetStc() { return m_scintilla1; } bool LookInCurrentFile() const { return uiLookIn->GetSelection() == 0; } bool IsRecursive() const { return uiIncludeSubFolders->GetValue(); } const wxString getReplaceText() const { return uiReplaceText->GetValue(); } bool KeepFilesOpen() const { return uiKeepFilesOpen->GetValue(); } protected: void OnCancel(wxCommandEvent& event); void OnOk(wxCommandEvent& event); void OnEnter(wxCommandEvent& event) { OnOk(event); } }; FindDlg::FindDlg(wxWindow* parent, const wxString& find, const ride::FindDlg& data, FindAction find_action, FindScope find_scope) : ui::Find(parent, wxID_ANY) { uiFindText->SetValue(find); uiFindText->SelectAll(); uiFindText->SetFocus(); uiLookIn->Append("Current file"); uiLookIn->Append("This project"); uiLookIn->SetSelection(static_cast<int>(find_scope)); // assume the enum is file -> project uiFindTarget->Append("Normal text"); uiFindTarget->Append("Regex"); uiFindTarget->Append("Posix"); uiIncludeSubFolders->SetValue(data.sub_folders()); uiMatchCase->SetValue(data.match_case()); uiMatchWholeWord->SetValue(data.match_whole_word()); uiFindWordStart->SetValue(data.match_start()); uiFileTypes->SetValue(data.file_types().c_str()); uiFindTarget->SetSelection(data.target()); uiReplaceStatic->Enable(find_action == FindAction::Replace); uiReplaceText->Enable(find_action == FindAction::Replace); } void FindDlg::ToData(ride::FindDlg& data) const { data.set_sub_folders(uiIncludeSubFolders->GetValue()); data.set_match_case(uiMatchCase->GetValue()); data.set_match_whole_word(uiMatchWholeWord->GetValue()); data.set_match_start(uiFindWordStart->GetValue()); data.set_file_types(uiFileTypes->GetValue()); data.set_target(static_cast<::ride::FindDlgTarget>(uiFindTarget->GetSelection())); } void FindDlg::OnCancel(wxCommandEvent& event) { EndModal(wxID_CANCEL); } void FindDlg::OnOk(wxCommandEvent& event) { if (uiFindText->GetValue().length() <= 0) { ShowInfo(this, "Need to enter search text", "Missing Search Text"); return; } EndModal(wxID_OK); } const int FindDlg::GetFlags() { int ret = 0; if (uiMatchCase->GetValue()) { ret |= wxSTC_FIND_MATCHCASE; } if (uiMatchWholeWord->GetValue()) { ret |= wxSTC_FIND_WHOLEWORD; } if (uiFindWordStart->GetValue()) { ret |= wxSTC_FIND_WORDSTART; } switch (uiFindTarget->GetSelection()) { case 0: break; case 1: ret |= wxSTC_FIND_REGEXP; break; case 2: ret |= wxSTC_FIND_POSIX; break; default: assert(false && "invalid selection"); break; } return ret; } struct FindResult { FindResult(const wxString& f, const wxString& co, const int sl, const int sc, const int el, const int ec) : file(f) , content(co) , start_line(sl) , start_col(sc) , end_line(el) , end_col(ec) { } wxString file; wxString content; int start_line; int start_col; int end_line; int end_col; }; int FindInStc(wxStyledTextCtrl* stc, const wxString& file, const wxString& text, int flags, std::vector<FindResult>* res, FindAction find_action, const wxString& replaceText) { assert(res); assert(stc); int next_index = 0; int count = 0; while (true) { int end_index = 0; const int start_index = stc->FindText(next_index, stc->GetLength(), text, &end_index, flags); if (start_index == -1) return count; assert(start_index != end_index); const int target_start_index = start_index; int target_end_index = end_index; // replace text if (find_action == FindAction::Replace) { stc->SetTargetStart(start_index); stc->SetTargetEnd(end_index); const bool useRegex = flags & wxSTC_FIND_REGEXP || flags & wxSTC_FIND_POSIX; const int change = useRegex ? stc->ReplaceTargetRE(replaceText) : stc->ReplaceTarget(replaceText); assert(change > 0); next_index = start_index + change; target_end_index = start_index + change; } else { next_index = end_index; } // add item to the result list const int start_line = stc->LineFromPosition(target_start_index); const int start_col = target_start_index - stc->PositionFromLine(target_start_index); const int end_line = stc->LineFromPosition(target_end_index); const int end_col = target_end_index - stc->PositionFromLine(end_line); res->push_back(FindResult(file, stc->GetLine(start_line).Trim(true).Trim(false), start_line + 1, start_col + 1, end_line + 1, end_col + 1)); ++count; } return count; } void FindInFiles(MainWindow* parent, wxStyledTextCtrl* fallback, const wxString& file, const wxString& text, int flags, std::vector<FindResult>* res, FindAction find_action, const wxString& replaceText, bool keepFilesOpen) { FileEdit* edit = parent->GetFile(file); wxStyledTextCtrl* stc = NULL; if (edit) { stc = edit->GetStc(); } else { fallback->LoadFile(file); if (find_action == FindAction::Replace && keepFilesOpen) { int found = fallback->FindText(0, stc->GetLength(), text, NULL, flags); if (found > 0) { FileEdit* opened_edit = parent->OpenFile(file); stc = opened_edit->GetStc(); } } if( stc == NULL ) { stc = fallback; } } assert(stc); int count = FindInStc(stc, file, text, flags, res, find_action, replaceText); if (find_action == FindAction::Replace && count > 0 && stc == fallback) { if (false == stc->SaveFile(file)) { ShowError(parent, "Failed to save after replace!", "Error saving!"); } } } bool ShowFindDlg(MainWindow* parent, const wxString& current_selection, const wxString& current_file, const wxString root_folder, wxStyledTextCtrl* output, FindAction find_action, FindScope find_scope) { static ride::FindDlg find_dlg_data; FindDlg dlg(parent, current_selection, find_dlg_data, find_action, find_scope); if (wxID_OK != dlg.ShowModal()) return false; dlg.ToData(find_dlg_data); std::vector<FindResult> results; wxString file_info = current_file; // we can't create a styled ctrl so we cheat by having a 0x0 widget on the find dlg // and use that for searching/replacing... wxStyledTextCtrl* fallback = dlg.GetStc(); if (dlg.LookInCurrentFile()) { FindInFiles(parent, fallback, current_file, dlg.GetText(), dlg.GetFlags(), &results, find_action, dlg.getReplaceText(), dlg.KeepFilesOpen()); } else { wxArrayString files; const std::vector<wxString> patterns = Split(find_dlg_data.file_types(), ";"); size_t count = 0; for (const auto pattern : patterns) { count += wxDir::GetAllFiles(root_folder, &files, pattern, dlg.IsRecursive() ? wxDIR_FILES | wxDIR_DIRS : wxDIR_FILES); } file_info = wxString::Format("%d files in %s", count, root_folder); for (const auto file : files) { FindInFiles(parent, fallback, file, dlg.GetText(), dlg.GetFlags(), &results, find_action, dlg.getReplaceText(), dlg.KeepFilesOpen()); } } const auto count = results.size(); ClearOutput(output); const wxString find_text = find_action == FindAction::Find ? wxString::Format("Searched for '%s'", dlg.GetText()) : wxString::Format("Replaced '%s' with '%s'", dlg.GetText(), dlg.getReplaceText()); WriteLine(output, wxString::Format("%s in %s", find_text, file_info)); WriteLine(output, wxString::Format("%s %d matches", find_action == FindAction::Find ? "Found" : "Replaced", count)); WriteLine(output, ""); for (auto res : results) { // try to format the same way rust related error looks like so we can reuse the parser code for both and get some synergy effects const wxString mess = wxString::Format("%s:%d : %d : %d : %d %s: %s", res.file, res.start_line, res.start_col, res.end_line, res.end_col, find_action == FindAction::Find ? "found" : "replaced", res.content); WriteLine(output, mess); } return true; } Fixed wrong index bug #include "ride/finddlg.h" #include "ride/wx.h" #include "ride/generated/ui.h" #include "ride/wxutils.h" #include "wx/stc/stc.h" #include "ride/settings.h" #include <wx/dir.h> #include "ride/mainwindow.h" #include "ride/fileedit.h" class FindDlg : public ui::Find { public: FindDlg(wxWindow* parent, const wxString& find, const ride::FindDlg& data, FindAction find_action, FindScope find_scope); const wxString GetText() const { return uiFindText->GetValue(); } const int GetFlags(); void ToData(ride::FindDlg& data) const; wxStyledTextCtrl* GetStc() { return m_scintilla1; } bool LookInCurrentFile() const { return uiLookIn->GetSelection() == 0; } bool IsRecursive() const { return uiIncludeSubFolders->GetValue(); } const wxString getReplaceText() const { return uiReplaceText->GetValue(); } bool KeepFilesOpen() const { return uiKeepFilesOpen->GetValue(); } protected: void OnCancel(wxCommandEvent& event); void OnOk(wxCommandEvent& event); void OnEnter(wxCommandEvent& event) { OnOk(event); } }; FindDlg::FindDlg(wxWindow* parent, const wxString& find, const ride::FindDlg& data, FindAction find_action, FindScope find_scope) : ui::Find(parent, wxID_ANY) { uiFindText->SetValue(find); uiFindText->SelectAll(); uiFindText->SetFocus(); uiLookIn->Append("Current file"); uiLookIn->Append("This project"); uiLookIn->SetSelection(static_cast<int>(find_scope)); // assume the enum is file -> project uiFindTarget->Append("Normal text"); uiFindTarget->Append("Regex"); uiFindTarget->Append("Posix"); uiIncludeSubFolders->SetValue(data.sub_folders()); uiMatchCase->SetValue(data.match_case()); uiMatchWholeWord->SetValue(data.match_whole_word()); uiFindWordStart->SetValue(data.match_start()); uiFileTypes->SetValue(data.file_types().c_str()); uiFindTarget->SetSelection(data.target()); uiReplaceStatic->Enable(find_action == FindAction::Replace); uiReplaceText->Enable(find_action == FindAction::Replace); } void FindDlg::ToData(ride::FindDlg& data) const { data.set_sub_folders(uiIncludeSubFolders->GetValue()); data.set_match_case(uiMatchCase->GetValue()); data.set_match_whole_word(uiMatchWholeWord->GetValue()); data.set_match_start(uiFindWordStart->GetValue()); data.set_file_types(uiFileTypes->GetValue()); data.set_target(static_cast<::ride::FindDlgTarget>(uiFindTarget->GetSelection())); } void FindDlg::OnCancel(wxCommandEvent& event) { EndModal(wxID_CANCEL); } void FindDlg::OnOk(wxCommandEvent& event) { if (uiFindText->GetValue().length() <= 0) { ShowInfo(this, "Need to enter search text", "Missing Search Text"); return; } EndModal(wxID_OK); } const int FindDlg::GetFlags() { int ret = 0; if (uiMatchCase->GetValue()) { ret |= wxSTC_FIND_MATCHCASE; } if (uiMatchWholeWord->GetValue()) { ret |= wxSTC_FIND_WHOLEWORD; } if (uiFindWordStart->GetValue()) { ret |= wxSTC_FIND_WORDSTART; } switch (uiFindTarget->GetSelection()) { case 0: break; case 1: ret |= wxSTC_FIND_REGEXP; break; case 2: ret |= wxSTC_FIND_POSIX; break; default: assert(false && "invalid selection"); break; } return ret; } struct FindResult { FindResult(const wxString& f, const wxString& co, const int sl, const int sc, const int el, const int ec) : file(f) , content(co) , start_line(sl) , start_col(sc) , end_line(el) , end_col(ec) { } wxString file; wxString content; int start_line; int start_col; int end_line; int end_col; }; int FindInStc(wxStyledTextCtrl* stc, const wxString& file, const wxString& text, int flags, std::vector<FindResult>* res, FindAction find_action, const wxString& replaceText) { assert(res); assert(stc); int next_index = 0; int count = 0; while (true) { int end_index = 0; const int start_index = stc->FindText(next_index, stc->GetLength(), text, &end_index, flags); if (start_index == -1) return count; assert(start_index != end_index); const int target_start_index = start_index; int target_end_index = end_index; // replace text if (find_action == FindAction::Replace) { stc->SetTargetStart(start_index); stc->SetTargetEnd(end_index); const bool useRegex = flags & wxSTC_FIND_REGEXP || flags & wxSTC_FIND_POSIX; const int change = useRegex ? stc->ReplaceTargetRE(replaceText) : stc->ReplaceTarget(replaceText); assert(change > 0); next_index = start_index + change; target_end_index = start_index + change; } else { next_index = end_index; } // add item to the result list const int start_line = stc->LineFromPosition(target_start_index); const int start_col = target_start_index - stc->PositionFromLine(start_line); const int end_line = stc->LineFromPosition(target_end_index); const int end_col = target_end_index - stc->PositionFromLine(end_line); res->push_back(FindResult(file, stc->GetLine(start_line).Trim(true).Trim(false), start_line + 1, start_col + 1, end_line + 1, end_col + 1)); ++count; } return count; } void FindInFiles(MainWindow* parent, wxStyledTextCtrl* fallback, const wxString& file, const wxString& text, int flags, std::vector<FindResult>* res, FindAction find_action, const wxString& replaceText, bool keepFilesOpen) { FileEdit* edit = parent->GetFile(file); wxStyledTextCtrl* stc = NULL; if (edit) { stc = edit->GetStc(); } else { fallback->LoadFile(file); if (find_action == FindAction::Replace && keepFilesOpen) { int found = fallback->FindText(0, stc->GetLength(), text, NULL, flags); if (found > 0) { FileEdit* opened_edit = parent->OpenFile(file); stc = opened_edit->GetStc(); } } if( stc == NULL ) { stc = fallback; } } assert(stc); int count = FindInStc(stc, file, text, flags, res, find_action, replaceText); if (find_action == FindAction::Replace && count > 0 && stc == fallback) { if (false == stc->SaveFile(file)) { ShowError(parent, "Failed to save after replace!", "Error saving!"); } } } bool ShowFindDlg(MainWindow* parent, const wxString& current_selection, const wxString& current_file, const wxString root_folder, wxStyledTextCtrl* output, FindAction find_action, FindScope find_scope) { static ride::FindDlg find_dlg_data; FindDlg dlg(parent, current_selection, find_dlg_data, find_action, find_scope); if (wxID_OK != dlg.ShowModal()) return false; dlg.ToData(find_dlg_data); std::vector<FindResult> results; wxString file_info = current_file; // we can't create a styled ctrl so we cheat by having a 0x0 widget on the find dlg // and use that for searching/replacing... wxStyledTextCtrl* fallback = dlg.GetStc(); if (dlg.LookInCurrentFile()) { FindInFiles(parent, fallback, current_file, dlg.GetText(), dlg.GetFlags(), &results, find_action, dlg.getReplaceText(), dlg.KeepFilesOpen()); } else { wxArrayString files; const std::vector<wxString> patterns = Split(find_dlg_data.file_types(), ";"); size_t count = 0; for (const auto pattern : patterns) { count += wxDir::GetAllFiles(root_folder, &files, pattern, dlg.IsRecursive() ? wxDIR_FILES | wxDIR_DIRS : wxDIR_FILES); } file_info = wxString::Format("%d files in %s", count, root_folder); for (const auto file : files) { FindInFiles(parent, fallback, file, dlg.GetText(), dlg.GetFlags(), &results, find_action, dlg.getReplaceText(), dlg.KeepFilesOpen()); } } const auto count = results.size(); ClearOutput(output); const wxString find_text = find_action == FindAction::Find ? wxString::Format("Searched for '%s'", dlg.GetText()) : wxString::Format("Replaced '%s' with '%s'", dlg.GetText(), dlg.getReplaceText()); WriteLine(output, wxString::Format("%s in %s", find_text, file_info)); WriteLine(output, wxString::Format("%s %d matches", find_action == FindAction::Find ? "Found" : "Replaced", count)); WriteLine(output, ""); for (auto res : results) { // try to format the same way rust related error looks like so we can reuse the parser code for both and get some synergy effects const wxString mess = wxString::Format("%s:%d : %d : %d : %d %s: %s", res.file, res.start_line, res.start_col, res.end_line, res.end_col, find_action == FindAction::Find ? "found" : "replaced", res.content); WriteLine(output, mess); } return true; }
/** * Copyright (c) 2017 DeepCortex GmbH <legal@eventql.io> * Authors: * - Laura Schlimmer <laura@eventql.io> * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License ("the license") as * published by the Free Software Foundation, either version 3 of the License, * or any later version. * * In accordance with Section 7(e) of the license, the licensing of the Program * under the license does not imply a trademark license. Therefore any rights, * title and interest in our trademarks remain entirely with us. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the license for more details. * * You can be released from the requirements of the license by purchasing a * commercial license. Buying such a license is mandatory as soon as you develop * commercial activities involving this program without disclosing the source * code of your own applications */ #include <iostream> #include "eventql/util/stdtypes.h" #include "eventql/util/exception.h" #include "eventql/util/status.h" #include "eventql/util/stringutil.h" #include "eventql/util/io/fileutil.h" #include "eventql/util/io/inputstream.h" #include "eventql/util/cli/flagparser.h" #include "eventql/util/csv/CSVInputStream.h" #include "eventql/util/csv/CSVOutputStream.h" #include "eventql/sql/runtime/defaultruntime.h" #include "eventql/sql/CSTableScanProvider.h" #include "eventql/sql/result_list.h" #include "eventql/eventql.h" using namespace csql; enum class ResultExpectation { TABLE, CHART, ERROR }; const auto kTestListFile = "./sql_tests.lst"; const auto kDirectoryPath = "./sql"; const auto kSQLPathEnding = ".sql"; const auto kResultPathEnding = ".result.txt"; const auto kChartColumnName = "__chart"; const auto kDefaultResultExpectation = ResultExpectation::TABLE; std::string getResultCSV(ResultList* result, const std::string& row_sep = "\n") { std::string result_csv; auto is = new StringOutputStream(&result_csv); auto csv_is = new CSVOutputStream( std::unique_ptr<OutputStream>(is), ";", row_sep); auto columns = result->getColumns(); csv_is->appendRow(columns); auto num_rows = result->getNumRows(); for (size_t i = 0; i < num_rows; ++i) { auto row = result->getRow(i); csv_is->appendRow(row); } return result_csv; } Status checkTableResult( ResultList* result, const std::string& result_file_path) { auto csv_is = CSVInputStream::openFile(result_file_path); std::vector<std::string> columns; if (!csv_is->readNextRow(&columns)) { return Status(eRuntimeError, "CSV needs a header"); } /* compare columns */ if (result->getNumColumns() != columns.size()) { return Status(eRuntimeError, StringUtil::format( "wrong number of columns, expected $0 to be $1", result->getNumColumns(), columns.size())); } auto returned_columns = result->getColumns(); for (size_t i = 0; i < returned_columns.size(); ++i) { if (returned_columns[i] != columns[i]) { return Status(eRuntimeError, StringUtil::format( "wrong columns name, expected $0 to be $1", returned_columns[i], columns[i])); } } /* compare rows */ auto num_returned_rows = result->getNumRows(); size_t count = 0; std::vector<std::string> row; while (csv_is->readNextRow(&row)) { if (count >= num_returned_rows) { return Status(eRuntimeError, "not enough rows returned"); } auto returned_row = result->getRow(count); if (returned_row.size() != row.size()) { return Status(eRuntimeError, StringUtil::format( "wrong number of values, expected $0 to be $1", returned_row.size(), row.size())); } for (size_t i = 0; i < row.size(); ++i) { if (row[i] != returned_row[i]) { return Status( eRuntimeError, StringUtil::format( "result mismatch at row $0, column $1; expected: >$2<, got: >$3<", count, i, row[i], returned_row[i])); } } ++count; } if (count < num_returned_rows) { return Status(eRuntimeError, StringUtil::format( "too many rows, expected $0 to be $1", num_returned_rows, count)); } return Status::success(); } Status checkChartResult( ResultList* result, const std::string& result_file_path) { auto num_returned_rows = result->getNumRows(); if (num_returned_rows != 1) { return Status(eRuntimeError, StringUtil::format( "wrong number of rows returned, expected $0 to be 1", num_returned_rows)); } auto is = FileInputStream::openFile(result_file_path); std::string expected_result; is->readUntilEOF(&expected_result); auto returned_result = result->getRow(0)[0]; if (expected_result != returned_result) { return Status(eRuntimeError, "result charts don't match"); } return Status::success(); } Status checkErrorResult( const std::string& error_message, ResultList* result, const std::string& result_file_path) { auto is = FileInputStream::openFile(result_file_path); { std::string result_expectation_line; is->readLine(&result_expectation_line); } std::string expected_error; is->readUntilEOF(&expected_error); StringUtil::chomp(&expected_error); if (expected_error == error_message) { return Status::success(); } else { if (error_message.empty()) { auto result_csv = getResultCSV(result, " "); return Status(eRuntimeError, StringUtil::format( "expected error: $0 but got result: $1", expected_error, result_csv)); } else { return Status(eRuntimeError, StringUtil::format( "expected error: $0 but got error $1", expected_error, error_message)); } } } Status runTest(const std::string& test) { auto sql_file_path = FileUtil::joinPaths( kDirectoryPath, StringUtil::format("$0$1", test, kSQLPathEnding)); if (!FileUtil::exists(sql_file_path)) { return Status( eIOError, StringUtil::format("File does not exist: $0", sql_file_path)); } auto result_file_path = FileUtil::joinPaths( kDirectoryPath, StringUtil::format("$0$1", test, kResultPathEnding)); if (!FileUtil::exists(result_file_path)) { return Status( eIOError, StringUtil::format("File does not exist: $0", result_file_path)); } auto result_expectation = kDefaultResultExpectation; { auto result_is = FileInputStream::openFile(result_file_path); std::string first_line; if (result_is->readLine(&first_line)) { StringUtil::chomp(&first_line); if (first_line == "ERROR!") { result_expectation = ResultExpectation::ERROR; } } } /* input table path */ auto sql_is = FileInputStream::openFile(sql_file_path); std::string input_table_path; if (!sql_is->readLine(&input_table_path) || !StringUtil::beginsWith(input_table_path, "--")) { return Status(eRuntimeError, "no input table provided"); } StringUtil::replaceAll(&input_table_path, "--"); StringUtil::ltrim(&input_table_path); StringUtil::chomp(&input_table_path); if (!FileUtil::exists(input_table_path)) { return Status( eRuntimeError, StringUtil::format("file does not exist: $0", input_table_path)); } std::string query; sql_is->readUntilEOF(&query); /* execute query */ auto runtime = Runtime::getDefaultRuntime(); auto txn = runtime->newTransaction(); txn->setTableProvider(new CSTableScanProvider("testtable", input_table_path)); ResultList result; std::string error_message; try { auto qplan = runtime->buildQueryPlan(txn.get(), query); qplan->execute(0, &result); } catch (const std::exception& e) { error_message = e.what(); if (result_expectation != ResultExpectation::ERROR) { return Status( eRuntimeError, StringUtil::format("unexpected error: $0", error_message)); } } if (result.getNumColumns() == 1 && result.getColumns()[0] == kChartColumnName) { result_expectation = ResultExpectation::CHART; } switch (result_expectation) { case ResultExpectation::TABLE: return checkTableResult(&result, result_file_path); case ResultExpectation::CHART: return checkChartResult(&result, result_file_path); case ResultExpectation::ERROR: return checkErrorResult(error_message, &result, result_file_path); } } int main(int argc, const char** argv) { cli::FlagParser flags; flags.defineFlag( "help", cli::FlagParser::T_SWITCH, false, "?", NULL, "help", "<help>"); flags.defineFlag( "test", cli::FlagParser::T_STRING, false, "t", NULL, "test", "<test_number>"); flags.parseArgv(argc, argv); if (flags.isSet("help")) { std::cout << StringUtil::format( "EventQL $0 ($1)\n" "Copyright (c) 2016, DeepCortex GmbH. All rights reserved.\n\n", eventql::kVersionString, eventql::kBuildID); std::cout << "Usage: $ evql-test-sql [OPTIONS]" << std::endl << " --verbose Print debug output to STDERR" << std::endl << " -?, --help Display this help text and exit" <<std::endl << " -t, --test <test_number> Run a test specified by its test number" <<std::endl; return 0; } std::string test_nr; if (flags.isSet("test")) { test_nr = flags.getString("test"); } try { auto is = FileInputStream::openFile(kTestListFile); std::string line; size_t count = 1; while (is->readLine(&line)) { StringUtil::chomp(&line); if (!test_nr.empty() && !StringUtil::beginsWith(line, test_nr)) { continue; } auto ret = runTest(line); if (ret.isSuccess()) { std::cout << "ok " << count << " - " << "[" << line << "] " << "Test passed" << std::endl; } else { std::cout << "not ok " << count << " - " << "[" << line << "] " << ret.message() << std::endl; } line.clear(); ++count; } } catch (const std::exception& e) { std::cout << e.what(); return 1; } return 0; } evql-test-sql: added csv output format /** * Copyright (c) 2017 DeepCortex GmbH <legal@eventql.io> * Authors: * - Laura Schlimmer <laura@eventql.io> * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License ("the license") as * published by the Free Software Foundation, either version 3 of the License, * or any later version. * * In accordance with Section 7(e) of the license, the licensing of the Program * under the license does not imply a trademark license. Therefore any rights, * title and interest in our trademarks remain entirely with us. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the license for more details. * * You can be released from the requirements of the license by purchasing a * commercial license. Buying such a license is mandatory as soon as you develop * commercial activities involving this program without disclosing the source * code of your own applications */ #include <iostream> #include "eventql/util/stdtypes.h" #include "eventql/util/exception.h" #include "eventql/util/status.h" #include "eventql/util/stringutil.h" #include "eventql/util/io/fileutil.h" #include "eventql/util/io/inputstream.h" #include "eventql/util/io/TerminalOutputStream.h" #include "eventql/util/cli/flagparser.h" #include "eventql/util/csv/CSVInputStream.h" #include "eventql/util/csv/CSVOutputStream.h" #include "eventql/sql/runtime/defaultruntime.h" #include "eventql/sql/CSTableScanProvider.h" #include "eventql/sql/result_list.h" #include "eventql/eventql.h" using namespace csql; enum class ResultExpectation { TABLE, CHART, ERROR }; enum class OutputFormat { TAP, CSV, VERBOSE }; const auto kTestListFile = "./sql_tests.lst"; const auto kDirectoryPath = "./sql"; const auto kSQLPathEnding = ".sql"; const auto kResultPathEnding = ".result.txt"; const auto kChartColumnName = "__chart"; const auto kDefaultResultExpectation = ResultExpectation::TABLE; const auto kDefaultOutputFormat = OutputFormat::TAP; static void printError(const std::string& error_string) { auto stderr_os = TerminalOutputStream::fromStream(OutputStream::getStderr()); stderr_os->print( "ERROR:", { TerminalStyle::RED, TerminalStyle::UNDERSCORE }); stderr_os->print(" " + error_string + "\n"); } std::string getResultCSV(ResultList* result, const std::string& row_sep = "\n") { std::string result_csv; auto is = new StringOutputStream(&result_csv); auto csv_is = new CSVOutputStream( std::unique_ptr<OutputStream>(is), ";", row_sep); auto columns = result->getColumns(); csv_is->appendRow(columns); auto num_rows = result->getNumRows(); for (size_t i = 0; i < num_rows; ++i) { auto row = result->getRow(i); csv_is->appendRow(row); } return result_csv; } Status checkTableResult( ResultList* result, const std::string& result_file_path) { auto csv_is = CSVInputStream::openFile(result_file_path); std::vector<std::string> columns; if (!csv_is->readNextRow(&columns)) { return Status(eRuntimeError, "CSV needs a header"); } /* compare columns */ if (result->getNumColumns() != columns.size()) { return Status(eRuntimeError, StringUtil::format( "wrong number of columns, expected $0 to be $1", result->getNumColumns(), columns.size())); } auto returned_columns = result->getColumns(); for (size_t i = 0; i < returned_columns.size(); ++i) { if (returned_columns[i] != columns[i]) { return Status(eRuntimeError, StringUtil::format( "wrong columns name, expected $0 to be $1", returned_columns[i], columns[i])); } } /* compare rows */ auto num_returned_rows = result->getNumRows(); size_t count = 0; std::vector<std::string> row; while (csv_is->readNextRow(&row)) { if (count >= num_returned_rows) { return Status(eRuntimeError, "not enough rows returned"); } auto returned_row = result->getRow(count); if (returned_row.size() != row.size()) { return Status(eRuntimeError, StringUtil::format( "wrong number of values, expected $0 to be $1", returned_row.size(), row.size())); } for (size_t i = 0; i < row.size(); ++i) { if (row[i] != returned_row[i]) { return Status( eRuntimeError, StringUtil::format( "result mismatch at row $0, column $1; expected: >$2<, got: >$3<", count, i, row[i], returned_row[i])); } } ++count; } if (count < num_returned_rows) { return Status(eRuntimeError, StringUtil::format( "too many rows, expected $0 to be $1", num_returned_rows, count)); } return Status::success(); } Status checkChartResult( ResultList* result, const std::string& result_file_path) { auto num_returned_rows = result->getNumRows(); if (num_returned_rows != 1) { return Status(eRuntimeError, StringUtil::format( "wrong number of rows returned, expected $0 to be 1", num_returned_rows)); } auto is = FileInputStream::openFile(result_file_path); std::string expected_result; is->readUntilEOF(&expected_result); auto returned_result = result->getRow(0)[0]; if (expected_result != returned_result) { return Status(eRuntimeError, "result charts don't match"); } return Status::success(); } Status checkErrorResult( const std::string& error_message, ResultList* result, const std::string& result_file_path) { auto is = FileInputStream::openFile(result_file_path); { std::string result_expectation_line; is->readLine(&result_expectation_line); } std::string expected_error; is->readUntilEOF(&expected_error); StringUtil::chomp(&expected_error); if (expected_error == error_message) { return Status::success(); } else { if (error_message.empty()) { auto result_csv = getResultCSV(result, " "); return Status(eRuntimeError, StringUtil::format( "expected error: $0 but got result: $1", expected_error, result_csv)); } else { return Status(eRuntimeError, StringUtil::format( "expected error: $0 but got error $1", expected_error, error_message)); } } } Status runTest(const std::string& test, OutputFormat output_format) { auto sql_file_path = FileUtil::joinPaths( kDirectoryPath, StringUtil::format("$0$1", test, kSQLPathEnding)); if (!FileUtil::exists(sql_file_path)) { return Status( eIOError, StringUtil::format("File does not exist: $0", sql_file_path)); } auto result_file_path = FileUtil::joinPaths( kDirectoryPath, StringUtil::format("$0$1", test, kResultPathEnding)); if (!FileUtil::exists(result_file_path)) { return Status( eIOError, StringUtil::format("File does not exist: $0", result_file_path)); } auto result_expectation = kDefaultResultExpectation; { auto result_is = FileInputStream::openFile(result_file_path); std::string first_line; if (result_is->readLine(&first_line)) { StringUtil::chomp(&first_line); if (first_line == "ERROR!") { result_expectation = ResultExpectation::ERROR; } } } /* input table path */ auto sql_is = FileInputStream::openFile(sql_file_path); std::string input_table_path; if (!sql_is->readLine(&input_table_path) || !StringUtil::beginsWith(input_table_path, "--")) { return Status(eRuntimeError, "no input table provided"); } StringUtil::replaceAll(&input_table_path, "--"); StringUtil::ltrim(&input_table_path); StringUtil::chomp(&input_table_path); if (!FileUtil::exists(input_table_path)) { return Status( eRuntimeError, StringUtil::format("file does not exist: $0", input_table_path)); } std::string query; sql_is->readUntilEOF(&query); /* execute query */ auto runtime = Runtime::getDefaultRuntime(); auto txn = runtime->newTransaction(); txn->setTableProvider(new CSTableScanProvider("testtable", input_table_path)); ResultList result; std::string error_message; auto rc = Status::success(); try { auto qplan = runtime->buildQueryPlan(txn.get(), query); qplan->execute(0, &result); } catch (const std::exception& e) { error_message = e.what(); if (result_expectation != ResultExpectation::ERROR) { return Status( eRuntimeError, StringUtil::format("unexpected error: $0", error_message)); } } if (result.getNumColumns() == 1 && result.getColumns()[0] == kChartColumnName) { result_expectation = ResultExpectation::CHART; } switch (result_expectation) { case ResultExpectation::TABLE: rc = checkTableResult(&result, result_file_path); break; case ResultExpectation::CHART: rc = checkChartResult(&result, result_file_path); break; case ResultExpectation::ERROR: rc = checkErrorResult(error_message, &result, result_file_path); break; } if (rc.isSuccess()) { return rc; } switch (output_format) { case OutputFormat::CSV: return Status(eRuntimeError, getResultCSV(&result)); case OutputFormat::VERBOSE: case OutputFormat::TAP: return rc; } } int main(int argc, const char** argv) { cli::FlagParser flags; flags.defineFlag( "help", cli::FlagParser::T_SWITCH, false, "?", NULL, "help", "<help>"); flags.defineFlag( "test", cli::FlagParser::T_STRING, false, "t", NULL, "test", "<test_number>"); flags.defineFlag( "tap", cli::FlagParser::T_SWITCH, false, NULL, NULL, "tap", "<tap>"); flags.defineFlag( "csv", cli::FlagParser::T_SWITCH, false, NULL, NULL, "csv", "<csv>"); flags.defineFlag( "verbose", cli::FlagParser::T_SWITCH, false, NULL, NULL, "verbose", "<verbose>"); flags.parseArgv(argc, argv); if (flags.isSet("help")) { std::cout << StringUtil::format( "EventQL $0 ($1)\n" "Copyright (c) 2016, DeepCortex GmbH. All rights reserved.\n\n", eventql::kVersionString, eventql::kBuildID); std::cout << "Usage: $ evql-test-sql [OPTIONS]" << std::endl << " --tap Print the test output as TAP" << std::endl << " -t, --test <test_number> Run a test specified by its test number" <<std::endl << " --csv Print the result as CSV (use only together with --test) " << std::endl << " --verbose Print the expected and the actual result as tables (use only togehter with --test)" << std::endl << " -?, --help Display this help text and exit" <<std::endl; return 0; } if (flags.getArgv().size() > 0) { printError(StringUtil::format( "invalid argument: '$0', run evql-test-sql --help for help\n", flags.getArgv()[0])); return 1; } if (flags.isSet("csv") && !flags.isSet("test")) { printError("--csv can only be used if --test is set, run evql-test-sql --help for help\n"); return 1; } if (flags.isSet("verbose") && !flags.isSet("test")) { printError("--verbose can only be used if --test is set, run evql-test-sql --help for help\n"); return 1; } auto output_format = kDefaultOutputFormat; if (flags.isSet("tap")) { output_format = OutputFormat::TAP; } if (flags.isSet("csv")) { output_format = OutputFormat::CSV; } if (flags.isSet("verbose")) { output_format = OutputFormat::VERBOSE; } std::string test_nr; if (flags.isSet("test")) { test_nr = flags.getString("test"); } try { auto is = FileInputStream::openFile(kTestListFile); std::string line; size_t count = 1; while (is->readLine(&line)) { StringUtil::chomp(&line); if (!test_nr.empty() && !StringUtil::beginsWith(line, test_nr)) { continue; } auto ret = runTest(line, output_format); if (ret.isSuccess()) { std::cout << "ok " << count << " - " << "[" << line << "] " << "Test passed" << std::endl; } else { switch (output_format) { case OutputFormat::TAP: std::cout << "not ok " << count << " - " << "[" << line << "] "; case OutputFormat::VERBOSE: case OutputFormat::CSV: std::cout << ret.message() << std::endl; } } line.clear(); ++count; } } catch (const std::exception& e) { printError(e.what()); return 1; } return 0; }
/** * @file * @copyright defined in eos/LICENSE.txt * @defgroup eosclienttool EOSIO Command Line Client Reference * @brief Tool for sending transactions and querying state from @ref nodeos * @ingroup eosclienttool */ /** @defgroup eosclienttool @section intro Introduction to cleos `cleos` is a command line tool that interfaces with the REST api exposed by @ref nodeos. In order to use `cleos` you will need to have a local copy of `nodeos` running and configured to load the 'eosio::chain_api_plugin'. cleos contains documentation for all of its commands. For a list of all commands known to cleos, simply run it with no arguments: ``` $ ./cleos Command Line Interface to EOSIO Client Usage: programs/cleos/cleos [OPTIONS] SUBCOMMAND Options: -h,--help Print this help message and exit -u,--url TEXT=http://localhost:8888/ the http/https URL where nodeos is running --wallet-url TEXT=http://localhost:8888/ the http/https URL where keosd is running -r,--header pass specific HTTP header, repeat this option to pass multiple headers -n,--no-verify don't verify peer certificate when using HTTPS -v,--verbose output verbose actions on error Subcommands: version Retrieve version information create Create various items, on and off the blockchain get Retrieve various items and information from the blockchain set Set or update blockchain state transfer Transfer EOS from account to account net Interact with local p2p network connections wallet Interact with local wallet sign Sign a transaction push Push arbitrary transactions to the blockchain multisig Multisig contract commands ``` To get help with any particular subcommand, run it with no arguments as well: ``` $ ./cleos create Create various items, on and off the blockchain Usage: ./cleos create SUBCOMMAND Subcommands: key Create a new keypair and print the public and private keys account Create a new account on the blockchain $ ./cleos create account Create a new account on the blockchain Usage: ./cleos create account [OPTIONS] creator name OwnerKey ActiveKey Positionals: creator TEXT The name of the account creating the new account name TEXT The name of the new account OwnerKey TEXT The owner public key for the new account ActiveKey TEXT The active public key for the new account Options: -x,--expiration set the time in seconds before a transaction expires, defaults to 30s -f,--force-unique force the transaction to be unique. this will consume extra bandwidth and remove any protections against accidently issuing the same transaction multiple times -s,--skip-sign Specify if unlocked wallet keys should be used to sign transaction -d,--dont-broadcast don't broadcast transaction to the network (just print to stdout) -p,--permission TEXT ... An account and permission level to authorize, as in 'account@permission' (defaults to 'creator@active') ``` */ #include <pwd.h> #include <string> #include <vector> #include <regex> #include <iostream> #include <fc/crypto/hex.hpp> #include <fc/variant.hpp> #include <fc/io/datastream.hpp> #include <fc/io/json.hpp> #include <fc/io/console.hpp> #include <fc/exception/exception.hpp> #include <fc/variant_object.hpp> #include <eosio/utilities/key_conversion.hpp> #include <eosio/chain/name.hpp> #include <eosio/chain/config.hpp> #include <eosio/chain/wast_to_wasm.hpp> #include <eosio/chain/trace.hpp> #include <eosio/chain_plugin/chain_plugin.hpp> #include <eosio/chain/contract_types.hpp> #pragma push_macro("N") #undef N #include <boost/asio.hpp> #include <boost/format.hpp> #include <boost/dll/runtime_symbol_info.hpp> #include <boost/filesystem.hpp> #include <boost/process.hpp> #include <boost/process/spawn.hpp> #include <boost/range/algorithm/find_if.hpp> #include <boost/range/algorithm/sort.hpp> #include <boost/range/adaptor/transformed.hpp> #include <boost/algorithm/string/predicate.hpp> #include <boost/algorithm/string/split.hpp> #include <boost/range/algorithm/copy.hpp> #include <boost/algorithm/string/classification.hpp> #pragma pop_macro("N") #include <Inline/BasicTypes.h> #include <IR/Module.h> #include <IR/Validate.h> #include <WASM/WASM.h> #include <Runtime/Runtime.h> #include <fc/io/fstream.hpp> #include "CLI11.hpp" #include "help_text.hpp" #include "localize.hpp" #include "config.hpp" #include "httpc.hpp" using namespace std; using namespace eosio; using namespace eosio::chain; using namespace eosio::utilities; using namespace eosio::client::help; using namespace eosio::client::http; using namespace eosio::client::localize; using namespace eosio::client::config; using namespace boost::filesystem; FC_DECLARE_EXCEPTION( explained_exception, 9000000, "explained exception, see error log" ); FC_DECLARE_EXCEPTION( localized_exception, 10000000, "an error occured" ); #define EOSC_ASSERT( TEST, ... ) \ FC_EXPAND_MACRO( \ FC_MULTILINE_MACRO_BEGIN \ if( UNLIKELY(!(TEST)) ) \ { \ std::cerr << localized( __VA_ARGS__ ) << std::endl; \ FC_THROW_EXCEPTION( explained_exception, #TEST ); \ } \ FC_MULTILINE_MACRO_END \ ) //copy pasta from keosd's main.cpp bfs::path determine_home_directory() { bfs::path home; struct passwd* pwd = getpwuid(getuid()); if(pwd) { home = pwd->pw_dir; } else { home = getenv("HOME"); } if(home.empty()) home = "./"; return home; } string url = "http://127.0.0.1:8888/"; string default_wallet_url = "unix://" + (determine_home_directory() / "eosio-wallet" / (string(key_store_executable_name) + ".sock")).string(); string wallet_url; //to be set to default_wallet_url in main bool no_verify = false; vector<string> headers; auto tx_expiration = fc::seconds(30); const fc::microseconds abi_serializer_max_time = fc::seconds(10); // No risk to client side serialization taking a long time string tx_ref_block_num_or_id; bool tx_force_unique = false; bool tx_dont_broadcast = false; bool tx_return_packed = false; bool tx_skip_sign = false; bool tx_print_json = false; bool print_request = false; bool print_response = false; bool no_auto_keosd = false; uint8_t tx_max_cpu_usage = 0; uint32_t tx_max_net_usage = 0; uint32_t delaysec = 0; vector<string> tx_permission; eosio::client::http::http_context context; void add_standard_transaction_options(CLI::App* cmd, string default_permission = "") { CLI::callback_t parse_expiration = [](CLI::results_t res) -> bool { double value_s; if (res.size() == 0 || !CLI::detail::lexical_cast(res[0], value_s)) { return false; } tx_expiration = fc::seconds(static_cast<uint64_t>(value_s)); return true; }; cmd->add_option("-x,--expiration", parse_expiration, localized("set the time in seconds before a transaction expires, defaults to 30s")); cmd->add_flag("-f,--force-unique", tx_force_unique, localized("force the transaction to be unique. this will consume extra bandwidth and remove any protections against accidently issuing the same transaction multiple times")); cmd->add_flag("-s,--skip-sign", tx_skip_sign, localized("Specify if unlocked wallet keys should be used to sign transaction")); cmd->add_flag("-j,--json", tx_print_json, localized("print result as json")); cmd->add_flag("-d,--dont-broadcast", tx_dont_broadcast, localized("don't broadcast transaction to the network (just print to stdout)")); cmd->add_flag("--return-packed", tx_return_packed, localized("used in conjunction with --dont-broadcast to get the packed transaction")); cmd->add_option("-r,--ref-block", tx_ref_block_num_or_id, (localized("set the reference block num or block id used for TAPOS (Transaction as Proof-of-Stake)"))); string msg = "An account and permission level to authorize, as in 'account@permission'"; if(!default_permission.empty()) msg += " (defaults to '" + default_permission + "')"; cmd->add_option("-p,--permission", tx_permission, localized(msg.c_str())); cmd->add_option("--max-cpu-usage-ms", tx_max_cpu_usage, localized("set an upper limit on the milliseconds of cpu usage budget, for the execution of the transaction (defaults to 0 which means no limit)")); cmd->add_option("--max-net-usage", tx_max_net_usage, localized("set an upper limit on the net usage budget, in bytes, for the transaction (defaults to 0 which means no limit)")); cmd->add_option("--delay-sec", delaysec, localized("set the delay_sec seconds, defaults to 0s")); } vector<chain::permission_level> get_account_permissions(const vector<string>& permissions) { auto fixedPermissions = permissions | boost::adaptors::transformed([](const string& p) { vector<string> pieces; split(pieces, p, boost::algorithm::is_any_of("@")); if( pieces.size() == 1 ) pieces.push_back( "active" ); return chain::permission_level{ .actor = pieces[0], .permission = pieces[1] }; }); vector<chain::permission_level> accountPermissions; boost::range::copy(fixedPermissions, back_inserter(accountPermissions)); return accountPermissions; } template<typename T> fc::variant call( const std::string& url, const std::string& path, const T& v ) { try { auto sp = std::make_unique<eosio::client::http::connection_param>(context, parse_url(url) + path, no_verify ? false : true, headers); return eosio::client::http::do_http_call(*sp, fc::variant(v), print_request, print_response ); } catch(boost::system::system_error& e) { if(url == ::url) std::cerr << localized("Failed to connect to nodeos at ${u}; is nodeos running?", ("u", url)) << std::endl; else if(url == ::wallet_url) std::cerr << localized("Failed to connect to keosd at ${u}; is keosd running?", ("u", url)) << std::endl; throw connection_exception(fc::log_messages{FC_LOG_MESSAGE(error, e.what())}); } } template<typename T> fc::variant call( const std::string& path, const T& v ) { return call( url, path, fc::variant(v) ); } template<> fc::variant call( const std::string& url, const std::string& path) { return call( url, path, fc::variant() ); } eosio::chain_apis::read_only::get_info_results get_info() { return call(url, get_info_func).as<eosio::chain_apis::read_only::get_info_results>(); } string generate_nonce_string() { return fc::to_string(fc::time_point::now().time_since_epoch().count()); } chain::action generate_nonce_action() { return chain::action( {}, config::null_account_name, "nonce", fc::raw::pack(fc::time_point::now().time_since_epoch().count())); } void prompt_for_wallet_password(string& pw, const string& name) { if(pw.size() == 0 && name != "SecureEnclave") { std::cout << localized("password: "); fc::set_console_echo(false); std::getline( std::cin, pw, '\n' ); fc::set_console_echo(true); } } fc::variant determine_required_keys(const signed_transaction& trx) { // TODO better error checking //wdump((trx)); const auto& public_keys = call(wallet_url, wallet_public_keys); auto get_arg = fc::mutable_variant_object ("transaction", (transaction)trx) ("available_keys", public_keys); const auto& required_keys = call(get_required_keys, get_arg); return required_keys["required_keys"]; } void sign_transaction(signed_transaction& trx, fc::variant& required_keys, const chain_id_type& chain_id) { fc::variants sign_args = {fc::variant(trx), required_keys, fc::variant(chain_id)}; const auto& signed_trx = call(wallet_url, wallet_sign_trx, sign_args); trx = signed_trx.as<signed_transaction>(); } fc::variant push_transaction( signed_transaction& trx, int32_t extra_kcpu = 1000, packed_transaction::compression_type compression = packed_transaction::none ) { auto info = get_info(); if (trx.signatures.size() == 0) { // #5445 can't change txn content if already signed trx.expiration = info.head_block_time + tx_expiration; // Set tapos, default to last irreversible block if it's not specified by the user block_id_type ref_block_id = info.last_irreversible_block_id; try { fc::variant ref_block; if (!tx_ref_block_num_or_id.empty()) { ref_block = call(get_block_func, fc::mutable_variant_object("block_num_or_id", tx_ref_block_num_or_id)); ref_block_id = ref_block["id"].as<block_id_type>(); } } EOS_RETHROW_EXCEPTIONS(invalid_ref_block_exception, "Invalid reference block num or id: ${block_num_or_id}", ("block_num_or_id", tx_ref_block_num_or_id)); trx.set_reference_block(ref_block_id); if (tx_force_unique) { trx.context_free_actions.emplace_back( generate_nonce_action() ); } trx.max_cpu_usage_ms = tx_max_cpu_usage; trx.max_net_usage_words = (tx_max_net_usage + 7)/8; trx.delay_sec = delaysec; } if (!tx_skip_sign) { auto required_keys = determine_required_keys(trx); sign_transaction(trx, required_keys, info.chain_id); } if (!tx_dont_broadcast) { return call(push_txn_func, packed_transaction(trx, compression)); } else { if (!tx_return_packed) { return fc::variant(trx); } else { return fc::variant(packed_transaction(trx, compression)); } } } fc::variant push_actions(std::vector<chain::action>&& actions, int32_t extra_kcpu, packed_transaction::compression_type compression = packed_transaction::none ) { signed_transaction trx; trx.actions = std::forward<decltype(actions)>(actions); return push_transaction(trx, extra_kcpu, compression); } void print_action( const fc::variant& at ) { const auto& receipt = at["receipt"]; auto receiver = receipt["receiver"].as_string(); const auto& act = at["act"].get_object(); auto code = act["account"].as_string(); auto func = act["name"].as_string(); auto args = fc::json::to_string( act["data"] ); auto console = at["console"].as_string(); /* if( code == "eosio" && func == "setcode" ) args = args.substr(40)+"..."; if( name(code) == config::system_account_name && func == "setabi" ) args = args.substr(40)+"..."; */ if( args.size() > 100 ) args = args.substr(0,100) + "..."; cout << "#" << std::setw(14) << right << receiver << " <= " << std::setw(28) << std::left << (code +"::" + func) << " " << args << "\n"; if( console.size() ) { std::stringstream ss(console); string line; std::getline( ss, line ); cout << ">> " << line << "\n"; } } //resolver for ABI serializer to decode actions in proposed transaction in multisig contract auto abi_serializer_resolver = [](const name& account) -> optional<abi_serializer> { static unordered_map<account_name, optional<abi_serializer> > abi_cache; auto it = abi_cache.find( account ); if ( it == abi_cache.end() ) { auto result = call(get_abi_func, fc::mutable_variant_object("account_name", account)); auto abi_results = result.as<eosio::chain_apis::read_only::get_abi_results>(); optional<abi_serializer> abis; if( abi_results.abi.valid() ) { abis.emplace( *abi_results.abi, abi_serializer_max_time ); } else { std::cerr << "ABI for contract " << account.to_string() << " not found. Action data will be shown in hex only." << std::endl; } abi_cache.emplace( account, abis ); return abis; } return it->second; }; bytes variant_to_bin( const account_name& account, const action_name& action, const fc::variant& action_args_var ) { auto abis = abi_serializer_resolver( account ); FC_ASSERT( abis.valid(), "No ABI found for ${contract}", ("contract", account)); auto action_type = abis->get_action_type( action ); FC_ASSERT( !action_type.empty(), "Unknown action ${action} in contract ${contract}", ("action", action)( "contract", account )); return abis->variant_to_binary( action_type, action_args_var, abi_serializer_max_time ); } fc::variant bin_to_variant( const account_name& account, const action_name& action, const bytes& action_args) { auto abis = abi_serializer_resolver( account ); FC_ASSERT( abis.valid(), "No ABI found for ${contract}", ("contract", account)); auto action_type = abis->get_action_type( action ); FC_ASSERT( !action_type.empty(), "Unknown action ${action} in contract ${contract}", ("action", action)( "contract", account )); return abis->binary_to_variant( action_type, action_args, abi_serializer_max_time ); } fc::variant json_from_file_or_string(const string& file_or_str, fc::json::parse_type ptype = fc::json::legacy_parser) { regex r("^[ \t]*[\{\[]"); if ( !regex_search(file_or_str, r) && fc::is_regular_file(file_or_str) ) { return fc::json::from_file(file_or_str, ptype); } else { return fc::json::from_string(file_or_str, ptype); } } bytes json_or_file_to_bin( const account_name& account, const action_name& action, const string& data_or_filename ) { fc::variant action_args_var; if( !data_or_filename.empty() ) { try { action_args_var = json_from_file_or_string(data_or_filename, fc::json::relaxed_parser); } EOS_RETHROW_EXCEPTIONS(action_type_exception, "Fail to parse action JSON data='${data}'", ("data", data_or_filename)); } return variant_to_bin( account, action, action_args_var ); } void print_action_tree( const fc::variant& action ) { print_action( action ); const auto& inline_traces = action["inline_traces"].get_array(); for( const auto& t : inline_traces ) { print_action_tree( t ); } } void print_result( const fc::variant& result ) { try { if (result.is_object() && result.get_object().contains("processed")) { const auto& processed = result["processed"]; const auto& transaction_id = processed["id"].as_string(); string status = processed["receipt"].is_object() ? processed["receipt"]["status"].as_string() : "failed"; int64_t net = -1; int64_t cpu = -1; if( processed.get_object().contains( "receipt" )) { const auto& receipt = processed["receipt"]; if( receipt.is_object()) { net = receipt["net_usage_words"].as_int64() * 8; cpu = receipt["cpu_usage_us"].as_int64(); } } cerr << status << " transaction: " << transaction_id << " "; if( net < 0 ) { cerr << "<unknown>"; } else { cerr << net; } cerr << " bytes "; if( cpu < 0 ) { cerr << "<unknown>"; } else { cerr << cpu; } cerr << " us\n"; if( status == "failed" ) { auto soft_except = processed["except"].as<optional<fc::exception>>(); if( soft_except ) { edump((soft_except->to_detail_string())); } } else { const auto& actions = processed["action_traces"].get_array(); for( const auto& a : actions ) { print_action_tree( a ); } wlog( "\rwarning: transaction executed locally, but may not be confirmed by the network yet" ); } } else { cerr << fc::json::to_pretty_string( result ) << endl; } } FC_CAPTURE_AND_RETHROW( (result) ) } using std::cout; void send_actions(std::vector<chain::action>&& actions, int32_t extra_kcpu = 1000, packed_transaction::compression_type compression = packed_transaction::none ) { auto result = push_actions( move(actions), extra_kcpu, compression); if( tx_print_json ) { cout << fc::json::to_pretty_string( result ) << endl; } else { print_result( result ); } } void send_transaction( signed_transaction& trx, int32_t extra_kcpu, packed_transaction::compression_type compression = packed_transaction::none ) { auto result = push_transaction(trx, extra_kcpu, compression); if( tx_print_json ) { cout << fc::json::to_pretty_string( result ) << endl; } else { print_result( result ); } } chain::action create_newaccount(const name& creator, const name& newaccount, public_key_type owner, public_key_type active) { return action { tx_permission.empty() ? vector<chain::permission_level>{{creator,config::active_name}} : get_account_permissions(tx_permission), eosio::chain::newaccount{ .creator = creator, .name = newaccount, .owner = eosio::chain::authority{1, {{owner, 1}}, {}}, .active = eosio::chain::authority{1, {{active, 1}}, {}} } }; } chain::action create_action(const vector<permission_level>& authorization, const account_name& code, const action_name& act, const fc::variant& args) { return chain::action{authorization, code, act, variant_to_bin(code, act, args)}; } chain::action create_buyram(const name& creator, const name& newaccount, const asset& quantity) { fc::variant act_payload = fc::mutable_variant_object() ("payer", creator.to_string()) ("receiver", newaccount.to_string()) ("quant", quantity.to_string()); return create_action(tx_permission.empty() ? vector<chain::permission_level>{{creator,config::active_name}} : get_account_permissions(tx_permission), config::system_account_name, N(buyram), act_payload); } chain::action create_buyrambytes(const name& creator, const name& newaccount, uint32_t numbytes) { fc::variant act_payload = fc::mutable_variant_object() ("payer", creator.to_string()) ("receiver", newaccount.to_string()) ("bytes", numbytes); return create_action(tx_permission.empty() ? vector<chain::permission_level>{{creator,config::active_name}} : get_account_permissions(tx_permission), config::system_account_name, N(buyrambytes), act_payload); } chain::action create_delegate(const name& from, const name& receiver, const asset& net, const asset& cpu, bool transfer) { fc::variant act_payload = fc::mutable_variant_object() ("from", from.to_string()) ("receiver", receiver.to_string()) ("stake_net_quantity", net.to_string()) ("stake_cpu_quantity", cpu.to_string()) ("transfer", transfer); return create_action(tx_permission.empty() ? vector<chain::permission_level>{{from,config::active_name}} : get_account_permissions(tx_permission), config::system_account_name, N(delegatebw), act_payload); } fc::variant regproducer_variant(const account_name& producer, const public_key_type& key, const string& url, uint16_t location) { return fc::mutable_variant_object() ("producer", producer) ("producer_key", key) ("url", url) ("location", location) ; } chain::action create_open(const string& contract, const name& owner, symbol sym, const name& ram_payer) { auto open_ = fc::mutable_variant_object ("owner", owner) ("symbol", sym) ("ram_payer", ram_payer); return action { tx_permission.empty() ? vector<chain::permission_level>{{ram_payer,config::active_name}} : get_account_permissions(tx_permission), contract, "open", variant_to_bin( contract, N(open), open_ ) }; } chain::action create_transfer(const string& contract, const name& sender, const name& recipient, asset amount, const string& memo ) { auto transfer = fc::mutable_variant_object ("from", sender) ("to", recipient) ("quantity", amount) ("memo", memo); return action { tx_permission.empty() ? vector<chain::permission_level>{{sender,config::active_name}} : get_account_permissions(tx_permission), contract, "transfer", variant_to_bin( contract, N(transfer), transfer ) }; } chain::action create_setabi(const name& account, const bytes& abi) { return action { tx_permission.empty() ? vector<chain::permission_level>{{account,config::active_name}} : get_account_permissions(tx_permission), setabi{ .account = account, .abi = abi } }; } chain::action create_setcode(const name& account, const bytes& code) { return action { tx_permission.empty() ? vector<chain::permission_level>{{account,config::active_name}} : get_account_permissions(tx_permission), setcode{ .account = account, .vmtype = 0, .vmversion = 0, .code = code } }; } chain::action create_updateauth(const name& account, const name& permission, const name& parent, const authority& auth) { return action { tx_permission.empty() ? vector<chain::permission_level>{{account,config::active_name}} : get_account_permissions(tx_permission), updateauth{account, permission, parent, auth}}; } chain::action create_deleteauth(const name& account, const name& permission) { return action { tx_permission.empty() ? vector<chain::permission_level>{{account,config::active_name}} : get_account_permissions(tx_permission), deleteauth{account, permission}}; } chain::action create_linkauth(const name& account, const name& code, const name& type, const name& requirement) { return action { tx_permission.empty() ? vector<chain::permission_level>{{account,config::active_name}} : get_account_permissions(tx_permission), linkauth{account, code, type, requirement}}; } chain::action create_unlinkauth(const name& account, const name& code, const name& type) { return action { tx_permission.empty() ? vector<chain::permission_level>{{account,config::active_name}} : get_account_permissions(tx_permission), unlinkauth{account, code, type}}; } authority parse_json_authority(const std::string& authorityJsonOrFile) { try { return json_from_file_or_string(authorityJsonOrFile).as<authority>(); } EOS_RETHROW_EXCEPTIONS(authority_type_exception, "Fail to parse Authority JSON '${data}'", ("data",authorityJsonOrFile)) } authority parse_json_authority_or_key(const std::string& authorityJsonOrFile) { if (boost::istarts_with(authorityJsonOrFile, "EOS") || boost::istarts_with(authorityJsonOrFile, "PUB_R1")) { try { return authority(public_key_type(authorityJsonOrFile)); } EOS_RETHROW_EXCEPTIONS(public_key_type_exception, "Invalid public key: ${public_key}", ("public_key", authorityJsonOrFile)) } else { auto result = parse_json_authority(authorityJsonOrFile); EOS_ASSERT( eosio::chain::validate(result), authority_type_exception, "Authority failed validation! ensure that keys, accounts, and waits are sorted and that the threshold is valid and satisfiable!"); return result; } } asset to_asset( account_name code, const string& s ) { static map< pair<account_name, eosio::chain::symbol_code>, eosio::chain::symbol> cache; auto a = asset::from_string( s ); eosio::chain::symbol_code sym = a.get_symbol().to_symbol_code(); auto it = cache.find( make_pair(code, sym) ); auto sym_str = a.symbol_name(); if ( it == cache.end() ) { auto json = call(get_currency_stats_func, fc::mutable_variant_object("json", false) ("code", code) ("symbol", sym_str) ); auto obj = json.get_object(); auto obj_it = obj.find( sym_str ); if (obj_it != obj.end()) { auto result = obj_it->value().as<eosio::chain_apis::read_only::get_currency_stats_result>(); auto p = cache.emplace( make_pair( code, sym ), result.max_supply.get_symbol() ); it = p.first; } else { EOS_THROW(symbol_type_exception, "Symbol ${s} is not supported by token contract ${c}", ("s", sym_str)("c", code)); } } auto expected_symbol = it->second; if ( a.decimals() < expected_symbol.decimals() ) { auto factor = expected_symbol.precision() / a.precision(); auto a_old = a; a = asset( a.get_amount() * factor, expected_symbol ); } else if ( a.decimals() > expected_symbol.decimals() ) { EOS_THROW(symbol_type_exception, "Too many decimal digits in ${a}, only ${d} supported", ("a", a)("d", expected_symbol.decimals())); } // else precision matches return a; } inline asset to_asset( const string& s ) { return to_asset( N(eosio.token), s ); } struct set_account_permission_subcommand { string accountStr; string permissionStr; string authorityJsonOrFile; string parentStr; set_account_permission_subcommand(CLI::App* accountCmd) { auto permissions = accountCmd->add_subcommand("permission", localized("set parameters dealing with account permissions")); permissions->add_option("account", accountStr, localized("The account to set/delete a permission authority for"))->required(); permissions->add_option("permission", permissionStr, localized("The permission name to set/delete an authority for"))->required(); permissions->add_option("authority", authorityJsonOrFile, localized("[delete] NULL, [create/update] public key, JSON string, or filename defining the authority"))->required(); permissions->add_option("parent", parentStr, localized("[create] The permission name of this parents permission (Defaults to: \"Active\")")); add_standard_transaction_options(permissions, "account@active"); permissions->set_callback([this] { name account = name(accountStr); name permission = name(permissionStr); bool is_delete = boost::iequals(authorityJsonOrFile, "null"); if (is_delete) { send_actions({create_deleteauth(account, permission)}); } else { authority auth = parse_json_authority_or_key(authorityJsonOrFile); name parent; if (parentStr.size() == 0 && permissionStr != "owner") { // see if we can auto-determine the proper parent const auto account_result = call(get_account_func, fc::mutable_variant_object("account_name", accountStr)); const auto& existing_permissions = account_result.get_object()["permissions"].get_array(); auto permissionPredicate = [this](const auto& perm) { return perm.is_object() && perm.get_object().contains("perm_name") && boost::equals(perm.get_object()["perm_name"].get_string(), permissionStr); }; auto itr = boost::find_if(existing_permissions, permissionPredicate); if (itr != existing_permissions.end()) { parent = name((*itr).get_object()["parent"].get_string()); } else { // if this is a new permission and there is no parent we default to "active" parent = name(config::active_name); } } else { parent = name(parentStr); } send_actions({create_updateauth(account, permission, parent, auth)}); } }); } }; struct set_action_permission_subcommand { string accountStr; string codeStr; string typeStr; string requirementStr; set_action_permission_subcommand(CLI::App* actionRoot) { auto permissions = actionRoot->add_subcommand("permission", localized("set parmaters dealing with account permissions")); permissions->add_option("account", accountStr, localized("The account to set/delete a permission authority for"))->required(); permissions->add_option("code", codeStr, localized("The account that owns the code for the action"))->required(); permissions->add_option("type", typeStr, localized("the type of the action"))->required(); permissions->add_option("requirement", requirementStr, localized("[delete] NULL, [set/update] The permission name require for executing the given action"))->required(); add_standard_transaction_options(permissions, "account@active"); permissions->set_callback([this] { name account = name(accountStr); name code = name(codeStr); name type = name(typeStr); bool is_delete = boost::iequals(requirementStr, "null"); if (is_delete) { send_actions({create_unlinkauth(account, code, type)}); } else { name requirement = name(requirementStr); send_actions({create_linkauth(account, code, type, requirement)}); } }); } }; bool local_port_used() { using namespace boost::asio; io_service ios; local::stream_protocol::endpoint endpoint(wallet_url.substr(strlen("unix://"))); local::stream_protocol::socket socket(ios); boost::system::error_code ec; socket.connect(endpoint, ec); return !ec; } void try_local_port(uint32_t duration) { using namespace std::chrono; auto start_time = duration_cast<std::chrono::milliseconds>( system_clock::now().time_since_epoch() ).count(); while ( !local_port_used()) { if (duration_cast<std::chrono::milliseconds>( system_clock::now().time_since_epoch()).count() - start_time > duration ) { std::cerr << "Unable to connect to keosd, if keosd is running please kill the process and try again.\n"; throw connection_exception(fc::log_messages{FC_LOG_MESSAGE(error, "Unable to connect to keosd")}); } } } void ensure_keosd_running(CLI::App* app) { if (no_auto_keosd) return; // get, version, net do not require keosd if (tx_skip_sign || app->got_subcommand("get") || app->got_subcommand("version") || app->got_subcommand("net")) return; if (app->get_subcommand("create")->got_subcommand("key")) // create key does not require wallet return; if (auto* subapp = app->get_subcommand("system")) { if (subapp->got_subcommand("listproducers") || subapp->got_subcommand("listbw") || subapp->got_subcommand("bidnameinfo")) // system list* do not require wallet return; } if (wallet_url != default_wallet_url) return; if (local_port_used()) return; boost::filesystem::path binPath = boost::dll::program_location(); binPath.remove_filename(); // This extra check is necessary when running cleos like this: ./cleos ... if (binPath.filename_is_dot()) binPath.remove_filename(); binPath.append(key_store_executable_name); // if cleos and keosd are in the same installation directory if (!boost::filesystem::exists(binPath)) { binPath.remove_filename().remove_filename().append("keosd").append(key_store_executable_name); } if (boost::filesystem::exists(binPath)) { namespace bp = boost::process; binPath = boost::filesystem::canonical(binPath); vector<std::string> pargs; pargs.push_back("--http-server-address"); pargs.push_back(""); pargs.push_back("--https-server-address"); pargs.push_back(""); ::boost::process::child keos(binPath, pargs, bp::std_in.close(), bp::std_out > bp::null, bp::std_err > bp::null); if (keos.running()) { std::cerr << binPath << " launched" << std::endl; keos.detach(); try_local_port(2000); } else { std::cerr << "No wallet service listening on " << wallet_url << ". Failed to launch " << binPath << std::endl; } } else { std::cerr << "No wallet service listening on " << ". Cannot automatically start keosd because keosd was not found." << std::endl; } } CLI::callback_t obsoleted_option_host_port = [](CLI::results_t) { std::cerr << localized("Host and port options (-H, --wallet-host, etc.) have been replaced with -u/--url and --wallet-url\n" "Use for example -u http://localhost:8888 or --url https://example.invalid/\n"); exit(1); return false; }; struct register_producer_subcommand { string producer_str; string producer_key_str; string url; uint16_t loc = 0; register_producer_subcommand(CLI::App* actionRoot) { auto register_producer = actionRoot->add_subcommand("regproducer", localized("Register a new producer")); register_producer->add_option("account", producer_str, localized("The account to register as a producer"))->required(); register_producer->add_option("producer_key", producer_key_str, localized("The producer's public key"))->required(); register_producer->add_option("url", url, localized("url where info about producer can be found"), true); register_producer->add_option("location", loc, localized("relative location for purpose of nearest neighbor scheduling"), true); add_standard_transaction_options(register_producer); register_producer->set_callback([this] { public_key_type producer_key; try { producer_key = public_key_type(producer_key_str); } EOS_RETHROW_EXCEPTIONS(public_key_type_exception, "Invalid producer public key: ${public_key}", ("public_key", producer_key_str)) auto regprod_var = regproducer_variant(producer_str, producer_key, url, loc ); send_actions({create_action({permission_level{producer_str,config::active_name}}, config::system_account_name, N(regproducer), regprod_var)}); }); } }; struct create_account_subcommand { string creator; string account_name; string owner_key_str; string active_key_str; string stake_net; string stake_cpu; uint32_t buy_ram_bytes_in_kbytes = 0; uint32_t buy_ram_bytes = 0; string buy_ram_eos; bool transfer; bool simple; create_account_subcommand(CLI::App* actionRoot, bool s) : simple(s) { auto createAccount = actionRoot->add_subcommand( (simple ? "account" : "newaccount"), localized("Create an account, buy ram, stake for bandwidth for the account")); createAccount->add_option("creator", creator, localized("The name of the account creating the new account"))->required(); createAccount->add_option("name", account_name, localized("The name of the new account"))->required(); createAccount->add_option("OwnerKey", owner_key_str, localized("The owner public key for the new account"))->required(); createAccount->add_option("ActiveKey", active_key_str, localized("The active public key for the new account")); if (!simple) { createAccount->add_option("--stake-net", stake_net, (localized("The amount of EOS delegated for net bandwidth")))->required(); createAccount->add_option("--stake-cpu", stake_cpu, (localized("The amount of EOS delegated for CPU bandwidth")))->required(); createAccount->add_option("--buy-ram-kbytes", buy_ram_bytes_in_kbytes, (localized("The amount of RAM bytes to purchase for the new account in kibibytes (KiB)"))); createAccount->add_option("--buy-ram-bytes", buy_ram_bytes, (localized("The amount of RAM bytes to purchase for the new account in bytes"))); createAccount->add_option("--buy-ram", buy_ram_eos, (localized("The amount of RAM bytes to purchase for the new account in EOS"))); createAccount->add_flag("--transfer", transfer, (localized("Transfer voting power and right to unstake EOS to receiver"))); } add_standard_transaction_options(createAccount); createAccount->set_callback([this] { if( !active_key_str.size() ) active_key_str = owner_key_str; public_key_type owner_key, active_key; try { owner_key = public_key_type(owner_key_str); } EOS_RETHROW_EXCEPTIONS(public_key_type_exception, "Invalid owner public key: ${public_key}", ("public_key", owner_key_str)); try { active_key = public_key_type(active_key_str); } EOS_RETHROW_EXCEPTIONS(public_key_type_exception, "Invalid active public key: ${public_key}", ("public_key", active_key_str)); auto create = create_newaccount(creator, account_name, owner_key, active_key); if (!simple) { EOSC_ASSERT( buy_ram_eos.size() || buy_ram_bytes_in_kbytes || buy_ram_bytes, "ERROR: One of --buy-ram, --buy-ram-kbytes or --buy-ram-bytes should have non-zero value" ); EOSC_ASSERT( !buy_ram_bytes_in_kbytes || !buy_ram_bytes, "ERROR: --buy-ram-kbytes and --buy-ram-bytes cannot be set at the same time" ); action buyram = !buy_ram_eos.empty() ? create_buyram(creator, account_name, to_asset(buy_ram_eos)) : create_buyrambytes(creator, account_name, (buy_ram_bytes_in_kbytes) ? (buy_ram_bytes_in_kbytes * 1024) : buy_ram_bytes); auto net = to_asset(stake_net); auto cpu = to_asset(stake_cpu); if ( net.get_amount() != 0 || cpu.get_amount() != 0 ) { action delegate = create_delegate( creator, account_name, net, cpu, transfer); send_actions( { create, buyram, delegate } ); } else { send_actions( { create, buyram } ); } } else { send_actions( { create } ); } }); } }; struct unregister_producer_subcommand { string producer_str; unregister_producer_subcommand(CLI::App* actionRoot) { auto unregister_producer = actionRoot->add_subcommand("unregprod", localized("Unregister an existing producer")); unregister_producer->add_option("account", producer_str, localized("The account to unregister as a producer"))->required(); add_standard_transaction_options(unregister_producer); unregister_producer->set_callback([this] { fc::variant act_payload = fc::mutable_variant_object() ("producer", producer_str); send_actions({create_action({permission_level{producer_str,config::active_name}}, config::system_account_name, N(unregprod), act_payload)}); }); } }; struct vote_producer_proxy_subcommand { string voter_str; string proxy_str; vote_producer_proxy_subcommand(CLI::App* actionRoot) { auto vote_proxy = actionRoot->add_subcommand("proxy", localized("Vote your stake through a proxy")); vote_proxy->add_option("voter", voter_str, localized("The voting account"))->required(); vote_proxy->add_option("proxy", proxy_str, localized("The proxy account"))->required(); add_standard_transaction_options(vote_proxy); vote_proxy->set_callback([this] { fc::variant act_payload = fc::mutable_variant_object() ("voter", voter_str) ("proxy", proxy_str) ("producers", std::vector<account_name>{}); send_actions({create_action({permission_level{voter_str,config::active_name}}, config::system_account_name, N(voteproducer), act_payload)}); }); } }; struct vote_producers_subcommand { string voter_str; vector<eosio::name> producer_names; vote_producers_subcommand(CLI::App* actionRoot) { auto vote_producers = actionRoot->add_subcommand("prods", localized("Vote for one or more producers")); vote_producers->add_option("voter", voter_str, localized("The voting account"))->required(); vote_producers->add_option("producers", producer_names, localized("The account(s) to vote for. All options from this position and following will be treated as the producer list."))->required(); add_standard_transaction_options(vote_producers); vote_producers->set_callback([this] { std::sort( producer_names.begin(), producer_names.end() ); fc::variant act_payload = fc::mutable_variant_object() ("voter", voter_str) ("proxy", "") ("producers", producer_names); send_actions({create_action({permission_level{voter_str,config::active_name}}, config::system_account_name, N(voteproducer), act_payload)}); }); } }; struct approve_producer_subcommand { eosio::name voter; eosio::name producer_name; approve_producer_subcommand(CLI::App* actionRoot) { auto approve_producer = actionRoot->add_subcommand("approve", localized("Add one producer to list of voted producers")); approve_producer->add_option("voter", voter, localized("The voting account"))->required(); approve_producer->add_option("producer", producer_name, localized("The account to vote for"))->required(); add_standard_transaction_options(approve_producer); approve_producer->set_callback([this] { auto result = call(get_table_func, fc::mutable_variant_object("json", true) ("code", name(config::system_account_name).to_string()) ("scope", name(config::system_account_name).to_string()) ("table", "voters") ("table_key", "owner") ("lower_bound", voter.value) ("limit", 1) ); auto res = result.as<eosio::chain_apis::read_only::get_table_rows_result>(); if ( res.rows.empty() || res.rows[0]["owner"].as_string() != name(voter).to_string() ) { std::cerr << "Voter info not found for account " << voter << std::endl; return; } EOS_ASSERT( 1 == res.rows.size(), multiple_voter_info, "More than one voter_info for account" ); auto prod_vars = res.rows[0]["producers"].get_array(); vector<eosio::name> prods; for ( auto& x : prod_vars ) { prods.push_back( name(x.as_string()) ); } prods.push_back( producer_name ); std::sort( prods.begin(), prods.end() ); auto it = std::unique( prods.begin(), prods.end() ); if (it != prods.end() ) { std::cerr << "Producer \"" << producer_name << "\" is already on the list." << std::endl; return; } fc::variant act_payload = fc::mutable_variant_object() ("voter", voter) ("proxy", "") ("producers", prods); send_actions({create_action({permission_level{voter,config::active_name}}, config::system_account_name, N(voteproducer), act_payload)}); }); } }; struct unapprove_producer_subcommand { eosio::name voter; eosio::name producer_name; unapprove_producer_subcommand(CLI::App* actionRoot) { auto approve_producer = actionRoot->add_subcommand("unapprove", localized("Remove one producer from list of voted producers")); approve_producer->add_option("voter", voter, localized("The voting account"))->required(); approve_producer->add_option("producer", producer_name, localized("The account to remove from voted producers"))->required(); add_standard_transaction_options(approve_producer); approve_producer->set_callback([this] { auto result = call(get_table_func, fc::mutable_variant_object("json", true) ("code", name(config::system_account_name).to_string()) ("scope", name(config::system_account_name).to_string()) ("table", "voters") ("table_key", "owner") ("lower_bound", voter.value) ("limit", 1) ); auto res = result.as<eosio::chain_apis::read_only::get_table_rows_result>(); if ( res.rows.empty() || res.rows[0]["owner"].as_string() != name(voter).to_string() ) { std::cerr << "Voter info not found for account " << voter << std::endl; return; } EOS_ASSERT( 1 == res.rows.size(), multiple_voter_info, "More than one voter_info for account" ); auto prod_vars = res.rows[0]["producers"].get_array(); vector<eosio::name> prods; for ( auto& x : prod_vars ) { prods.push_back( name(x.as_string()) ); } auto it = std::remove( prods.begin(), prods.end(), producer_name ); if (it == prods.end() ) { std::cerr << "Cannot remove: producer \"" << producer_name << "\" is not on the list." << std::endl; return; } prods.erase( it, prods.end() ); //should always delete only one element fc::variant act_payload = fc::mutable_variant_object() ("voter", voter) ("proxy", "") ("producers", prods); send_actions({create_action({permission_level{voter,config::active_name}}, config::system_account_name, N(voteproducer), act_payload)}); }); } }; struct list_producers_subcommand { bool print_json = false; uint32_t limit = 50; std::string lower; list_producers_subcommand(CLI::App* actionRoot) { auto list_producers = actionRoot->add_subcommand("listproducers", localized("List producers")); list_producers->add_flag("--json,-j", print_json, localized("Output in JSON format")); list_producers->add_option("-l,--limit", limit, localized("The maximum number of rows to return")); list_producers->add_option("-L,--lower", lower, localized("lower bound value of key, defaults to first")); list_producers->set_callback([this] { auto rawResult = call(get_producers_func, fc::mutable_variant_object ("json", true)("lower_bound", lower)("limit", limit)); if ( print_json ) { std::cout << fc::json::to_pretty_string(rawResult) << std::endl; return; } auto result = rawResult.as<eosio::chain_apis::read_only::get_producers_result>(); if ( result.rows.empty() ) { std::cout << "No producers found" << std::endl; return; } auto weight = result.total_producer_vote_weight; if ( !weight ) weight = 1; printf("%-13s %-57s %-59s %s\n", "Producer", "Producer key", "Url", "Scaled votes"); for ( auto& row : result.rows ) printf("%-13.13s %-57.57s %-59.59s %1.4f\n", row["owner"].as_string().c_str(), row["producer_key"].as_string().c_str(), row["url"].as_string().c_str(), row["total_votes"].as_double() / weight); if ( !result.more.empty() ) std::cout << "-L " << result.more << " for more" << std::endl; }); } }; struct get_schedule_subcommand { bool print_json = false; void print(const char* name, const fc::variant& schedule) { if (schedule.is_null()) { printf("%s schedule empty\n\n", name); return; } printf("%s schedule version %s\n", name, schedule["version"].as_string().c_str()); printf(" %-13s %s\n", "Producer", "Producer key"); printf(" %-13s %s\n", "=============", "=================="); for (auto& row: schedule["producers"].get_array()) printf(" %-13s %s\n", row["producer_name"].as_string().c_str(), row["block_signing_key"].as_string().c_str()); printf("\n"); } get_schedule_subcommand(CLI::App* actionRoot) { auto get_schedule = actionRoot->add_subcommand("schedule", localized("Retrieve the producer schedule")); get_schedule->add_flag("--json,-j", print_json, localized("Output in JSON format")); get_schedule->set_callback([this] { auto result = call(get_schedule_func, fc::mutable_variant_object()); if ( print_json ) { std::cout << fc::json::to_pretty_string(result) << std::endl; return; } print("active", result["active"]); print("pending", result["pending"]); print("proposed", result["proposed"]); }); } }; struct get_transaction_id_subcommand { string trx_to_check; get_transaction_id_subcommand(CLI::App* actionRoot) { auto get_transaction_id = actionRoot->add_subcommand("transaction_id", localized("Get transaction id given transaction object")); get_transaction_id->add_option("transaction", trx_to_check, localized("The JSON string or filename defining the transaction which transaction id we want to retrieve"))->required(); get_transaction_id->set_callback([&] { try { auto trx_var = json_from_file_or_string(trx_to_check); auto trx = trx_var.as<transaction>(); std::cout << string(trx.id()) << std::endl; } EOS_RETHROW_EXCEPTIONS(transaction_type_exception, "Fail to parse transaction JSON '${data}'", ("data",trx_to_check)) }); } }; struct delegate_bandwidth_subcommand { string from_str; string receiver_str; string stake_net_amount; string stake_cpu_amount; string stake_storage_amount; string buy_ram_amount; uint32_t buy_ram_bytes = 0; bool transfer = false; delegate_bandwidth_subcommand(CLI::App* actionRoot) { auto delegate_bandwidth = actionRoot->add_subcommand("delegatebw", localized("Delegate bandwidth")); delegate_bandwidth->add_option("from", from_str, localized("The account to delegate bandwidth from"))->required(); delegate_bandwidth->add_option("receiver", receiver_str, localized("The account to receive the delegated bandwidth"))->required(); delegate_bandwidth->add_option("stake_net_quantity", stake_net_amount, localized("The amount of EOS to stake for network bandwidth"))->required(); delegate_bandwidth->add_option("stake_cpu_quantity", stake_cpu_amount, localized("The amount of EOS to stake for CPU bandwidth"))->required(); delegate_bandwidth->add_option("--buyram", buy_ram_amount, localized("The amount of EOS to buyram")); delegate_bandwidth->add_option("--buy-ram-bytes", buy_ram_bytes, localized("The amount of RAM to buy in number of bytes")); delegate_bandwidth->add_flag("--transfer", transfer, localized("Transfer voting power and right to unstake EOS to receiver")); add_standard_transaction_options(delegate_bandwidth); delegate_bandwidth->set_callback([this] { fc::variant act_payload = fc::mutable_variant_object() ("from", from_str) ("receiver", receiver_str) ("stake_net_quantity", to_asset(stake_net_amount)) ("stake_cpu_quantity", to_asset(stake_cpu_amount)) ("transfer", transfer); std::vector<chain::action> acts{create_action({permission_level{from_str,config::active_name}}, config::system_account_name, N(delegatebw), act_payload)}; EOSC_ASSERT( !(buy_ram_amount.size()) || !buy_ram_bytes, "ERROR: --buyram and --buy-ram-bytes cannot be set at the same time" ); if (buy_ram_amount.size()) { acts.push_back( create_buyram(from_str, receiver_str, to_asset(buy_ram_amount)) ); } else if (buy_ram_bytes) { acts.push_back( create_buyrambytes(from_str, receiver_str, buy_ram_bytes) ); } send_actions(std::move(acts)); }); } }; struct undelegate_bandwidth_subcommand { string from_str; string receiver_str; string unstake_net_amount; string unstake_cpu_amount; uint64_t unstake_storage_bytes; undelegate_bandwidth_subcommand(CLI::App* actionRoot) { auto undelegate_bandwidth = actionRoot->add_subcommand("undelegatebw", localized("Undelegate bandwidth")); undelegate_bandwidth->add_option("from", from_str, localized("The account undelegating bandwidth"))->required(); undelegate_bandwidth->add_option("receiver", receiver_str, localized("The account to undelegate bandwidth from"))->required(); undelegate_bandwidth->add_option("unstake_net_quantity", unstake_net_amount, localized("The amount of EOS to undelegate for network bandwidth"))->required(); undelegate_bandwidth->add_option("unstake_cpu_quantity", unstake_cpu_amount, localized("The amount of EOS to undelegate for CPU bandwidth"))->required(); add_standard_transaction_options(undelegate_bandwidth); undelegate_bandwidth->set_callback([this] { fc::variant act_payload = fc::mutable_variant_object() ("from", from_str) ("receiver", receiver_str) ("unstake_net_quantity", to_asset(unstake_net_amount)) ("unstake_cpu_quantity", to_asset(unstake_cpu_amount)); send_actions({create_action({permission_level{from_str,config::active_name}}, config::system_account_name, N(undelegatebw), act_payload)}); }); } }; struct bidname_subcommand { string bidder_str; string newname_str; string bid_amount; bidname_subcommand(CLI::App *actionRoot) { auto bidname = actionRoot->add_subcommand("bidname", localized("Name bidding")); bidname->add_option("bidder", bidder_str, localized("The bidding account"))->required(); bidname->add_option("newname", newname_str, localized("The bidding name"))->required(); bidname->add_option("bid", bid_amount, localized("The amount of EOS to bid"))->required(); add_standard_transaction_options(bidname); bidname->set_callback([this] { fc::variant act_payload = fc::mutable_variant_object() ("bidder", bidder_str) ("newname", newname_str) ("bid", to_asset(bid_amount)); send_actions({create_action({permission_level{bidder_str, config::active_name}}, config::system_account_name, N(bidname), act_payload)}); }); } }; struct bidname_info_subcommand { bool print_json = false; string newname_str; bidname_info_subcommand(CLI::App* actionRoot) { auto list_producers = actionRoot->add_subcommand("bidnameinfo", localized("Get bidname info")); list_producers->add_flag("--json,-j", print_json, localized("Output in JSON format")); list_producers->add_option("newname", newname_str, localized("The bidding name"))->required(); list_producers->set_callback([this] { auto rawResult = call(get_table_func, fc::mutable_variant_object("json", true) ("code", "eosio")("scope", "eosio")("table", "namebids") ("lower_bound", eosio::chain::string_to_name(newname_str.c_str()))("limit", 1)); if ( print_json ) { std::cout << fc::json::to_pretty_string(rawResult) << std::endl; return; } auto result = rawResult.as<eosio::chain_apis::read_only::get_table_rows_result>(); if ( result.rows.empty() ) { std::cout << "No bidname record found" << std::endl; return; } for ( auto& row : result.rows ) { fc::time_point time(fc::microseconds(row["last_bid_time"].as_uint64())); int64_t bid = row["high_bid"].as_int64(); std::cout << std::left << std::setw(18) << "bidname:" << std::right << std::setw(24) << row["newname"].as_string() << "\n" << std::left << std::setw(18) << "highest bidder:" << std::right << std::setw(24) << row["high_bidder"].as_string() << "\n" << std::left << std::setw(18) << "highest bid:" << std::right << std::setw(24) << (bid > 0 ? bid : -bid) << "\n" << std::left << std::setw(18) << "last bid time:" << std::right << std::setw(24) << ((std::string)time).c_str() << std::endl; if (bid < 0) std::cout << "This auction has already closed" << std::endl; } }); } }; struct list_bw_subcommand { eosio::name account; bool print_json = false; list_bw_subcommand(CLI::App* actionRoot) { auto list_bw = actionRoot->add_subcommand("listbw", localized("List delegated bandwidth")); list_bw->add_option("account", account, localized("The account delegated bandwidth"))->required(); list_bw->add_flag("--json,-j", print_json, localized("Output in JSON format") ); list_bw->set_callback([this] { //get entire table in scope of user account auto result = call(get_table_func, fc::mutable_variant_object("json", true) ("code", name(config::system_account_name).to_string()) ("scope", account.to_string()) ("table", "delband") ); if (!print_json) { auto res = result.as<eosio::chain_apis::read_only::get_table_rows_result>(); if ( !res.rows.empty() ) { std::cout << std::setw(13) << std::left << "Receiver" << std::setw(21) << std::left << "Net bandwidth" << std::setw(21) << std::left << "CPU bandwidth" << std::endl; for ( auto& r : res.rows ){ std::cout << std::setw(13) << std::left << r["to"].as_string() << std::setw(21) << std::left << r["net_weight"].as_string() << std::setw(21) << std::left << r["cpu_weight"].as_string() << std::endl; } } else { std::cerr << "Delegated bandwidth not found" << std::endl; } } else { std::cout << fc::json::to_pretty_string(result) << std::endl; } }); } }; struct buyram_subcommand { string from_str; string receiver_str; string amount; bool kbytes = false; bool bytes = false; buyram_subcommand(CLI::App* actionRoot) { auto buyram = actionRoot->add_subcommand("buyram", localized("Buy RAM")); buyram->add_option("payer", from_str, localized("The account paying for RAM"))->required(); buyram->add_option("receiver", receiver_str, localized("The account receiving bought RAM"))->required(); buyram->add_option("amount", amount, localized("The amount of EOS to pay for RAM, or number of bytes/kibibytes of RAM if --bytes/--kbytes is set"))->required(); buyram->add_flag("--kbytes,-k", kbytes, localized("buyram in number of kibibytes (KiB)")); buyram->add_flag("--bytes,-b", bytes, localized("buyram in number of bytes")); add_standard_transaction_options(buyram); buyram->set_callback([this] { EOSC_ASSERT( !kbytes || !bytes, "ERROR: --kbytes and --bytes cannot be set at the same time" ); if (kbytes || bytes) { send_actions( { create_buyrambytes(from_str, receiver_str, fc::to_uint64(amount) * ((kbytes) ? 1024ull : 1ull)) } ); } else { send_actions( { create_buyram(from_str, receiver_str, to_asset(amount)) } ); } }); } }; struct sellram_subcommand { string from_str; string receiver_str; uint64_t amount; sellram_subcommand(CLI::App* actionRoot) { auto sellram = actionRoot->add_subcommand("sellram", localized("Sell RAM")); sellram->add_option("account", receiver_str, localized("The account to receive EOS for sold RAM"))->required(); sellram->add_option("bytes", amount, localized("Number of RAM bytes to sell"))->required(); add_standard_transaction_options(sellram); sellram->set_callback([this] { fc::variant act_payload = fc::mutable_variant_object() ("account", receiver_str) ("bytes", amount); send_actions({create_action({permission_level{receiver_str,config::active_name}}, config::system_account_name, N(sellram), act_payload)}); }); } }; struct claimrewards_subcommand { string owner; claimrewards_subcommand(CLI::App* actionRoot) { auto claim_rewards = actionRoot->add_subcommand("claimrewards", localized("Claim producer rewards")); claim_rewards->add_option("owner", owner, localized("The account to claim rewards for"))->required(); add_standard_transaction_options(claim_rewards); claim_rewards->set_callback([this] { fc::variant act_payload = fc::mutable_variant_object() ("owner", owner); send_actions({create_action({permission_level{owner,config::active_name}}, config::system_account_name, N(claimrewards), act_payload)}); }); } }; struct regproxy_subcommand { string proxy; regproxy_subcommand(CLI::App* actionRoot) { auto register_proxy = actionRoot->add_subcommand("regproxy", localized("Register an account as a proxy (for voting)")); register_proxy->add_option("proxy", proxy, localized("The proxy account to register"))->required(); add_standard_transaction_options(register_proxy); register_proxy->set_callback([this] { fc::variant act_payload = fc::mutable_variant_object() ("proxy", proxy) ("isproxy", true); send_actions({create_action({permission_level{proxy,config::active_name}}, config::system_account_name, N(regproxy), act_payload)}); }); } }; struct unregproxy_subcommand { string proxy; unregproxy_subcommand(CLI::App* actionRoot) { auto unregister_proxy = actionRoot->add_subcommand("unregproxy", localized("Unregister an account as a proxy (for voting)")); unregister_proxy->add_option("proxy", proxy, localized("The proxy account to unregister"))->required(); add_standard_transaction_options(unregister_proxy); unregister_proxy->set_callback([this] { fc::variant act_payload = fc::mutable_variant_object() ("proxy", proxy) ("isproxy", false); send_actions({create_action({permission_level{proxy,config::active_name}}, config::system_account_name, N(regproxy), act_payload)}); }); } }; struct canceldelay_subcommand { string canceling_account; string canceling_permission; string trx_id; canceldelay_subcommand(CLI::App* actionRoot) { auto cancel_delay = actionRoot->add_subcommand("canceldelay", localized("Cancel a delayed transaction")); cancel_delay->add_option("canceling_account", canceling_account, localized("Account from authorization on the original delayed transaction"))->required(); cancel_delay->add_option("canceling_permission", canceling_permission, localized("Permission from authorization on the original delayed transaction"))->required(); cancel_delay->add_option("trx_id", trx_id, localized("The transaction id of the original delayed transaction"))->required(); add_standard_transaction_options(cancel_delay); cancel_delay->set_callback([this] { const auto canceling_auth = permission_level{canceling_account, canceling_permission}; fc::variant act_payload = fc::mutable_variant_object() ("canceling_auth", canceling_auth) ("trx_id", trx_id); send_actions({create_action({canceling_auth}, config::system_account_name, N(canceldelay), act_payload)}); }); } }; void get_account( const string& accountName, bool json_format ) { auto json = call(get_account_func, fc::mutable_variant_object("account_name", accountName)); auto res = json.as<eosio::chain_apis::read_only::get_account_results>(); if (!json_format) { asset staked; asset unstaking; if( res.core_liquid_balance.valid() ) { unstaking = asset( 0, res.core_liquid_balance->get_symbol() ); // Correct core symbol for unstaking asset. staked = asset( 0, res.core_liquid_balance->get_symbol() ); // Correct core symbol for staked asset. } std::cout << "created: " << string(res.created) << std::endl; if(res.privileged) std::cout << "privileged: true" << std::endl; constexpr size_t indent_size = 5; const string indent(indent_size, ' '); std::cout << "permissions: " << std::endl; unordered_map<name, vector<name>/*children*/> tree; vector<name> roots; //we don't have multiple roots, but we can easily handle them here, so let's do it just in case unordered_map<name, eosio::chain_apis::permission> cache; for ( auto& perm : res.permissions ) { if ( perm.parent ) { tree[perm.parent].push_back( perm.perm_name ); } else { roots.push_back( perm.perm_name ); } auto name = perm.perm_name; //keep copy before moving `perm`, since thirst argument of emplace can be evaluated first // looks a little crazy, but should be efficient cache.insert( std::make_pair(name, std::move(perm)) ); } std::function<void (account_name, int)> dfs_print = [&]( account_name name, int depth ) -> void { auto& p = cache.at(name); std::cout << indent << std::string(depth*3, ' ') << name << ' ' << std::setw(5) << p.required_auth.threshold << ": "; const char *sep = ""; for ( auto it = p.required_auth.keys.begin(); it != p.required_auth.keys.end(); ++it ) { std::cout << sep << it->weight << ' ' << string(it->key); sep = ", "; } for ( auto& acc : p.required_auth.accounts ) { std::cout << sep << acc.weight << ' ' << string(acc.permission.actor) << '@' << string(acc.permission.permission); sep = ", "; } std::cout << std::endl; auto it = tree.find( name ); if (it != tree.end()) { auto& children = it->second; sort( children.begin(), children.end() ); for ( auto& n : children ) { // we have a tree, not a graph, so no need to check for already visited nodes dfs_print( n, depth+1 ); } } // else it's a leaf node }; std::sort(roots.begin(), roots.end()); for ( auto r : roots ) { dfs_print( r, 0 ); } auto to_pretty_net = []( int64_t nbytes, uint8_t width_for_units = 5 ) { if(nbytes == -1) { // special case. Treat it as unlimited return std::string("unlimited"); } string unit = "bytes"; double bytes = static_cast<double> (nbytes); if (bytes >= 1024 * 1024 * 1024 * 1024ll) { unit = "TiB"; bytes /= 1024 * 1024 * 1024 * 1024ll; } else if (bytes >= 1024 * 1024 * 1024) { unit = "GiB"; bytes /= 1024 * 1024 * 1024; } else if (bytes >= 1024 * 1024) { unit = "MiB"; bytes /= 1024 * 1024; } else if (bytes >= 1024) { unit = "KiB"; bytes /= 1024; } std::stringstream ss; ss << setprecision(4); ss << bytes << " "; if( width_for_units > 0 ) ss << std::left << setw( width_for_units ); ss << unit; return ss.str(); }; std::cout << "memory: " << std::endl << indent << "quota: " << std::setw(15) << to_pretty_net(res.ram_quota) << " used: " << std::setw(15) << to_pretty_net(res.ram_usage) << std::endl << std::endl; std::cout << "net bandwidth: " << std::endl; if ( res.total_resources.is_object() ) { auto net_total = to_asset(res.total_resources.get_object()["net_weight"].as_string()); if( net_total.get_symbol() != unstaking.get_symbol() ) { // Core symbol of nodeos responding to the request is different than core symbol built into cleos unstaking = asset( 0, net_total.get_symbol() ); // Correct core symbol for unstaking asset. staked = asset( 0, net_total.get_symbol() ); // Correct core symbol for staked asset. } if( res.self_delegated_bandwidth.is_object() ) { asset net_own = asset::from_string( res.self_delegated_bandwidth.get_object()["net_weight"].as_string() ); staked = net_own; auto net_others = net_total - net_own; std::cout << indent << "staked:" << std::setw(20) << net_own << std::string(11, ' ') << "(total stake delegated from account to self)" << std::endl << indent << "delegated:" << std::setw(17) << net_others << std::string(11, ' ') << "(total staked delegated to account from others)" << std::endl; } else { auto net_others = net_total; std::cout << indent << "delegated:" << std::setw(17) << net_others << std::string(11, ' ') << "(total staked delegated to account from others)" << std::endl; } } auto to_pretty_time = []( int64_t nmicro, uint8_t width_for_units = 5 ) { if(nmicro == -1) { // special case. Treat it as unlimited return std::string("unlimited"); } string unit = "us"; double micro = static_cast<double>(nmicro); if( micro > 1000000*60*60ll ) { micro /= 1000000*60*60ll; unit = "hr"; } else if( micro > 1000000*60 ) { micro /= 1000000*60; unit = "min"; } else if( micro > 1000000 ) { micro /= 1000000; unit = "sec"; } else if( micro > 1000 ) { micro /= 1000; unit = "ms"; } std::stringstream ss; ss << setprecision(4); ss << micro << " "; if( width_for_units > 0 ) ss << std::left << setw( width_for_units ); ss << unit; return ss.str(); }; std::cout << std::fixed << setprecision(3); std::cout << indent << std::left << std::setw(11) << "used:" << std::right << std::setw(18) << to_pretty_net( res.net_limit.used ) << "\n"; std::cout << indent << std::left << std::setw(11) << "available:" << std::right << std::setw(18) << to_pretty_net( res.net_limit.available ) << "\n"; std::cout << indent << std::left << std::setw(11) << "limit:" << std::right << std::setw(18) << to_pretty_net( res.net_limit.max ) << "\n"; std::cout << std::endl; std::cout << "cpu bandwidth:" << std::endl; if ( res.total_resources.is_object() ) { auto cpu_total = to_asset(res.total_resources.get_object()["cpu_weight"].as_string()); if( res.self_delegated_bandwidth.is_object() ) { asset cpu_own = asset::from_string( res.self_delegated_bandwidth.get_object()["cpu_weight"].as_string() ); staked += cpu_own; auto cpu_others = cpu_total - cpu_own; std::cout << indent << "staked:" << std::setw(20) << cpu_own << std::string(11, ' ') << "(total stake delegated from account to self)" << std::endl << indent << "delegated:" << std::setw(17) << cpu_others << std::string(11, ' ') << "(total staked delegated to account from others)" << std::endl; } else { auto cpu_others = cpu_total; std::cout << indent << "delegated:" << std::setw(17) << cpu_others << std::string(11, ' ') << "(total staked delegated to account from others)" << std::endl; } } std::cout << std::fixed << setprecision(3); std::cout << indent << std::left << std::setw(11) << "used:" << std::right << std::setw(18) << to_pretty_time( res.cpu_limit.used ) << "\n"; std::cout << indent << std::left << std::setw(11) << "available:" << std::right << std::setw(18) << to_pretty_time( res.cpu_limit.available ) << "\n"; std::cout << indent << std::left << std::setw(11) << "limit:" << std::right << std::setw(18) << to_pretty_time( res.cpu_limit.max ) << "\n"; std::cout << std::endl; if( res.refund_request.is_object() ) { auto obj = res.refund_request.get_object(); auto request_time = fc::time_point_sec::from_iso_string( obj["request_time"].as_string() ); fc::time_point refund_time = request_time + fc::days(3); auto now = res.head_block_time; asset net = asset::from_string( obj["net_amount"].as_string() ); asset cpu = asset::from_string( obj["cpu_amount"].as_string() ); unstaking = net + cpu; if( unstaking > asset( 0, unstaking.get_symbol() ) ) { std::cout << std::fixed << setprecision(3); std::cout << "unstaking tokens:" << std::endl; std::cout << indent << std::left << std::setw(25) << "time of unstake request:" << std::right << std::setw(20) << string(request_time); if( now >= refund_time ) { std::cout << " (available to claim now with 'eosio::refund' action)\n"; } else { std::cout << " (funds will be available in " << to_pretty_time( (refund_time - now).count(), 0 ) << ")\n"; } std::cout << indent << std::left << std::setw(25) << "from net bandwidth:" << std::right << std::setw(18) << net << std::endl; std::cout << indent << std::left << std::setw(25) << "from cpu bandwidth:" << std::right << std::setw(18) << cpu << std::endl; std::cout << indent << std::left << std::setw(25) << "total:" << std::right << std::setw(18) << unstaking << std::endl; std::cout << std::endl; } } if( res.core_liquid_balance.valid() ) { std::cout << res.core_liquid_balance->get_symbol().name() << " balances: " << std::endl; std::cout << indent << std::left << std::setw(11) << "liquid:" << std::right << std::setw(18) << *res.core_liquid_balance << std::endl; std::cout << indent << std::left << std::setw(11) << "staked:" << std::right << std::setw(18) << staked << std::endl; std::cout << indent << std::left << std::setw(11) << "unstaking:" << std::right << std::setw(18) << unstaking << std::endl; std::cout << indent << std::left << std::setw(11) << "total:" << std::right << std::setw(18) << (*res.core_liquid_balance + staked + unstaking) << std::endl; std::cout << std::endl; } if ( res.voter_info.is_object() ) { auto& obj = res.voter_info.get_object(); string proxy = obj["proxy"].as_string(); if ( proxy.empty() ) { auto& prods = obj["producers"].get_array(); std::cout << "producers:"; if ( !prods.empty() ) { for ( int i = 0; i < prods.size(); ++i ) { if ( i%3 == 0 ) { std::cout << std::endl << indent; } std::cout << std::setw(16) << std::left << prods[i].as_string(); } std::cout << std::endl; } else { std::cout << indent << "<not voted>" << std::endl; } } else { std::cout << "proxy:" << indent << proxy << std::endl; } } std::cout << std::endl; } else { std::cout << fc::json::to_pretty_string(json) << std::endl; } } CLI::callback_t header_opt_callback = [](CLI::results_t res) { vector<string>::iterator itr; for (itr = res.begin(); itr != res.end(); itr++) { headers.push_back(*itr); } return true; }; int main( int argc, char** argv ) { setlocale(LC_ALL, ""); bindtextdomain(locale_domain, locale_path); textdomain(locale_domain); context = eosio::client::http::create_http_context(); wallet_url = default_wallet_url; CLI::App app{"Command Line Interface to EOSIO Client"}; app.require_subcommand(); app.add_option( "-H,--host", obsoleted_option_host_port, localized("the host where nodeos is running") )->group("hidden"); app.add_option( "-p,--port", obsoleted_option_host_port, localized("the port where nodeos is running") )->group("hidden"); app.add_option( "--wallet-host", obsoleted_option_host_port, localized("the host where keosd is running") )->group("hidden"); app.add_option( "--wallet-port", obsoleted_option_host_port, localized("the port where keosd is running") )->group("hidden"); app.add_option( "-u,--url", url, localized("the http/https URL where nodeos is running"), true ); app.add_option( "--wallet-url", wallet_url, localized("the http/https URL where keosd is running"), true ); app.add_option( "-r,--header", header_opt_callback, localized("pass specific HTTP header; repeat this option to pass multiple headers")); app.add_flag( "-n,--no-verify", no_verify, localized("don't verify peer certificate when using HTTPS")); app.add_flag( "--no-auto-keosd", no_auto_keosd, localized("don't automatically launch a keosd if one is not currently running")); app.set_callback([&app]{ ensure_keosd_running(&app);}); bool verbose_errors = false; app.add_flag( "-v,--verbose", verbose_errors, localized("output verbose actions on error")); app.add_flag("--print-request", print_request, localized("print HTTP request to STDERR")); app.add_flag("--print-response", print_response, localized("print HTTP response to STDERR")); auto version = app.add_subcommand("version", localized("Retrieve version information"), false); version->require_subcommand(); version->add_subcommand("client", localized("Retrieve version information of the client"))->set_callback([] { std::cout << localized("Build version: ${ver}", ("ver", eosio::client::config::version_str)) << std::endl; }); // Create subcommand auto create = app.add_subcommand("create", localized("Create various items, on and off the blockchain"), false); create->require_subcommand(); bool r1 = false; string key_file; bool print_console = false; // create key auto create_key = create->add_subcommand("key", localized("Create a new keypair and print the public and private keys"))->set_callback( [&r1, &key_file, &print_console](){ if (key_file.empty() && !print_console) { std::cerr << "ERROR: Either indicate a file using \"--file\" or pass \"--to-console\"" << std::endl; return; } auto pk = r1 ? private_key_type::generate_r1() : private_key_type::generate(); auto privs = string(pk); auto pubs = string(pk.get_public_key()); if (print_console) { std::cout << localized("Private key: ${key}", ("key", privs) ) << std::endl; std::cout << localized("Public key: ${key}", ("key", pubs ) ) << std::endl; } else { std::cerr << localized("saving keys to ${filename}", ("filename", key_file)) << std::endl; std::ofstream out( key_file.c_str() ); out << localized("Private key: ${key}", ("key", privs) ) << std::endl; out << localized("Public key: ${key}", ("key", pubs ) ) << std::endl; } }); create_key->add_flag( "--r1", r1, "Generate a key using the R1 curve (iPhone), instead of the K1 curve (Bitcoin)" ); create_key->add_option("-f,--file", key_file, localized("Name of file to write private/public key output to. (Must be set, unless \"--to-console\" is passed")); create_key->add_flag( "--to-console", print_console, localized("Print private/public keys to console.")); // create account auto createAccount = create_account_subcommand( create, true /*simple*/ ); // convert subcommand auto convert = app.add_subcommand("convert", localized("Pack and unpack transactions"), false); // TODO also add converting action args based on abi from here ? convert->require_subcommand(); // pack transaction string plain_signed_transaction_json; bool pack_action_data_flag = false; auto pack_transaction = convert->add_subcommand("pack_transaction", localized("From plain signed json to packed form")); pack_transaction->add_option("transaction", plain_signed_transaction_json, localized("The plain signed json (string)"))->required(); pack_transaction->add_flag("--pack-action-data", pack_action_data_flag, localized("Pack all action data within transaction, needs interaction with nodeos")); pack_transaction->set_callback([&] { fc::variant trx_var; try { trx_var = json_from_file_or_string( plain_signed_transaction_json ); } EOS_RETHROW_EXCEPTIONS( transaction_type_exception, "Fail to parse plain transaction JSON '${data}'", ("data", plain_signed_transaction_json)) if( pack_action_data_flag ) { signed_transaction trx; abi_serializer::from_variant( trx_var, trx, abi_serializer_resolver, abi_serializer_max_time ); std::cout << fc::json::to_pretty_string( packed_transaction( trx, packed_transaction::none )) << std::endl; } else { try { signed_transaction trx = trx_var.as<signed_transaction>(); std::cout << fc::json::to_pretty_string( fc::variant( packed_transaction( trx, packed_transaction::none ))) << std::endl; } EOS_RETHROW_EXCEPTIONS( transaction_type_exception, "Fail to convert transaction, --pack-action-data likely needed" ) } }); // unpack transaction string packed_transaction_json; bool unpack_action_data_flag = false; auto unpack_transaction = convert->add_subcommand("unpack_transaction", localized("From packed to plain signed json form")); unpack_transaction->add_option("transaction", packed_transaction_json, localized("The packed transaction json (string containing packed_trx and optionally compression fields)"))->required(); unpack_transaction->add_flag("--unpack-action-data", unpack_action_data_flag, localized("Unpack all action data within transaction, needs interaction with nodeos")); unpack_transaction->set_callback([&] { fc::variant packed_trx_var; packed_transaction packed_trx; try { packed_trx_var = json_from_file_or_string( packed_transaction_json ); fc::from_variant<packed_transaction>( packed_trx_var, packed_trx ); } EOS_RETHROW_EXCEPTIONS( transaction_type_exception, "Fail to parse packed transaction JSON '${data}'", ("data", packed_transaction_json)) signed_transaction strx = packed_trx.get_signed_transaction(); fc::variant trx_var; if( unpack_action_data_flag ) { abi_serializer::to_variant( strx, trx_var, abi_serializer_resolver, abi_serializer_max_time ); } else { trx_var = strx; } std::cout << fc::json::to_pretty_string( trx_var ) << std::endl; }); // pack action data string unpacked_action_data_account_string; string unpacked_action_data_name_string; string unpacked_action_data_string; auto pack_action_data = convert->add_subcommand("pack_action_data", localized("From json action data to packed form")); pack_action_data->add_option("account", unpacked_action_data_account_string, localized("The name of the account that hosts the contract"))->required(); pack_action_data->add_option("name", unpacked_action_data_name_string, localized("The name of the function that's called by this action"))->required(); pack_action_data->add_option("unpacked_action_data", unpacked_action_data_string, localized("The action data expressed as json"))->required(); pack_action_data->set_callback([&] { fc::variant unpacked_action_data_json; try { unpacked_action_data_json = json_from_file_or_string(unpacked_action_data_string); } EOS_RETHROW_EXCEPTIONS(transaction_type_exception, "Fail to parse unpacked action data JSON") bytes packed_action_data_string = variant_to_bin(unpacked_action_data_account_string, unpacked_action_data_name_string, unpacked_action_data_json); std::cout << fc::to_hex(packed_action_data_string.data(), packed_action_data_string.size()) << std::endl; }); // unpack action data string packed_action_data_account_string; string packed_action_data_name_string; string packed_action_data_string; auto unpack_action_data = convert->add_subcommand("unpack_action_data", localized("From packed to json action data form")); unpack_action_data->add_option("account", packed_action_data_account_string, localized("The name of the account that hosts the contract"))->required(); unpack_action_data->add_option("name", packed_action_data_name_string, localized("The name of the function that's called by this action"))->required(); unpack_action_data->add_option("packed_action_data", packed_action_data_string, localized("The action data expressed as packed hex string"))->required(); unpack_action_data->set_callback([&] { EOS_ASSERT( packed_action_data_string.size() >= 2, transaction_type_exception, "No packed_action_data found" ); vector<char> packed_action_data_blob(packed_action_data_string.size()/2); fc::from_hex(packed_action_data_string, packed_action_data_blob.data(), packed_action_data_blob.size()); fc::variant unpacked_action_data_json = bin_to_variant(packed_action_data_account_string, packed_action_data_name_string, packed_action_data_blob); std::cout << fc::json::to_pretty_string(unpacked_action_data_json) << std::endl; }); // Get subcommand auto get = app.add_subcommand("get", localized("Retrieve various items and information from the blockchain"), false); get->require_subcommand(); // get info get->add_subcommand("info", localized("Get current blockchain information"))->set_callback([] { std::cout << fc::json::to_pretty_string(get_info()) << std::endl; }); // get block string blockArg; bool get_bhs = false; auto getBlock = get->add_subcommand("block", localized("Retrieve a full block from the blockchain"), false); getBlock->add_option("block", blockArg, localized("The number or ID of the block to retrieve"))->required(); getBlock->add_flag("--header-state", get_bhs, localized("Get block header state from fork database instead") ); getBlock->set_callback([&blockArg,&get_bhs] { auto arg = fc::mutable_variant_object("block_num_or_id", blockArg); if( get_bhs ) { std::cout << fc::json::to_pretty_string(call(get_block_header_state_func, arg)) << std::endl; } else { std::cout << fc::json::to_pretty_string(call(get_block_func, arg)) << std::endl; } }); // get account string accountName; bool print_json; auto getAccount = get->add_subcommand("account", localized("Retrieve an account from the blockchain"), false); getAccount->add_option("name", accountName, localized("The name of the account to retrieve"))->required(); getAccount->add_flag("--json,-j", print_json, localized("Output in JSON format") ); getAccount->set_callback([&]() { get_account(accountName, print_json); }); // get code string codeFilename; string abiFilename; bool code_as_wasm = false; auto getCode = get->add_subcommand("code", localized("Retrieve the code and ABI for an account"), false); getCode->add_option("name", accountName, localized("The name of the account whose code should be retrieved"))->required(); getCode->add_option("-c,--code",codeFilename, localized("The name of the file to save the contract .wast/wasm to") ); getCode->add_option("-a,--abi",abiFilename, localized("The name of the file to save the contract .abi to") ); getCode->add_flag("--wasm", code_as_wasm, localized("Save contract as wasm")); getCode->set_callback([&] { string code_hash, wasm, wast, abi; try { const auto result = call(get_raw_code_and_abi_func, fc::mutable_variant_object("account_name", accountName)); const std::vector<char> wasm_v = result["wasm"].as_blob().data; const std::vector<char> abi_v = result["abi"].as_blob().data; fc::sha256 hash; if(wasm_v.size()) hash = fc::sha256::hash(wasm_v.data(), wasm_v.size()); code_hash = (string)hash; wasm = string(wasm_v.begin(), wasm_v.end()); if(!code_as_wasm && wasm_v.size()) wast = wasm_to_wast((const uint8_t*)wasm_v.data(), wasm_v.size(), false); abi_def abi_d; if(abi_serializer::to_abi(abi_v, abi_d)) abi = fc::json::to_pretty_string(abi_d); } catch(chain::missing_chain_api_plugin_exception&) { //see if this is an old nodeos that doesn't support get_raw_code_and_abi const auto old_result = call(get_code_func, fc::mutable_variant_object("account_name", accountName)("code_as_wasm",code_as_wasm)); code_hash = old_result["code_hash"].as_string(); if(code_as_wasm) { wasm = old_result["wasm"].as_string(); std::cout << localized("Warning: communicating to older nodeos which returns malformed binary wasm") << std::endl; } else wast = old_result["wast"].as_string(); abi = fc::json::to_pretty_string(old_result["abi"]); } std::cout << localized("code hash: ${code_hash}", ("code_hash", code_hash)) << std::endl; if( codeFilename.size() ){ std::cout << localized("saving ${type} to ${codeFilename}", ("type", (code_as_wasm ? "wasm" : "wast"))("codeFilename", codeFilename)) << std::endl; std::ofstream out( codeFilename.c_str() ); if(code_as_wasm) out << wasm; else out << wast; } if( abiFilename.size() ) { std::cout << localized("saving abi to ${abiFilename}", ("abiFilename", abiFilename)) << std::endl; std::ofstream abiout( abiFilename.c_str() ); abiout << abi; } }); // get abi string filename; auto getAbi = get->add_subcommand("abi", localized("Retrieve the ABI for an account"), false); getAbi->add_option("name", accountName, localized("The name of the account whose abi should be retrieved"))->required(); getAbi->add_option("-f,--file",filename, localized("The name of the file to save the contract .abi to instead of writing to console") ); getAbi->set_callback([&] { auto result = call(get_abi_func, fc::mutable_variant_object("account_name", accountName)); auto abi = fc::json::to_pretty_string( result["abi"] ); if( filename.size() ) { std::cerr << localized("saving abi to ${filename}", ("filename", filename)) << std::endl; std::ofstream abiout( filename.c_str() ); abiout << abi; } else { std::cout << abi << "\n"; } }); // get table string scope; string code; string table; string lower; string upper; string table_key; string key_type; string encode_type{"dec"}; bool binary = false; uint32_t limit = 10; string index_position; auto getTable = get->add_subcommand( "table", localized("Retrieve the contents of a database table"), false); getTable->add_option( "account", code, localized("The account who owns the table") )->required(); getTable->add_option( "scope", scope, localized("The scope within the contract in which the table is found") )->required(); getTable->add_option( "table", table, localized("The name of the table as specified by the contract abi") )->required(); getTable->add_option( "-b,--binary", binary, localized("Return the value as BINARY rather than using abi to interpret as JSON") ); getTable->add_option( "-l,--limit", limit, localized("The maximum number of rows to return") ); getTable->add_option( "-k,--key", table_key, localized("Deprecated") ); getTable->add_option( "-L,--lower", lower, localized("JSON representation of lower bound value of key, defaults to first") ); getTable->add_option( "-U,--upper", upper, localized("JSON representation of upper bound value of key, defaults to last") ); getTable->add_option( "--index", index_position, localized("Index number, 1 - primary (first), 2 - secondary index (in order defined by multi_index), 3 - third index, etc.\n" "\t\t\t\tNumber or name of index can be specified, e.g. 'secondary' or '2'.")); getTable->add_option( "--key-type", key_type, localized("The key type of --index, primary only supports (i64), all others support (i64, i128, i256, float64, float128, ripemd160, sha256).\n" "\t\t\t\tSpecial type 'name' indicates an account name.")); getTable->add_option( "--encode-type", encode_type, localized("The encoding type of key_type (i64 , i128 , float64, float128) only support decimal encoding e.g. 'dec'" "i256 - supports both 'dec' and 'hex', ripemd160 and sha256 is 'hex' only\n")); getTable->set_callback([&] { auto result = call(get_table_func, fc::mutable_variant_object("json", !binary) ("code",code) ("scope",scope) ("table",table) ("table_key",table_key) // not used ("lower_bound",lower) ("upper_bound",upper) ("limit",limit) ("key_type",key_type) ("index_position", index_position) ("encode_type", encode_type) ); std::cout << fc::json::to_pretty_string(result) << std::endl; }); auto getScope = get->add_subcommand( "scope", localized("Retrieve a list of scopes and tables owned by a contract"), false); getScope->add_option( "contract", code, localized("The contract who owns the table") )->required(); getScope->add_option( "-t,--table", table, localized("The name of the table as filter") ); getScope->add_option( "-l,--limit", limit, localized("The maximum number of rows to return") ); getScope->add_option( "-L,--lower", lower, localized("lower bound of scope") ); getScope->add_option( "-U,--upper", upper, localized("upper bound of scope") ); getScope->set_callback([&] { auto result = call(get_table_by_scope_func, fc::mutable_variant_object("code",code) ("table",table) ("lower_bound",lower) ("upper_bound",upper) ("limit",limit) ); std::cout << fc::json::to_pretty_string(result) << std::endl; }); // currency accessors // get currency balance string symbol; auto get_currency = get->add_subcommand( "currency", localized("Retrieve information related to standard currencies"), true); get_currency->require_subcommand(); auto get_balance = get_currency->add_subcommand( "balance", localized("Retrieve the balance of an account for a given currency"), false); get_balance->add_option( "contract", code, localized("The contract that operates the currency") )->required(); get_balance->add_option( "account", accountName, localized("The account to query balances for") )->required(); get_balance->add_option( "symbol", symbol, localized("The symbol for the currency if the contract operates multiple currencies") ); get_balance->set_callback([&] { auto result = call(get_currency_balance_func, fc::mutable_variant_object ("account", accountName) ("code", code) ("symbol", symbol.empty() ? fc::variant() : symbol) ); const auto& rows = result.get_array(); for( const auto& r : rows ) { std::cout << r.as_string() << std::endl; } }); auto get_currency_stats = get_currency->add_subcommand( "stats", localized("Retrieve the stats of for a given currency"), false); get_currency_stats->add_option( "contract", code, localized("The contract that operates the currency") )->required(); get_currency_stats->add_option( "symbol", symbol, localized("The symbol for the currency if the contract operates multiple currencies") )->required(); get_currency_stats->set_callback([&] { auto result = call(get_currency_stats_func, fc::mutable_variant_object("json", false) ("code", code) ("symbol", symbol) ); std::cout << fc::json::to_pretty_string(result) << std::endl; }); // get accounts string public_key_str; auto getAccounts = get->add_subcommand("accounts", localized("Retrieve accounts associated with a public key"), false); getAccounts->add_option("public_key", public_key_str, localized("The public key to retrieve accounts for"))->required(); getAccounts->set_callback([&] { public_key_type public_key; try { public_key = public_key_type(public_key_str); } EOS_RETHROW_EXCEPTIONS(public_key_type_exception, "Invalid public key: ${public_key}", ("public_key", public_key_str)) auto arg = fc::mutable_variant_object( "public_key", public_key); std::cout << fc::json::to_pretty_string(call(get_key_accounts_func, arg)) << std::endl; }); // get servants string controllingAccount; auto getServants = get->add_subcommand("servants", localized("Retrieve accounts which are servants of a given account "), false); getServants->add_option("account", controllingAccount, localized("The name of the controlling account"))->required(); getServants->set_callback([&] { auto arg = fc::mutable_variant_object( "controlling_account", controllingAccount); std::cout << fc::json::to_pretty_string(call(get_controlled_accounts_func, arg)) << std::endl; }); // get transaction string transaction_id_str; uint32_t block_num_hint = 0; auto getTransaction = get->add_subcommand("transaction", localized("Retrieve a transaction from the blockchain"), false); getTransaction->add_option("id", transaction_id_str, localized("ID of the transaction to retrieve"))->required(); getTransaction->add_option( "-b,--block-hint", block_num_hint, localized("the block number this transaction may be in") ); getTransaction->set_callback([&] { auto arg= fc::mutable_variant_object( "id", transaction_id_str); if ( block_num_hint > 0 ) { arg = arg("block_num_hint", block_num_hint); } std::cout << fc::json::to_pretty_string(call(get_transaction_func, arg)) << std::endl; }); // get actions string account_name; string skip_seq_str; string num_seq_str; bool printjson = false; bool fullact = false; bool prettyact = false; bool printconsole = false; int32_t pos_seq = -1; int32_t offset = -20; auto getActions = get->add_subcommand("actions", localized("Retrieve all actions with specific account name referenced in authorization or receiver"), false); getActions->add_option("account_name", account_name, localized("name of account to query on"))->required(); getActions->add_option("pos", pos_seq, localized("sequence number of action for this account, -1 for last")); getActions->add_option("offset", offset, localized("get actions [pos,pos+offset] for positive offset or [pos-offset,pos) for negative offset")); getActions->add_flag("--json,-j", printjson, localized("print full json")); getActions->add_flag("--full", fullact, localized("don't truncate action json")); getActions->add_flag("--pretty", prettyact, localized("pretty print full action json ")); getActions->add_flag("--console", printconsole, localized("print console output generated by action ")); getActions->set_callback([&] { fc::mutable_variant_object arg; arg( "account_name", account_name ); arg( "pos", pos_seq ); arg( "offset", offset); auto result = call(get_actions_func, arg); if( printjson ) { std::cout << fc::json::to_pretty_string(result) << std::endl; } else { auto& traces = result["actions"].get_array(); uint32_t lib = result["last_irreversible_block"].as_uint64(); cout << "#" << setw(5) << "seq" << " " << setw( 24 ) << left << "when"<< " " << setw(24) << right << "contract::action" << " => " << setw(13) << left << "receiver" << " " << setw(11) << left << "trx id..." << " args\n"; cout << "================================================================================================================\n"; for( const auto& trace: traces ) { std::stringstream out; if( trace["block_num"].as_uint64() <= lib ) out << "#"; else out << "?"; out << setw(5) << trace["account_action_seq"].as_uint64() <<" "; out << setw(24) << trace["block_time"].as_string() <<" "; const auto& at = trace["action_trace"].get_object(); auto id = at["trx_id"].as_string(); const auto& receipt = at["receipt"]; auto receiver = receipt["receiver"].as_string(); const auto& act = at["act"].get_object(); auto code = act["account"].as_string(); auto func = act["name"].as_string(); string args; if( prettyact ) { args = fc::json::to_pretty_string( act["data"] ); } else { args = fc::json::to_string( act["data"] ); if( !fullact ) { args = args.substr(0,60) + "..."; } } out << std::setw(24) << std::right<< (code +"::" + func) << " => " << left << std::setw(13) << receiver; out << " " << setw(11) << (id.substr(0,8) + "..."); if( fullact || prettyact ) out << "\n"; else out << " "; out << args ;//<< "\n"; if( trace["block_num"].as_uint64() <= lib ) { dlog( "\r${m}", ("m",out.str()) ); } else { wlog( "\r${m}", ("m",out.str()) ); } if( printconsole ) { auto console = at["console"].as_string(); if( console.size() ) { stringstream out; std::stringstream ss(console); string line; std::getline( ss, line ); out << ">> " << line << "\n"; cerr << out.str(); //ilog( "\r${m} ", ("m",out.str()) ); } } } } }); auto getSchedule = get_schedule_subcommand{get}; auto getTransactionId = get_transaction_id_subcommand{get}; /* auto getTransactions = get->add_subcommand("transactions", localized("Retrieve all transactions with specific account name referenced in their scope"), false); getTransactions->add_option("account_name", account_name, localized("name of account to query on"))->required(); getTransactions->add_option("skip_seq", skip_seq_str, localized("Number of most recent transactions to skip (0 would start at most recent transaction)")); getTransactions->add_option("num_seq", num_seq_str, localized("Number of transactions to return")); getTransactions->add_flag("--json,-j", printjson, localized("print full json")); getTransactions->set_callback([&] { fc::mutable_variant_object arg; if (skip_seq_str.empty()) { arg = fc::mutable_variant_object( "account_name", account_name); } else { uint64_t skip_seq; try { skip_seq = boost::lexical_cast<uint64_t>(skip_seq_str); } EOS_RETHROW_EXCEPTIONS(chain_type_exception, "Invalid Skip Seq: ${skip_seq}", ("skip_seq", skip_seq_str)) if (num_seq_str.empty()) { arg = fc::mutable_variant_object( "account_name", account_name)("skip_seq", skip_seq); } else { uint64_t num_seq; try { num_seq = boost::lexical_cast<uint64_t>(num_seq_str); } EOS_RETHROW_EXCEPTIONS(chain_type_exception, "Invalid Num Seq: ${num_seq}", ("num_seq", num_seq_str)) arg = fc::mutable_variant_object( "account_name", account_name)("skip_seq", skip_seq_str)("num_seq", num_seq); } } auto result = call(get_transactions_func, arg); if( printjson ) { std::cout << fc::json::to_pretty_string(result) << std::endl; } else { const auto& trxs = result.get_object()["transactions"].get_array(); for( const auto& t : trxs ) { const auto& tobj = t.get_object(); const auto& trx = tobj["transaction"].get_object(); const auto& data = trx["transaction"].get_object(); const auto& msgs = data["actions"].get_array(); for( const auto& msg : msgs ) { int64_t seq_num = tobj["seq_num"].as<int64_t>(); string id = tobj["transaction_id"].as_string(); const auto& exp = data["expiration"].as<fc::time_point_sec>(); std::cout << tobj["seq_num"].as_string() <<"] " << id.substr(0,8) << "... " << data["expiration"].as_string() << " "; auto code = msg["account"].as_string(); auto func = msg["name"].as_string(); auto args = fc::json::to_string( msg["data"] ); std::cout << setw(26) << left << (code + "::" + func) << " " << args; std::cout << std::endl; } } } }); */ // set subcommand auto setSubcommand = app.add_subcommand("set", localized("Set or update blockchain state")); setSubcommand->require_subcommand(); // set contract subcommand string account; string contractPath; string wasmPath; string abiPath; bool shouldSend = true; bool contract_clear = false; bool suppress_duplicate_check = false; auto codeSubcommand = setSubcommand->add_subcommand("code", localized("Create or update the code on an account")); codeSubcommand->add_option("account", account, localized("The account to set code for"))->required(); codeSubcommand->add_option("code-file", wasmPath, localized("The fullpath containing the contract WASM"));//->required(); codeSubcommand->add_flag( "-c,--clear", contract_clear, localized("Remove code on an account")); codeSubcommand->add_flag( "--suppress-duplicate-check", suppress_duplicate_check, localized("Don't check for duplicate")); auto abiSubcommand = setSubcommand->add_subcommand("abi", localized("Create or update the abi on an account")); abiSubcommand->add_option("account", account, localized("The account to set the ABI for"))->required(); abiSubcommand->add_option("abi-file", abiPath, localized("The fullpath containing the contract ABI"));//->required(); abiSubcommand->add_flag( "-c,--clear", contract_clear, localized("Remove abi on an account")); abiSubcommand->add_flag( "--suppress-duplicate-check", suppress_duplicate_check, localized("Don't check for duplicate")); auto contractSubcommand = setSubcommand->add_subcommand("contract", localized("Create or update the contract on an account")); contractSubcommand->add_option("account", account, localized("The account to publish a contract for")) ->required(); contractSubcommand->add_option("contract-dir", contractPath, localized("The path containing the .wasm and .abi")); // ->required(); contractSubcommand->add_option("wasm-file", wasmPath, localized("The file containing the contract WASM relative to contract-dir")); // ->check(CLI::ExistingFile); auto abi = contractSubcommand->add_option("abi-file,-a,--abi", abiPath, localized("The ABI for the contract relative to contract-dir")); // ->check(CLI::ExistingFile); contractSubcommand->add_flag( "-c,--clear", contract_clear, localized("Rmove contract on an account")); contractSubcommand->add_flag( "--suppress-duplicate-check", suppress_duplicate_check, localized("Don't check for duplicate")); std::vector<chain::action> actions; auto set_code_callback = [&]() { std::vector<char> old_wasm; bool duplicate = false; fc::sha256 old_hash, new_hash; if (!suppress_duplicate_check) { try { const auto result = call(get_code_hash_func, fc::mutable_variant_object("account_name", account)); old_hash = fc::sha256(result["code_hash"].as_string()); } catch (...) { std::cerr << "Failed to get existing code hash, continue without duplicate check..." << std::endl; suppress_duplicate_check = true; } } bytes code_bytes; if(!contract_clear){ std::string wasm; fc::path cpath(contractPath); if( cpath.filename().generic_string() == "." ) cpath = cpath.parent_path(); if( wasmPath.empty() ) wasmPath = (cpath / (cpath.filename().generic_string()+".wasm")).generic_string(); else wasmPath = (cpath / wasmPath).generic_string(); std::cerr << localized(("Reading WASM from " + wasmPath + "...").c_str()) << std::endl; fc::read_file_contents(wasmPath, wasm); EOS_ASSERT( !wasm.empty(), wast_file_not_found, "no wasm file found ${f}", ("f", wasmPath) ); const string binary_wasm_header("\x00\x61\x73\x6d\x01\x00\x00\x00", 8); if(wasm.compare(0, 8, binary_wasm_header)) std::cerr << localized("WARNING: ") << wasmPath << localized(" doesn't look like a binary WASM file. Is it something else, like WAST? Trying anyways...") << std::endl; code_bytes = bytes(wasm.begin(), wasm.end()); } else { code_bytes = bytes(); } if (!suppress_duplicate_check) { if (code_bytes.size()) { new_hash = fc::sha256::hash(&(code_bytes[0]), code_bytes.size()); } duplicate = (old_hash == new_hash); } if (!duplicate) { actions.emplace_back( create_setcode(account, code_bytes ) ); if ( shouldSend ) { std::cerr << localized("Setting Code...") << std::endl; send_actions(std::move(actions), 10000, packed_transaction::zlib); } } else { std::cout << "Skipping set code because the new code is the same as the existing code" << std::endl; } }; auto set_abi_callback = [&]() { bytes old_abi; bool duplicate = false; if (!suppress_duplicate_check) { try { const auto result = call(get_raw_abi_func, fc::mutable_variant_object("account_name", account)); old_abi = result["abi"].as_blob().data; } catch (...) { std::cerr << "Failed to get existing raw abi, continue without duplicate check..." << std::endl; suppress_duplicate_check = true; } } bytes abi_bytes; if(!contract_clear){ fc::path cpath(contractPath); if( cpath.filename().generic_string() == "." ) cpath = cpath.parent_path(); if( abiPath.empty() ) { abiPath = (cpath / (cpath.filename().generic_string()+".abi")).generic_string(); } else { abiPath = (cpath / abiPath).generic_string(); } EOS_ASSERT( fc::exists( abiPath ), abi_file_not_found, "no abi file found ${f}", ("f", abiPath) ); abi_bytes = fc::raw::pack(fc::json::from_file(abiPath).as<abi_def>()); } else { abi_bytes = bytes(); } if (!suppress_duplicate_check) { duplicate = (old_abi.size() == abi_bytes.size() && std::equal(old_abi.begin(), old_abi.end(), abi_bytes.begin())); } if (!duplicate) { try { actions.emplace_back( create_setabi(account, abi_bytes) ); } EOS_RETHROW_EXCEPTIONS(abi_type_exception, "Fail to parse ABI JSON") if ( shouldSend ) { std::cerr << localized("Setting ABI...") << std::endl; send_actions(std::move(actions), 10000, packed_transaction::zlib); } } else { std::cout << "Skipping set abi because the new abi is the same as the existing abi" << std::endl; } }; add_standard_transaction_options(contractSubcommand, "account@active"); add_standard_transaction_options(codeSubcommand, "account@active"); add_standard_transaction_options(abiSubcommand, "account@active"); contractSubcommand->set_callback([&] { if(!contract_clear) EOS_ASSERT( !contractPath.empty(), contract_exception, " contract-dir is null ", ("f", contractPath) ); shouldSend = false; set_code_callback(); set_abi_callback(); if (actions.size()) { std::cerr << localized("Publishing contract...") << std::endl; send_actions(std::move(actions), 10000, packed_transaction::zlib); } else { std::cout << "no transaction is sent" << std::endl; } }); codeSubcommand->set_callback(set_code_callback); abiSubcommand->set_callback(set_abi_callback); // set account auto setAccount = setSubcommand->add_subcommand("account", localized("set or update blockchain account state"))->require_subcommand(); // set account permission auto setAccountPermission = set_account_permission_subcommand(setAccount); // set action auto setAction = setSubcommand->add_subcommand("action", localized("set or update blockchain action state"))->require_subcommand(); // set action permission auto setActionPermission = set_action_permission_subcommand(setAction); // Transfer subcommand string con = "eosio.token"; string sender; string recipient; string amount; string memo; bool pay_ram = false; auto transfer = app.add_subcommand("transfer", localized("Transfer EOS from account to account"), false); transfer->add_option("sender", sender, localized("The account sending EOS"))->required(); transfer->add_option("recipient", recipient, localized("The account receiving EOS"))->required(); transfer->add_option("amount", amount, localized("The amount of EOS to send"))->required(); transfer->add_option("memo", memo, localized("The memo for the transfer")); transfer->add_option("--contract,-c", con, localized("The contract which controls the token")); transfer->add_flag("--pay-ram-to-open", pay_ram, localized("Pay ram to open recipient's token balance row")); add_standard_transaction_options(transfer, "sender@active"); transfer->set_callback([&] { if (tx_force_unique && memo.size() == 0) { // use the memo to add a nonce memo = generate_nonce_string(); tx_force_unique = false; } auto transfer_amount = to_asset(con, amount); auto transfer = create_transfer(con, sender, recipient, transfer_amount, memo); if (!pay_ram) { send_actions( { transfer }); } else { auto open_ = create_open(con, recipient, transfer_amount.get_symbol(), sender); send_actions( { open_, transfer } ); } }); // Net subcommand string new_host; auto net = app.add_subcommand( "net", localized("Interact with local p2p network connections"), false ); net->require_subcommand(); auto connect = net->add_subcommand("connect", localized("start a new connection to a peer"), false); connect->add_option("host", new_host, localized("The hostname:port to connect to."))->required(); connect->set_callback([&] { const auto& v = call(url, net_connect, new_host); std::cout << fc::json::to_pretty_string(v) << std::endl; }); auto disconnect = net->add_subcommand("disconnect", localized("close an existing connection"), false); disconnect->add_option("host", new_host, localized("The hostname:port to disconnect from."))->required(); disconnect->set_callback([&] { const auto& v = call(url, net_disconnect, new_host); std::cout << fc::json::to_pretty_string(v) << std::endl; }); auto status = net->add_subcommand("status", localized("status of existing connection"), false); status->add_option("host", new_host, localized("The hostname:port to query status of connection"))->required(); status->set_callback([&] { const auto& v = call(url, net_status, new_host); std::cout << fc::json::to_pretty_string(v) << std::endl; }); auto connections = net->add_subcommand("peers", localized("status of all existing peers"), false); connections->set_callback([&] { const auto& v = call(url, net_connections, new_host); std::cout << fc::json::to_pretty_string(v) << std::endl; }); // Wallet subcommand auto wallet = app.add_subcommand( "wallet", localized("Interact with local wallet"), false ); wallet->require_subcommand(); // create wallet string wallet_name = "default"; string password_file; auto createWallet = wallet->add_subcommand("create", localized("Create a new wallet locally"), false); createWallet->add_option("-n,--name", wallet_name, localized("The name of the new wallet"), true); createWallet->add_option("-f,--file", password_file, localized("Name of file to write wallet password output to. (Must be set, unless \"--to-console\" is passed")); createWallet->add_flag( "--to-console", print_console, localized("Print password to console.")); createWallet->set_callback([&wallet_name, &password_file, &print_console] { if (password_file.empty() && !print_console) { std::cerr << "ERROR: Either indicate a file using \"--file\" or pass \"--to-console\"" << std::endl; return; } const auto& v = call(wallet_url, wallet_create, wallet_name); std::cout << localized("Creating wallet: ${wallet_name}", ("wallet_name", wallet_name)) << std::endl; std::cout << localized("Save password to use in the future to unlock this wallet.") << std::endl; std::cout << localized("Without password imported keys will not be retrievable.") << std::endl; if (print_console) { std::cout << fc::json::to_pretty_string(v) << std::endl; } else { std::cerr << localized("saving password to ${filename}", ("filename", password_file)) << std::endl; std::ofstream out( password_file.c_str() ); out << fc::json::to_pretty_string(v); } }); // open wallet auto openWallet = wallet->add_subcommand("open", localized("Open an existing wallet"), false); openWallet->add_option("-n,--name", wallet_name, localized("The name of the wallet to open")); openWallet->set_callback([&wallet_name] { call(wallet_url, wallet_open, wallet_name); std::cout << localized("Opened: ${wallet_name}", ("wallet_name", wallet_name)) << std::endl; }); // lock wallet auto lockWallet = wallet->add_subcommand("lock", localized("Lock wallet"), false); lockWallet->add_option("-n,--name", wallet_name, localized("The name of the wallet to lock")); lockWallet->set_callback([&wallet_name] { call(wallet_url, wallet_lock, wallet_name); std::cout << localized("Locked: ${wallet_name}", ("wallet_name", wallet_name)) << std::endl; }); // lock all wallets auto locakAllWallets = wallet->add_subcommand("lock_all", localized("Lock all unlocked wallets"), false); locakAllWallets->set_callback([] { call(wallet_url, wallet_lock_all); std::cout << localized("Locked All Wallets") << std::endl; }); // unlock wallet string wallet_pw; auto unlockWallet = wallet->add_subcommand("unlock", localized("Unlock wallet"), false); unlockWallet->add_option("-n,--name", wallet_name, localized("The name of the wallet to unlock")); unlockWallet->add_option("--password", wallet_pw, localized("The password returned by wallet create")); unlockWallet->set_callback([&wallet_name, &wallet_pw] { prompt_for_wallet_password(wallet_pw, wallet_name); fc::variants vs = {fc::variant(wallet_name), fc::variant(wallet_pw)}; call(wallet_url, wallet_unlock, vs); std::cout << localized("Unlocked: ${wallet_name}", ("wallet_name", wallet_name)) << std::endl; }); // import keys into wallet string wallet_key_str; auto importWallet = wallet->add_subcommand("import", localized("Import private key into wallet"), false); importWallet->add_option("-n,--name", wallet_name, localized("The name of the wallet to import key into")); importWallet->add_option("--private-key", wallet_key_str, localized("Private key in WIF format to import")); importWallet->set_callback([&wallet_name, &wallet_key_str] { if( wallet_key_str.size() == 0 ) { std::cout << localized("private key: "); fc::set_console_echo(false); std::getline( std::cin, wallet_key_str, '\n' ); fc::set_console_echo(true); } private_key_type wallet_key; try { wallet_key = private_key_type( wallet_key_str ); } catch (...) { EOS_THROW(private_key_type_exception, "Invalid private key: ${private_key}", ("private_key", wallet_key_str)) } public_key_type pubkey = wallet_key.get_public_key(); fc::variants vs = {fc::variant(wallet_name), fc::variant(wallet_key)}; call(wallet_url, wallet_import_key, vs); std::cout << localized("imported private key for: ${pubkey}", ("pubkey", std::string(pubkey))) << std::endl; }); // remove keys from wallet string wallet_rm_key_str; auto removeKeyWallet = wallet->add_subcommand("remove_key", localized("Remove key from wallet"), false); removeKeyWallet->add_option("-n,--name", wallet_name, localized("The name of the wallet to remove key from")); removeKeyWallet->add_option("key", wallet_rm_key_str, localized("Public key in WIF format to remove"))->required(); removeKeyWallet->add_option("--password", wallet_pw, localized("The password returned by wallet create")); removeKeyWallet->set_callback([&wallet_name, &wallet_pw, &wallet_rm_key_str] { prompt_for_wallet_password(wallet_pw, wallet_name); public_key_type pubkey; try { pubkey = public_key_type( wallet_rm_key_str ); } catch (...) { EOS_THROW(public_key_type_exception, "Invalid public key: ${public_key}", ("public_key", wallet_rm_key_str)) } fc::variants vs = {fc::variant(wallet_name), fc::variant(wallet_pw), fc::variant(wallet_rm_key_str)}; call(wallet_url, wallet_remove_key, vs); std::cout << localized("removed private key for: ${pubkey}", ("pubkey", wallet_rm_key_str)) << std::endl; }); // create a key within wallet string wallet_create_key_type; auto createKeyInWallet = wallet->add_subcommand("create_key", localized("Create private key within wallet"), false); createKeyInWallet->add_option("-n,--name", wallet_name, localized("The name of the wallet to create key into"), true); createKeyInWallet->add_option("key_type", wallet_create_key_type, localized("Key type to create (K1/R1)"), true)->set_type_name("K1/R1"); createKeyInWallet->set_callback([&wallet_name, &wallet_create_key_type] { //an empty key type is allowed -- it will let the underlying wallet pick which type it prefers fc::variants vs = {fc::variant(wallet_name), fc::variant(wallet_create_key_type)}; const auto& v = call(wallet_url, wallet_create_key, vs); std::cout << localized("Created new private key with a public key of: ") << fc::json::to_pretty_string(v) << std::endl; }); // list wallets auto listWallet = wallet->add_subcommand("list", localized("List opened wallets, * = unlocked"), false); listWallet->set_callback([] { std::cout << localized("Wallets:") << std::endl; const auto& v = call(wallet_url, wallet_list); std::cout << fc::json::to_pretty_string(v) << std::endl; }); // list keys auto listKeys = wallet->add_subcommand("keys", localized("List of public keys from all unlocked wallets."), false); listKeys->set_callback([] { const auto& v = call(wallet_url, wallet_public_keys); std::cout << fc::json::to_pretty_string(v) << std::endl; }); // list private keys auto listPrivKeys = wallet->add_subcommand("private_keys", localized("List of private keys from an unlocked wallet in wif or PVT_R1 format."), false); listPrivKeys->add_option("-n,--name", wallet_name, localized("The name of the wallet to list keys from"), true); listPrivKeys->add_option("--password", wallet_pw, localized("The password returned by wallet create")); listPrivKeys->set_callback([&wallet_name, &wallet_pw] { prompt_for_wallet_password(wallet_pw, wallet_name); fc::variants vs = {fc::variant(wallet_name), fc::variant(wallet_pw)}; const auto& v = call(wallet_url, wallet_list_keys, vs); std::cout << fc::json::to_pretty_string(v) << std::endl; }); auto stopKeosd = wallet->add_subcommand("stop", localized("Stop keosd (doesn't work with nodeos)."), false); stopKeosd->set_callback([] { const auto& v = call(wallet_url, keosd_stop); if ( !v.is_object() || v.get_object().size() != 0 ) { //on success keosd responds with empty object std::cerr << fc::json::to_pretty_string(v) << std::endl; } else { std::cout << "OK" << std::endl; } }); // sign subcommand string trx_json_to_sign; string str_private_key; string str_chain_id; bool push_trx = false; auto sign = app.add_subcommand("sign", localized("Sign a transaction"), false); sign->add_option("transaction", trx_json_to_sign, localized("The JSON string or filename defining the transaction to sign"), true)->required(); sign->add_option("-k,--private-key", str_private_key, localized("The private key that will be used to sign the transaction")); sign->add_option("-c,--chain-id", str_chain_id, localized("The chain id that will be used to sign the transaction")); sign->add_flag( "-p,--push-transaction", push_trx, localized("Push transaction after signing")); sign->set_callback([&] { signed_transaction trx = json_from_file_or_string(trx_json_to_sign).as<signed_transaction>(); fc::optional<chain_id_type> chain_id; if( str_chain_id.size() == 0 ) { ilog( "grabbing chain_id from nodeos" ); auto info = get_info(); chain_id = info.chain_id; } else { chain_id = chain_id_type(str_chain_id); } if( str_private_key.size() == 0 ) { std::cerr << localized("private key: "); fc::set_console_echo(false); std::getline( std::cin, str_private_key, '\n' ); fc::set_console_echo(true); } auto priv_key = fc::crypto::private_key::regenerate(*utilities::wif_to_key(str_private_key)); trx.sign(priv_key, *chain_id); if(push_trx) { auto trx_result = call(push_txn_func, packed_transaction(trx, packed_transaction::none)); std::cout << fc::json::to_pretty_string(trx_result) << std::endl; } else { std::cout << fc::json::to_pretty_string(trx) << std::endl; } }); // Push subcommand auto push = app.add_subcommand("push", localized("Push arbitrary transactions to the blockchain"), false); push->require_subcommand(); // push action string contract_account; string action; string data; vector<string> permissions; auto actionsSubcommand = push->add_subcommand("action", localized("Push a transaction with a single action")); actionsSubcommand->fallthrough(false); actionsSubcommand->add_option("account", contract_account, localized("The account providing the contract to execute"), true)->required(); actionsSubcommand->add_option("action", action, localized("A JSON string or filename defining the action to execute on the contract"), true)->required(); actionsSubcommand->add_option("data", data, localized("The arguments to the contract"))->required(); add_standard_transaction_options(actionsSubcommand); actionsSubcommand->set_callback([&] { fc::variant action_args_var; if( !data.empty() ) { try { action_args_var = json_from_file_or_string(data, fc::json::relaxed_parser); } EOS_RETHROW_EXCEPTIONS(action_type_exception, "Fail to parse action JSON data='${data}'", ("data", data)) } auto accountPermissions = get_account_permissions(tx_permission); send_actions({chain::action{accountPermissions, contract_account, action, variant_to_bin( contract_account, action, action_args_var ) }}); }); // push transaction string trx_to_push; auto trxSubcommand = push->add_subcommand("transaction", localized("Push an arbitrary JSON transaction")); trxSubcommand->add_option("transaction", trx_to_push, localized("The JSON string or filename defining the transaction to push"))->required(); add_standard_transaction_options(trxSubcommand); trxSubcommand->set_callback([&] { fc::variant trx_var; try { trx_var = json_from_file_or_string(trx_to_push); } EOS_RETHROW_EXCEPTIONS(transaction_type_exception, "Fail to parse transaction JSON '${data}'", ("data",trx_to_push)) try { signed_transaction trx = trx_var.as<signed_transaction>(); std::cout << fc::json::to_pretty_string( push_transaction( trx )) << std::endl; } catch( fc::exception& ) { // unable to convert so try via abi signed_transaction trx; abi_serializer::from_variant( trx_var, trx, abi_serializer_resolver, abi_serializer_max_time ); std::cout << fc::json::to_pretty_string( push_transaction( trx )) << std::endl; } }); string trxsJson; auto trxsSubcommand = push->add_subcommand("transactions", localized("Push an array of arbitrary JSON transactions")); trxsSubcommand->add_option("transactions", trxsJson, localized("The JSON string or filename defining the array of the transactions to push"))->required(); trxsSubcommand->set_callback([&] { fc::variant trx_var; try { trx_var = json_from_file_or_string(trxsJson); } EOS_RETHROW_EXCEPTIONS(transaction_type_exception, "Fail to parse transaction JSON '${data}'", ("data",trxsJson)) auto trxs_result = call(push_txns_func, trx_var); std::cout << fc::json::to_pretty_string(trxs_result) << std::endl; }); // multisig subcommand auto msig = app.add_subcommand("multisig", localized("Multisig contract commands"), false); msig->require_subcommand(); // multisig propose string proposal_name; string requested_perm; string transaction_perm; string proposed_transaction; string proposed_contract; string proposed_action; string proposer; unsigned int proposal_expiration_hours = 24; CLI::callback_t parse_expiration_hours = [&](CLI::results_t res) -> bool { unsigned int value_s; if (res.size() == 0 || !CLI::detail::lexical_cast(res[0], value_s)) { return false; } proposal_expiration_hours = static_cast<uint64_t>(value_s); return true; }; auto propose_action = msig->add_subcommand("propose", localized("Propose action")); add_standard_transaction_options(propose_action); propose_action->add_option("proposal_name", proposal_name, localized("proposal name (string)"))->required(); propose_action->add_option("requested_permissions", requested_perm, localized("The JSON string or filename defining requested permissions"))->required(); propose_action->add_option("trx_permissions", transaction_perm, localized("The JSON string or filename defining transaction permissions"))->required(); propose_action->add_option("contract", proposed_contract, localized("contract to which deferred transaction should be delivered"))->required(); propose_action->add_option("action", proposed_action, localized("action of deferred transaction"))->required(); propose_action->add_option("data", proposed_transaction, localized("The JSON string or filename defining the action to propose"))->required(); propose_action->add_option("proposer", proposer, localized("Account proposing the transaction")); propose_action->add_option("proposal_expiration", parse_expiration_hours, localized("Proposal expiration interval in hours")); propose_action->set_callback([&] { fc::variant requested_perm_var; try { requested_perm_var = json_from_file_or_string(requested_perm); } EOS_RETHROW_EXCEPTIONS(transaction_type_exception, "Fail to parse permissions JSON '${data}'", ("data",requested_perm)) fc::variant transaction_perm_var; try { transaction_perm_var = json_from_file_or_string(transaction_perm); } EOS_RETHROW_EXCEPTIONS(transaction_type_exception, "Fail to parse permissions JSON '${data}'", ("data",transaction_perm)) fc::variant trx_var; try { trx_var = json_from_file_or_string(proposed_transaction); } EOS_RETHROW_EXCEPTIONS(transaction_type_exception, "Fail to parse transaction JSON '${data}'", ("data",proposed_transaction)) transaction proposed_trx = trx_var.as<transaction>(); bytes proposed_trx_serialized = variant_to_bin( proposed_contract, proposed_action, trx_var ); vector<permission_level> reqperm; try { reqperm = requested_perm_var.as<vector<permission_level>>(); } EOS_RETHROW_EXCEPTIONS(transaction_type_exception, "Wrong requested permissions format: '${data}'", ("data",requested_perm_var)); vector<permission_level> trxperm; try { trxperm = transaction_perm_var.as<vector<permission_level>>(); } EOS_RETHROW_EXCEPTIONS(transaction_type_exception, "Wrong transaction permissions format: '${data}'", ("data",transaction_perm_var)); auto accountPermissions = get_account_permissions(tx_permission); if (accountPermissions.empty()) { if (!proposer.empty()) { accountPermissions = vector<permission_level>{{proposer, config::active_name}}; } else { EOS_THROW(missing_auth_exception, "Authority is not provided (either by multisig parameter <proposer> or -p)"); } } if (proposer.empty()) { proposer = name(accountPermissions.at(0).actor).to_string(); } transaction trx; trx.expiration = fc::time_point_sec( fc::time_point::now() + fc::hours(proposal_expiration_hours) ); trx.ref_block_num = 0; trx.ref_block_prefix = 0; trx.max_net_usage_words = 0; trx.max_cpu_usage_ms = 0; trx.delay_sec = 0; trx.actions = { chain::action(trxperm, name(proposed_contract), name(proposed_action), proposed_trx_serialized) }; fc::to_variant(trx, trx_var); auto args = fc::mutable_variant_object() ("proposer", proposer ) ("proposal_name", proposal_name) ("requested", requested_perm_var) ("trx", trx_var); send_actions({chain::action{accountPermissions, "eosio.msig", "propose", variant_to_bin( N(eosio.msig), N(propose), args ) }}); }); //multisige propose transaction auto propose_trx = msig->add_subcommand("propose_trx", localized("Propose transaction")); add_standard_transaction_options(propose_trx); propose_trx->add_option("proposal_name", proposal_name, localized("proposal name (string)"))->required(); propose_trx->add_option("requested_permissions", requested_perm, localized("The JSON string or filename defining requested permissions"))->required(); propose_trx->add_option("transaction", trx_to_push, localized("The JSON string or filename defining the transaction to push"))->required(); propose_trx->add_option("proposer", proposer, localized("Account proposing the transaction")); propose_trx->set_callback([&] { fc::variant requested_perm_var; try { requested_perm_var = json_from_file_or_string(requested_perm); } EOS_RETHROW_EXCEPTIONS(transaction_type_exception, "Fail to parse permissions JSON '${data}'", ("data",requested_perm)) fc::variant trx_var; try { trx_var = json_from_file_or_string(trx_to_push); } EOS_RETHROW_EXCEPTIONS(transaction_type_exception, "Fail to parse transaction JSON '${data}'", ("data",trx_to_push)) auto accountPermissions = get_account_permissions(tx_permission); if (accountPermissions.empty()) { if (!proposer.empty()) { accountPermissions = vector<permission_level>{{proposer, config::active_name}}; } else { EOS_THROW(missing_auth_exception, "Authority is not provided (either by multisig parameter <proposer> or -p)"); } } if (proposer.empty()) { proposer = name(accountPermissions.at(0).actor).to_string(); } auto args = fc::mutable_variant_object() ("proposer", proposer ) ("proposal_name", proposal_name) ("requested", requested_perm_var) ("trx", trx_var); send_actions({chain::action{accountPermissions, "eosio.msig", "propose", variant_to_bin( N(eosio.msig), N(propose), args ) }}); }); // multisig review auto review = msig->add_subcommand("review", localized("Review transaction")); review->add_option("proposer", proposer, localized("proposer name (string)"))->required(); review->add_option("proposal_name", proposal_name, localized("proposal name (string)"))->required(); review->set_callback([&] { auto result = call(get_table_func, fc::mutable_variant_object("json", true) ("code", "eosio.msig") ("scope", proposer) ("table", "proposal") ("table_key", "") ("lower_bound", eosio::chain::string_to_name(proposal_name.c_str())) ("upper_bound", "") ("limit", 1) ); //std::cout << fc::json::to_pretty_string(result) << std::endl; fc::variants rows = result.get_object()["rows"].get_array(); if (rows.empty()) { std::cerr << "Proposal not found" << std::endl; return; } fc::mutable_variant_object obj = rows[0].get_object(); if (obj["proposal_name"] != proposal_name) { std::cerr << "Proposal not found" << std::endl; return; } auto trx_hex = obj["packed_transaction"].as_string(); vector<char> trx_blob(trx_hex.size()/2); fc::from_hex(trx_hex, trx_blob.data(), trx_blob.size()); transaction trx = fc::raw::unpack<transaction>(trx_blob); fc::variant trx_var; abi_serializer abi; abi.to_variant(trx, trx_var, abi_serializer_resolver, abi_serializer_max_time); obj["transaction"] = trx_var; std::cout << fc::json::to_pretty_string(obj) << std::endl; }); string perm; auto approve_or_unapprove = [&](const string& action) { fc::variant perm_var; try { perm_var = json_from_file_or_string(perm); } EOS_RETHROW_EXCEPTIONS(transaction_type_exception, "Fail to parse permissions JSON '${data}'", ("data",perm)) auto args = fc::mutable_variant_object() ("proposer", proposer) ("proposal_name", proposal_name) ("level", perm_var); auto accountPermissions = tx_permission.empty() ? vector<chain::permission_level>{{sender,config::active_name}} : get_account_permissions(tx_permission); send_actions({chain::action{accountPermissions, "eosio.msig", action, variant_to_bin( N(eosio.msig), action, args ) }}); }; // multisig approve auto approve = msig->add_subcommand("approve", localized("Approve proposed transaction")); add_standard_transaction_options(approve); approve->add_option("proposer", proposer, localized("proposer name (string)"))->required(); approve->add_option("proposal_name", proposal_name, localized("proposal name (string)"))->required(); approve->add_option("permissions", perm, localized("The JSON string of filename defining approving permissions"))->required(); approve->set_callback([&] { approve_or_unapprove("approve"); }); // multisig unapprove auto unapprove = msig->add_subcommand("unapprove", localized("Unapprove proposed transaction")); add_standard_transaction_options(unapprove); unapprove->add_option("proposer", proposer, localized("proposer name (string)"))->required(); unapprove->add_option("proposal_name", proposal_name, localized("proposal name (string)"))->required(); unapprove->add_option("permissions", perm, localized("The JSON string of filename defining approving permissions"))->required(); unapprove->set_callback([&] { approve_or_unapprove("unapprove"); }); // multisig cancel string canceler; auto cancel = msig->add_subcommand("cancel", localized("Cancel proposed transaction")); add_standard_transaction_options(cancel); cancel->add_option("proposer", proposer, localized("proposer name (string)"))->required(); cancel->add_option("proposal_name", proposal_name, localized("proposal name (string)"))->required(); cancel->add_option("canceler", canceler, localized("canceler name (string)")); cancel->set_callback([&]() { auto accountPermissions = get_account_permissions(tx_permission); if (accountPermissions.empty()) { if (!canceler.empty()) { accountPermissions = vector<permission_level>{{canceler, config::active_name}}; } else { EOS_THROW(missing_auth_exception, "Authority is not provided (either by multisig parameter <canceler> or -p)"); } } if (canceler.empty()) { canceler = name(accountPermissions.at(0).actor).to_string(); } auto args = fc::mutable_variant_object() ("proposer", proposer) ("proposal_name", proposal_name) ("canceler", canceler); send_actions({chain::action{accountPermissions, "eosio.msig", "cancel", variant_to_bin( N(eosio.msig), N(cancel), args ) }}); } ); // multisig exec string executer; auto exec = msig->add_subcommand("exec", localized("Execute proposed transaction")); add_standard_transaction_options(exec); exec->add_option("proposer", proposer, localized("proposer name (string)"))->required(); exec->add_option("proposal_name", proposal_name, localized("proposal name (string)"))->required(); exec->add_option("executer", executer, localized("account paying for execution (string)")); exec->set_callback([&] { auto accountPermissions = get_account_permissions(tx_permission); if (accountPermissions.empty()) { if (!executer.empty()) { accountPermissions = vector<permission_level>{{executer, config::active_name}}; } else { EOS_THROW(missing_auth_exception, "Authority is not provided (either by multisig parameter <executer> or -p)"); } } if (executer.empty()) { executer = name(accountPermissions.at(0).actor).to_string(); } auto args = fc::mutable_variant_object() ("proposer", proposer ) ("proposal_name", proposal_name) ("executer", executer); send_actions({chain::action{accountPermissions, "eosio.msig", "exec", variant_to_bin( N(eosio.msig), N(exec), args ) }}); } ); // wrap subcommand auto wrap = app.add_subcommand("wrap", localized("Wrap contract commands"), false); wrap->require_subcommand(); // wrap exec con = "eosio.wrap"; executer = ""; string trx_to_exec; auto wrap_exec = wrap->add_subcommand("exec", localized("Execute a transaction while bypassing authorization checks")); add_standard_transaction_options(wrap_exec); wrap_exec->add_option("executer", executer, localized("Account executing the transaction and paying for the deferred transaction RAM"))->required(); wrap_exec->add_option("transaction", trx_to_exec, localized("The JSON string or filename defining the transaction to execute"))->required(); wrap_exec->add_option("--contract,-c", con, localized("The contract which controls the wrap contract")); wrap_exec->set_callback([&] { fc::variant trx_var; try { trx_var = json_from_file_or_string(trx_to_exec); } EOS_RETHROW_EXCEPTIONS(transaction_type_exception, "Fail to parse transaction JSON '${data}'", ("data",trx_to_exec)) auto accountPermissions = get_account_permissions(tx_permission); if( accountPermissions.empty() ) { accountPermissions = vector<permission_level>{{executer, config::active_name}, {con, config::active_name}}; } auto args = fc::mutable_variant_object() ("executer", executer ) ("trx", trx_var); send_actions({chain::action{accountPermissions, con, "exec", variant_to_bin( con, N(exec), args ) }}); }); // system subcommand auto system = app.add_subcommand("system", localized("Send eosio.system contract action to the blockchain."), false); system->require_subcommand(); auto createAccountSystem = create_account_subcommand( system, false /*simple*/ ); auto registerProducer = register_producer_subcommand(system); auto unregisterProducer = unregister_producer_subcommand(system); auto voteProducer = system->add_subcommand("voteproducer", localized("Vote for a producer")); voteProducer->require_subcommand(); auto voteProxy = vote_producer_proxy_subcommand(voteProducer); auto voteProducers = vote_producers_subcommand(voteProducer); auto approveProducer = approve_producer_subcommand(voteProducer); auto unapproveProducer = unapprove_producer_subcommand(voteProducer); auto listProducers = list_producers_subcommand(system); auto delegateBandWidth = delegate_bandwidth_subcommand(system); auto undelegateBandWidth = undelegate_bandwidth_subcommand(system); auto listBandWidth = list_bw_subcommand(system); auto bidname = bidname_subcommand(system); auto bidnameinfo = bidname_info_subcommand(system); auto biyram = buyram_subcommand(system); auto sellram = sellram_subcommand(system); auto claimRewards = claimrewards_subcommand(system); auto regProxy = regproxy_subcommand(system); auto unregProxy = unregproxy_subcommand(system); auto cancelDelay = canceldelay_subcommand(system); try { app.parse(argc, argv); } catch (const CLI::ParseError &e) { return app.exit(e); } catch (const explained_exception& e) { return 1; } catch (connection_exception& e) { if (verbose_errors) { elog("connect error: ${e}", ("e", e.to_detail_string())); } return 1; } catch (const fc::exception& e) { // attempt to extract the error code if one is present if (!print_recognized_errors(e, verbose_errors)) { // Error is not recognized if (!print_help_text(e) || verbose_errors) { elog("Failed with error: ${e}", ("e", verbose_errors ? e.to_detail_string() : e.to_string())); } } return 1; } return 0; } fix bug with cleos wrap change /** * @file * @copyright defined in eos/LICENSE.txt * @defgroup eosclienttool EOSIO Command Line Client Reference * @brief Tool for sending transactions and querying state from @ref nodeos * @ingroup eosclienttool */ /** @defgroup eosclienttool @section intro Introduction to cleos `cleos` is a command line tool that interfaces with the REST api exposed by @ref nodeos. In order to use `cleos` you will need to have a local copy of `nodeos` running and configured to load the 'eosio::chain_api_plugin'. cleos contains documentation for all of its commands. For a list of all commands known to cleos, simply run it with no arguments: ``` $ ./cleos Command Line Interface to EOSIO Client Usage: programs/cleos/cleos [OPTIONS] SUBCOMMAND Options: -h,--help Print this help message and exit -u,--url TEXT=http://localhost:8888/ the http/https URL where nodeos is running --wallet-url TEXT=http://localhost:8888/ the http/https URL where keosd is running -r,--header pass specific HTTP header, repeat this option to pass multiple headers -n,--no-verify don't verify peer certificate when using HTTPS -v,--verbose output verbose actions on error Subcommands: version Retrieve version information create Create various items, on and off the blockchain get Retrieve various items and information from the blockchain set Set or update blockchain state transfer Transfer EOS from account to account net Interact with local p2p network connections wallet Interact with local wallet sign Sign a transaction push Push arbitrary transactions to the blockchain multisig Multisig contract commands ``` To get help with any particular subcommand, run it with no arguments as well: ``` $ ./cleos create Create various items, on and off the blockchain Usage: ./cleos create SUBCOMMAND Subcommands: key Create a new keypair and print the public and private keys account Create a new account on the blockchain $ ./cleos create account Create a new account on the blockchain Usage: ./cleos create account [OPTIONS] creator name OwnerKey ActiveKey Positionals: creator TEXT The name of the account creating the new account name TEXT The name of the new account OwnerKey TEXT The owner public key for the new account ActiveKey TEXT The active public key for the new account Options: -x,--expiration set the time in seconds before a transaction expires, defaults to 30s -f,--force-unique force the transaction to be unique. this will consume extra bandwidth and remove any protections against accidently issuing the same transaction multiple times -s,--skip-sign Specify if unlocked wallet keys should be used to sign transaction -d,--dont-broadcast don't broadcast transaction to the network (just print to stdout) -p,--permission TEXT ... An account and permission level to authorize, as in 'account@permission' (defaults to 'creator@active') ``` */ #include <pwd.h> #include <string> #include <vector> #include <regex> #include <iostream> #include <fc/crypto/hex.hpp> #include <fc/variant.hpp> #include <fc/io/datastream.hpp> #include <fc/io/json.hpp> #include <fc/io/console.hpp> #include <fc/exception/exception.hpp> #include <fc/variant_object.hpp> #include <eosio/utilities/key_conversion.hpp> #include <eosio/chain/name.hpp> #include <eosio/chain/config.hpp> #include <eosio/chain/wast_to_wasm.hpp> #include <eosio/chain/trace.hpp> #include <eosio/chain_plugin/chain_plugin.hpp> #include <eosio/chain/contract_types.hpp> #pragma push_macro("N") #undef N #include <boost/asio.hpp> #include <boost/format.hpp> #include <boost/dll/runtime_symbol_info.hpp> #include <boost/filesystem.hpp> #include <boost/process.hpp> #include <boost/process/spawn.hpp> #include <boost/range/algorithm/find_if.hpp> #include <boost/range/algorithm/sort.hpp> #include <boost/range/adaptor/transformed.hpp> #include <boost/algorithm/string/predicate.hpp> #include <boost/algorithm/string/split.hpp> #include <boost/range/algorithm/copy.hpp> #include <boost/algorithm/string/classification.hpp> #pragma pop_macro("N") #include <Inline/BasicTypes.h> #include <IR/Module.h> #include <IR/Validate.h> #include <WASM/WASM.h> #include <Runtime/Runtime.h> #include <fc/io/fstream.hpp> #include "CLI11.hpp" #include "help_text.hpp" #include "localize.hpp" #include "config.hpp" #include "httpc.hpp" using namespace std; using namespace eosio; using namespace eosio::chain; using namespace eosio::utilities; using namespace eosio::client::help; using namespace eosio::client::http; using namespace eosio::client::localize; using namespace eosio::client::config; using namespace boost::filesystem; FC_DECLARE_EXCEPTION( explained_exception, 9000000, "explained exception, see error log" ); FC_DECLARE_EXCEPTION( localized_exception, 10000000, "an error occured" ); #define EOSC_ASSERT( TEST, ... ) \ FC_EXPAND_MACRO( \ FC_MULTILINE_MACRO_BEGIN \ if( UNLIKELY(!(TEST)) ) \ { \ std::cerr << localized( __VA_ARGS__ ) << std::endl; \ FC_THROW_EXCEPTION( explained_exception, #TEST ); \ } \ FC_MULTILINE_MACRO_END \ ) //copy pasta from keosd's main.cpp bfs::path determine_home_directory() { bfs::path home; struct passwd* pwd = getpwuid(getuid()); if(pwd) { home = pwd->pw_dir; } else { home = getenv("HOME"); } if(home.empty()) home = "./"; return home; } string url = "http://127.0.0.1:8888/"; string default_wallet_url = "unix://" + (determine_home_directory() / "eosio-wallet" / (string(key_store_executable_name) + ".sock")).string(); string wallet_url; //to be set to default_wallet_url in main bool no_verify = false; vector<string> headers; auto tx_expiration = fc::seconds(30); const fc::microseconds abi_serializer_max_time = fc::seconds(10); // No risk to client side serialization taking a long time string tx_ref_block_num_or_id; bool tx_force_unique = false; bool tx_dont_broadcast = false; bool tx_return_packed = false; bool tx_skip_sign = false; bool tx_print_json = false; bool print_request = false; bool print_response = false; bool no_auto_keosd = false; uint8_t tx_max_cpu_usage = 0; uint32_t tx_max_net_usage = 0; uint32_t delaysec = 0; vector<string> tx_permission; eosio::client::http::http_context context; void add_standard_transaction_options(CLI::App* cmd, string default_permission = "") { CLI::callback_t parse_expiration = [](CLI::results_t res) -> bool { double value_s; if (res.size() == 0 || !CLI::detail::lexical_cast(res[0], value_s)) { return false; } tx_expiration = fc::seconds(static_cast<uint64_t>(value_s)); return true; }; cmd->add_option("-x,--expiration", parse_expiration, localized("set the time in seconds before a transaction expires, defaults to 30s")); cmd->add_flag("-f,--force-unique", tx_force_unique, localized("force the transaction to be unique. this will consume extra bandwidth and remove any protections against accidently issuing the same transaction multiple times")); cmd->add_flag("-s,--skip-sign", tx_skip_sign, localized("Specify if unlocked wallet keys should be used to sign transaction")); cmd->add_flag("-j,--json", tx_print_json, localized("print result as json")); cmd->add_flag("-d,--dont-broadcast", tx_dont_broadcast, localized("don't broadcast transaction to the network (just print to stdout)")); cmd->add_flag("--return-packed", tx_return_packed, localized("used in conjunction with --dont-broadcast to get the packed transaction")); cmd->add_option("-r,--ref-block", tx_ref_block_num_or_id, (localized("set the reference block num or block id used for TAPOS (Transaction as Proof-of-Stake)"))); string msg = "An account and permission level to authorize, as in 'account@permission'"; if(!default_permission.empty()) msg += " (defaults to '" + default_permission + "')"; cmd->add_option("-p,--permission", tx_permission, localized(msg.c_str())); cmd->add_option("--max-cpu-usage-ms", tx_max_cpu_usage, localized("set an upper limit on the milliseconds of cpu usage budget, for the execution of the transaction (defaults to 0 which means no limit)")); cmd->add_option("--max-net-usage", tx_max_net_usage, localized("set an upper limit on the net usage budget, in bytes, for the transaction (defaults to 0 which means no limit)")); cmd->add_option("--delay-sec", delaysec, localized("set the delay_sec seconds, defaults to 0s")); } vector<chain::permission_level> get_account_permissions(const vector<string>& permissions) { auto fixedPermissions = permissions | boost::adaptors::transformed([](const string& p) { vector<string> pieces; split(pieces, p, boost::algorithm::is_any_of("@")); if( pieces.size() == 1 ) pieces.push_back( "active" ); return chain::permission_level{ .actor = pieces[0], .permission = pieces[1] }; }); vector<chain::permission_level> accountPermissions; boost::range::copy(fixedPermissions, back_inserter(accountPermissions)); return accountPermissions; } template<typename T> fc::variant call( const std::string& url, const std::string& path, const T& v ) { try { auto sp = std::make_unique<eosio::client::http::connection_param>(context, parse_url(url) + path, no_verify ? false : true, headers); return eosio::client::http::do_http_call(*sp, fc::variant(v), print_request, print_response ); } catch(boost::system::system_error& e) { if(url == ::url) std::cerr << localized("Failed to connect to nodeos at ${u}; is nodeos running?", ("u", url)) << std::endl; else if(url == ::wallet_url) std::cerr << localized("Failed to connect to keosd at ${u}; is keosd running?", ("u", url)) << std::endl; throw connection_exception(fc::log_messages{FC_LOG_MESSAGE(error, e.what())}); } } template<typename T> fc::variant call( const std::string& path, const T& v ) { return call( url, path, fc::variant(v) ); } template<> fc::variant call( const std::string& url, const std::string& path) { return call( url, path, fc::variant() ); } eosio::chain_apis::read_only::get_info_results get_info() { return call(url, get_info_func).as<eosio::chain_apis::read_only::get_info_results>(); } string generate_nonce_string() { return fc::to_string(fc::time_point::now().time_since_epoch().count()); } chain::action generate_nonce_action() { return chain::action( {}, config::null_account_name, "nonce", fc::raw::pack(fc::time_point::now().time_since_epoch().count())); } void prompt_for_wallet_password(string& pw, const string& name) { if(pw.size() == 0 && name != "SecureEnclave") { std::cout << localized("password: "); fc::set_console_echo(false); std::getline( std::cin, pw, '\n' ); fc::set_console_echo(true); } } fc::variant determine_required_keys(const signed_transaction& trx) { // TODO better error checking //wdump((trx)); const auto& public_keys = call(wallet_url, wallet_public_keys); auto get_arg = fc::mutable_variant_object ("transaction", (transaction)trx) ("available_keys", public_keys); const auto& required_keys = call(get_required_keys, get_arg); return required_keys["required_keys"]; } void sign_transaction(signed_transaction& trx, fc::variant& required_keys, const chain_id_type& chain_id) { fc::variants sign_args = {fc::variant(trx), required_keys, fc::variant(chain_id)}; const auto& signed_trx = call(wallet_url, wallet_sign_trx, sign_args); trx = signed_trx.as<signed_transaction>(); } fc::variant push_transaction( signed_transaction& trx, int32_t extra_kcpu = 1000, packed_transaction::compression_type compression = packed_transaction::none ) { auto info = get_info(); if (trx.signatures.size() == 0) { // #5445 can't change txn content if already signed trx.expiration = info.head_block_time + tx_expiration; // Set tapos, default to last irreversible block if it's not specified by the user block_id_type ref_block_id = info.last_irreversible_block_id; try { fc::variant ref_block; if (!tx_ref_block_num_or_id.empty()) { ref_block = call(get_block_func, fc::mutable_variant_object("block_num_or_id", tx_ref_block_num_or_id)); ref_block_id = ref_block["id"].as<block_id_type>(); } } EOS_RETHROW_EXCEPTIONS(invalid_ref_block_exception, "Invalid reference block num or id: ${block_num_or_id}", ("block_num_or_id", tx_ref_block_num_or_id)); trx.set_reference_block(ref_block_id); if (tx_force_unique) { trx.context_free_actions.emplace_back( generate_nonce_action() ); } trx.max_cpu_usage_ms = tx_max_cpu_usage; trx.max_net_usage_words = (tx_max_net_usage + 7)/8; trx.delay_sec = delaysec; } if (!tx_skip_sign) { auto required_keys = determine_required_keys(trx); sign_transaction(trx, required_keys, info.chain_id); } if (!tx_dont_broadcast) { return call(push_txn_func, packed_transaction(trx, compression)); } else { if (!tx_return_packed) { return fc::variant(trx); } else { return fc::variant(packed_transaction(trx, compression)); } } } fc::variant push_actions(std::vector<chain::action>&& actions, int32_t extra_kcpu, packed_transaction::compression_type compression = packed_transaction::none ) { signed_transaction trx; trx.actions = std::forward<decltype(actions)>(actions); return push_transaction(trx, extra_kcpu, compression); } void print_action( const fc::variant& at ) { const auto& receipt = at["receipt"]; auto receiver = receipt["receiver"].as_string(); const auto& act = at["act"].get_object(); auto code = act["account"].as_string(); auto func = act["name"].as_string(); auto args = fc::json::to_string( act["data"] ); auto console = at["console"].as_string(); /* if( code == "eosio" && func == "setcode" ) args = args.substr(40)+"..."; if( name(code) == config::system_account_name && func == "setabi" ) args = args.substr(40)+"..."; */ if( args.size() > 100 ) args = args.substr(0,100) + "..."; cout << "#" << std::setw(14) << right << receiver << " <= " << std::setw(28) << std::left << (code +"::" + func) << " " << args << "\n"; if( console.size() ) { std::stringstream ss(console); string line; std::getline( ss, line ); cout << ">> " << line << "\n"; } } //resolver for ABI serializer to decode actions in proposed transaction in multisig contract auto abi_serializer_resolver = [](const name& account) -> optional<abi_serializer> { static unordered_map<account_name, optional<abi_serializer> > abi_cache; auto it = abi_cache.find( account ); if ( it == abi_cache.end() ) { auto result = call(get_abi_func, fc::mutable_variant_object("account_name", account)); auto abi_results = result.as<eosio::chain_apis::read_only::get_abi_results>(); optional<abi_serializer> abis; if( abi_results.abi.valid() ) { abis.emplace( *abi_results.abi, abi_serializer_max_time ); } else { std::cerr << "ABI for contract " << account.to_string() << " not found. Action data will be shown in hex only." << std::endl; } abi_cache.emplace( account, abis ); return abis; } return it->second; }; bytes variant_to_bin( const account_name& account, const action_name& action, const fc::variant& action_args_var ) { auto abis = abi_serializer_resolver( account ); FC_ASSERT( abis.valid(), "No ABI found for ${contract}", ("contract", account)); auto action_type = abis->get_action_type( action ); FC_ASSERT( !action_type.empty(), "Unknown action ${action} in contract ${contract}", ("action", action)( "contract", account )); return abis->variant_to_binary( action_type, action_args_var, abi_serializer_max_time ); } fc::variant bin_to_variant( const account_name& account, const action_name& action, const bytes& action_args) { auto abis = abi_serializer_resolver( account ); FC_ASSERT( abis.valid(), "No ABI found for ${contract}", ("contract", account)); auto action_type = abis->get_action_type( action ); FC_ASSERT( !action_type.empty(), "Unknown action ${action} in contract ${contract}", ("action", action)( "contract", account )); return abis->binary_to_variant( action_type, action_args, abi_serializer_max_time ); } fc::variant json_from_file_or_string(const string& file_or_str, fc::json::parse_type ptype = fc::json::legacy_parser) { regex r("^[ \t]*[\{\[]"); if ( !regex_search(file_or_str, r) && fc::is_regular_file(file_or_str) ) { return fc::json::from_file(file_or_str, ptype); } else { return fc::json::from_string(file_or_str, ptype); } } bytes json_or_file_to_bin( const account_name& account, const action_name& action, const string& data_or_filename ) { fc::variant action_args_var; if( !data_or_filename.empty() ) { try { action_args_var = json_from_file_or_string(data_or_filename, fc::json::relaxed_parser); } EOS_RETHROW_EXCEPTIONS(action_type_exception, "Fail to parse action JSON data='${data}'", ("data", data_or_filename)); } return variant_to_bin( account, action, action_args_var ); } void print_action_tree( const fc::variant& action ) { print_action( action ); const auto& inline_traces = action["inline_traces"].get_array(); for( const auto& t : inline_traces ) { print_action_tree( t ); } } void print_result( const fc::variant& result ) { try { if (result.is_object() && result.get_object().contains("processed")) { const auto& processed = result["processed"]; const auto& transaction_id = processed["id"].as_string(); string status = processed["receipt"].is_object() ? processed["receipt"]["status"].as_string() : "failed"; int64_t net = -1; int64_t cpu = -1; if( processed.get_object().contains( "receipt" )) { const auto& receipt = processed["receipt"]; if( receipt.is_object()) { net = receipt["net_usage_words"].as_int64() * 8; cpu = receipt["cpu_usage_us"].as_int64(); } } cerr << status << " transaction: " << transaction_id << " "; if( net < 0 ) { cerr << "<unknown>"; } else { cerr << net; } cerr << " bytes "; if( cpu < 0 ) { cerr << "<unknown>"; } else { cerr << cpu; } cerr << " us\n"; if( status == "failed" ) { auto soft_except = processed["except"].as<optional<fc::exception>>(); if( soft_except ) { edump((soft_except->to_detail_string())); } } else { const auto& actions = processed["action_traces"].get_array(); for( const auto& a : actions ) { print_action_tree( a ); } wlog( "\rwarning: transaction executed locally, but may not be confirmed by the network yet" ); } } else { cerr << fc::json::to_pretty_string( result ) << endl; } } FC_CAPTURE_AND_RETHROW( (result) ) } using std::cout; void send_actions(std::vector<chain::action>&& actions, int32_t extra_kcpu = 1000, packed_transaction::compression_type compression = packed_transaction::none ) { auto result = push_actions( move(actions), extra_kcpu, compression); if( tx_print_json ) { cout << fc::json::to_pretty_string( result ) << endl; } else { print_result( result ); } } void send_transaction( signed_transaction& trx, int32_t extra_kcpu, packed_transaction::compression_type compression = packed_transaction::none ) { auto result = push_transaction(trx, extra_kcpu, compression); if( tx_print_json ) { cout << fc::json::to_pretty_string( result ) << endl; } else { print_result( result ); } } chain::action create_newaccount(const name& creator, const name& newaccount, public_key_type owner, public_key_type active) { return action { tx_permission.empty() ? vector<chain::permission_level>{{creator,config::active_name}} : get_account_permissions(tx_permission), eosio::chain::newaccount{ .creator = creator, .name = newaccount, .owner = eosio::chain::authority{1, {{owner, 1}}, {}}, .active = eosio::chain::authority{1, {{active, 1}}, {}} } }; } chain::action create_action(const vector<permission_level>& authorization, const account_name& code, const action_name& act, const fc::variant& args) { return chain::action{authorization, code, act, variant_to_bin(code, act, args)}; } chain::action create_buyram(const name& creator, const name& newaccount, const asset& quantity) { fc::variant act_payload = fc::mutable_variant_object() ("payer", creator.to_string()) ("receiver", newaccount.to_string()) ("quant", quantity.to_string()); return create_action(tx_permission.empty() ? vector<chain::permission_level>{{creator,config::active_name}} : get_account_permissions(tx_permission), config::system_account_name, N(buyram), act_payload); } chain::action create_buyrambytes(const name& creator, const name& newaccount, uint32_t numbytes) { fc::variant act_payload = fc::mutable_variant_object() ("payer", creator.to_string()) ("receiver", newaccount.to_string()) ("bytes", numbytes); return create_action(tx_permission.empty() ? vector<chain::permission_level>{{creator,config::active_name}} : get_account_permissions(tx_permission), config::system_account_name, N(buyrambytes), act_payload); } chain::action create_delegate(const name& from, const name& receiver, const asset& net, const asset& cpu, bool transfer) { fc::variant act_payload = fc::mutable_variant_object() ("from", from.to_string()) ("receiver", receiver.to_string()) ("stake_net_quantity", net.to_string()) ("stake_cpu_quantity", cpu.to_string()) ("transfer", transfer); return create_action(tx_permission.empty() ? vector<chain::permission_level>{{from,config::active_name}} : get_account_permissions(tx_permission), config::system_account_name, N(delegatebw), act_payload); } fc::variant regproducer_variant(const account_name& producer, const public_key_type& key, const string& url, uint16_t location) { return fc::mutable_variant_object() ("producer", producer) ("producer_key", key) ("url", url) ("location", location) ; } chain::action create_open(const string& contract, const name& owner, symbol sym, const name& ram_payer) { auto open_ = fc::mutable_variant_object ("owner", owner) ("symbol", sym) ("ram_payer", ram_payer); return action { tx_permission.empty() ? vector<chain::permission_level>{{ram_payer,config::active_name}} : get_account_permissions(tx_permission), contract, "open", variant_to_bin( contract, N(open), open_ ) }; } chain::action create_transfer(const string& contract, const name& sender, const name& recipient, asset amount, const string& memo ) { auto transfer = fc::mutable_variant_object ("from", sender) ("to", recipient) ("quantity", amount) ("memo", memo); return action { tx_permission.empty() ? vector<chain::permission_level>{{sender,config::active_name}} : get_account_permissions(tx_permission), contract, "transfer", variant_to_bin( contract, N(transfer), transfer ) }; } chain::action create_setabi(const name& account, const bytes& abi) { return action { tx_permission.empty() ? vector<chain::permission_level>{{account,config::active_name}} : get_account_permissions(tx_permission), setabi{ .account = account, .abi = abi } }; } chain::action create_setcode(const name& account, const bytes& code) { return action { tx_permission.empty() ? vector<chain::permission_level>{{account,config::active_name}} : get_account_permissions(tx_permission), setcode{ .account = account, .vmtype = 0, .vmversion = 0, .code = code } }; } chain::action create_updateauth(const name& account, const name& permission, const name& parent, const authority& auth) { return action { tx_permission.empty() ? vector<chain::permission_level>{{account,config::active_name}} : get_account_permissions(tx_permission), updateauth{account, permission, parent, auth}}; } chain::action create_deleteauth(const name& account, const name& permission) { return action { tx_permission.empty() ? vector<chain::permission_level>{{account,config::active_name}} : get_account_permissions(tx_permission), deleteauth{account, permission}}; } chain::action create_linkauth(const name& account, const name& code, const name& type, const name& requirement) { return action { tx_permission.empty() ? vector<chain::permission_level>{{account,config::active_name}} : get_account_permissions(tx_permission), linkauth{account, code, type, requirement}}; } chain::action create_unlinkauth(const name& account, const name& code, const name& type) { return action { tx_permission.empty() ? vector<chain::permission_level>{{account,config::active_name}} : get_account_permissions(tx_permission), unlinkauth{account, code, type}}; } authority parse_json_authority(const std::string& authorityJsonOrFile) { try { return json_from_file_or_string(authorityJsonOrFile).as<authority>(); } EOS_RETHROW_EXCEPTIONS(authority_type_exception, "Fail to parse Authority JSON '${data}'", ("data",authorityJsonOrFile)) } authority parse_json_authority_or_key(const std::string& authorityJsonOrFile) { if (boost::istarts_with(authorityJsonOrFile, "EOS") || boost::istarts_with(authorityJsonOrFile, "PUB_R1")) { try { return authority(public_key_type(authorityJsonOrFile)); } EOS_RETHROW_EXCEPTIONS(public_key_type_exception, "Invalid public key: ${public_key}", ("public_key", authorityJsonOrFile)) } else { auto result = parse_json_authority(authorityJsonOrFile); EOS_ASSERT( eosio::chain::validate(result), authority_type_exception, "Authority failed validation! ensure that keys, accounts, and waits are sorted and that the threshold is valid and satisfiable!"); return result; } } asset to_asset( account_name code, const string& s ) { static map< pair<account_name, eosio::chain::symbol_code>, eosio::chain::symbol> cache; auto a = asset::from_string( s ); eosio::chain::symbol_code sym = a.get_symbol().to_symbol_code(); auto it = cache.find( make_pair(code, sym) ); auto sym_str = a.symbol_name(); if ( it == cache.end() ) { auto json = call(get_currency_stats_func, fc::mutable_variant_object("json", false) ("code", code) ("symbol", sym_str) ); auto obj = json.get_object(); auto obj_it = obj.find( sym_str ); if (obj_it != obj.end()) { auto result = obj_it->value().as<eosio::chain_apis::read_only::get_currency_stats_result>(); auto p = cache.emplace( make_pair( code, sym ), result.max_supply.get_symbol() ); it = p.first; } else { EOS_THROW(symbol_type_exception, "Symbol ${s} is not supported by token contract ${c}", ("s", sym_str)("c", code)); } } auto expected_symbol = it->second; if ( a.decimals() < expected_symbol.decimals() ) { auto factor = expected_symbol.precision() / a.precision(); auto a_old = a; a = asset( a.get_amount() * factor, expected_symbol ); } else if ( a.decimals() > expected_symbol.decimals() ) { EOS_THROW(symbol_type_exception, "Too many decimal digits in ${a}, only ${d} supported", ("a", a)("d", expected_symbol.decimals())); } // else precision matches return a; } inline asset to_asset( const string& s ) { return to_asset( N(eosio.token), s ); } struct set_account_permission_subcommand { string accountStr; string permissionStr; string authorityJsonOrFile; string parentStr; set_account_permission_subcommand(CLI::App* accountCmd) { auto permissions = accountCmd->add_subcommand("permission", localized("set parameters dealing with account permissions")); permissions->add_option("account", accountStr, localized("The account to set/delete a permission authority for"))->required(); permissions->add_option("permission", permissionStr, localized("The permission name to set/delete an authority for"))->required(); permissions->add_option("authority", authorityJsonOrFile, localized("[delete] NULL, [create/update] public key, JSON string, or filename defining the authority"))->required(); permissions->add_option("parent", parentStr, localized("[create] The permission name of this parents permission (Defaults to: \"Active\")")); add_standard_transaction_options(permissions, "account@active"); permissions->set_callback([this] { name account = name(accountStr); name permission = name(permissionStr); bool is_delete = boost::iequals(authorityJsonOrFile, "null"); if (is_delete) { send_actions({create_deleteauth(account, permission)}); } else { authority auth = parse_json_authority_or_key(authorityJsonOrFile); name parent; if (parentStr.size() == 0 && permissionStr != "owner") { // see if we can auto-determine the proper parent const auto account_result = call(get_account_func, fc::mutable_variant_object("account_name", accountStr)); const auto& existing_permissions = account_result.get_object()["permissions"].get_array(); auto permissionPredicate = [this](const auto& perm) { return perm.is_object() && perm.get_object().contains("perm_name") && boost::equals(perm.get_object()["perm_name"].get_string(), permissionStr); }; auto itr = boost::find_if(existing_permissions, permissionPredicate); if (itr != existing_permissions.end()) { parent = name((*itr).get_object()["parent"].get_string()); } else { // if this is a new permission and there is no parent we default to "active" parent = name(config::active_name); } } else { parent = name(parentStr); } send_actions({create_updateauth(account, permission, parent, auth)}); } }); } }; struct set_action_permission_subcommand { string accountStr; string codeStr; string typeStr; string requirementStr; set_action_permission_subcommand(CLI::App* actionRoot) { auto permissions = actionRoot->add_subcommand("permission", localized("set parmaters dealing with account permissions")); permissions->add_option("account", accountStr, localized("The account to set/delete a permission authority for"))->required(); permissions->add_option("code", codeStr, localized("The account that owns the code for the action"))->required(); permissions->add_option("type", typeStr, localized("the type of the action"))->required(); permissions->add_option("requirement", requirementStr, localized("[delete] NULL, [set/update] The permission name require for executing the given action"))->required(); add_standard_transaction_options(permissions, "account@active"); permissions->set_callback([this] { name account = name(accountStr); name code = name(codeStr); name type = name(typeStr); bool is_delete = boost::iequals(requirementStr, "null"); if (is_delete) { send_actions({create_unlinkauth(account, code, type)}); } else { name requirement = name(requirementStr); send_actions({create_linkauth(account, code, type, requirement)}); } }); } }; bool local_port_used() { using namespace boost::asio; io_service ios; local::stream_protocol::endpoint endpoint(wallet_url.substr(strlen("unix://"))); local::stream_protocol::socket socket(ios); boost::system::error_code ec; socket.connect(endpoint, ec); return !ec; } void try_local_port(uint32_t duration) { using namespace std::chrono; auto start_time = duration_cast<std::chrono::milliseconds>( system_clock::now().time_since_epoch() ).count(); while ( !local_port_used()) { if (duration_cast<std::chrono::milliseconds>( system_clock::now().time_since_epoch()).count() - start_time > duration ) { std::cerr << "Unable to connect to keosd, if keosd is running please kill the process and try again.\n"; throw connection_exception(fc::log_messages{FC_LOG_MESSAGE(error, "Unable to connect to keosd")}); } } } void ensure_keosd_running(CLI::App* app) { if (no_auto_keosd) return; // get, version, net do not require keosd if (tx_skip_sign || app->got_subcommand("get") || app->got_subcommand("version") || app->got_subcommand("net")) return; if (app->get_subcommand("create")->got_subcommand("key")) // create key does not require wallet return; if (auto* subapp = app->get_subcommand("system")) { if (subapp->got_subcommand("listproducers") || subapp->got_subcommand("listbw") || subapp->got_subcommand("bidnameinfo")) // system list* do not require wallet return; } if (wallet_url != default_wallet_url) return; if (local_port_used()) return; boost::filesystem::path binPath = boost::dll::program_location(); binPath.remove_filename(); // This extra check is necessary when running cleos like this: ./cleos ... if (binPath.filename_is_dot()) binPath.remove_filename(); binPath.append(key_store_executable_name); // if cleos and keosd are in the same installation directory if (!boost::filesystem::exists(binPath)) { binPath.remove_filename().remove_filename().append("keosd").append(key_store_executable_name); } if (boost::filesystem::exists(binPath)) { namespace bp = boost::process; binPath = boost::filesystem::canonical(binPath); vector<std::string> pargs; pargs.push_back("--http-server-address"); pargs.push_back(""); pargs.push_back("--https-server-address"); pargs.push_back(""); ::boost::process::child keos(binPath, pargs, bp::std_in.close(), bp::std_out > bp::null, bp::std_err > bp::null); if (keos.running()) { std::cerr << binPath << " launched" << std::endl; keos.detach(); try_local_port(2000); } else { std::cerr << "No wallet service listening on " << wallet_url << ". Failed to launch " << binPath << std::endl; } } else { std::cerr << "No wallet service listening on " << ". Cannot automatically start keosd because keosd was not found." << std::endl; } } CLI::callback_t obsoleted_option_host_port = [](CLI::results_t) { std::cerr << localized("Host and port options (-H, --wallet-host, etc.) have been replaced with -u/--url and --wallet-url\n" "Use for example -u http://localhost:8888 or --url https://example.invalid/\n"); exit(1); return false; }; struct register_producer_subcommand { string producer_str; string producer_key_str; string url; uint16_t loc = 0; register_producer_subcommand(CLI::App* actionRoot) { auto register_producer = actionRoot->add_subcommand("regproducer", localized("Register a new producer")); register_producer->add_option("account", producer_str, localized("The account to register as a producer"))->required(); register_producer->add_option("producer_key", producer_key_str, localized("The producer's public key"))->required(); register_producer->add_option("url", url, localized("url where info about producer can be found"), true); register_producer->add_option("location", loc, localized("relative location for purpose of nearest neighbor scheduling"), true); add_standard_transaction_options(register_producer); register_producer->set_callback([this] { public_key_type producer_key; try { producer_key = public_key_type(producer_key_str); } EOS_RETHROW_EXCEPTIONS(public_key_type_exception, "Invalid producer public key: ${public_key}", ("public_key", producer_key_str)) auto regprod_var = regproducer_variant(producer_str, producer_key, url, loc ); send_actions({create_action({permission_level{producer_str,config::active_name}}, config::system_account_name, N(regproducer), regprod_var)}); }); } }; struct create_account_subcommand { string creator; string account_name; string owner_key_str; string active_key_str; string stake_net; string stake_cpu; uint32_t buy_ram_bytes_in_kbytes = 0; uint32_t buy_ram_bytes = 0; string buy_ram_eos; bool transfer; bool simple; create_account_subcommand(CLI::App* actionRoot, bool s) : simple(s) { auto createAccount = actionRoot->add_subcommand( (simple ? "account" : "newaccount"), localized("Create an account, buy ram, stake for bandwidth for the account")); createAccount->add_option("creator", creator, localized("The name of the account creating the new account"))->required(); createAccount->add_option("name", account_name, localized("The name of the new account"))->required(); createAccount->add_option("OwnerKey", owner_key_str, localized("The owner public key for the new account"))->required(); createAccount->add_option("ActiveKey", active_key_str, localized("The active public key for the new account")); if (!simple) { createAccount->add_option("--stake-net", stake_net, (localized("The amount of EOS delegated for net bandwidth")))->required(); createAccount->add_option("--stake-cpu", stake_cpu, (localized("The amount of EOS delegated for CPU bandwidth")))->required(); createAccount->add_option("--buy-ram-kbytes", buy_ram_bytes_in_kbytes, (localized("The amount of RAM bytes to purchase for the new account in kibibytes (KiB)"))); createAccount->add_option("--buy-ram-bytes", buy_ram_bytes, (localized("The amount of RAM bytes to purchase for the new account in bytes"))); createAccount->add_option("--buy-ram", buy_ram_eos, (localized("The amount of RAM bytes to purchase for the new account in EOS"))); createAccount->add_flag("--transfer", transfer, (localized("Transfer voting power and right to unstake EOS to receiver"))); } add_standard_transaction_options(createAccount); createAccount->set_callback([this] { if( !active_key_str.size() ) active_key_str = owner_key_str; public_key_type owner_key, active_key; try { owner_key = public_key_type(owner_key_str); } EOS_RETHROW_EXCEPTIONS(public_key_type_exception, "Invalid owner public key: ${public_key}", ("public_key", owner_key_str)); try { active_key = public_key_type(active_key_str); } EOS_RETHROW_EXCEPTIONS(public_key_type_exception, "Invalid active public key: ${public_key}", ("public_key", active_key_str)); auto create = create_newaccount(creator, account_name, owner_key, active_key); if (!simple) { EOSC_ASSERT( buy_ram_eos.size() || buy_ram_bytes_in_kbytes || buy_ram_bytes, "ERROR: One of --buy-ram, --buy-ram-kbytes or --buy-ram-bytes should have non-zero value" ); EOSC_ASSERT( !buy_ram_bytes_in_kbytes || !buy_ram_bytes, "ERROR: --buy-ram-kbytes and --buy-ram-bytes cannot be set at the same time" ); action buyram = !buy_ram_eos.empty() ? create_buyram(creator, account_name, to_asset(buy_ram_eos)) : create_buyrambytes(creator, account_name, (buy_ram_bytes_in_kbytes) ? (buy_ram_bytes_in_kbytes * 1024) : buy_ram_bytes); auto net = to_asset(stake_net); auto cpu = to_asset(stake_cpu); if ( net.get_amount() != 0 || cpu.get_amount() != 0 ) { action delegate = create_delegate( creator, account_name, net, cpu, transfer); send_actions( { create, buyram, delegate } ); } else { send_actions( { create, buyram } ); } } else { send_actions( { create } ); } }); } }; struct unregister_producer_subcommand { string producer_str; unregister_producer_subcommand(CLI::App* actionRoot) { auto unregister_producer = actionRoot->add_subcommand("unregprod", localized("Unregister an existing producer")); unregister_producer->add_option("account", producer_str, localized("The account to unregister as a producer"))->required(); add_standard_transaction_options(unregister_producer); unregister_producer->set_callback([this] { fc::variant act_payload = fc::mutable_variant_object() ("producer", producer_str); send_actions({create_action({permission_level{producer_str,config::active_name}}, config::system_account_name, N(unregprod), act_payload)}); }); } }; struct vote_producer_proxy_subcommand { string voter_str; string proxy_str; vote_producer_proxy_subcommand(CLI::App* actionRoot) { auto vote_proxy = actionRoot->add_subcommand("proxy", localized("Vote your stake through a proxy")); vote_proxy->add_option("voter", voter_str, localized("The voting account"))->required(); vote_proxy->add_option("proxy", proxy_str, localized("The proxy account"))->required(); add_standard_transaction_options(vote_proxy); vote_proxy->set_callback([this] { fc::variant act_payload = fc::mutable_variant_object() ("voter", voter_str) ("proxy", proxy_str) ("producers", std::vector<account_name>{}); send_actions({create_action({permission_level{voter_str,config::active_name}}, config::system_account_name, N(voteproducer), act_payload)}); }); } }; struct vote_producers_subcommand { string voter_str; vector<eosio::name> producer_names; vote_producers_subcommand(CLI::App* actionRoot) { auto vote_producers = actionRoot->add_subcommand("prods", localized("Vote for one or more producers")); vote_producers->add_option("voter", voter_str, localized("The voting account"))->required(); vote_producers->add_option("producers", producer_names, localized("The account(s) to vote for. All options from this position and following will be treated as the producer list."))->required(); add_standard_transaction_options(vote_producers); vote_producers->set_callback([this] { std::sort( producer_names.begin(), producer_names.end() ); fc::variant act_payload = fc::mutable_variant_object() ("voter", voter_str) ("proxy", "") ("producers", producer_names); send_actions({create_action({permission_level{voter_str,config::active_name}}, config::system_account_name, N(voteproducer), act_payload)}); }); } }; struct approve_producer_subcommand { eosio::name voter; eosio::name producer_name; approve_producer_subcommand(CLI::App* actionRoot) { auto approve_producer = actionRoot->add_subcommand("approve", localized("Add one producer to list of voted producers")); approve_producer->add_option("voter", voter, localized("The voting account"))->required(); approve_producer->add_option("producer", producer_name, localized("The account to vote for"))->required(); add_standard_transaction_options(approve_producer); approve_producer->set_callback([this] { auto result = call(get_table_func, fc::mutable_variant_object("json", true) ("code", name(config::system_account_name).to_string()) ("scope", name(config::system_account_name).to_string()) ("table", "voters") ("table_key", "owner") ("lower_bound", voter.value) ("limit", 1) ); auto res = result.as<eosio::chain_apis::read_only::get_table_rows_result>(); if ( res.rows.empty() || res.rows[0]["owner"].as_string() != name(voter).to_string() ) { std::cerr << "Voter info not found for account " << voter << std::endl; return; } EOS_ASSERT( 1 == res.rows.size(), multiple_voter_info, "More than one voter_info for account" ); auto prod_vars = res.rows[0]["producers"].get_array(); vector<eosio::name> prods; for ( auto& x : prod_vars ) { prods.push_back( name(x.as_string()) ); } prods.push_back( producer_name ); std::sort( prods.begin(), prods.end() ); auto it = std::unique( prods.begin(), prods.end() ); if (it != prods.end() ) { std::cerr << "Producer \"" << producer_name << "\" is already on the list." << std::endl; return; } fc::variant act_payload = fc::mutable_variant_object() ("voter", voter) ("proxy", "") ("producers", prods); send_actions({create_action({permission_level{voter,config::active_name}}, config::system_account_name, N(voteproducer), act_payload)}); }); } }; struct unapprove_producer_subcommand { eosio::name voter; eosio::name producer_name; unapprove_producer_subcommand(CLI::App* actionRoot) { auto approve_producer = actionRoot->add_subcommand("unapprove", localized("Remove one producer from list of voted producers")); approve_producer->add_option("voter", voter, localized("The voting account"))->required(); approve_producer->add_option("producer", producer_name, localized("The account to remove from voted producers"))->required(); add_standard_transaction_options(approve_producer); approve_producer->set_callback([this] { auto result = call(get_table_func, fc::mutable_variant_object("json", true) ("code", name(config::system_account_name).to_string()) ("scope", name(config::system_account_name).to_string()) ("table", "voters") ("table_key", "owner") ("lower_bound", voter.value) ("limit", 1) ); auto res = result.as<eosio::chain_apis::read_only::get_table_rows_result>(); if ( res.rows.empty() || res.rows[0]["owner"].as_string() != name(voter).to_string() ) { std::cerr << "Voter info not found for account " << voter << std::endl; return; } EOS_ASSERT( 1 == res.rows.size(), multiple_voter_info, "More than one voter_info for account" ); auto prod_vars = res.rows[0]["producers"].get_array(); vector<eosio::name> prods; for ( auto& x : prod_vars ) { prods.push_back( name(x.as_string()) ); } auto it = std::remove( prods.begin(), prods.end(), producer_name ); if (it == prods.end() ) { std::cerr << "Cannot remove: producer \"" << producer_name << "\" is not on the list." << std::endl; return; } prods.erase( it, prods.end() ); //should always delete only one element fc::variant act_payload = fc::mutable_variant_object() ("voter", voter) ("proxy", "") ("producers", prods); send_actions({create_action({permission_level{voter,config::active_name}}, config::system_account_name, N(voteproducer), act_payload)}); }); } }; struct list_producers_subcommand { bool print_json = false; uint32_t limit = 50; std::string lower; list_producers_subcommand(CLI::App* actionRoot) { auto list_producers = actionRoot->add_subcommand("listproducers", localized("List producers")); list_producers->add_flag("--json,-j", print_json, localized("Output in JSON format")); list_producers->add_option("-l,--limit", limit, localized("The maximum number of rows to return")); list_producers->add_option("-L,--lower", lower, localized("lower bound value of key, defaults to first")); list_producers->set_callback([this] { auto rawResult = call(get_producers_func, fc::mutable_variant_object ("json", true)("lower_bound", lower)("limit", limit)); if ( print_json ) { std::cout << fc::json::to_pretty_string(rawResult) << std::endl; return; } auto result = rawResult.as<eosio::chain_apis::read_only::get_producers_result>(); if ( result.rows.empty() ) { std::cout << "No producers found" << std::endl; return; } auto weight = result.total_producer_vote_weight; if ( !weight ) weight = 1; printf("%-13s %-57s %-59s %s\n", "Producer", "Producer key", "Url", "Scaled votes"); for ( auto& row : result.rows ) printf("%-13.13s %-57.57s %-59.59s %1.4f\n", row["owner"].as_string().c_str(), row["producer_key"].as_string().c_str(), row["url"].as_string().c_str(), row["total_votes"].as_double() / weight); if ( !result.more.empty() ) std::cout << "-L " << result.more << " for more" << std::endl; }); } }; struct get_schedule_subcommand { bool print_json = false; void print(const char* name, const fc::variant& schedule) { if (schedule.is_null()) { printf("%s schedule empty\n\n", name); return; } printf("%s schedule version %s\n", name, schedule["version"].as_string().c_str()); printf(" %-13s %s\n", "Producer", "Producer key"); printf(" %-13s %s\n", "=============", "=================="); for (auto& row: schedule["producers"].get_array()) printf(" %-13s %s\n", row["producer_name"].as_string().c_str(), row["block_signing_key"].as_string().c_str()); printf("\n"); } get_schedule_subcommand(CLI::App* actionRoot) { auto get_schedule = actionRoot->add_subcommand("schedule", localized("Retrieve the producer schedule")); get_schedule->add_flag("--json,-j", print_json, localized("Output in JSON format")); get_schedule->set_callback([this] { auto result = call(get_schedule_func, fc::mutable_variant_object()); if ( print_json ) { std::cout << fc::json::to_pretty_string(result) << std::endl; return; } print("active", result["active"]); print("pending", result["pending"]); print("proposed", result["proposed"]); }); } }; struct get_transaction_id_subcommand { string trx_to_check; get_transaction_id_subcommand(CLI::App* actionRoot) { auto get_transaction_id = actionRoot->add_subcommand("transaction_id", localized("Get transaction id given transaction object")); get_transaction_id->add_option("transaction", trx_to_check, localized("The JSON string or filename defining the transaction which transaction id we want to retrieve"))->required(); get_transaction_id->set_callback([&] { try { auto trx_var = json_from_file_or_string(trx_to_check); auto trx = trx_var.as<transaction>(); std::cout << string(trx.id()) << std::endl; } EOS_RETHROW_EXCEPTIONS(transaction_type_exception, "Fail to parse transaction JSON '${data}'", ("data",trx_to_check)) }); } }; struct delegate_bandwidth_subcommand { string from_str; string receiver_str; string stake_net_amount; string stake_cpu_amount; string stake_storage_amount; string buy_ram_amount; uint32_t buy_ram_bytes = 0; bool transfer = false; delegate_bandwidth_subcommand(CLI::App* actionRoot) { auto delegate_bandwidth = actionRoot->add_subcommand("delegatebw", localized("Delegate bandwidth")); delegate_bandwidth->add_option("from", from_str, localized("The account to delegate bandwidth from"))->required(); delegate_bandwidth->add_option("receiver", receiver_str, localized("The account to receive the delegated bandwidth"))->required(); delegate_bandwidth->add_option("stake_net_quantity", stake_net_amount, localized("The amount of EOS to stake for network bandwidth"))->required(); delegate_bandwidth->add_option("stake_cpu_quantity", stake_cpu_amount, localized("The amount of EOS to stake for CPU bandwidth"))->required(); delegate_bandwidth->add_option("--buyram", buy_ram_amount, localized("The amount of EOS to buyram")); delegate_bandwidth->add_option("--buy-ram-bytes", buy_ram_bytes, localized("The amount of RAM to buy in number of bytes")); delegate_bandwidth->add_flag("--transfer", transfer, localized("Transfer voting power and right to unstake EOS to receiver")); add_standard_transaction_options(delegate_bandwidth); delegate_bandwidth->set_callback([this] { fc::variant act_payload = fc::mutable_variant_object() ("from", from_str) ("receiver", receiver_str) ("stake_net_quantity", to_asset(stake_net_amount)) ("stake_cpu_quantity", to_asset(stake_cpu_amount)) ("transfer", transfer); std::vector<chain::action> acts{create_action({permission_level{from_str,config::active_name}}, config::system_account_name, N(delegatebw), act_payload)}; EOSC_ASSERT( !(buy_ram_amount.size()) || !buy_ram_bytes, "ERROR: --buyram and --buy-ram-bytes cannot be set at the same time" ); if (buy_ram_amount.size()) { acts.push_back( create_buyram(from_str, receiver_str, to_asset(buy_ram_amount)) ); } else if (buy_ram_bytes) { acts.push_back( create_buyrambytes(from_str, receiver_str, buy_ram_bytes) ); } send_actions(std::move(acts)); }); } }; struct undelegate_bandwidth_subcommand { string from_str; string receiver_str; string unstake_net_amount; string unstake_cpu_amount; uint64_t unstake_storage_bytes; undelegate_bandwidth_subcommand(CLI::App* actionRoot) { auto undelegate_bandwidth = actionRoot->add_subcommand("undelegatebw", localized("Undelegate bandwidth")); undelegate_bandwidth->add_option("from", from_str, localized("The account undelegating bandwidth"))->required(); undelegate_bandwidth->add_option("receiver", receiver_str, localized("The account to undelegate bandwidth from"))->required(); undelegate_bandwidth->add_option("unstake_net_quantity", unstake_net_amount, localized("The amount of EOS to undelegate for network bandwidth"))->required(); undelegate_bandwidth->add_option("unstake_cpu_quantity", unstake_cpu_amount, localized("The amount of EOS to undelegate for CPU bandwidth"))->required(); add_standard_transaction_options(undelegate_bandwidth); undelegate_bandwidth->set_callback([this] { fc::variant act_payload = fc::mutable_variant_object() ("from", from_str) ("receiver", receiver_str) ("unstake_net_quantity", to_asset(unstake_net_amount)) ("unstake_cpu_quantity", to_asset(unstake_cpu_amount)); send_actions({create_action({permission_level{from_str,config::active_name}}, config::system_account_name, N(undelegatebw), act_payload)}); }); } }; struct bidname_subcommand { string bidder_str; string newname_str; string bid_amount; bidname_subcommand(CLI::App *actionRoot) { auto bidname = actionRoot->add_subcommand("bidname", localized("Name bidding")); bidname->add_option("bidder", bidder_str, localized("The bidding account"))->required(); bidname->add_option("newname", newname_str, localized("The bidding name"))->required(); bidname->add_option("bid", bid_amount, localized("The amount of EOS to bid"))->required(); add_standard_transaction_options(bidname); bidname->set_callback([this] { fc::variant act_payload = fc::mutable_variant_object() ("bidder", bidder_str) ("newname", newname_str) ("bid", to_asset(bid_amount)); send_actions({create_action({permission_level{bidder_str, config::active_name}}, config::system_account_name, N(bidname), act_payload)}); }); } }; struct bidname_info_subcommand { bool print_json = false; string newname_str; bidname_info_subcommand(CLI::App* actionRoot) { auto list_producers = actionRoot->add_subcommand("bidnameinfo", localized("Get bidname info")); list_producers->add_flag("--json,-j", print_json, localized("Output in JSON format")); list_producers->add_option("newname", newname_str, localized("The bidding name"))->required(); list_producers->set_callback([this] { auto rawResult = call(get_table_func, fc::mutable_variant_object("json", true) ("code", "eosio")("scope", "eosio")("table", "namebids") ("lower_bound", eosio::chain::string_to_name(newname_str.c_str()))("limit", 1)); if ( print_json ) { std::cout << fc::json::to_pretty_string(rawResult) << std::endl; return; } auto result = rawResult.as<eosio::chain_apis::read_only::get_table_rows_result>(); if ( result.rows.empty() ) { std::cout << "No bidname record found" << std::endl; return; } for ( auto& row : result.rows ) { fc::time_point time(fc::microseconds(row["last_bid_time"].as_uint64())); int64_t bid = row["high_bid"].as_int64(); std::cout << std::left << std::setw(18) << "bidname:" << std::right << std::setw(24) << row["newname"].as_string() << "\n" << std::left << std::setw(18) << "highest bidder:" << std::right << std::setw(24) << row["high_bidder"].as_string() << "\n" << std::left << std::setw(18) << "highest bid:" << std::right << std::setw(24) << (bid > 0 ? bid : -bid) << "\n" << std::left << std::setw(18) << "last bid time:" << std::right << std::setw(24) << ((std::string)time).c_str() << std::endl; if (bid < 0) std::cout << "This auction has already closed" << std::endl; } }); } }; struct list_bw_subcommand { eosio::name account; bool print_json = false; list_bw_subcommand(CLI::App* actionRoot) { auto list_bw = actionRoot->add_subcommand("listbw", localized("List delegated bandwidth")); list_bw->add_option("account", account, localized("The account delegated bandwidth"))->required(); list_bw->add_flag("--json,-j", print_json, localized("Output in JSON format") ); list_bw->set_callback([this] { //get entire table in scope of user account auto result = call(get_table_func, fc::mutable_variant_object("json", true) ("code", name(config::system_account_name).to_string()) ("scope", account.to_string()) ("table", "delband") ); if (!print_json) { auto res = result.as<eosio::chain_apis::read_only::get_table_rows_result>(); if ( !res.rows.empty() ) { std::cout << std::setw(13) << std::left << "Receiver" << std::setw(21) << std::left << "Net bandwidth" << std::setw(21) << std::left << "CPU bandwidth" << std::endl; for ( auto& r : res.rows ){ std::cout << std::setw(13) << std::left << r["to"].as_string() << std::setw(21) << std::left << r["net_weight"].as_string() << std::setw(21) << std::left << r["cpu_weight"].as_string() << std::endl; } } else { std::cerr << "Delegated bandwidth not found" << std::endl; } } else { std::cout << fc::json::to_pretty_string(result) << std::endl; } }); } }; struct buyram_subcommand { string from_str; string receiver_str; string amount; bool kbytes = false; bool bytes = false; buyram_subcommand(CLI::App* actionRoot) { auto buyram = actionRoot->add_subcommand("buyram", localized("Buy RAM")); buyram->add_option("payer", from_str, localized("The account paying for RAM"))->required(); buyram->add_option("receiver", receiver_str, localized("The account receiving bought RAM"))->required(); buyram->add_option("amount", amount, localized("The amount of EOS to pay for RAM, or number of bytes/kibibytes of RAM if --bytes/--kbytes is set"))->required(); buyram->add_flag("--kbytes,-k", kbytes, localized("buyram in number of kibibytes (KiB)")); buyram->add_flag("--bytes,-b", bytes, localized("buyram in number of bytes")); add_standard_transaction_options(buyram); buyram->set_callback([this] { EOSC_ASSERT( !kbytes || !bytes, "ERROR: --kbytes and --bytes cannot be set at the same time" ); if (kbytes || bytes) { send_actions( { create_buyrambytes(from_str, receiver_str, fc::to_uint64(amount) * ((kbytes) ? 1024ull : 1ull)) } ); } else { send_actions( { create_buyram(from_str, receiver_str, to_asset(amount)) } ); } }); } }; struct sellram_subcommand { string from_str; string receiver_str; uint64_t amount; sellram_subcommand(CLI::App* actionRoot) { auto sellram = actionRoot->add_subcommand("sellram", localized("Sell RAM")); sellram->add_option("account", receiver_str, localized("The account to receive EOS for sold RAM"))->required(); sellram->add_option("bytes", amount, localized("Number of RAM bytes to sell"))->required(); add_standard_transaction_options(sellram); sellram->set_callback([this] { fc::variant act_payload = fc::mutable_variant_object() ("account", receiver_str) ("bytes", amount); send_actions({create_action({permission_level{receiver_str,config::active_name}}, config::system_account_name, N(sellram), act_payload)}); }); } }; struct claimrewards_subcommand { string owner; claimrewards_subcommand(CLI::App* actionRoot) { auto claim_rewards = actionRoot->add_subcommand("claimrewards", localized("Claim producer rewards")); claim_rewards->add_option("owner", owner, localized("The account to claim rewards for"))->required(); add_standard_transaction_options(claim_rewards); claim_rewards->set_callback([this] { fc::variant act_payload = fc::mutable_variant_object() ("owner", owner); send_actions({create_action({permission_level{owner,config::active_name}}, config::system_account_name, N(claimrewards), act_payload)}); }); } }; struct regproxy_subcommand { string proxy; regproxy_subcommand(CLI::App* actionRoot) { auto register_proxy = actionRoot->add_subcommand("regproxy", localized("Register an account as a proxy (for voting)")); register_proxy->add_option("proxy", proxy, localized("The proxy account to register"))->required(); add_standard_transaction_options(register_proxy); register_proxy->set_callback([this] { fc::variant act_payload = fc::mutable_variant_object() ("proxy", proxy) ("isproxy", true); send_actions({create_action({permission_level{proxy,config::active_name}}, config::system_account_name, N(regproxy), act_payload)}); }); } }; struct unregproxy_subcommand { string proxy; unregproxy_subcommand(CLI::App* actionRoot) { auto unregister_proxy = actionRoot->add_subcommand("unregproxy", localized("Unregister an account as a proxy (for voting)")); unregister_proxy->add_option("proxy", proxy, localized("The proxy account to unregister"))->required(); add_standard_transaction_options(unregister_proxy); unregister_proxy->set_callback([this] { fc::variant act_payload = fc::mutable_variant_object() ("proxy", proxy) ("isproxy", false); send_actions({create_action({permission_level{proxy,config::active_name}}, config::system_account_name, N(regproxy), act_payload)}); }); } }; struct canceldelay_subcommand { string canceling_account; string canceling_permission; string trx_id; canceldelay_subcommand(CLI::App* actionRoot) { auto cancel_delay = actionRoot->add_subcommand("canceldelay", localized("Cancel a delayed transaction")); cancel_delay->add_option("canceling_account", canceling_account, localized("Account from authorization on the original delayed transaction"))->required(); cancel_delay->add_option("canceling_permission", canceling_permission, localized("Permission from authorization on the original delayed transaction"))->required(); cancel_delay->add_option("trx_id", trx_id, localized("The transaction id of the original delayed transaction"))->required(); add_standard_transaction_options(cancel_delay); cancel_delay->set_callback([this] { const auto canceling_auth = permission_level{canceling_account, canceling_permission}; fc::variant act_payload = fc::mutable_variant_object() ("canceling_auth", canceling_auth) ("trx_id", trx_id); send_actions({create_action({canceling_auth}, config::system_account_name, N(canceldelay), act_payload)}); }); } }; void get_account( const string& accountName, bool json_format ) { auto json = call(get_account_func, fc::mutable_variant_object("account_name", accountName)); auto res = json.as<eosio::chain_apis::read_only::get_account_results>(); if (!json_format) { asset staked; asset unstaking; if( res.core_liquid_balance.valid() ) { unstaking = asset( 0, res.core_liquid_balance->get_symbol() ); // Correct core symbol for unstaking asset. staked = asset( 0, res.core_liquid_balance->get_symbol() ); // Correct core symbol for staked asset. } std::cout << "created: " << string(res.created) << std::endl; if(res.privileged) std::cout << "privileged: true" << std::endl; constexpr size_t indent_size = 5; const string indent(indent_size, ' '); std::cout << "permissions: " << std::endl; unordered_map<name, vector<name>/*children*/> tree; vector<name> roots; //we don't have multiple roots, but we can easily handle them here, so let's do it just in case unordered_map<name, eosio::chain_apis::permission> cache; for ( auto& perm : res.permissions ) { if ( perm.parent ) { tree[perm.parent].push_back( perm.perm_name ); } else { roots.push_back( perm.perm_name ); } auto name = perm.perm_name; //keep copy before moving `perm`, since thirst argument of emplace can be evaluated first // looks a little crazy, but should be efficient cache.insert( std::make_pair(name, std::move(perm)) ); } std::function<void (account_name, int)> dfs_print = [&]( account_name name, int depth ) -> void { auto& p = cache.at(name); std::cout << indent << std::string(depth*3, ' ') << name << ' ' << std::setw(5) << p.required_auth.threshold << ": "; const char *sep = ""; for ( auto it = p.required_auth.keys.begin(); it != p.required_auth.keys.end(); ++it ) { std::cout << sep << it->weight << ' ' << string(it->key); sep = ", "; } for ( auto& acc : p.required_auth.accounts ) { std::cout << sep << acc.weight << ' ' << string(acc.permission.actor) << '@' << string(acc.permission.permission); sep = ", "; } std::cout << std::endl; auto it = tree.find( name ); if (it != tree.end()) { auto& children = it->second; sort( children.begin(), children.end() ); for ( auto& n : children ) { // we have a tree, not a graph, so no need to check for already visited nodes dfs_print( n, depth+1 ); } } // else it's a leaf node }; std::sort(roots.begin(), roots.end()); for ( auto r : roots ) { dfs_print( r, 0 ); } auto to_pretty_net = []( int64_t nbytes, uint8_t width_for_units = 5 ) { if(nbytes == -1) { // special case. Treat it as unlimited return std::string("unlimited"); } string unit = "bytes"; double bytes = static_cast<double> (nbytes); if (bytes >= 1024 * 1024 * 1024 * 1024ll) { unit = "TiB"; bytes /= 1024 * 1024 * 1024 * 1024ll; } else if (bytes >= 1024 * 1024 * 1024) { unit = "GiB"; bytes /= 1024 * 1024 * 1024; } else if (bytes >= 1024 * 1024) { unit = "MiB"; bytes /= 1024 * 1024; } else if (bytes >= 1024) { unit = "KiB"; bytes /= 1024; } std::stringstream ss; ss << setprecision(4); ss << bytes << " "; if( width_for_units > 0 ) ss << std::left << setw( width_for_units ); ss << unit; return ss.str(); }; std::cout << "memory: " << std::endl << indent << "quota: " << std::setw(15) << to_pretty_net(res.ram_quota) << " used: " << std::setw(15) << to_pretty_net(res.ram_usage) << std::endl << std::endl; std::cout << "net bandwidth: " << std::endl; if ( res.total_resources.is_object() ) { auto net_total = to_asset(res.total_resources.get_object()["net_weight"].as_string()); if( net_total.get_symbol() != unstaking.get_symbol() ) { // Core symbol of nodeos responding to the request is different than core symbol built into cleos unstaking = asset( 0, net_total.get_symbol() ); // Correct core symbol for unstaking asset. staked = asset( 0, net_total.get_symbol() ); // Correct core symbol for staked asset. } if( res.self_delegated_bandwidth.is_object() ) { asset net_own = asset::from_string( res.self_delegated_bandwidth.get_object()["net_weight"].as_string() ); staked = net_own; auto net_others = net_total - net_own; std::cout << indent << "staked:" << std::setw(20) << net_own << std::string(11, ' ') << "(total stake delegated from account to self)" << std::endl << indent << "delegated:" << std::setw(17) << net_others << std::string(11, ' ') << "(total staked delegated to account from others)" << std::endl; } else { auto net_others = net_total; std::cout << indent << "delegated:" << std::setw(17) << net_others << std::string(11, ' ') << "(total staked delegated to account from others)" << std::endl; } } auto to_pretty_time = []( int64_t nmicro, uint8_t width_for_units = 5 ) { if(nmicro == -1) { // special case. Treat it as unlimited return std::string("unlimited"); } string unit = "us"; double micro = static_cast<double>(nmicro); if( micro > 1000000*60*60ll ) { micro /= 1000000*60*60ll; unit = "hr"; } else if( micro > 1000000*60 ) { micro /= 1000000*60; unit = "min"; } else if( micro > 1000000 ) { micro /= 1000000; unit = "sec"; } else if( micro > 1000 ) { micro /= 1000; unit = "ms"; } std::stringstream ss; ss << setprecision(4); ss << micro << " "; if( width_for_units > 0 ) ss << std::left << setw( width_for_units ); ss << unit; return ss.str(); }; std::cout << std::fixed << setprecision(3); std::cout << indent << std::left << std::setw(11) << "used:" << std::right << std::setw(18) << to_pretty_net( res.net_limit.used ) << "\n"; std::cout << indent << std::left << std::setw(11) << "available:" << std::right << std::setw(18) << to_pretty_net( res.net_limit.available ) << "\n"; std::cout << indent << std::left << std::setw(11) << "limit:" << std::right << std::setw(18) << to_pretty_net( res.net_limit.max ) << "\n"; std::cout << std::endl; std::cout << "cpu bandwidth:" << std::endl; if ( res.total_resources.is_object() ) { auto cpu_total = to_asset(res.total_resources.get_object()["cpu_weight"].as_string()); if( res.self_delegated_bandwidth.is_object() ) { asset cpu_own = asset::from_string( res.self_delegated_bandwidth.get_object()["cpu_weight"].as_string() ); staked += cpu_own; auto cpu_others = cpu_total - cpu_own; std::cout << indent << "staked:" << std::setw(20) << cpu_own << std::string(11, ' ') << "(total stake delegated from account to self)" << std::endl << indent << "delegated:" << std::setw(17) << cpu_others << std::string(11, ' ') << "(total staked delegated to account from others)" << std::endl; } else { auto cpu_others = cpu_total; std::cout << indent << "delegated:" << std::setw(17) << cpu_others << std::string(11, ' ') << "(total staked delegated to account from others)" << std::endl; } } std::cout << std::fixed << setprecision(3); std::cout << indent << std::left << std::setw(11) << "used:" << std::right << std::setw(18) << to_pretty_time( res.cpu_limit.used ) << "\n"; std::cout << indent << std::left << std::setw(11) << "available:" << std::right << std::setw(18) << to_pretty_time( res.cpu_limit.available ) << "\n"; std::cout << indent << std::left << std::setw(11) << "limit:" << std::right << std::setw(18) << to_pretty_time( res.cpu_limit.max ) << "\n"; std::cout << std::endl; if( res.refund_request.is_object() ) { auto obj = res.refund_request.get_object(); auto request_time = fc::time_point_sec::from_iso_string( obj["request_time"].as_string() ); fc::time_point refund_time = request_time + fc::days(3); auto now = res.head_block_time; asset net = asset::from_string( obj["net_amount"].as_string() ); asset cpu = asset::from_string( obj["cpu_amount"].as_string() ); unstaking = net + cpu; if( unstaking > asset( 0, unstaking.get_symbol() ) ) { std::cout << std::fixed << setprecision(3); std::cout << "unstaking tokens:" << std::endl; std::cout << indent << std::left << std::setw(25) << "time of unstake request:" << std::right << std::setw(20) << string(request_time); if( now >= refund_time ) { std::cout << " (available to claim now with 'eosio::refund' action)\n"; } else { std::cout << " (funds will be available in " << to_pretty_time( (refund_time - now).count(), 0 ) << ")\n"; } std::cout << indent << std::left << std::setw(25) << "from net bandwidth:" << std::right << std::setw(18) << net << std::endl; std::cout << indent << std::left << std::setw(25) << "from cpu bandwidth:" << std::right << std::setw(18) << cpu << std::endl; std::cout << indent << std::left << std::setw(25) << "total:" << std::right << std::setw(18) << unstaking << std::endl; std::cout << std::endl; } } if( res.core_liquid_balance.valid() ) { std::cout << res.core_liquid_balance->get_symbol().name() << " balances: " << std::endl; std::cout << indent << std::left << std::setw(11) << "liquid:" << std::right << std::setw(18) << *res.core_liquid_balance << std::endl; std::cout << indent << std::left << std::setw(11) << "staked:" << std::right << std::setw(18) << staked << std::endl; std::cout << indent << std::left << std::setw(11) << "unstaking:" << std::right << std::setw(18) << unstaking << std::endl; std::cout << indent << std::left << std::setw(11) << "total:" << std::right << std::setw(18) << (*res.core_liquid_balance + staked + unstaking) << std::endl; std::cout << std::endl; } if ( res.voter_info.is_object() ) { auto& obj = res.voter_info.get_object(); string proxy = obj["proxy"].as_string(); if ( proxy.empty() ) { auto& prods = obj["producers"].get_array(); std::cout << "producers:"; if ( !prods.empty() ) { for ( int i = 0; i < prods.size(); ++i ) { if ( i%3 == 0 ) { std::cout << std::endl << indent; } std::cout << std::setw(16) << std::left << prods[i].as_string(); } std::cout << std::endl; } else { std::cout << indent << "<not voted>" << std::endl; } } else { std::cout << "proxy:" << indent << proxy << std::endl; } } std::cout << std::endl; } else { std::cout << fc::json::to_pretty_string(json) << std::endl; } } CLI::callback_t header_opt_callback = [](CLI::results_t res) { vector<string>::iterator itr; for (itr = res.begin(); itr != res.end(); itr++) { headers.push_back(*itr); } return true; }; int main( int argc, char** argv ) { setlocale(LC_ALL, ""); bindtextdomain(locale_domain, locale_path); textdomain(locale_domain); context = eosio::client::http::create_http_context(); wallet_url = default_wallet_url; CLI::App app{"Command Line Interface to EOSIO Client"}; app.require_subcommand(); app.add_option( "-H,--host", obsoleted_option_host_port, localized("the host where nodeos is running") )->group("hidden"); app.add_option( "-p,--port", obsoleted_option_host_port, localized("the port where nodeos is running") )->group("hidden"); app.add_option( "--wallet-host", obsoleted_option_host_port, localized("the host where keosd is running") )->group("hidden"); app.add_option( "--wallet-port", obsoleted_option_host_port, localized("the port where keosd is running") )->group("hidden"); app.add_option( "-u,--url", url, localized("the http/https URL where nodeos is running"), true ); app.add_option( "--wallet-url", wallet_url, localized("the http/https URL where keosd is running"), true ); app.add_option( "-r,--header", header_opt_callback, localized("pass specific HTTP header; repeat this option to pass multiple headers")); app.add_flag( "-n,--no-verify", no_verify, localized("don't verify peer certificate when using HTTPS")); app.add_flag( "--no-auto-keosd", no_auto_keosd, localized("don't automatically launch a keosd if one is not currently running")); app.set_callback([&app]{ ensure_keosd_running(&app);}); bool verbose_errors = false; app.add_flag( "-v,--verbose", verbose_errors, localized("output verbose actions on error")); app.add_flag("--print-request", print_request, localized("print HTTP request to STDERR")); app.add_flag("--print-response", print_response, localized("print HTTP response to STDERR")); auto version = app.add_subcommand("version", localized("Retrieve version information"), false); version->require_subcommand(); version->add_subcommand("client", localized("Retrieve version information of the client"))->set_callback([] { std::cout << localized("Build version: ${ver}", ("ver", eosio::client::config::version_str)) << std::endl; }); // Create subcommand auto create = app.add_subcommand("create", localized("Create various items, on and off the blockchain"), false); create->require_subcommand(); bool r1 = false; string key_file; bool print_console = false; // create key auto create_key = create->add_subcommand("key", localized("Create a new keypair and print the public and private keys"))->set_callback( [&r1, &key_file, &print_console](){ if (key_file.empty() && !print_console) { std::cerr << "ERROR: Either indicate a file using \"--file\" or pass \"--to-console\"" << std::endl; return; } auto pk = r1 ? private_key_type::generate_r1() : private_key_type::generate(); auto privs = string(pk); auto pubs = string(pk.get_public_key()); if (print_console) { std::cout << localized("Private key: ${key}", ("key", privs) ) << std::endl; std::cout << localized("Public key: ${key}", ("key", pubs ) ) << std::endl; } else { std::cerr << localized("saving keys to ${filename}", ("filename", key_file)) << std::endl; std::ofstream out( key_file.c_str() ); out << localized("Private key: ${key}", ("key", privs) ) << std::endl; out << localized("Public key: ${key}", ("key", pubs ) ) << std::endl; } }); create_key->add_flag( "--r1", r1, "Generate a key using the R1 curve (iPhone), instead of the K1 curve (Bitcoin)" ); create_key->add_option("-f,--file", key_file, localized("Name of file to write private/public key output to. (Must be set, unless \"--to-console\" is passed")); create_key->add_flag( "--to-console", print_console, localized("Print private/public keys to console.")); // create account auto createAccount = create_account_subcommand( create, true /*simple*/ ); // convert subcommand auto convert = app.add_subcommand("convert", localized("Pack and unpack transactions"), false); // TODO also add converting action args based on abi from here ? convert->require_subcommand(); // pack transaction string plain_signed_transaction_json; bool pack_action_data_flag = false; auto pack_transaction = convert->add_subcommand("pack_transaction", localized("From plain signed json to packed form")); pack_transaction->add_option("transaction", plain_signed_transaction_json, localized("The plain signed json (string)"))->required(); pack_transaction->add_flag("--pack-action-data", pack_action_data_flag, localized("Pack all action data within transaction, needs interaction with nodeos")); pack_transaction->set_callback([&] { fc::variant trx_var; try { trx_var = json_from_file_or_string( plain_signed_transaction_json ); } EOS_RETHROW_EXCEPTIONS( transaction_type_exception, "Fail to parse plain transaction JSON '${data}'", ("data", plain_signed_transaction_json)) if( pack_action_data_flag ) { signed_transaction trx; abi_serializer::from_variant( trx_var, trx, abi_serializer_resolver, abi_serializer_max_time ); std::cout << fc::json::to_pretty_string( packed_transaction( trx, packed_transaction::none )) << std::endl; } else { try { signed_transaction trx = trx_var.as<signed_transaction>(); std::cout << fc::json::to_pretty_string( fc::variant( packed_transaction( trx, packed_transaction::none ))) << std::endl; } EOS_RETHROW_EXCEPTIONS( transaction_type_exception, "Fail to convert transaction, --pack-action-data likely needed" ) } }); // unpack transaction string packed_transaction_json; bool unpack_action_data_flag = false; auto unpack_transaction = convert->add_subcommand("unpack_transaction", localized("From packed to plain signed json form")); unpack_transaction->add_option("transaction", packed_transaction_json, localized("The packed transaction json (string containing packed_trx and optionally compression fields)"))->required(); unpack_transaction->add_flag("--unpack-action-data", unpack_action_data_flag, localized("Unpack all action data within transaction, needs interaction with nodeos")); unpack_transaction->set_callback([&] { fc::variant packed_trx_var; packed_transaction packed_trx; try { packed_trx_var = json_from_file_or_string( packed_transaction_json ); fc::from_variant<packed_transaction>( packed_trx_var, packed_trx ); } EOS_RETHROW_EXCEPTIONS( transaction_type_exception, "Fail to parse packed transaction JSON '${data}'", ("data", packed_transaction_json)) signed_transaction strx = packed_trx.get_signed_transaction(); fc::variant trx_var; if( unpack_action_data_flag ) { abi_serializer::to_variant( strx, trx_var, abi_serializer_resolver, abi_serializer_max_time ); } else { trx_var = strx; } std::cout << fc::json::to_pretty_string( trx_var ) << std::endl; }); // pack action data string unpacked_action_data_account_string; string unpacked_action_data_name_string; string unpacked_action_data_string; auto pack_action_data = convert->add_subcommand("pack_action_data", localized("From json action data to packed form")); pack_action_data->add_option("account", unpacked_action_data_account_string, localized("The name of the account that hosts the contract"))->required(); pack_action_data->add_option("name", unpacked_action_data_name_string, localized("The name of the function that's called by this action"))->required(); pack_action_data->add_option("unpacked_action_data", unpacked_action_data_string, localized("The action data expressed as json"))->required(); pack_action_data->set_callback([&] { fc::variant unpacked_action_data_json; try { unpacked_action_data_json = json_from_file_or_string(unpacked_action_data_string); } EOS_RETHROW_EXCEPTIONS(transaction_type_exception, "Fail to parse unpacked action data JSON") bytes packed_action_data_string = variant_to_bin(unpacked_action_data_account_string, unpacked_action_data_name_string, unpacked_action_data_json); std::cout << fc::to_hex(packed_action_data_string.data(), packed_action_data_string.size()) << std::endl; }); // unpack action data string packed_action_data_account_string; string packed_action_data_name_string; string packed_action_data_string; auto unpack_action_data = convert->add_subcommand("unpack_action_data", localized("From packed to json action data form")); unpack_action_data->add_option("account", packed_action_data_account_string, localized("The name of the account that hosts the contract"))->required(); unpack_action_data->add_option("name", packed_action_data_name_string, localized("The name of the function that's called by this action"))->required(); unpack_action_data->add_option("packed_action_data", packed_action_data_string, localized("The action data expressed as packed hex string"))->required(); unpack_action_data->set_callback([&] { EOS_ASSERT( packed_action_data_string.size() >= 2, transaction_type_exception, "No packed_action_data found" ); vector<char> packed_action_data_blob(packed_action_data_string.size()/2); fc::from_hex(packed_action_data_string, packed_action_data_blob.data(), packed_action_data_blob.size()); fc::variant unpacked_action_data_json = bin_to_variant(packed_action_data_account_string, packed_action_data_name_string, packed_action_data_blob); std::cout << fc::json::to_pretty_string(unpacked_action_data_json) << std::endl; }); // Get subcommand auto get = app.add_subcommand("get", localized("Retrieve various items and information from the blockchain"), false); get->require_subcommand(); // get info get->add_subcommand("info", localized("Get current blockchain information"))->set_callback([] { std::cout << fc::json::to_pretty_string(get_info()) << std::endl; }); // get block string blockArg; bool get_bhs = false; auto getBlock = get->add_subcommand("block", localized("Retrieve a full block from the blockchain"), false); getBlock->add_option("block", blockArg, localized("The number or ID of the block to retrieve"))->required(); getBlock->add_flag("--header-state", get_bhs, localized("Get block header state from fork database instead") ); getBlock->set_callback([&blockArg,&get_bhs] { auto arg = fc::mutable_variant_object("block_num_or_id", blockArg); if( get_bhs ) { std::cout << fc::json::to_pretty_string(call(get_block_header_state_func, arg)) << std::endl; } else { std::cout << fc::json::to_pretty_string(call(get_block_func, arg)) << std::endl; } }); // get account string accountName; bool print_json; auto getAccount = get->add_subcommand("account", localized("Retrieve an account from the blockchain"), false); getAccount->add_option("name", accountName, localized("The name of the account to retrieve"))->required(); getAccount->add_flag("--json,-j", print_json, localized("Output in JSON format") ); getAccount->set_callback([&]() { get_account(accountName, print_json); }); // get code string codeFilename; string abiFilename; bool code_as_wasm = false; auto getCode = get->add_subcommand("code", localized("Retrieve the code and ABI for an account"), false); getCode->add_option("name", accountName, localized("The name of the account whose code should be retrieved"))->required(); getCode->add_option("-c,--code",codeFilename, localized("The name of the file to save the contract .wast/wasm to") ); getCode->add_option("-a,--abi",abiFilename, localized("The name of the file to save the contract .abi to") ); getCode->add_flag("--wasm", code_as_wasm, localized("Save contract as wasm")); getCode->set_callback([&] { string code_hash, wasm, wast, abi; try { const auto result = call(get_raw_code_and_abi_func, fc::mutable_variant_object("account_name", accountName)); const std::vector<char> wasm_v = result["wasm"].as_blob().data; const std::vector<char> abi_v = result["abi"].as_blob().data; fc::sha256 hash; if(wasm_v.size()) hash = fc::sha256::hash(wasm_v.data(), wasm_v.size()); code_hash = (string)hash; wasm = string(wasm_v.begin(), wasm_v.end()); if(!code_as_wasm && wasm_v.size()) wast = wasm_to_wast((const uint8_t*)wasm_v.data(), wasm_v.size(), false); abi_def abi_d; if(abi_serializer::to_abi(abi_v, abi_d)) abi = fc::json::to_pretty_string(abi_d); } catch(chain::missing_chain_api_plugin_exception&) { //see if this is an old nodeos that doesn't support get_raw_code_and_abi const auto old_result = call(get_code_func, fc::mutable_variant_object("account_name", accountName)("code_as_wasm",code_as_wasm)); code_hash = old_result["code_hash"].as_string(); if(code_as_wasm) { wasm = old_result["wasm"].as_string(); std::cout << localized("Warning: communicating to older nodeos which returns malformed binary wasm") << std::endl; } else wast = old_result["wast"].as_string(); abi = fc::json::to_pretty_string(old_result["abi"]); } std::cout << localized("code hash: ${code_hash}", ("code_hash", code_hash)) << std::endl; if( codeFilename.size() ){ std::cout << localized("saving ${type} to ${codeFilename}", ("type", (code_as_wasm ? "wasm" : "wast"))("codeFilename", codeFilename)) << std::endl; std::ofstream out( codeFilename.c_str() ); if(code_as_wasm) out << wasm; else out << wast; } if( abiFilename.size() ) { std::cout << localized("saving abi to ${abiFilename}", ("abiFilename", abiFilename)) << std::endl; std::ofstream abiout( abiFilename.c_str() ); abiout << abi; } }); // get abi string filename; auto getAbi = get->add_subcommand("abi", localized("Retrieve the ABI for an account"), false); getAbi->add_option("name", accountName, localized("The name of the account whose abi should be retrieved"))->required(); getAbi->add_option("-f,--file",filename, localized("The name of the file to save the contract .abi to instead of writing to console") ); getAbi->set_callback([&] { auto result = call(get_abi_func, fc::mutable_variant_object("account_name", accountName)); auto abi = fc::json::to_pretty_string( result["abi"] ); if( filename.size() ) { std::cerr << localized("saving abi to ${filename}", ("filename", filename)) << std::endl; std::ofstream abiout( filename.c_str() ); abiout << abi; } else { std::cout << abi << "\n"; } }); // get table string scope; string code; string table; string lower; string upper; string table_key; string key_type; string encode_type{"dec"}; bool binary = false; uint32_t limit = 10; string index_position; auto getTable = get->add_subcommand( "table", localized("Retrieve the contents of a database table"), false); getTable->add_option( "account", code, localized("The account who owns the table") )->required(); getTable->add_option( "scope", scope, localized("The scope within the contract in which the table is found") )->required(); getTable->add_option( "table", table, localized("The name of the table as specified by the contract abi") )->required(); getTable->add_option( "-b,--binary", binary, localized("Return the value as BINARY rather than using abi to interpret as JSON") ); getTable->add_option( "-l,--limit", limit, localized("The maximum number of rows to return") ); getTable->add_option( "-k,--key", table_key, localized("Deprecated") ); getTable->add_option( "-L,--lower", lower, localized("JSON representation of lower bound value of key, defaults to first") ); getTable->add_option( "-U,--upper", upper, localized("JSON representation of upper bound value of key, defaults to last") ); getTable->add_option( "--index", index_position, localized("Index number, 1 - primary (first), 2 - secondary index (in order defined by multi_index), 3 - third index, etc.\n" "\t\t\t\tNumber or name of index can be specified, e.g. 'secondary' or '2'.")); getTable->add_option( "--key-type", key_type, localized("The key type of --index, primary only supports (i64), all others support (i64, i128, i256, float64, float128, ripemd160, sha256).\n" "\t\t\t\tSpecial type 'name' indicates an account name.")); getTable->add_option( "--encode-type", encode_type, localized("The encoding type of key_type (i64 , i128 , float64, float128) only support decimal encoding e.g. 'dec'" "i256 - supports both 'dec' and 'hex', ripemd160 and sha256 is 'hex' only\n")); getTable->set_callback([&] { auto result = call(get_table_func, fc::mutable_variant_object("json", !binary) ("code",code) ("scope",scope) ("table",table) ("table_key",table_key) // not used ("lower_bound",lower) ("upper_bound",upper) ("limit",limit) ("key_type",key_type) ("index_position", index_position) ("encode_type", encode_type) ); std::cout << fc::json::to_pretty_string(result) << std::endl; }); auto getScope = get->add_subcommand( "scope", localized("Retrieve a list of scopes and tables owned by a contract"), false); getScope->add_option( "contract", code, localized("The contract who owns the table") )->required(); getScope->add_option( "-t,--table", table, localized("The name of the table as filter") ); getScope->add_option( "-l,--limit", limit, localized("The maximum number of rows to return") ); getScope->add_option( "-L,--lower", lower, localized("lower bound of scope") ); getScope->add_option( "-U,--upper", upper, localized("upper bound of scope") ); getScope->set_callback([&] { auto result = call(get_table_by_scope_func, fc::mutable_variant_object("code",code) ("table",table) ("lower_bound",lower) ("upper_bound",upper) ("limit",limit) ); std::cout << fc::json::to_pretty_string(result) << std::endl; }); // currency accessors // get currency balance string symbol; auto get_currency = get->add_subcommand( "currency", localized("Retrieve information related to standard currencies"), true); get_currency->require_subcommand(); auto get_balance = get_currency->add_subcommand( "balance", localized("Retrieve the balance of an account for a given currency"), false); get_balance->add_option( "contract", code, localized("The contract that operates the currency") )->required(); get_balance->add_option( "account", accountName, localized("The account to query balances for") )->required(); get_balance->add_option( "symbol", symbol, localized("The symbol for the currency if the contract operates multiple currencies") ); get_balance->set_callback([&] { auto result = call(get_currency_balance_func, fc::mutable_variant_object ("account", accountName) ("code", code) ("symbol", symbol.empty() ? fc::variant() : symbol) ); const auto& rows = result.get_array(); for( const auto& r : rows ) { std::cout << r.as_string() << std::endl; } }); auto get_currency_stats = get_currency->add_subcommand( "stats", localized("Retrieve the stats of for a given currency"), false); get_currency_stats->add_option( "contract", code, localized("The contract that operates the currency") )->required(); get_currency_stats->add_option( "symbol", symbol, localized("The symbol for the currency if the contract operates multiple currencies") )->required(); get_currency_stats->set_callback([&] { auto result = call(get_currency_stats_func, fc::mutable_variant_object("json", false) ("code", code) ("symbol", symbol) ); std::cout << fc::json::to_pretty_string(result) << std::endl; }); // get accounts string public_key_str; auto getAccounts = get->add_subcommand("accounts", localized("Retrieve accounts associated with a public key"), false); getAccounts->add_option("public_key", public_key_str, localized("The public key to retrieve accounts for"))->required(); getAccounts->set_callback([&] { public_key_type public_key; try { public_key = public_key_type(public_key_str); } EOS_RETHROW_EXCEPTIONS(public_key_type_exception, "Invalid public key: ${public_key}", ("public_key", public_key_str)) auto arg = fc::mutable_variant_object( "public_key", public_key); std::cout << fc::json::to_pretty_string(call(get_key_accounts_func, arg)) << std::endl; }); // get servants string controllingAccount; auto getServants = get->add_subcommand("servants", localized("Retrieve accounts which are servants of a given account "), false); getServants->add_option("account", controllingAccount, localized("The name of the controlling account"))->required(); getServants->set_callback([&] { auto arg = fc::mutable_variant_object( "controlling_account", controllingAccount); std::cout << fc::json::to_pretty_string(call(get_controlled_accounts_func, arg)) << std::endl; }); // get transaction string transaction_id_str; uint32_t block_num_hint = 0; auto getTransaction = get->add_subcommand("transaction", localized("Retrieve a transaction from the blockchain"), false); getTransaction->add_option("id", transaction_id_str, localized("ID of the transaction to retrieve"))->required(); getTransaction->add_option( "-b,--block-hint", block_num_hint, localized("the block number this transaction may be in") ); getTransaction->set_callback([&] { auto arg= fc::mutable_variant_object( "id", transaction_id_str); if ( block_num_hint > 0 ) { arg = arg("block_num_hint", block_num_hint); } std::cout << fc::json::to_pretty_string(call(get_transaction_func, arg)) << std::endl; }); // get actions string account_name; string skip_seq_str; string num_seq_str; bool printjson = false; bool fullact = false; bool prettyact = false; bool printconsole = false; int32_t pos_seq = -1; int32_t offset = -20; auto getActions = get->add_subcommand("actions", localized("Retrieve all actions with specific account name referenced in authorization or receiver"), false); getActions->add_option("account_name", account_name, localized("name of account to query on"))->required(); getActions->add_option("pos", pos_seq, localized("sequence number of action for this account, -1 for last")); getActions->add_option("offset", offset, localized("get actions [pos,pos+offset] for positive offset or [pos-offset,pos) for negative offset")); getActions->add_flag("--json,-j", printjson, localized("print full json")); getActions->add_flag("--full", fullact, localized("don't truncate action json")); getActions->add_flag("--pretty", prettyact, localized("pretty print full action json ")); getActions->add_flag("--console", printconsole, localized("print console output generated by action ")); getActions->set_callback([&] { fc::mutable_variant_object arg; arg( "account_name", account_name ); arg( "pos", pos_seq ); arg( "offset", offset); auto result = call(get_actions_func, arg); if( printjson ) { std::cout << fc::json::to_pretty_string(result) << std::endl; } else { auto& traces = result["actions"].get_array(); uint32_t lib = result["last_irreversible_block"].as_uint64(); cout << "#" << setw(5) << "seq" << " " << setw( 24 ) << left << "when"<< " " << setw(24) << right << "contract::action" << " => " << setw(13) << left << "receiver" << " " << setw(11) << left << "trx id..." << " args\n"; cout << "================================================================================================================\n"; for( const auto& trace: traces ) { std::stringstream out; if( trace["block_num"].as_uint64() <= lib ) out << "#"; else out << "?"; out << setw(5) << trace["account_action_seq"].as_uint64() <<" "; out << setw(24) << trace["block_time"].as_string() <<" "; const auto& at = trace["action_trace"].get_object(); auto id = at["trx_id"].as_string(); const auto& receipt = at["receipt"]; auto receiver = receipt["receiver"].as_string(); const auto& act = at["act"].get_object(); auto code = act["account"].as_string(); auto func = act["name"].as_string(); string args; if( prettyact ) { args = fc::json::to_pretty_string( act["data"] ); } else { args = fc::json::to_string( act["data"] ); if( !fullact ) { args = args.substr(0,60) + "..."; } } out << std::setw(24) << std::right<< (code +"::" + func) << " => " << left << std::setw(13) << receiver; out << " " << setw(11) << (id.substr(0,8) + "..."); if( fullact || prettyact ) out << "\n"; else out << " "; out << args ;//<< "\n"; if( trace["block_num"].as_uint64() <= lib ) { dlog( "\r${m}", ("m",out.str()) ); } else { wlog( "\r${m}", ("m",out.str()) ); } if( printconsole ) { auto console = at["console"].as_string(); if( console.size() ) { stringstream out; std::stringstream ss(console); string line; std::getline( ss, line ); out << ">> " << line << "\n"; cerr << out.str(); //ilog( "\r${m} ", ("m",out.str()) ); } } } } }); auto getSchedule = get_schedule_subcommand{get}; auto getTransactionId = get_transaction_id_subcommand{get}; /* auto getTransactions = get->add_subcommand("transactions", localized("Retrieve all transactions with specific account name referenced in their scope"), false); getTransactions->add_option("account_name", account_name, localized("name of account to query on"))->required(); getTransactions->add_option("skip_seq", skip_seq_str, localized("Number of most recent transactions to skip (0 would start at most recent transaction)")); getTransactions->add_option("num_seq", num_seq_str, localized("Number of transactions to return")); getTransactions->add_flag("--json,-j", printjson, localized("print full json")); getTransactions->set_callback([&] { fc::mutable_variant_object arg; if (skip_seq_str.empty()) { arg = fc::mutable_variant_object( "account_name", account_name); } else { uint64_t skip_seq; try { skip_seq = boost::lexical_cast<uint64_t>(skip_seq_str); } EOS_RETHROW_EXCEPTIONS(chain_type_exception, "Invalid Skip Seq: ${skip_seq}", ("skip_seq", skip_seq_str)) if (num_seq_str.empty()) { arg = fc::mutable_variant_object( "account_name", account_name)("skip_seq", skip_seq); } else { uint64_t num_seq; try { num_seq = boost::lexical_cast<uint64_t>(num_seq_str); } EOS_RETHROW_EXCEPTIONS(chain_type_exception, "Invalid Num Seq: ${num_seq}", ("num_seq", num_seq_str)) arg = fc::mutable_variant_object( "account_name", account_name)("skip_seq", skip_seq_str)("num_seq", num_seq); } } auto result = call(get_transactions_func, arg); if( printjson ) { std::cout << fc::json::to_pretty_string(result) << std::endl; } else { const auto& trxs = result.get_object()["transactions"].get_array(); for( const auto& t : trxs ) { const auto& tobj = t.get_object(); const auto& trx = tobj["transaction"].get_object(); const auto& data = trx["transaction"].get_object(); const auto& msgs = data["actions"].get_array(); for( const auto& msg : msgs ) { int64_t seq_num = tobj["seq_num"].as<int64_t>(); string id = tobj["transaction_id"].as_string(); const auto& exp = data["expiration"].as<fc::time_point_sec>(); std::cout << tobj["seq_num"].as_string() <<"] " << id.substr(0,8) << "... " << data["expiration"].as_string() << " "; auto code = msg["account"].as_string(); auto func = msg["name"].as_string(); auto args = fc::json::to_string( msg["data"] ); std::cout << setw(26) << left << (code + "::" + func) << " " << args; std::cout << std::endl; } } } }); */ // set subcommand auto setSubcommand = app.add_subcommand("set", localized("Set or update blockchain state")); setSubcommand->require_subcommand(); // set contract subcommand string account; string contractPath; string wasmPath; string abiPath; bool shouldSend = true; bool contract_clear = false; bool suppress_duplicate_check = false; auto codeSubcommand = setSubcommand->add_subcommand("code", localized("Create or update the code on an account")); codeSubcommand->add_option("account", account, localized("The account to set code for"))->required(); codeSubcommand->add_option("code-file", wasmPath, localized("The fullpath containing the contract WASM"));//->required(); codeSubcommand->add_flag( "-c,--clear", contract_clear, localized("Remove code on an account")); codeSubcommand->add_flag( "--suppress-duplicate-check", suppress_duplicate_check, localized("Don't check for duplicate")); auto abiSubcommand = setSubcommand->add_subcommand("abi", localized("Create or update the abi on an account")); abiSubcommand->add_option("account", account, localized("The account to set the ABI for"))->required(); abiSubcommand->add_option("abi-file", abiPath, localized("The fullpath containing the contract ABI"));//->required(); abiSubcommand->add_flag( "-c,--clear", contract_clear, localized("Remove abi on an account")); abiSubcommand->add_flag( "--suppress-duplicate-check", suppress_duplicate_check, localized("Don't check for duplicate")); auto contractSubcommand = setSubcommand->add_subcommand("contract", localized("Create or update the contract on an account")); contractSubcommand->add_option("account", account, localized("The account to publish a contract for")) ->required(); contractSubcommand->add_option("contract-dir", contractPath, localized("The path containing the .wasm and .abi")); // ->required(); contractSubcommand->add_option("wasm-file", wasmPath, localized("The file containing the contract WASM relative to contract-dir")); // ->check(CLI::ExistingFile); auto abi = contractSubcommand->add_option("abi-file,-a,--abi", abiPath, localized("The ABI for the contract relative to contract-dir")); // ->check(CLI::ExistingFile); contractSubcommand->add_flag( "-c,--clear", contract_clear, localized("Rmove contract on an account")); contractSubcommand->add_flag( "--suppress-duplicate-check", suppress_duplicate_check, localized("Don't check for duplicate")); std::vector<chain::action> actions; auto set_code_callback = [&]() { std::vector<char> old_wasm; bool duplicate = false; fc::sha256 old_hash, new_hash; if (!suppress_duplicate_check) { try { const auto result = call(get_code_hash_func, fc::mutable_variant_object("account_name", account)); old_hash = fc::sha256(result["code_hash"].as_string()); } catch (...) { std::cerr << "Failed to get existing code hash, continue without duplicate check..." << std::endl; suppress_duplicate_check = true; } } bytes code_bytes; if(!contract_clear){ std::string wasm; fc::path cpath(contractPath); if( cpath.filename().generic_string() == "." ) cpath = cpath.parent_path(); if( wasmPath.empty() ) wasmPath = (cpath / (cpath.filename().generic_string()+".wasm")).generic_string(); else wasmPath = (cpath / wasmPath).generic_string(); std::cerr << localized(("Reading WASM from " + wasmPath + "...").c_str()) << std::endl; fc::read_file_contents(wasmPath, wasm); EOS_ASSERT( !wasm.empty(), wast_file_not_found, "no wasm file found ${f}", ("f", wasmPath) ); const string binary_wasm_header("\x00\x61\x73\x6d\x01\x00\x00\x00", 8); if(wasm.compare(0, 8, binary_wasm_header)) std::cerr << localized("WARNING: ") << wasmPath << localized(" doesn't look like a binary WASM file. Is it something else, like WAST? Trying anyways...") << std::endl; code_bytes = bytes(wasm.begin(), wasm.end()); } else { code_bytes = bytes(); } if (!suppress_duplicate_check) { if (code_bytes.size()) { new_hash = fc::sha256::hash(&(code_bytes[0]), code_bytes.size()); } duplicate = (old_hash == new_hash); } if (!duplicate) { actions.emplace_back( create_setcode(account, code_bytes ) ); if ( shouldSend ) { std::cerr << localized("Setting Code...") << std::endl; send_actions(std::move(actions), 10000, packed_transaction::zlib); } } else { std::cout << "Skipping set code because the new code is the same as the existing code" << std::endl; } }; auto set_abi_callback = [&]() { bytes old_abi; bool duplicate = false; if (!suppress_duplicate_check) { try { const auto result = call(get_raw_abi_func, fc::mutable_variant_object("account_name", account)); old_abi = result["abi"].as_blob().data; } catch (...) { std::cerr << "Failed to get existing raw abi, continue without duplicate check..." << std::endl; suppress_duplicate_check = true; } } bytes abi_bytes; if(!contract_clear){ fc::path cpath(contractPath); if( cpath.filename().generic_string() == "." ) cpath = cpath.parent_path(); if( abiPath.empty() ) { abiPath = (cpath / (cpath.filename().generic_string()+".abi")).generic_string(); } else { abiPath = (cpath / abiPath).generic_string(); } EOS_ASSERT( fc::exists( abiPath ), abi_file_not_found, "no abi file found ${f}", ("f", abiPath) ); abi_bytes = fc::raw::pack(fc::json::from_file(abiPath).as<abi_def>()); } else { abi_bytes = bytes(); } if (!suppress_duplicate_check) { duplicate = (old_abi.size() == abi_bytes.size() && std::equal(old_abi.begin(), old_abi.end(), abi_bytes.begin())); } if (!duplicate) { try { actions.emplace_back( create_setabi(account, abi_bytes) ); } EOS_RETHROW_EXCEPTIONS(abi_type_exception, "Fail to parse ABI JSON") if ( shouldSend ) { std::cerr << localized("Setting ABI...") << std::endl; send_actions(std::move(actions), 10000, packed_transaction::zlib); } } else { std::cout << "Skipping set abi because the new abi is the same as the existing abi" << std::endl; } }; add_standard_transaction_options(contractSubcommand, "account@active"); add_standard_transaction_options(codeSubcommand, "account@active"); add_standard_transaction_options(abiSubcommand, "account@active"); contractSubcommand->set_callback([&] { if(!contract_clear) EOS_ASSERT( !contractPath.empty(), contract_exception, " contract-dir is null ", ("f", contractPath) ); shouldSend = false; set_code_callback(); set_abi_callback(); if (actions.size()) { std::cerr << localized("Publishing contract...") << std::endl; send_actions(std::move(actions), 10000, packed_transaction::zlib); } else { std::cout << "no transaction is sent" << std::endl; } }); codeSubcommand->set_callback(set_code_callback); abiSubcommand->set_callback(set_abi_callback); // set account auto setAccount = setSubcommand->add_subcommand("account", localized("set or update blockchain account state"))->require_subcommand(); // set account permission auto setAccountPermission = set_account_permission_subcommand(setAccount); // set action auto setAction = setSubcommand->add_subcommand("action", localized("set or update blockchain action state"))->require_subcommand(); // set action permission auto setActionPermission = set_action_permission_subcommand(setAction); // Transfer subcommand string con = "eosio.token"; string sender; string recipient; string amount; string memo; bool pay_ram = false; auto transfer = app.add_subcommand("transfer", localized("Transfer EOS from account to account"), false); transfer->add_option("sender", sender, localized("The account sending EOS"))->required(); transfer->add_option("recipient", recipient, localized("The account receiving EOS"))->required(); transfer->add_option("amount", amount, localized("The amount of EOS to send"))->required(); transfer->add_option("memo", memo, localized("The memo for the transfer")); transfer->add_option("--contract,-c", con, localized("The contract which controls the token")); transfer->add_flag("--pay-ram-to-open", pay_ram, localized("Pay ram to open recipient's token balance row")); add_standard_transaction_options(transfer, "sender@active"); transfer->set_callback([&] { if (tx_force_unique && memo.size() == 0) { // use the memo to add a nonce memo = generate_nonce_string(); tx_force_unique = false; } auto transfer_amount = to_asset(con, amount); auto transfer = create_transfer(con, sender, recipient, transfer_amount, memo); if (!pay_ram) { send_actions( { transfer }); } else { auto open_ = create_open(con, recipient, transfer_amount.get_symbol(), sender); send_actions( { open_, transfer } ); } }); // Net subcommand string new_host; auto net = app.add_subcommand( "net", localized("Interact with local p2p network connections"), false ); net->require_subcommand(); auto connect = net->add_subcommand("connect", localized("start a new connection to a peer"), false); connect->add_option("host", new_host, localized("The hostname:port to connect to."))->required(); connect->set_callback([&] { const auto& v = call(url, net_connect, new_host); std::cout << fc::json::to_pretty_string(v) << std::endl; }); auto disconnect = net->add_subcommand("disconnect", localized("close an existing connection"), false); disconnect->add_option("host", new_host, localized("The hostname:port to disconnect from."))->required(); disconnect->set_callback([&] { const auto& v = call(url, net_disconnect, new_host); std::cout << fc::json::to_pretty_string(v) << std::endl; }); auto status = net->add_subcommand("status", localized("status of existing connection"), false); status->add_option("host", new_host, localized("The hostname:port to query status of connection"))->required(); status->set_callback([&] { const auto& v = call(url, net_status, new_host); std::cout << fc::json::to_pretty_string(v) << std::endl; }); auto connections = net->add_subcommand("peers", localized("status of all existing peers"), false); connections->set_callback([&] { const auto& v = call(url, net_connections, new_host); std::cout << fc::json::to_pretty_string(v) << std::endl; }); // Wallet subcommand auto wallet = app.add_subcommand( "wallet", localized("Interact with local wallet"), false ); wallet->require_subcommand(); // create wallet string wallet_name = "default"; string password_file; auto createWallet = wallet->add_subcommand("create", localized("Create a new wallet locally"), false); createWallet->add_option("-n,--name", wallet_name, localized("The name of the new wallet"), true); createWallet->add_option("-f,--file", password_file, localized("Name of file to write wallet password output to. (Must be set, unless \"--to-console\" is passed")); createWallet->add_flag( "--to-console", print_console, localized("Print password to console.")); createWallet->set_callback([&wallet_name, &password_file, &print_console] { if (password_file.empty() && !print_console) { std::cerr << "ERROR: Either indicate a file using \"--file\" or pass \"--to-console\"" << std::endl; return; } const auto& v = call(wallet_url, wallet_create, wallet_name); std::cout << localized("Creating wallet: ${wallet_name}", ("wallet_name", wallet_name)) << std::endl; std::cout << localized("Save password to use in the future to unlock this wallet.") << std::endl; std::cout << localized("Without password imported keys will not be retrievable.") << std::endl; if (print_console) { std::cout << fc::json::to_pretty_string(v) << std::endl; } else { std::cerr << localized("saving password to ${filename}", ("filename", password_file)) << std::endl; std::ofstream out( password_file.c_str() ); out << fc::json::to_pretty_string(v); } }); // open wallet auto openWallet = wallet->add_subcommand("open", localized("Open an existing wallet"), false); openWallet->add_option("-n,--name", wallet_name, localized("The name of the wallet to open")); openWallet->set_callback([&wallet_name] { call(wallet_url, wallet_open, wallet_name); std::cout << localized("Opened: ${wallet_name}", ("wallet_name", wallet_name)) << std::endl; }); // lock wallet auto lockWallet = wallet->add_subcommand("lock", localized("Lock wallet"), false); lockWallet->add_option("-n,--name", wallet_name, localized("The name of the wallet to lock")); lockWallet->set_callback([&wallet_name] { call(wallet_url, wallet_lock, wallet_name); std::cout << localized("Locked: ${wallet_name}", ("wallet_name", wallet_name)) << std::endl; }); // lock all wallets auto locakAllWallets = wallet->add_subcommand("lock_all", localized("Lock all unlocked wallets"), false); locakAllWallets->set_callback([] { call(wallet_url, wallet_lock_all); std::cout << localized("Locked All Wallets") << std::endl; }); // unlock wallet string wallet_pw; auto unlockWallet = wallet->add_subcommand("unlock", localized("Unlock wallet"), false); unlockWallet->add_option("-n,--name", wallet_name, localized("The name of the wallet to unlock")); unlockWallet->add_option("--password", wallet_pw, localized("The password returned by wallet create")); unlockWallet->set_callback([&wallet_name, &wallet_pw] { prompt_for_wallet_password(wallet_pw, wallet_name); fc::variants vs = {fc::variant(wallet_name), fc::variant(wallet_pw)}; call(wallet_url, wallet_unlock, vs); std::cout << localized("Unlocked: ${wallet_name}", ("wallet_name", wallet_name)) << std::endl; }); // import keys into wallet string wallet_key_str; auto importWallet = wallet->add_subcommand("import", localized("Import private key into wallet"), false); importWallet->add_option("-n,--name", wallet_name, localized("The name of the wallet to import key into")); importWallet->add_option("--private-key", wallet_key_str, localized("Private key in WIF format to import")); importWallet->set_callback([&wallet_name, &wallet_key_str] { if( wallet_key_str.size() == 0 ) { std::cout << localized("private key: "); fc::set_console_echo(false); std::getline( std::cin, wallet_key_str, '\n' ); fc::set_console_echo(true); } private_key_type wallet_key; try { wallet_key = private_key_type( wallet_key_str ); } catch (...) { EOS_THROW(private_key_type_exception, "Invalid private key: ${private_key}", ("private_key", wallet_key_str)) } public_key_type pubkey = wallet_key.get_public_key(); fc::variants vs = {fc::variant(wallet_name), fc::variant(wallet_key)}; call(wallet_url, wallet_import_key, vs); std::cout << localized("imported private key for: ${pubkey}", ("pubkey", std::string(pubkey))) << std::endl; }); // remove keys from wallet string wallet_rm_key_str; auto removeKeyWallet = wallet->add_subcommand("remove_key", localized("Remove key from wallet"), false); removeKeyWallet->add_option("-n,--name", wallet_name, localized("The name of the wallet to remove key from")); removeKeyWallet->add_option("key", wallet_rm_key_str, localized("Public key in WIF format to remove"))->required(); removeKeyWallet->add_option("--password", wallet_pw, localized("The password returned by wallet create")); removeKeyWallet->set_callback([&wallet_name, &wallet_pw, &wallet_rm_key_str] { prompt_for_wallet_password(wallet_pw, wallet_name); public_key_type pubkey; try { pubkey = public_key_type( wallet_rm_key_str ); } catch (...) { EOS_THROW(public_key_type_exception, "Invalid public key: ${public_key}", ("public_key", wallet_rm_key_str)) } fc::variants vs = {fc::variant(wallet_name), fc::variant(wallet_pw), fc::variant(wallet_rm_key_str)}; call(wallet_url, wallet_remove_key, vs); std::cout << localized("removed private key for: ${pubkey}", ("pubkey", wallet_rm_key_str)) << std::endl; }); // create a key within wallet string wallet_create_key_type; auto createKeyInWallet = wallet->add_subcommand("create_key", localized("Create private key within wallet"), false); createKeyInWallet->add_option("-n,--name", wallet_name, localized("The name of the wallet to create key into"), true); createKeyInWallet->add_option("key_type", wallet_create_key_type, localized("Key type to create (K1/R1)"), true)->set_type_name("K1/R1"); createKeyInWallet->set_callback([&wallet_name, &wallet_create_key_type] { //an empty key type is allowed -- it will let the underlying wallet pick which type it prefers fc::variants vs = {fc::variant(wallet_name), fc::variant(wallet_create_key_type)}; const auto& v = call(wallet_url, wallet_create_key, vs); std::cout << localized("Created new private key with a public key of: ") << fc::json::to_pretty_string(v) << std::endl; }); // list wallets auto listWallet = wallet->add_subcommand("list", localized("List opened wallets, * = unlocked"), false); listWallet->set_callback([] { std::cout << localized("Wallets:") << std::endl; const auto& v = call(wallet_url, wallet_list); std::cout << fc::json::to_pretty_string(v) << std::endl; }); // list keys auto listKeys = wallet->add_subcommand("keys", localized("List of public keys from all unlocked wallets."), false); listKeys->set_callback([] { const auto& v = call(wallet_url, wallet_public_keys); std::cout << fc::json::to_pretty_string(v) << std::endl; }); // list private keys auto listPrivKeys = wallet->add_subcommand("private_keys", localized("List of private keys from an unlocked wallet in wif or PVT_R1 format."), false); listPrivKeys->add_option("-n,--name", wallet_name, localized("The name of the wallet to list keys from"), true); listPrivKeys->add_option("--password", wallet_pw, localized("The password returned by wallet create")); listPrivKeys->set_callback([&wallet_name, &wallet_pw] { prompt_for_wallet_password(wallet_pw, wallet_name); fc::variants vs = {fc::variant(wallet_name), fc::variant(wallet_pw)}; const auto& v = call(wallet_url, wallet_list_keys, vs); std::cout << fc::json::to_pretty_string(v) << std::endl; }); auto stopKeosd = wallet->add_subcommand("stop", localized("Stop keosd (doesn't work with nodeos)."), false); stopKeosd->set_callback([] { const auto& v = call(wallet_url, keosd_stop); if ( !v.is_object() || v.get_object().size() != 0 ) { //on success keosd responds with empty object std::cerr << fc::json::to_pretty_string(v) << std::endl; } else { std::cout << "OK" << std::endl; } }); // sign subcommand string trx_json_to_sign; string str_private_key; string str_chain_id; bool push_trx = false; auto sign = app.add_subcommand("sign", localized("Sign a transaction"), false); sign->add_option("transaction", trx_json_to_sign, localized("The JSON string or filename defining the transaction to sign"), true)->required(); sign->add_option("-k,--private-key", str_private_key, localized("The private key that will be used to sign the transaction")); sign->add_option("-c,--chain-id", str_chain_id, localized("The chain id that will be used to sign the transaction")); sign->add_flag( "-p,--push-transaction", push_trx, localized("Push transaction after signing")); sign->set_callback([&] { signed_transaction trx = json_from_file_or_string(trx_json_to_sign).as<signed_transaction>(); fc::optional<chain_id_type> chain_id; if( str_chain_id.size() == 0 ) { ilog( "grabbing chain_id from nodeos" ); auto info = get_info(); chain_id = info.chain_id; } else { chain_id = chain_id_type(str_chain_id); } if( str_private_key.size() == 0 ) { std::cerr << localized("private key: "); fc::set_console_echo(false); std::getline( std::cin, str_private_key, '\n' ); fc::set_console_echo(true); } auto priv_key = fc::crypto::private_key::regenerate(*utilities::wif_to_key(str_private_key)); trx.sign(priv_key, *chain_id); if(push_trx) { auto trx_result = call(push_txn_func, packed_transaction(trx, packed_transaction::none)); std::cout << fc::json::to_pretty_string(trx_result) << std::endl; } else { std::cout << fc::json::to_pretty_string(trx) << std::endl; } }); // Push subcommand auto push = app.add_subcommand("push", localized("Push arbitrary transactions to the blockchain"), false); push->require_subcommand(); // push action string contract_account; string action; string data; vector<string> permissions; auto actionsSubcommand = push->add_subcommand("action", localized("Push a transaction with a single action")); actionsSubcommand->fallthrough(false); actionsSubcommand->add_option("account", contract_account, localized("The account providing the contract to execute"), true)->required(); actionsSubcommand->add_option("action", action, localized("A JSON string or filename defining the action to execute on the contract"), true)->required(); actionsSubcommand->add_option("data", data, localized("The arguments to the contract"))->required(); add_standard_transaction_options(actionsSubcommand); actionsSubcommand->set_callback([&] { fc::variant action_args_var; if( !data.empty() ) { try { action_args_var = json_from_file_or_string(data, fc::json::relaxed_parser); } EOS_RETHROW_EXCEPTIONS(action_type_exception, "Fail to parse action JSON data='${data}'", ("data", data)) } auto accountPermissions = get_account_permissions(tx_permission); send_actions({chain::action{accountPermissions, contract_account, action, variant_to_bin( contract_account, action, action_args_var ) }}); }); // push transaction string trx_to_push; auto trxSubcommand = push->add_subcommand("transaction", localized("Push an arbitrary JSON transaction")); trxSubcommand->add_option("transaction", trx_to_push, localized("The JSON string or filename defining the transaction to push"))->required(); add_standard_transaction_options(trxSubcommand); trxSubcommand->set_callback([&] { fc::variant trx_var; try { trx_var = json_from_file_or_string(trx_to_push); } EOS_RETHROW_EXCEPTIONS(transaction_type_exception, "Fail to parse transaction JSON '${data}'", ("data",trx_to_push)) try { signed_transaction trx = trx_var.as<signed_transaction>(); std::cout << fc::json::to_pretty_string( push_transaction( trx )) << std::endl; } catch( fc::exception& ) { // unable to convert so try via abi signed_transaction trx; abi_serializer::from_variant( trx_var, trx, abi_serializer_resolver, abi_serializer_max_time ); std::cout << fc::json::to_pretty_string( push_transaction( trx )) << std::endl; } }); string trxsJson; auto trxsSubcommand = push->add_subcommand("transactions", localized("Push an array of arbitrary JSON transactions")); trxsSubcommand->add_option("transactions", trxsJson, localized("The JSON string or filename defining the array of the transactions to push"))->required(); trxsSubcommand->set_callback([&] { fc::variant trx_var; try { trx_var = json_from_file_or_string(trxsJson); } EOS_RETHROW_EXCEPTIONS(transaction_type_exception, "Fail to parse transaction JSON '${data}'", ("data",trxsJson)) auto trxs_result = call(push_txns_func, trx_var); std::cout << fc::json::to_pretty_string(trxs_result) << std::endl; }); // multisig subcommand auto msig = app.add_subcommand("multisig", localized("Multisig contract commands"), false); msig->require_subcommand(); // multisig propose string proposal_name; string requested_perm; string transaction_perm; string proposed_transaction; string proposed_contract; string proposed_action; string proposer; unsigned int proposal_expiration_hours = 24; CLI::callback_t parse_expiration_hours = [&](CLI::results_t res) -> bool { unsigned int value_s; if (res.size() == 0 || !CLI::detail::lexical_cast(res[0], value_s)) { return false; } proposal_expiration_hours = static_cast<uint64_t>(value_s); return true; }; auto propose_action = msig->add_subcommand("propose", localized("Propose action")); add_standard_transaction_options(propose_action); propose_action->add_option("proposal_name", proposal_name, localized("proposal name (string)"))->required(); propose_action->add_option("requested_permissions", requested_perm, localized("The JSON string or filename defining requested permissions"))->required(); propose_action->add_option("trx_permissions", transaction_perm, localized("The JSON string or filename defining transaction permissions"))->required(); propose_action->add_option("contract", proposed_contract, localized("contract to which deferred transaction should be delivered"))->required(); propose_action->add_option("action", proposed_action, localized("action of deferred transaction"))->required(); propose_action->add_option("data", proposed_transaction, localized("The JSON string or filename defining the action to propose"))->required(); propose_action->add_option("proposer", proposer, localized("Account proposing the transaction")); propose_action->add_option("proposal_expiration", parse_expiration_hours, localized("Proposal expiration interval in hours")); propose_action->set_callback([&] { fc::variant requested_perm_var; try { requested_perm_var = json_from_file_or_string(requested_perm); } EOS_RETHROW_EXCEPTIONS(transaction_type_exception, "Fail to parse permissions JSON '${data}'", ("data",requested_perm)) fc::variant transaction_perm_var; try { transaction_perm_var = json_from_file_or_string(transaction_perm); } EOS_RETHROW_EXCEPTIONS(transaction_type_exception, "Fail to parse permissions JSON '${data}'", ("data",transaction_perm)) fc::variant trx_var; try { trx_var = json_from_file_or_string(proposed_transaction); } EOS_RETHROW_EXCEPTIONS(transaction_type_exception, "Fail to parse transaction JSON '${data}'", ("data",proposed_transaction)) transaction proposed_trx = trx_var.as<transaction>(); bytes proposed_trx_serialized = variant_to_bin( proposed_contract, proposed_action, trx_var ); vector<permission_level> reqperm; try { reqperm = requested_perm_var.as<vector<permission_level>>(); } EOS_RETHROW_EXCEPTIONS(transaction_type_exception, "Wrong requested permissions format: '${data}'", ("data",requested_perm_var)); vector<permission_level> trxperm; try { trxperm = transaction_perm_var.as<vector<permission_level>>(); } EOS_RETHROW_EXCEPTIONS(transaction_type_exception, "Wrong transaction permissions format: '${data}'", ("data",transaction_perm_var)); auto accountPermissions = get_account_permissions(tx_permission); if (accountPermissions.empty()) { if (!proposer.empty()) { accountPermissions = vector<permission_level>{{proposer, config::active_name}}; } else { EOS_THROW(missing_auth_exception, "Authority is not provided (either by multisig parameter <proposer> or -p)"); } } if (proposer.empty()) { proposer = name(accountPermissions.at(0).actor).to_string(); } transaction trx; trx.expiration = fc::time_point_sec( fc::time_point::now() + fc::hours(proposal_expiration_hours) ); trx.ref_block_num = 0; trx.ref_block_prefix = 0; trx.max_net_usage_words = 0; trx.max_cpu_usage_ms = 0; trx.delay_sec = 0; trx.actions = { chain::action(trxperm, name(proposed_contract), name(proposed_action), proposed_trx_serialized) }; fc::to_variant(trx, trx_var); auto args = fc::mutable_variant_object() ("proposer", proposer ) ("proposal_name", proposal_name) ("requested", requested_perm_var) ("trx", trx_var); send_actions({chain::action{accountPermissions, "eosio.msig", "propose", variant_to_bin( N(eosio.msig), N(propose), args ) }}); }); //multisige propose transaction auto propose_trx = msig->add_subcommand("propose_trx", localized("Propose transaction")); add_standard_transaction_options(propose_trx); propose_trx->add_option("proposal_name", proposal_name, localized("proposal name (string)"))->required(); propose_trx->add_option("requested_permissions", requested_perm, localized("The JSON string or filename defining requested permissions"))->required(); propose_trx->add_option("transaction", trx_to_push, localized("The JSON string or filename defining the transaction to push"))->required(); propose_trx->add_option("proposer", proposer, localized("Account proposing the transaction")); propose_trx->set_callback([&] { fc::variant requested_perm_var; try { requested_perm_var = json_from_file_or_string(requested_perm); } EOS_RETHROW_EXCEPTIONS(transaction_type_exception, "Fail to parse permissions JSON '${data}'", ("data",requested_perm)) fc::variant trx_var; try { trx_var = json_from_file_or_string(trx_to_push); } EOS_RETHROW_EXCEPTIONS(transaction_type_exception, "Fail to parse transaction JSON '${data}'", ("data",trx_to_push)) auto accountPermissions = get_account_permissions(tx_permission); if (accountPermissions.empty()) { if (!proposer.empty()) { accountPermissions = vector<permission_level>{{proposer, config::active_name}}; } else { EOS_THROW(missing_auth_exception, "Authority is not provided (either by multisig parameter <proposer> or -p)"); } } if (proposer.empty()) { proposer = name(accountPermissions.at(0).actor).to_string(); } auto args = fc::mutable_variant_object() ("proposer", proposer ) ("proposal_name", proposal_name) ("requested", requested_perm_var) ("trx", trx_var); send_actions({chain::action{accountPermissions, "eosio.msig", "propose", variant_to_bin( N(eosio.msig), N(propose), args ) }}); }); // multisig review auto review = msig->add_subcommand("review", localized("Review transaction")); review->add_option("proposer", proposer, localized("proposer name (string)"))->required(); review->add_option("proposal_name", proposal_name, localized("proposal name (string)"))->required(); review->set_callback([&] { auto result = call(get_table_func, fc::mutable_variant_object("json", true) ("code", "eosio.msig") ("scope", proposer) ("table", "proposal") ("table_key", "") ("lower_bound", eosio::chain::string_to_name(proposal_name.c_str())) ("upper_bound", "") ("limit", 1) ); //std::cout << fc::json::to_pretty_string(result) << std::endl; fc::variants rows = result.get_object()["rows"].get_array(); if (rows.empty()) { std::cerr << "Proposal not found" << std::endl; return; } fc::mutable_variant_object obj = rows[0].get_object(); if (obj["proposal_name"] != proposal_name) { std::cerr << "Proposal not found" << std::endl; return; } auto trx_hex = obj["packed_transaction"].as_string(); vector<char> trx_blob(trx_hex.size()/2); fc::from_hex(trx_hex, trx_blob.data(), trx_blob.size()); transaction trx = fc::raw::unpack<transaction>(trx_blob); fc::variant trx_var; abi_serializer abi; abi.to_variant(trx, trx_var, abi_serializer_resolver, abi_serializer_max_time); obj["transaction"] = trx_var; std::cout << fc::json::to_pretty_string(obj) << std::endl; }); string perm; auto approve_or_unapprove = [&](const string& action) { fc::variant perm_var; try { perm_var = json_from_file_or_string(perm); } EOS_RETHROW_EXCEPTIONS(transaction_type_exception, "Fail to parse permissions JSON '${data}'", ("data",perm)) auto args = fc::mutable_variant_object() ("proposer", proposer) ("proposal_name", proposal_name) ("level", perm_var); auto accountPermissions = tx_permission.empty() ? vector<chain::permission_level>{{sender,config::active_name}} : get_account_permissions(tx_permission); send_actions({chain::action{accountPermissions, "eosio.msig", action, variant_to_bin( N(eosio.msig), action, args ) }}); }; // multisig approve auto approve = msig->add_subcommand("approve", localized("Approve proposed transaction")); add_standard_transaction_options(approve); approve->add_option("proposer", proposer, localized("proposer name (string)"))->required(); approve->add_option("proposal_name", proposal_name, localized("proposal name (string)"))->required(); approve->add_option("permissions", perm, localized("The JSON string of filename defining approving permissions"))->required(); approve->set_callback([&] { approve_or_unapprove("approve"); }); // multisig unapprove auto unapprove = msig->add_subcommand("unapprove", localized("Unapprove proposed transaction")); add_standard_transaction_options(unapprove); unapprove->add_option("proposer", proposer, localized("proposer name (string)"))->required(); unapprove->add_option("proposal_name", proposal_name, localized("proposal name (string)"))->required(); unapprove->add_option("permissions", perm, localized("The JSON string of filename defining approving permissions"))->required(); unapprove->set_callback([&] { approve_or_unapprove("unapprove"); }); // multisig cancel string canceler; auto cancel = msig->add_subcommand("cancel", localized("Cancel proposed transaction")); add_standard_transaction_options(cancel); cancel->add_option("proposer", proposer, localized("proposer name (string)"))->required(); cancel->add_option("proposal_name", proposal_name, localized("proposal name (string)"))->required(); cancel->add_option("canceler", canceler, localized("canceler name (string)")); cancel->set_callback([&]() { auto accountPermissions = get_account_permissions(tx_permission); if (accountPermissions.empty()) { if (!canceler.empty()) { accountPermissions = vector<permission_level>{{canceler, config::active_name}}; } else { EOS_THROW(missing_auth_exception, "Authority is not provided (either by multisig parameter <canceler> or -p)"); } } if (canceler.empty()) { canceler = name(accountPermissions.at(0).actor).to_string(); } auto args = fc::mutable_variant_object() ("proposer", proposer) ("proposal_name", proposal_name) ("canceler", canceler); send_actions({chain::action{accountPermissions, "eosio.msig", "cancel", variant_to_bin( N(eosio.msig), N(cancel), args ) }}); } ); // multisig exec string executer; auto exec = msig->add_subcommand("exec", localized("Execute proposed transaction")); add_standard_transaction_options(exec); exec->add_option("proposer", proposer, localized("proposer name (string)"))->required(); exec->add_option("proposal_name", proposal_name, localized("proposal name (string)"))->required(); exec->add_option("executer", executer, localized("account paying for execution (string)")); exec->set_callback([&] { auto accountPermissions = get_account_permissions(tx_permission); if (accountPermissions.empty()) { if (!executer.empty()) { accountPermissions = vector<permission_level>{{executer, config::active_name}}; } else { EOS_THROW(missing_auth_exception, "Authority is not provided (either by multisig parameter <executer> or -p)"); } } if (executer.empty()) { executer = name(accountPermissions.at(0).actor).to_string(); } auto args = fc::mutable_variant_object() ("proposer", proposer ) ("proposal_name", proposal_name) ("executer", executer); send_actions({chain::action{accountPermissions, "eosio.msig", "exec", variant_to_bin( N(eosio.msig), N(exec), args ) }}); } ); // wrap subcommand auto wrap = app.add_subcommand("wrap", localized("Wrap contract commands"), false); wrap->require_subcommand(); // wrap exec string wrap_con = "eosio.wrap"; executer = ""; string trx_to_exec; auto wrap_exec = wrap->add_subcommand("exec", localized("Execute a transaction while bypassing authorization checks")); add_standard_transaction_options(wrap_exec); wrap_exec->add_option("executer", executer, localized("Account executing the transaction and paying for the deferred transaction RAM"))->required(); wrap_exec->add_option("transaction", trx_to_exec, localized("The JSON string or filename defining the transaction to execute"))->required(); wrap_exec->add_option("--contract,-c", wrap_con, localized("The account which controls the wrap contract")); wrap_exec->set_callback([&] { fc::variant trx_var; try { trx_var = json_from_file_or_string(trx_to_exec); } EOS_RETHROW_EXCEPTIONS(transaction_type_exception, "Fail to parse transaction JSON '${data}'", ("data",trx_to_exec)) auto accountPermissions = get_account_permissions(tx_permission); if( accountPermissions.empty() ) { accountPermissions = vector<permission_level>{{executer, config::active_name}, {wrap_con, config::active_name}}; } auto args = fc::mutable_variant_object() ("executer", executer ) ("trx", trx_var); send_actions({chain::action{accountPermissions, wrap_con, "exec", variant_to_bin( wrap_con, N(exec), args ) }}); }); // system subcommand auto system = app.add_subcommand("system", localized("Send eosio.system contract action to the blockchain."), false); system->require_subcommand(); auto createAccountSystem = create_account_subcommand( system, false /*simple*/ ); auto registerProducer = register_producer_subcommand(system); auto unregisterProducer = unregister_producer_subcommand(system); auto voteProducer = system->add_subcommand("voteproducer", localized("Vote for a producer")); voteProducer->require_subcommand(); auto voteProxy = vote_producer_proxy_subcommand(voteProducer); auto voteProducers = vote_producers_subcommand(voteProducer); auto approveProducer = approve_producer_subcommand(voteProducer); auto unapproveProducer = unapprove_producer_subcommand(voteProducer); auto listProducers = list_producers_subcommand(system); auto delegateBandWidth = delegate_bandwidth_subcommand(system); auto undelegateBandWidth = undelegate_bandwidth_subcommand(system); auto listBandWidth = list_bw_subcommand(system); auto bidname = bidname_subcommand(system); auto bidnameinfo = bidname_info_subcommand(system); auto biyram = buyram_subcommand(system); auto sellram = sellram_subcommand(system); auto claimRewards = claimrewards_subcommand(system); auto regProxy = regproxy_subcommand(system); auto unregProxy = unregproxy_subcommand(system); auto cancelDelay = canceldelay_subcommand(system); try { app.parse(argc, argv); } catch (const CLI::ParseError &e) { return app.exit(e); } catch (const explained_exception& e) { return 1; } catch (connection_exception& e) { if (verbose_errors) { elog("connect error: ${e}", ("e", e.to_detail_string())); } return 1; } catch (const fc::exception& e) { // attempt to extract the error code if one is present if (!print_recognized_errors(e, verbose_errors)) { // Error is not recognized if (!print_help_text(e) || verbose_errors) { elog("Failed with error: ${e}", ("e", verbose_errors ? e.to_detail_string() : e.to_string())); } } return 1; } return 0; }
#ifndef SPECTYPES_H #define SPECTYPES_H #define INPUT_H "PSXINPUT.H" #define CMATH_H "LIBMATH.H" #include "TYPES.H" #ifdef PAELLA #define exit(x) exit() #define _STDDEF_H #define INLINE_H "PAELLA.H" #define ASSEMBLER #define _WCHAR_T #endif #include "TYPES.H" #ifdef PAELLA #define LMAX 256 #ifndef NULL #define NULL 0 /* null pointer constant */ #endif #ifndef _SIZE_T #define _SIZE_T typedef unsigned int size_t; /* result type of the sizeof operator (ANSI) */ #endif #if defined(_LANGUAGE_C_PLUS_PLUS)||defined(__cplusplus)||defined(c_plusplus) extern "C" { #endif /* To avoid conflicting */ extern void *memcpy(void *, void *, int); extern void *memmove(void *, const void *, int); /* To avoid conflicting */ extern int memcmp(void *, void *, int); extern void *memchr(const void *, int, int); extern void *memset(void *, int, int); extern void *bcopy(const void *, void *, int); /* src,dest */ extern void *bzero(void *, int); extern int bcmp(const void *, const void *, int); #if defined(_LANGUAGE_C_PLUS_PLUS)||defined(__cplusplus)||defined(c_plusplus) } #endif #if defined(_LANGUAGE_C_PLUS_PLUS)||defined(__cplusplus)||defined(c_plusplus) extern "C" { #endif extern char *strcat(char *, const char *); extern char *strncat(char *, const char *, int); extern int strcmp(char *, char *); extern int strncmp(const char *, const char *, int); extern char *strcpy(char *, char *); extern char *strncpy(char *, const char *, int); extern int strlen(char *); extern char *index(const char *, char); extern char *rindex(const char *, char); extern char *strchr(const char *, char); extern char *strrchr(const char *, char); extern char *strpbrk(const char *, const char *); extern int strspn(const char *, const char *); extern int strcspn(const char *, const char *); extern char *strtok(char *, const char *); extern char *strstr(const char *, const char *); #if defined(_LANGUAGE_C_PLUS_PLUS)||defined(__cplusplus)||defined(c_plusplus) } #endif #define strdup(p) ( strcpy(malloc(strlen(p)+1),p); ) #if defined(_LANGUAGE_C_PLUS_PLUS)||defined(__cplusplus)||defined(c_plusplus) extern "C" { #endif extern void InitGeom(); extern void EigenMatrix(struct MATRIX3D *m, struct MATRIX3D *t); extern int IsIdMatrix(struct MATRIX3D *m); extern struct MATRIX3D *MulMatrix0(struct MATRIX3D *m0, struct MATRIX3D *m1, struct MATRIX3D *m2); extern struct MATRIX3D *MulRotMatrix0(struct MATRIX3D *m0, struct MATRIX3D *m1); extern struct MATRIX3D *MulMatrix(struct MATRIX3D *m0, struct MATRIX3D *m1); extern struct MATRIX3D *MulMatrix2(struct MATRIX3D *m0, struct MATRIX3D *m1); extern struct MATRIX3D *MulRotMatrix(struct MATRIX3D *m0); extern struct MATRIX3D *SetMulMatrix(struct MATRIX3D *m0, struct MATRIX3D *m1); extern struct MATRIX3D *SetMulRotMatrix(struct MATRIX3D *m0); extern struct VECTOR *ApplyMatrix(struct MATRIX3D *m, struct SVECTOR *v0, struct VECTOR *v1); extern struct VECTOR *ApplyRotMatrix(struct SVECTOR *v0, struct VECTOR *v1); extern struct VECTOR *ApplyRotMatrixLV(struct VECTOR *v0, struct VECTOR *v1); extern struct VECTOR *ApplyMatrixLV(struct MATRIX3D *m, struct VECTOR *v0, struct VECTOR *v1); extern struct SVECTOR *ApplyMatrixSV(struct MATRIX3D *m, struct SVECTOR *v0, struct SVECTOR *v1); extern struct VECTOR *ApplyTransposeMatrixLV(struct MATRIX3D *m, struct VECTOR *v0, struct VECTOR *v1); extern struct MATRIX3D *RotMatrix(struct SVECTOR *r, struct MATRIX3D *m); extern struct MATRIX3D *RotMatrixXZY(struct SVECTOR *r, struct MATRIX3D *m); extern struct MATRIX3D *RotMatrixYXZ(struct SVECTOR *r, struct MATRIX3D *m); extern struct MATRIX3D *RotMatrixYZX(struct SVECTOR *r, struct MATRIX3D *m); extern struct MATRIX3D *RotMatrixZXY(struct SVECTOR *r, struct MATRIX3D *m); extern struct MATRIX3D *RotMatrixZYX(struct SVECTOR *r, struct MATRIX3D *m); extern struct MATRIX3D *RotMatrix_gte(struct SVECTOR *r, struct MATRIX3D *m); extern struct MATRIX3D *RotMatrixYXZ_gte(struct SVECTOR *r, struct MATRIX3D *m); extern struct MATRIX3D *RotMatrixZYX_gte(struct SVECTOR *r, struct MATRIX3D *m); extern struct MATRIX3D *RotMatrixX(long r, struct MATRIX3D *m); extern struct MATRIX3D *RotMatrixY(long r, struct MATRIX3D *m); extern struct MATRIX3D *RotMatrixZ(long r, struct MATRIX3D *m); extern struct MATRIX3D *RotMatrixC(struct SVECTOR *r, struct MATRIX3D *m); extern struct MATRIX3D *TransMatrix(struct MATRIX3D *m, struct VECTOR *v); extern struct MATRIX3D *ScaleMatrix(struct MATRIX3D *m, struct VECTOR *v); extern struct MATRIX3D *ScaleMatrixL(struct MATRIX3D *m, struct VECTOR *v); extern struct MATRIX3D *TransposeMatrix(struct MATRIX3D *m0, struct MATRIX3D *m1); extern struct MATRIX3D *CompMatrix(struct MATRIX3D *m0, struct MATRIX3D *m1, struct MATRIX3D *m2); extern struct MATRIX3D *CompMatrixLV(struct MATRIX3D *m0, struct MATRIX3D *m1, struct MATRIX3D *m2); extern void MatrixNormal(struct MATRIX3D *m, struct MATRIX3D *n); extern void MatrixNormal_0(struct MATRIX3D *m, struct MATRIX3D *n); extern void MatrixNormal_1(struct MATRIX3D *m, struct MATRIX3D *n); extern void MatrixNormal_2(struct MATRIX3D *m, struct MATRIX3D *n); extern void SetRotMatrix(struct MATRIX3D *m); extern void SetLightMatrix(struct MATRIX3D *m); extern void SetColorMatrix(struct MATRIX3D *m); extern void SetTransMatrix(struct MATRIX3D *m); extern void PushMatrix(); extern void PopMatrix(); extern void ReadRotMatrix(struct MATRIX3D *m); extern void ReadLightMatrix(struct MATRIX3D *m); extern void ReadColorMatrix(struct MATRIX3D *m); extern void SetRGBcd(struct CVECTOR *v); extern void SetBackColor(long rbk, long gbk, long bbk); extern void SetFarColor(long rfc, long gfc, long bfc); extern void SetGeomOffset(long ofx, long ofy); extern void SetGeomScreen(long h); extern void ReadSZfifo3(long *sz0, long *sz1, long *sz2); extern void ReadSZfifo4(long *szx, long *sz0, long *sz1, long *sz2); extern void ReadSXSYfifo(long *sxy0, long *sxy1, long *sxy2); extern void ReadRGBfifo(struct CVECTOR *v0, struct CVECTOR *v1, struct CVECTOR *v2); extern void ReadGeomOffset(long *ofx, long *ofy); extern long ReadGeomScreen(); extern void TransRot_32(struct VECTOR *v0, struct VECTOR *v1, long *flag); extern long TransRotPers(struct SVECTOR *v0, long *sxy, long *p, long *flag); extern long TransRotPers3(struct SVECTOR *v0, struct SVECTOR *v1, struct SVECTOR *v2, long *sxy0, long *sxy1, long *sxy2, long *p, long *flag); extern void pers_map(int abuf, struct SVECTOR **vertex, int tex[4][2], unsigned short *dtext); extern void PhongLine(int istart_x, int iend_x, int p, int q, unsigned short **pixx, int fs, int ft, int i4, int det); extern long RotTransPers(struct SVECTOR *v0, long *sxy, long *p, long *flag); extern long RotTransPers3(struct SVECTOR *v0, struct SVECTOR *v1, struct SVECTOR *v2, long *sxy0, long *sxy1, long *sxy2, long *p, long *flag); extern void RotTrans(struct SVECTOR *v0, struct VECTOR *v1, long *flag); extern void RotTransSV(struct SVECTOR *v0, struct SVECTOR *v1, long *flag); extern void LocalLight(struct SVECTOR *v0, struct VECTOR *v1); extern void LightColor(struct VECTOR *v0, struct VECTOR *v1); extern void DpqColorLight(struct VECTOR *v0, struct CVECTOR *v1, long p, struct CVECTOR *v2); extern void DpqColor(struct CVECTOR *v0, long p, struct CVECTOR *v1); extern void DpqColor3(struct CVECTOR *v0, struct CVECTOR *v1, struct CVECTOR *v2, long p, struct CVECTOR *v3, struct CVECTOR *v4, struct CVECTOR *v5); extern void Intpl(struct VECTOR *v0, long p, struct CVECTOR *v1); extern struct VECTOR *Square12(struct VECTOR *v0, struct VECTOR *v1); extern struct VECTOR *Square0(struct VECTOR *v0, struct VECTOR *v1); extern struct VECTOR *SquareSL12(struct SVECTOR *v0, struct VECTOR *v1); extern struct VECTOR *SquareSL0(struct SVECTOR *v0, struct VECTOR *v1); extern struct SVECTOR *SquareSS12(struct SVECTOR *v0, struct SVECTOR *v1); extern struct SVECTOR *SquareSS0(struct SVECTOR *v0, struct SVECTOR *v1); extern void NormalColor(struct SVECTOR *v0, struct CVECTOR *v1); extern void NormalColor3(struct SVECTOR *v0, struct SVECTOR *v1, struct SVECTOR *v2, struct CVECTOR *v3, struct CVECTOR *v4, struct CVECTOR *v5); extern void NormalColorDpq(struct SVECTOR *v0, struct CVECTOR *v1, long p, struct CVECTOR *v2); extern void NormalColorDpq3(struct SVECTOR *v0, struct SVECTOR *v1, struct SVECTOR *v2, struct CVECTOR *v3, long p, struct CVECTOR *v4, struct CVECTOR *v5, struct CVECTOR *v6); extern void NormalColorCol(struct SVECTOR *v0, struct CVECTOR *v1, struct CVECTOR *v2); extern void NormalColorCol3(struct SVECTOR *v0, struct SVECTOR *v1, struct SVECTOR *v2, struct CVECTOR *v3, struct CVECTOR *v4, struct CVECTOR *v5, struct CVECTOR *v6); extern void ColorDpq(struct VECTOR *v0, struct CVECTOR *v1, long p, struct CVECTOR *v2); extern void ColorCol(struct VECTOR *v0, struct CVECTOR *v1, struct CVECTOR *v2); extern long NormalClip(long sxy0, long sxy1, long sxy2); extern long AverageZ3(long sz0, long sz1, long sz2); extern long AverageZ4(long sz0, long sz1, long sz2, long sz3); extern void OuterProduct12(struct VECTOR *v0, struct VECTOR *v1, struct VECTOR *v2); extern void OuterProduct0(struct VECTOR *v0, struct VECTOR *v1, struct VECTOR *v2); extern long Lzc(long data); extern long RotTransPers4(struct SVECTOR *v0, struct SVECTOR *v1, struct SVECTOR *v2, struct SVECTOR *v3, long *sxy0, long *sxy1, long *sxy2, long *sxy3, long *p, long *flag); extern void RotTransPersN(struct SVECTOR *v0, struct DVECTOR *v1, unsigned short *sz, unsigned short *p, unsigned short *flag, long n); extern void RotTransPers3N(struct SVECTOR *v0, struct DVECTOR *v1, unsigned short *sz, unsigned short *flag, long n); extern void RotMeshH(short *Yheight, struct DVECTOR *Vo, unsigned short *sz, unsigned short *flag, short Xoffset, short Zoffset, short m, short n, struct DVECTOR *base); extern long RotAverage3(struct SVECTOR *v0, struct SVECTOR *v1, struct SVECTOR *v2, long *sxy0, long *sxy1, long *sxy2, long *p, long *flag); extern long RotAverage4(struct SVECTOR *v0, struct SVECTOR *v1, struct SVECTOR *v2, struct SVECTOR *v3, long *sxy0, long *sxy1, long *sxy2, long *sxy3, long *p, long *flag); extern long RotNclip3(struct SVECTOR *v0, struct SVECTOR *v1, struct SVECTOR *v2, long *sxy0, long *sxy1, long *sxy2, long *p, long *otz, long *flag); extern long RotNclip4(struct SVECTOR *v0, struct SVECTOR *v1, struct SVECTOR *v2, struct SVECTOR *v3, long *sxy0, long *sxy1, long *sxy2, long *sxy3, long *p, long *otz, long *flag); extern long RotAverageNclip3(struct SVECTOR *v0, struct SVECTOR *v1, struct SVECTOR *v2, long *sxy0, long *sxy1, long *sxy2, long *p, long *otz, long *flag); extern long RotAverageNclip4(struct SVECTOR *v0, struct SVECTOR *v1, struct SVECTOR *v2, struct SVECTOR *v3, long *sxy0, long *sxy1, long *sxy2, long *sxy3, long *p, long *otz, long *flag); extern long RotColorDpq(struct SVECTOR *v0, struct SVECTOR *v1, struct CVECTOR *v2, long *sxy, struct CVECTOR *v3, long *flag); extern long RotColorDpq3(struct SVECTOR *v0, struct SVECTOR *v1, struct SVECTOR *v2, struct SVECTOR *v3, struct SVECTOR *v4, struct SVECTOR *v5, struct CVECTOR *v6, long *sxy0, long *sxy1, long *sxy2, struct CVECTOR *v7, struct CVECTOR *v8, struct CVECTOR *v9, long *flag); extern long RotAverageNclipColorDpq3(struct SVECTOR *v0, struct SVECTOR *v1, struct SVECTOR *v2, struct SVECTOR *v3, struct SVECTOR *v4, struct SVECTOR *v5, struct CVECTOR *v6, long *sxy0, long *sxy1, long *sxy2, struct CVECTOR *v7, struct CVECTOR *v8, struct CVECTOR *v9, long *otz, long *flag); extern long RotAverageNclipColorCol3(struct SVECTOR *v0, struct SVECTOR *v1, struct SVECTOR *v2, struct SVECTOR *v3, struct SVECTOR *v4, struct SVECTOR *v5, struct CVECTOR *v6, long *sxy0, long *sxy1, long *sxy2, struct CVECTOR *v7, struct CVECTOR *v8, struct CVECTOR *v9, long *otz, long *flag); extern long RotColorMatDpq(struct SVECTOR *v0, struct SVECTOR *v1, struct CVECTOR *v2, long *sxy, struct CVECTOR *v3, long matc, long flag); extern void ColorMatDpq(struct SVECTOR *v0, struct CVECTOR *v1, long p, struct CVECTOR *v2, long matc); extern void ColorMatCol(struct SVECTOR *v0, struct CVECTOR *v1, struct CVECTOR *v2, long matc); extern void LoadAverage12(struct VECTOR *v0, struct VECTOR *v1, long p0, long p1, struct VECTOR *v2); extern void LoadAverageShort12(struct SVECTOR *v0, struct SVECTOR *v1, long p0, long p1, struct SVECTOR *v2); extern void LoadAverage0(struct VECTOR *v0, struct VECTOR *v1, long p0, long p1, struct VECTOR *v2); extern void LoadAverageShort0(struct SVECTOR *v0, struct SVECTOR *v1, long p0, long p1, struct SVECTOR *v2); extern void LoadAverageByte(unsigned char *v0, unsigned char *v1, long p0, long p1, unsigned char *v2); extern void LoadAverageCol(unsigned char *v0, unsigned char *v1, long p0, long p1, unsigned char *v2); extern long VectorNormal(struct VECTOR *v0, struct VECTOR *v1); extern long VectorNormalS(struct VECTOR *v0, struct SVECTOR *v1); extern long VectorNormalSS(struct SVECTOR *v0, struct SVECTOR *v1); extern long SquareRoot0(long a); extern long SquareRoot12(long a); extern void InvSquareRoot(long a, long *b, long *c); extern void gteMIMefunc(struct SVECTOR *otp, struct SVECTOR *dfp, long n, long p); extern void SetFogFar(long a, long h); extern void SetFogNear(long a, long h); extern void SetFogNearFar(long a, long b, long h); extern void SubPol4(struct POL4 *p, struct SPOL *sp, int ndiv); extern void SubPol3(struct POL3 *p, struct SPOL *sp, int ndiv); extern int rcos(int a); extern int rsin(int a); extern int ccos(int a); extern int csin(int a); extern int cln(int a); extern int csqrt(int a); extern int catan(int a); extern long ratan2(long y, long x); extern void RotPMD_F3(long *pa, unsigned long *ot, int otlen, int id, int backc); extern void RotPMD_G3(long *pa, unsigned long *ot, int otlen, int id, int backc); extern void RotPMD_FT3(long *pa, unsigned long *ot, int otlen, int id, int backc); extern void RotPMD_GT3(long *pa, unsigned long *ot, int otlen, int id, int backc); extern void RotPMD_F4(long *pa, unsigned long *ot, int otlen, int id, int backc); extern void RotPMD_G4(long *pa, unsigned long *ot, int otlen, int id, int backc); extern void RotPMD_FT4(long *pa, unsigned long *ot, int otlen, int id, int backc); extern void RotPMD_GT4(long *pa, unsigned long *ot, int otlen, int id, int backc); extern void RotPMD_SV_F3(long *pa, long *va, unsigned long *ot, int otlen, int id, int backc); extern void RotPMD_SV_G3(long *pa, long *va, unsigned long *ot, int otlen, int id, int backc); extern void RotPMD_SV_FT3(long *pa, long *va, unsigned long *ot, int otlen, int id, int backc); extern void RotPMD_SV_GT3(long *pa, long *va, unsigned long *ot, int otlen, int id, int backc); extern void RotPMD_SV_F4(long *pa, long *va, unsigned long *ot, int otlen, int id, int backc); extern void RotPMD_SV_G4(long *pa, long *va, unsigned long *ot, int otlen, int id, int backc); extern void RotPMD_SV_FT4(long *pa, long *va, unsigned long *ot, int otlen, int id, int backc); extern void RotPMD_SV_GT4(long *pa, long *va, unsigned long *ot, int otlen, int id, int backc); extern void InitClip(struct EVECTOR *evbfad, long hw, long vw, long h, long near, long far); extern long Clip3F(struct SVECTOR *v0, struct SVECTOR *v1, struct SVECTOR *v2, struct EVECTOR **evmx); extern long Clip3FP(struct SVECTOR *v0, struct SVECTOR *v1, struct SVECTOR *v2, struct EVECTOR **evmx); extern long Clip4F(struct SVECTOR *v0, struct SVECTOR *v1, struct SVECTOR *v2, struct SVECTOR *v3, struct EVECTOR **evmx); extern long Clip4FP(struct SVECTOR *v0, struct SVECTOR *v1, struct SVECTOR *v2, struct SVECTOR *v3, struct EVECTOR **evmx); extern long Clip3FT(struct SVECTOR *v0, struct SVECTOR *v1, struct SVECTOR *v2, short *uv0, short *uv1, short *uv2, struct EVECTOR **evmx); extern long Clip3FTP(struct SVECTOR *v0, struct SVECTOR *v1, struct SVECTOR *v2, short *uv0, short *uv1, short *uv2, struct EVECTOR **evmx); extern long Clip4FT(struct SVECTOR *v0, struct SVECTOR *v1, struct SVECTOR *v2, struct SVECTOR *v3, short *uv0, short *uv1, short *uv2, short *uv3, struct EVECTOR **evmx); extern long Clip4FTP(struct SVECTOR *v0, struct SVECTOR *v1, struct SVECTOR *v2, struct SVECTOR *v3, short *uv0, short *uv1, short *uv2, short *uv3, struct EVECTOR **evmx); extern long Clip3G(struct SVECTOR *v0, struct SVECTOR *v1, struct SVECTOR *v2, struct CVECTOR *rgb0, struct CVECTOR *rgb1, struct CVECTOR *rgb2, struct EVECTOR **evmx); extern long Clip3GP(struct SVECTOR *v0, struct SVECTOR *v1, struct SVECTOR *v2, struct CVECTOR *rgb0, struct CVECTOR *rgb1, struct CVECTOR *rgb2, struct EVECTOR **evmx); extern long Clip4G(struct SVECTOR *v0, struct SVECTOR *v1, struct SVECTOR *v2, struct SVECTOR *v3, struct CVECTOR *rgb0, struct CVECTOR *rgb1, struct CVECTOR *rgb2, struct CVECTOR *rgb3, struct EVECTOR **evmx); extern long Clip4GP(struct SVECTOR *v0, struct SVECTOR *v1, struct SVECTOR *v2, struct SVECTOR *v3, struct CVECTOR *rgb0, struct CVECTOR *rgb1, struct CVECTOR *rgb2, struct CVECTOR *rgb3, struct EVECTOR **evmx); extern long Clip3GT(struct SVECTOR *v0, struct SVECTOR *v1, struct SVECTOR *v2, short *uv0, short *uv1, short *uv2, struct CVECTOR *rgb0, struct CVECTOR *rgb1, struct CVECTOR *rgb2, struct EVECTOR **evmx); extern long Clip3GTP(struct SVECTOR *v0, struct SVECTOR *v1, struct SVECTOR *v2, short *uv0, short *uv1, short *uv2, struct CVECTOR *rgb0, struct CVECTOR *rgb1, struct CVECTOR *rgb2, struct EVECTOR **evmx); extern long Clip4GT(struct SVECTOR *v0, struct SVECTOR *v1, struct SVECTOR *v2, struct SVECTOR *v3, short *uv0, short *uv1, short *uv2, short *uv3, struct CVECTOR *rgb0, struct CVECTOR *rgb1, struct CVECTOR *rgb2, struct CVECTOR *rgb3, struct EVECTOR **evmx); extern long Clip4GTP(struct SVECTOR *v0, struct SVECTOR *v1, struct SVECTOR *v2, struct SVECTOR *v3, short *uv0, short *uv1, short *uv2, short *uv3, struct CVECTOR *rgb0, struct CVECTOR *rgb1, struct CVECTOR *rgb2, struct CVECTOR *rgb3, struct EVECTOR **evmx); extern void RotTransPers_nom(struct SVECTOR *v0); extern void RotTransPers3_nom(struct SVECTOR *v0, struct SVECTOR *v1, struct SVECTOR *v2); extern void RotTransPers4_nom(struct SVECTOR *v0, struct SVECTOR *v1, struct SVECTOR *v2, struct SVECTOR *v3); extern void RotTrans_nom(struct SVECTOR *v0); extern void RotAverage3_nom(struct SVECTOR *v0, struct SVECTOR *v1, struct SVECTOR *v2); extern void RotNclip3_nom(struct SVECTOR *v0, struct SVECTOR *v1, struct SVECTOR *v2); extern void RotAverageNclip3_nom(struct SVECTOR *v0, struct SVECTOR *v1, struct SVECTOR *v2); extern void RotAverageNclipColorDpq3_nom(struct SVECTOR *v0, struct SVECTOR *v1, struct SVECTOR *v2, struct SVECTOR *v3, struct SVECTOR *v4, struct SVECTOR *v5, struct CVECTOR *v6); extern void RotAverageNclipColorCol3_nom(struct SVECTOR *v0, struct SVECTOR *v1, struct SVECTOR *v2, struct SVECTOR *v3, struct SVECTOR *v4, struct SVECTOR *v5, struct CVECTOR *v6); extern void RotColorDpq_nom(struct SVECTOR *v0, struct SVECTOR *v1, struct CVECTOR *v2); extern long RotColorDpq3_nom(struct SVECTOR *v0, struct SVECTOR *v1, struct SVECTOR *v2, struct SVECTOR *v3, struct SVECTOR *v4, struct SVECTOR *v5, struct CVECTOR *v6); extern void NormalColor_nom(struct SVECTOR *v0); extern void NormalColor3_nom(struct SVECTOR *v0, struct SVECTOR *v1, struct SVECTOR *v2); extern void NormalColorDpq_nom(struct SVECTOR *v0, struct CVECTOR *v1, long p); extern void NormalColorDpq3_nom(struct SVECTOR *v0, struct SVECTOR *v1, struct SVECTOR *v2, struct CVECTOR *v3, long p); extern void NormalColorCol_nom(struct SVECTOR *v0, struct CVECTOR *v1); extern void NormalColorCol3_nom(struct SVECTOR *v0, struct SVECTOR *v1, struct SVECTOR *v2, struct CVECTOR *v3); /* extern unsigned long *DivideF3(struct SVECTOR *v0,struct SVECTOR *v1,struct SVECTOR *v2,struct CVECTOR *rgbc, POLY *otp); extern unsigned long *GsPrng n,unsigned long shift,GsOT *otp); extern unsigned long *GsTMDfastTG3LB(TMD_P_TG3 *primtop,struct SVECTOR *vertop,struct SVECTOR *nortop, POLY_GT3 *s,unsigned long n,unsigned long shift,GsOT *otp); extern unsigned long *GsTMDfastTG3LFGB(TMD_P_TG3 *primtop,struct SVECTOR *vertop, struct SVECTOR *nortop,POLY_GT3 *s,unsigned long n,unsigned long shift,GsOT *otp); extern unsigned long *GsTMDfastTG3NLB(TMD_P_TG3 *primtop,struct SVECTOR *vertop, struct SVECTOR *nortop,POLY_GT3 *s,unsigned long n,unsigned long shift,GsOT *otp); extern unsigned long *GsTMDfastTNG3B(TMD_P_TNG3 *primtop,struct SVECTOR *vertop, POLY_GT3 *s,unsigned long n,unsigned long shift,GsOT *otp); extern unsigned long *GsTMDfastTG4LB(TMD_P_TG4 *primtop,struct SVECTOR *vertop,struct SVECTOR *nortop, POLY_GT4 *s,unsigned long n,unsigned long shift,GsOT *otp); extern unsigned long *GsTMDfastTG4LFGB(TMD_P_TG4 *primtop,struct SVECTOR *vertop, struct SVECTOR *nortop,POLY_GT4 *s,unsigned long n,unsigned long shift,GsOT *otp); extern unsigned long *GsTMDfastTG4NLB(TMD_P_TG4 *primtop,struct SVECTOR *vertop, struct SVECTOR *nortop,POLY_GT4 *s,unsigned long n,unsigned long shift,GsOT *otp); extern unsigned long *GsTMDfastTNG4B(TMD_P_TNG4 *primtop,struct SVECTOR *vertop, POLY_GT4 *s,unsigned long n,unsigned long shift,GsOT *otp); extern unsigned long *GsTMDdivF3LB(TMD_P_F3 *primtop,struct SVECTOR *vertop,struct SVECTOR *nortop, POLY_F3 *s,unsigned long n,unsigned long shift,GsOT *otp,DIVPOLYGON3 *divp); extern unsigned long *GsTMDdivF3LFGB(TMD_P_F3 *primtop,struct SVECTOR *vertop,struct SVECTOR *nortop, POLY_F3 *s,unsigned long n,unsigned long shift,GsOT *otp,DIVPOLYGON3 *divp); extern unsigned long *GsTMDdivF3NLB(TMD_P_F3 *primtop,struct SVECTOR *vertop,struct SVECTOR *nortop, POLY_F3 *s,unsigned long n,unsigned long shift,GsOT *otp,DIVPOLYGON3 *divp); extern unsigned long *GsTMDdivNF3B(TMD_P_NF3 *primtop,struct SVECTOR *vertop, POLY_F3 *s,unsigned long n,unsigned long shift,GsOT *otp,DIVPOLYGON3 *divp); extern unsigned long *GsTMDdivF4LB(TMD_P_F4 *primtop,struct SVECTOR *vertop,struct SVECTOR *nortop, POLY_F4 *s,unsigned long n,unsigned long shift,GsOT *otp,DIVPOLYGON4 *divp); extern unsigned long *GsTMDdivF4LFGB(TMD_P_F4 *primtop,struct SVECTOR *vertop,struct SVECTOR *nortop, POLY_F4 *s,unsigned long n,unsigned long shift,GsOT *otp,DIVPOLYGON4 *divp); extern unsigned long *GsTMDdivF4NLB(TMD_P_F4 *primtop,struct SVECTOR *vertop,struct SVECTOR *nortop, POLY_F4 *s,unsigned long n,unsigned long shift,GsOT *otp,DIVPOLYGON4 *divp); extern unsigned long *GsTMDdivNF4B(TMD_P_NF4 *primtop,struct SVECTOR *vertop, POLY_F4 *s,unsigned long n,unsigned long shift,GsOT *otp,DIVPOLYGON4 *divp); extern unsigned long *GsTMDdivTF3LB(TMD_P_TF3 *primtop,struct SVECTOR *vertop,struct SVECTOR *nortop, POLY_FT3 *s,unsigned long n,unsigned long shift,GsOT *otp,DIVPOLYGON3 *divp); extern unsigned long *GsTMDdivTF3LFGB(TMD_P_TF3 *primtop,struct SVECTOR *vertop, struct SVECTOR *nortop,POLY_FT3 *s,unsigned long n,unsigned long shift, GsOT *otp,DIVPOLYGON3 *divp); extern unsigned long *GsTMDdivTF3NLB(TMD_P_TF3 *primtop,struct SVECTOR *vertop,struct SVECTOR *nortop, POLY_FT3 *s,unsigned long n,unsigned long shift,GsOT *otp,DIVPOLYGON3 *divp); extern unsigned long *GsTMDdivTNF3B(TMD_P_TNF3 *primtop,struct SVECTOR *vertop, POLY_FT3 *s,unsigned long n,unsigned long shift,GsOT *otp,DIVPOLYGON3 *divp); extern unsigned long *GsTMDdivTF4LB(TMD_P_TF4 *primtop,struct SVECTOR *vertop,struct SVECTOR *nortop, POLY_FT4 *s,unsigned long n,unsigned long shift,GsOT *otp,DIVPOLYGON4 *divp); extern unsigned long *GsTMDdivTF4LFGB(TMD_P_TF4 *primtop,struct SVECTOR *vertop, struct SVECTOR *nortop,POLY_FT4 *s,unsigned long n,unsigned long shift, GsOT *otp,DIVPOLYGON4 *divp); extern unsigned long *GsTMDdivTF4NLB(TMD_P_TF4 *primtop,struct SVECTOR *vertop,struct SVECTOR *nortop, POLY_FT4 *s,unsigned long n,unsigned long shift,GsOT *otp,DIVPOLYGON4 *divp); extern unsigned long *GsTMDdivTNF4B(TMD_P_TNF4 *primtop,struct SVECTOR *vertop, POLY_FT4 *s,unsigned long n,unsigned long shift,GsOT *otp,DIVPOLYGON4 *divp); extern unsigned long *GsTMDdivG3LB(TMD_P_G3 *primtop,struct SVECTOR *vertop,struct SVECTOR *nortop, POLY_G3 *s,unsigned long n,unsigned long shift,GsOT *otp,DIVPOLYGON3 *divp); extern unsigned long *GsTMDdivG3LFGB(TMD_P_G3 *primtop,struct SVECTOR *vertop,struct SVECTOR *nortop, POLY_G3 *s,unsigned long n,unsigned long shift,GsOT *otp,DIVPOLYGON3 *divp); extern unsigned long *GsTMDdivG3NLB(TMD_P_G3 *primtop,struct SVECTOR *vertop,struct SVECTOR *nortop, POLY_G3 *s,unsigned long n,unsigned long shift,GsOT *otp,DIVPOLYGON3 *divp); extern unsigned long *GsTMDdivNG3B(TMD_P_NG3 *primtop,struct SVECTOR *vertop, POLY_G3 *s,unsigned long n,unsigned long shift,GsOT *otp,DIVPOLYGON3 *divp); extern unsigned long *GsTMDdivG4LB(TMD_P_G4 *primtop,struct SVECTOR *vertop,struct SVECTOR *nortop, POLY_G4 *s,unsigned long n,unsigned long shift,GsOT *otp,DIVPOLYGON4 *divp); extern unsigned long *GsTMDdivG4LFGB(TMD_P_G4 *primtop,struct SVECTOR *vertop,struct SVECTOR *nortop, POLY_G4 *s,unsigned long n,unsigned long shift,GsOT *otp,DIVPOLYGON4 *divp); extern unsigned long *GsTMDdivG4NLB(TMD_P_G4 *primtop,struct SVECTOR *vertop,struct SVECTOR *nortop, POLY_G4 *s,unsigned long n,unsigned long shift,GsOT *otp,DIVPOLYGON4 *divp); extern unsigned long *GsTMDdivNG4B(TMD_P_NG4 *primtop,struct SVECTOR *vertop, POLY_G4 *s,unsigned long n,unsigned long shift,GsOT *otp,DIVPOLYGON4 *divp); extern unsigned long *GsTMDdivTG3LB(TMD_P_TG3 *primtop,struct SVECTOR *vertop,struct SVECTOR *nortop, POLY_GT3 *s,unsigned long n,unsigned long shift,GsOT *otp,DIVPOLYGON3 *divp); extern unsigned long *GsTMDdivTG3LFGB(TMD_P_TG3 *primtop,struct SVECTOR *vertop, struct SVECTOR *nortop,POLY_GT3 *s,unsigned long n,unsigned long shift, GsOT *otp,DIVPOLYGON3 *divp); extern unsigned long *GsTMDdivTG3NLB(TMD_P_TG3 *primtop,struct SVECTOR *vertop,struct SVECTOR *nortop, POLY_GT3 *s,unsigned long n,unsigned long shift,GsOT *otp,DIVPOLYGON3 *divp); extern unsigned long *GsTMDdivTNG3B(TMD_P_TNG3 *primtop,struct SVECTOR *vertop, POLY_GT3 *s,unsigned long n,unsigned long shift,GsOT *otp,DIVPOLYGON3 *divp); extern unsigned long *GsTMDdivTG4LB(TMD_P_TG4 *primtop,struct SVECTOR *vertop,struct SVECTOR *nortop, POLY_GT4 *s,unsigned long n,unsigned long shift,GsOT *otp,DIVPOLYGON4 *divp); extern unsigned long *GsTMDdivTG4LFGB(TMD_P_TG4 *primtop,struct SVECTOR *vertop, struct SVECTOR *nortop,POLY_GT4 *s,unsigned long n,unsigned long shift, GsOT *otp,DIVPOLYGON4 *divp); extern unsigned long *GsTMDdivTG4NLB(TMD_P_TG4 *primtop,struct SVECTOR *vertop,struct SVECTOR *nortop, POLY_GT4 *s,unsigned long n,unsigned long shift,GsOT *otp,DIVPOLYGON4 *divp); extern unsigned long *GsTMDdivTNG4B(TMD_P_TNG4 *primtop,struct SVECTOR *vertop, POLY_GT4 *s,unsigned long n,unsigned long shift,GsOT *otp,DIVPOLYGON4 *divp); */ extern void RotSMD_F3(long *pa, unsigned long *ot, int otlen, int id, int sclip, int hclip, int vclip, int nclipmode); extern void RotSMD_G3(long *pa, unsigned long *ot, int otlen, int id, int sclip, int hclip, int vclip, int nclipmode); extern void RotSMD_FT3(long *pa, unsigned long *ot, int otlen, int id, int sclip, int hclip, int vclip, int nclipmode); extern void RotSMD_GT3(long *pa, unsigned long *ot, int otlen, int id, int sclip, int hclip, int vclip, int nclipmode); extern void RotSMD_F4(long *pa, unsigned long *ot, int otlen, int id, int sclip, int hclip, int vclip, int nclipmode); extern void RotSMD_G4(long *pa, unsigned long *ot, int otlen, int id, int sclip, int hclip, int vclip, int nclipmode); extern void RotSMD_FT4(long *pa, unsigned long *ot, int otlen, int id, int sclip, int hclip, int vclip, int nclipmode); extern void RotSMD_GT4(long *pa, unsigned long *ot, int otlen, int id, int sclip, int hclip, int vclip, int nclipmode); extern void RotSMD_SV_F3(long *pa, long *va, unsigned long *ot, int otlen, int id, int sclip, int hclip, int vclip, int nclipmode); extern void RotSMD_SV_G3(long *pa, long *va, unsigned long *ot, int otlen, int id, int sclip, int hclip, int vclip, int nclipmode); extern void RotSMD_SV_FT3(long *pa, long *va, unsigned long *ot, int otlen, int id, int sclip, int hclip, int vclip, int nclipmode); extern void RotSMD_SV_GT3(long *pa, long *va, unsigned long *ot, int otlen, int id, int sclip, int hclip, int vclip, int nclipmode); extern void RotSMD_SV_F4(long *pa, long *va, unsigned long *ot, int otlen, int id, int sclip, int hclip, int vclip, int nclipmode); extern void RotSMD_SV_G4(long *pa, long *va, unsigned long *ot, int otlen, int id, int sclip, int hclip, int vclip, int nclipmode); extern void RotSMD_SV_FT4(long *pa, long *va, unsigned long *ot, int otlen, int id, int sclip, int hclip, int vclip, int nclipmode); extern void RotSMD_SV_GT4(long *pa, long *va, unsigned long *ot, int otlen, int id, int sclip, int hclip, int vclip, int nclipmode); extern void RotRMD_F3(long *pa, unsigned long *ot, int otlen, int id, int sclip, int hclip, int vclip, int nclipmode); extern void RotRMD_G3(long *pa, unsigned long *ot, int otlen, int id, int sclip, int hclip, int vclip, int nclipmode); extern void RotRMD_FT3(long *pa, unsigned long *ot, int otlen, int id, int sclip, int hclip, int vclip, int nclipmode); extern void RotRMD_GT3(long *pa, unsigned long *ot, int otlen, int id, int sclip, int hclip, int vclip, int nclipmode); extern void RotRMD_F4(long *pa, unsigned long *ot, int otlen, int id, int sclip, int hclip, int vclip, int nclipmode); extern void RotRMD_G4(long *pa, unsigned long *ot, int otlen, int id, int sclip, int hclip, int vclip, int nclipmode); extern void RotRMD_FT4(long *pa, unsigned long *ot, int otlen, int id, int sclip, int hclip, int vclip, int nclipmode); extern void RotRMD_GT4(long *pa, unsigned long *ot, int otlen, int id, int sclip, int hclip, int vclip, int nclipmode); extern void RotRMD_SV_F3(long *pa, long *va, unsigned long *ot, int otlen, int id, int sclip, int hclip, int vclip, int nclipmode); extern void RotRMD_SV_G3(long *pa, long *va, unsigned long *ot, int otlen, int id, int sclip, int hclip, int vclip, int nclipmode); extern void RotRMD_SV_FT3(long *pa, long *va, unsigned long *ot, int otlen, int id, int sclip, int hclip, int vclip, int nclipmode); extern void RotRMD_SV_GT3(long *pa, long *va, unsigned long *ot, int otlen, int id, int sclip, int hclip, int vclip, int nclipmode); extern void RotRMD_SV_F4(long *pa, long *va, unsigned long *ot, int otlen, int id, int sclip, int hclip, int vclip, int nclipmode); extern void RotRMD_SV_G4(long *pa, long *va, unsigned long *ot, int otlen, int id, int sclip, int hclip, int vclip, int nclipmode); extern void RotRMD_SV_FT4(long *pa, long *va, unsigned long *ot, int otlen, int id, int sclip, int hclip, int vclip, int nclipmode); extern void RotRMD_SV_GT4(long *pa, long *va, unsigned long *ot, int otlen, int id, int sclip, int hclip, int vclip, int nclipmode); extern long p2otz(long p, long projection); extern long otz2p(long otz, long projection); /* extern void RotMeshPrimS_F3(TMESH *msh,POLY_F3 *prim,u_long *ot, u_long otlen,long dpq,u_long backc); extern void RotMeshPrimS_G3(TMESH *msh,POLY_G3 *prim,u_long *ot, u_long otlen,long dpq,u_long backc); extern void RotMeshPrimS_FC3(TMESH *msh,POLY_F3 *prim,u_long *ot, u_long otlen,long dpq,u_long backc); extern void RotMeshPrimS_GC3(TMESH *msh,POLY_G3 *prim,u_long *ot, u_long otlen,long dpq,u_long backc); extern void RotMeshPrimS_FT3(TMESH *msh,POLY_FT3 *prim,u_long *ot, u_long otlen,long dpq,u_long backc); extern void RotMeshPrimS_GT3(TMESH *msh,POLY_GT3 *prim,u_long *ot, u_long otlen,long dpq,u_long backc); extern void RotMeshPrimS_FCT3(TMESH *msh,POLY_FT3 *prim,u_long *ot, u_long otlen,long dpq,u_long backc); extern void RotMeshPrimS_GCT3(TMESH *msh,POLY_GT3 *prim,u_long *ot, u_long otlen,long dpq,u_long backc); extern void RotMeshPrimS_T3(TMESH *msh,POLY_FT3 *prim,u_long *ot, u_long otlen,long dpq,u_long backc); extern void RotMeshPrimR_F3(TMESH *msh,POLY_F3 *prim,u_long *ot, u_long otlen,long dpq,u _long backc); extern void RotMeshPrimR_G3(TMESH *msh,POLY_G3 *prim,u_long *ot, u_long otlen,long dpq,u_long backc); extern void RotMeshPrimR_FC3(TMESH *msh,POLY_F3 *prim,u_long *ot, u_long otlen,long dpq,u_long backc); extern void RotMeshPrimR_GC3(TMESH *msh,POLY_G3 *prim,u_long *ot, u_long otlen,long dpq,u_long backc); extern void RotMeshPrimR_FT3(TMESH *msh,POLY_FT3 *prim,u_long *ot, u_long otlen,long dpq,u_long backc); extern void RotMeshPrimR_GT3(TMESH *msh,POLY_GT3 *prim,u_long *ot, u_long otlen,long dpq,u_long backc); extern void RotMeshPrimR_FCT3(TMESH *msh,POLY_FT3 *prim,u_long *ot, u_long otlen,long dpq,u_long backc); extern void RotMeshPrimR_GCT3(TMESH *msh,POLY_GT3 *prim,u_long *ot, u_long otlen,long dpq,u_long backc); extern void RotMeshPrimR_T3(TMESH *msh,POLY_FT3 *prim,u_long *ot, u_long otlen,long dpq,u_long backc); extern void RotMeshPrimQ_T(QMESH *msh,POLY_FT4 *prim,u_long *ot, u_long otlen,long dpq,long backc); */ #if defined(_LANGUAGE_C_PLUS_PLUS)||defined(__cplusplus)||defined(c_plusplus) } #endif #else #define INLINE_H <INLINE_C.H> #endif #include <sys/types.h> #include <LIBGTE.H> #include <LIBGPU.H> struct DB_STRUCT { int current_buffer; unsigned long* ot; char* polyptr; char* curpolybuf; char* polybuf_limit; int nOTSize; int nPBSize; unsigned long* order_table[2]; unsigned long* poly_buffer[2]; unsigned long* pickup_ot; unsigned long* pickup_order_table[2]; DRAWENV draw[2]; DISPENV disp[2]; }; struct room_info { short* data; // size=0, offset=0 short* door; // size=0, offset=4 struct FLOOR_INFO* floor; // size=8, offset=8 struct LIGHTINFO* light; // size=32, offset=12 struct MESH_INFO* mesh; // size=20, offset=16 long x; // size=0, offset=20 long y; // size=0, offset=24 long z; // size=0, offset=28 long minfloor; // size=0, offset=32 long maxceiling; // size=0, offset=36 short x_size; // size=0, offset=40 short y_size; // size=0, offset=42 CVECTOR ambient; // size=4, offset=44 short num_lights; // size=0, offset=48 short num_meshes; // size=0, offset=50 unsigned char ReverbType; // size=0, offset=52 unsigned char FlipNumber; // size=0, offset=53 char MeshEffect; // size=0, offset=54 char bound_active; // size=0, offset=55 short left; // size=0, offset=56 short right; // size=0, offset=58 short top; // size=0, offset=60 short bottom; // size=0, offset=62 short test_left; // size=0, offset=64 short test_right; short test_top; short test_bottom; short item_number; short fx_number; short flipped_room; unsigned short flags; }; struct object_info { short nmeshes; // size=0, offset=0 short mesh_index; // size=0, offset=2 long bone_index; // size=0, offset=4 short *frame_base; // size=0, offset=8 void(*initialise)(short item_number); // size=0, offset=12 void(*control)(short item_number); // size=0, offset=16 void(*floor)(struct ITEM_INFO* item, int x, int y, int z, int* height); // size=0, offset=20 void(*ceiling)(struct ITEM_INFO* item, int x, int y, int z, int* height); // size=0, offset=24 void(*draw_routine)(struct ITEM_INFO* item); // size=0, offset=28 void(*collision)(short item_num, struct ITEM_INFO* laraitem, struct COLL_INFO* coll); // size=0, offset=32 short object_mip; // size=0, offset=36 short anim_index; // size=0, offset=38 short hit_points; // size=0, offset=40 short pivot_length; // size=0, offset=42 short radius; // size=0, offset=44 short shadow_size; // size=0, offset=46 unsigned short bite_offset; // size=0, offset=48 unsigned short loaded : 1; // offset=50.0 unsigned short intelligent : 1; // offset=50.1 unsigned short non_lot : 1; // offset=50.2 unsigned short save_position : 1; // offset=50.3 unsigned short save_hitpoints : 1; // offset=50.4 unsigned short save_flags : 1; // offset=50.5 unsigned short save_anim : 1; // offset=50.6 unsigned short semi_transparent : 1; // offset=50.7 unsigned short water_creature : 1; // offset=51.0 unsigned short using_drawanimating_item : 1; // offset=51.1 unsigned short HitEffect : 2; // offset=51.2 unsigned short undead : 1; // offset=51.4 unsigned short save_mesh : 1; // offset=51.5 void(*draw_routine_extra)(struct ITEM_INFO* item); // size=0, offset=52 unsigned long explodable_meshbits; // size=0, offset=56 unsigned long padfuck; // size=0, offset=60 }; struct TEXTURE { unsigned char u0; unsigned char v0; unsigned short clut; unsigned char u1; unsigned char v1; unsigned short tpage; unsigned char u2; unsigned char v2; unsigned char id[2]; unsigned char u3; unsigned char v3; unsigned short wclut; }; struct static_info { short mesh_number; short flags; short x_minp; short x_maxp; short y_minp; short y_maxp; short z_minp; short z_maxp; short x_minc; short x_maxc; short y_minc; short y_maxc; short z_minc; short z_maxc; }; struct PSXTEXTI { unsigned char u0; unsigned char v0; unsigned short clut; unsigned char u1; unsigned char v1; unsigned short tpage; unsigned char u2; unsigned char v2; unsigned char codeGT4; unsigned char codeGT3; unsigned char u3; unsigned char v3; unsigned short pad3; }; struct VECTOR3D { long x; long y; long z; }; struct PSXTEXTSTRUCT { unsigned long u0v0clut; unsigned long u1v1tpage; unsigned long u2v2pad; unsigned long u3v3pad; }; struct PSXSPRITESTRUCT { short x1; short y1; short x2; short y2; unsigned short clut; unsigned short tpage; unsigned char u1; unsigned char v1; unsigned char u2; unsigned char v2; }; struct MMTEXTURE { struct TEXTURE t[3]; }; struct TSV { unsigned long xy; unsigned long rgz; }; typedef unsigned short PadData; typedef struct { unsigned short buttons; char xOffset; char yOffset; } MouseData; typedef struct { unsigned short digitalButtons; char centralTwist; char buttonI; char buttonII; char topLeft; } NegconData; typedef struct { unsigned char transStatus; unsigned char dataFormat; union { PadData pad; NegconData negcon; } data; } TapCtrllerData; typedef struct { TapCtrllerData ctrllers[4]; } MultiTapData; typedef struct { unsigned char transStatus; unsigned char dataFormat; union { PadData pad; MouseData mouse; NegconData negcon; MultiTapData tap; } data; } ControllerPacket; struct pad_configs { unsigned long pad_L2; unsigned long pad_R2; unsigned long pad_L1; unsigned long pad_R1; unsigned long pad_triangle; unsigned long pad_square; unsigned long pad_circle; unsigned long pad_cross; }; struct GouraudBarColourSet { unsigned char abLeftRed[5]; unsigned char abLeftGreen[5]; unsigned char abLeftBlue[5]; unsigned char abRightRed[5]; unsigned char abRightGreen[5]; unsigned char abRightBlue[5]; }; struct STASHEDOBJ { short clip; short numnodestodraw; struct ITEM_INFO* item; short* frmptr0; }; struct STASHEDDAT { short* mesh; char matrix[32]; }; struct WATERTAB { char shimmer; char choppy; unsigned char random; unsigned char abs; }; struct VIBRATION { short Rate; short Len; short Lev; short Acc; short Dec; short Sus; short Flag; short Vib; }; struct REQUESTER { unsigned short TitleTxt; unsigned short TitleCol : 5; unsigned short nOptions : 3; unsigned short CursorPos : 3; unsigned short OptionCol : 5; unsigned long JustifyL : 5; unsigned long JustifyR : 5; unsigned long Arrows : 5; unsigned long Ignore : 5; unsigned short OptionTxt[5]; }; struct SCALE { short xgrid; char scalefactor; char nummarks; }; struct COCKSUCK { unsigned char r; unsigned char g; unsigned char b; unsigned char pad; short finalcnt; short profile_xcnt; }; struct PACKEDNAME { char Name[12]; unsigned char Days; unsigned char Hours; unsigned char Min; unsigned char Sec; unsigned short Slot; unsigned char Level; unsigned char Pad; }; struct ILIGHT { short x; short y; short z; short pad1; unsigned char r; unsigned char g; unsigned char b; unsigned char pad; }; struct ITEM_LIGHT { struct ILIGHT Light[4]; }; struct ITEM_INFO { long floor; // size=0, offset=0 unsigned long touch_bits; // size=0, offset=4 unsigned long mesh_bits; // size=0, offset=8 short object_number; // size=0, offset=12 short current_anim_state; // size=0, offset=14 short goal_anim_state; // size=0, offset=16 short required_anim_state; // size=0, offset=18 short anim_number; // size=0, offset=20 short frame_number; // size=0, offset=22 short room_number; // size=0, offset=24 short next_item; // size=0, offset=26 short next_active; // size=0, offset=28 short speed; // size=0, offset=30 short fallspeed; // size=0, offset=32 short hit_points; // size=0, offset=34 unsigned short box_number; // size=0, offset=36 short timer; // size=0, offset=38 short flags; // size=0, offset=40 short shade; // size=0, offset=42 short trigger_flags; // size=0, offset=44 short carried_item; // size=0, offset=46 short after_death; // size=0, offset=48 unsigned short fired_weapon; // size=0, offset=50 short item_flags[4]; // size=8, offset=52 void* data; // size=0, offset=60 struct PHD_3DPOS pos; // size=20, offset=64 struct ITEM_LIGHT il; // size=48, offset=84 unsigned long active : 1; // offset=132.0 unsigned long status : 2; // offset=132.1 unsigned long gravity_status : 1; // offset=132.3 unsigned long hit_status : 1; // offset=132.4 unsigned long collidable : 1; // offset=132.5 unsigned long looked_at : 1; // offset=132.6 unsigned long dynamic_light : 1; // offset=132.7 unsigned long poisoned : 1; // offset=133.0 unsigned long ai_bits : 5; // offset=133.1 unsigned long really_active : 1; // offset=133.6 unsigned long InDrawRoom : 1; // offset=133.7 unsigned long meshswap_meshbits; // size=0, offset=136 short draw_room; // size=0, offset=140 short TOSSPAD; // size=0, offset=142 }; struct creature_info { short joint_rotation[4]; // size=8, offset=0 short maximum_turn; // size=0, offset=8 short flags; // size=0, offset=10 unsigned short alerted : 1; // offset=12.0 unsigned short head_left : 1; // offset=12.1 unsigned short head_right : 1; // offset=12.2 unsigned short reached_goal : 1; // offset=12.3 unsigned short hurt_by_lara : 1; // offset=12.4 unsigned short patrol2 : 1; // offset=12.5 unsigned short jump_ahead : 1; // offset=12.6 unsigned short monkey_ahead : 1; // offset=12.7 enum mood_type mood; // size=4, offset=16 struct ITEM_INFO* enemy; // size=144, offset=20 struct ITEM_INFO ai_target; // size=144, offset=24 short pad; // size=0, offset=168 short item_num; // size=0, offset=170 struct PHD_VECTOR target; // size=12, offset=172 struct lot_info LOT; // size=44, offset=184 }; struct DRIP_STRUCT { long x; // size=0, offset=0 long y; // size=0, offset=4 long z; // size=0, offset=8 unsigned char On; // size=0, offset=12 unsigned char R; // size=0, offset=13 unsigned char G; // size=0, offset=14 unsigned char B; // size=0, offset=15 short Yvel; // size=0, offset=16 unsigned char Gravity; // size=0, offset=18 unsigned char Life; // size=0, offset=19 short RoomNumber; // size=0, offset=20 unsigned char Outside; // size=0, offset=22 unsigned char Pad; // size=0, offset=23 }; #endif Header include correction. #ifndef SPECTYPES_H #define SPECTYPES_H #define INPUT_H "PSXINPUT.H" #define CMATH_H <LIBMATH.H> #include "TYPES.H" #ifdef PAELLA #define exit(x) exit() #define _STDDEF_H #define INLINE_H "PAELLA.H" #define ASSEMBLER #define _WCHAR_T #endif #include "TYPES.H" #ifdef PAELLA #define LMAX 256 #ifndef NULL #define NULL 0 /* null pointer constant */ #endif #ifndef _SIZE_T #define _SIZE_T typedef unsigned int size_t; /* result type of the sizeof operator (ANSI) */ #endif #if defined(_LANGUAGE_C_PLUS_PLUS)||defined(__cplusplus)||defined(c_plusplus) extern "C" { #endif /* To avoid conflicting */ extern void *memcpy(void *, void *, int); extern void *memmove(void *, const void *, int); /* To avoid conflicting */ extern int memcmp(void *, void *, int); extern void *memchr(const void *, int, int); extern void *memset(void *, int, int); extern void *bcopy(const void *, void *, int); /* src,dest */ extern void *bzero(void *, int); extern int bcmp(const void *, const void *, int); #if defined(_LANGUAGE_C_PLUS_PLUS)||defined(__cplusplus)||defined(c_plusplus) } #endif #if defined(_LANGUAGE_C_PLUS_PLUS)||defined(__cplusplus)||defined(c_plusplus) extern "C" { #endif extern char *strcat(char *, const char *); extern char *strncat(char *, const char *, int); extern int strcmp(char *, char *); extern int strncmp(const char *, const char *, int); extern char *strcpy(char *, char *); extern char *strncpy(char *, const char *, int); extern int strlen(char *); extern char *index(const char *, char); extern char *rindex(const char *, char); extern char *strchr(const char *, char); extern char *strrchr(const char *, char); extern char *strpbrk(const char *, const char *); extern int strspn(const char *, const char *); extern int strcspn(const char *, const char *); extern char *strtok(char *, const char *); extern char *strstr(const char *, const char *); #if defined(_LANGUAGE_C_PLUS_PLUS)||defined(__cplusplus)||defined(c_plusplus) } #endif #define strdup(p) ( strcpy(malloc(strlen(p)+1),p); ) #if defined(_LANGUAGE_C_PLUS_PLUS)||defined(__cplusplus)||defined(c_plusplus) extern "C" { #endif extern void InitGeom(); extern void EigenMatrix(struct MATRIX3D *m, struct MATRIX3D *t); extern int IsIdMatrix(struct MATRIX3D *m); extern struct MATRIX3D *MulMatrix0(struct MATRIX3D *m0, struct MATRIX3D *m1, struct MATRIX3D *m2); extern struct MATRIX3D *MulRotMatrix0(struct MATRIX3D *m0, struct MATRIX3D *m1); extern struct MATRIX3D *MulMatrix(struct MATRIX3D *m0, struct MATRIX3D *m1); extern struct MATRIX3D *MulMatrix2(struct MATRIX3D *m0, struct MATRIX3D *m1); extern struct MATRIX3D *MulRotMatrix(struct MATRIX3D *m0); extern struct MATRIX3D *SetMulMatrix(struct MATRIX3D *m0, struct MATRIX3D *m1); extern struct MATRIX3D *SetMulRotMatrix(struct MATRIX3D *m0); extern struct VECTOR *ApplyMatrix(struct MATRIX3D *m, struct SVECTOR *v0, struct VECTOR *v1); extern struct VECTOR *ApplyRotMatrix(struct SVECTOR *v0, struct VECTOR *v1); extern struct VECTOR *ApplyRotMatrixLV(struct VECTOR *v0, struct VECTOR *v1); extern struct VECTOR *ApplyMatrixLV(struct MATRIX3D *m, struct VECTOR *v0, struct VECTOR *v1); extern struct SVECTOR *ApplyMatrixSV(struct MATRIX3D *m, struct SVECTOR *v0, struct SVECTOR *v1); extern struct VECTOR *ApplyTransposeMatrixLV(struct MATRIX3D *m, struct VECTOR *v0, struct VECTOR *v1); extern struct MATRIX3D *RotMatrix(struct SVECTOR *r, struct MATRIX3D *m); extern struct MATRIX3D *RotMatrixXZY(struct SVECTOR *r, struct MATRIX3D *m); extern struct MATRIX3D *RotMatrixYXZ(struct SVECTOR *r, struct MATRIX3D *m); extern struct MATRIX3D *RotMatrixYZX(struct SVECTOR *r, struct MATRIX3D *m); extern struct MATRIX3D *RotMatrixZXY(struct SVECTOR *r, struct MATRIX3D *m); extern struct MATRIX3D *RotMatrixZYX(struct SVECTOR *r, struct MATRIX3D *m); extern struct MATRIX3D *RotMatrix_gte(struct SVECTOR *r, struct MATRIX3D *m); extern struct MATRIX3D *RotMatrixYXZ_gte(struct SVECTOR *r, struct MATRIX3D *m); extern struct MATRIX3D *RotMatrixZYX_gte(struct SVECTOR *r, struct MATRIX3D *m); extern struct MATRIX3D *RotMatrixX(long r, struct MATRIX3D *m); extern struct MATRIX3D *RotMatrixY(long r, struct MATRIX3D *m); extern struct MATRIX3D *RotMatrixZ(long r, struct MATRIX3D *m); extern struct MATRIX3D *RotMatrixC(struct SVECTOR *r, struct MATRIX3D *m); extern struct MATRIX3D *TransMatrix(struct MATRIX3D *m, struct VECTOR *v); extern struct MATRIX3D *ScaleMatrix(struct MATRIX3D *m, struct VECTOR *v); extern struct MATRIX3D *ScaleMatrixL(struct MATRIX3D *m, struct VECTOR *v); extern struct MATRIX3D *TransposeMatrix(struct MATRIX3D *m0, struct MATRIX3D *m1); extern struct MATRIX3D *CompMatrix(struct MATRIX3D *m0, struct MATRIX3D *m1, struct MATRIX3D *m2); extern struct MATRIX3D *CompMatrixLV(struct MATRIX3D *m0, struct MATRIX3D *m1, struct MATRIX3D *m2); extern void MatrixNormal(struct MATRIX3D *m, struct MATRIX3D *n); extern void MatrixNormal_0(struct MATRIX3D *m, struct MATRIX3D *n); extern void MatrixNormal_1(struct MATRIX3D *m, struct MATRIX3D *n); extern void MatrixNormal_2(struct MATRIX3D *m, struct MATRIX3D *n); extern void SetRotMatrix(struct MATRIX3D *m); extern void SetLightMatrix(struct MATRIX3D *m); extern void SetColorMatrix(struct MATRIX3D *m); extern void SetTransMatrix(struct MATRIX3D *m); extern void PushMatrix(); extern void PopMatrix(); extern void ReadRotMatrix(struct MATRIX3D *m); extern void ReadLightMatrix(struct MATRIX3D *m); extern void ReadColorMatrix(struct MATRIX3D *m); extern void SetRGBcd(struct CVECTOR *v); extern void SetBackColor(long rbk, long gbk, long bbk); extern void SetFarColor(long rfc, long gfc, long bfc); extern void SetGeomOffset(long ofx, long ofy); extern void SetGeomScreen(long h); extern void ReadSZfifo3(long *sz0, long *sz1, long *sz2); extern void ReadSZfifo4(long *szx, long *sz0, long *sz1, long *sz2); extern void ReadSXSYfifo(long *sxy0, long *sxy1, long *sxy2); extern void ReadRGBfifo(struct CVECTOR *v0, struct CVECTOR *v1, struct CVECTOR *v2); extern void ReadGeomOffset(long *ofx, long *ofy); extern long ReadGeomScreen(); extern void TransRot_32(struct VECTOR *v0, struct VECTOR *v1, long *flag); extern long TransRotPers(struct SVECTOR *v0, long *sxy, long *p, long *flag); extern long TransRotPers3(struct SVECTOR *v0, struct SVECTOR *v1, struct SVECTOR *v2, long *sxy0, long *sxy1, long *sxy2, long *p, long *flag); extern void pers_map(int abuf, struct SVECTOR **vertex, int tex[4][2], unsigned short *dtext); extern void PhongLine(int istart_x, int iend_x, int p, int q, unsigned short **pixx, int fs, int ft, int i4, int det); extern long RotTransPers(struct SVECTOR *v0, long *sxy, long *p, long *flag); extern long RotTransPers3(struct SVECTOR *v0, struct SVECTOR *v1, struct SVECTOR *v2, long *sxy0, long *sxy1, long *sxy2, long *p, long *flag); extern void RotTrans(struct SVECTOR *v0, struct VECTOR *v1, long *flag); extern void RotTransSV(struct SVECTOR *v0, struct SVECTOR *v1, long *flag); extern void LocalLight(struct SVECTOR *v0, struct VECTOR *v1); extern void LightColor(struct VECTOR *v0, struct VECTOR *v1); extern void DpqColorLight(struct VECTOR *v0, struct CVECTOR *v1, long p, struct CVECTOR *v2); extern void DpqColor(struct CVECTOR *v0, long p, struct CVECTOR *v1); extern void DpqColor3(struct CVECTOR *v0, struct CVECTOR *v1, struct CVECTOR *v2, long p, struct CVECTOR *v3, struct CVECTOR *v4, struct CVECTOR *v5); extern void Intpl(struct VECTOR *v0, long p, struct CVECTOR *v1); extern struct VECTOR *Square12(struct VECTOR *v0, struct VECTOR *v1); extern struct VECTOR *Square0(struct VECTOR *v0, struct VECTOR *v1); extern struct VECTOR *SquareSL12(struct SVECTOR *v0, struct VECTOR *v1); extern struct VECTOR *SquareSL0(struct SVECTOR *v0, struct VECTOR *v1); extern struct SVECTOR *SquareSS12(struct SVECTOR *v0, struct SVECTOR *v1); extern struct SVECTOR *SquareSS0(struct SVECTOR *v0, struct SVECTOR *v1); extern void NormalColor(struct SVECTOR *v0, struct CVECTOR *v1); extern void NormalColor3(struct SVECTOR *v0, struct SVECTOR *v1, struct SVECTOR *v2, struct CVECTOR *v3, struct CVECTOR *v4, struct CVECTOR *v5); extern void NormalColorDpq(struct SVECTOR *v0, struct CVECTOR *v1, long p, struct CVECTOR *v2); extern void NormalColorDpq3(struct SVECTOR *v0, struct SVECTOR *v1, struct SVECTOR *v2, struct CVECTOR *v3, long p, struct CVECTOR *v4, struct CVECTOR *v5, struct CVECTOR *v6); extern void NormalColorCol(struct SVECTOR *v0, struct CVECTOR *v1, struct CVECTOR *v2); extern void NormalColorCol3(struct SVECTOR *v0, struct SVECTOR *v1, struct SVECTOR *v2, struct CVECTOR *v3, struct CVECTOR *v4, struct CVECTOR *v5, struct CVECTOR *v6); extern void ColorDpq(struct VECTOR *v0, struct CVECTOR *v1, long p, struct CVECTOR *v2); extern void ColorCol(struct VECTOR *v0, struct CVECTOR *v1, struct CVECTOR *v2); extern long NormalClip(long sxy0, long sxy1, long sxy2); extern long AverageZ3(long sz0, long sz1, long sz2); extern long AverageZ4(long sz0, long sz1, long sz2, long sz3); extern void OuterProduct12(struct VECTOR *v0, struct VECTOR *v1, struct VECTOR *v2); extern void OuterProduct0(struct VECTOR *v0, struct VECTOR *v1, struct VECTOR *v2); extern long Lzc(long data); extern long RotTransPers4(struct SVECTOR *v0, struct SVECTOR *v1, struct SVECTOR *v2, struct SVECTOR *v3, long *sxy0, long *sxy1, long *sxy2, long *sxy3, long *p, long *flag); extern void RotTransPersN(struct SVECTOR *v0, struct DVECTOR *v1, unsigned short *sz, unsigned short *p, unsigned short *flag, long n); extern void RotTransPers3N(struct SVECTOR *v0, struct DVECTOR *v1, unsigned short *sz, unsigned short *flag, long n); extern void RotMeshH(short *Yheight, struct DVECTOR *Vo, unsigned short *sz, unsigned short *flag, short Xoffset, short Zoffset, short m, short n, struct DVECTOR *base); extern long RotAverage3(struct SVECTOR *v0, struct SVECTOR *v1, struct SVECTOR *v2, long *sxy0, long *sxy1, long *sxy2, long *p, long *flag); extern long RotAverage4(struct SVECTOR *v0, struct SVECTOR *v1, struct SVECTOR *v2, struct SVECTOR *v3, long *sxy0, long *sxy1, long *sxy2, long *sxy3, long *p, long *flag); extern long RotNclip3(struct SVECTOR *v0, struct SVECTOR *v1, struct SVECTOR *v2, long *sxy0, long *sxy1, long *sxy2, long *p, long *otz, long *flag); extern long RotNclip4(struct SVECTOR *v0, struct SVECTOR *v1, struct SVECTOR *v2, struct SVECTOR *v3, long *sxy0, long *sxy1, long *sxy2, long *sxy3, long *p, long *otz, long *flag); extern long RotAverageNclip3(struct SVECTOR *v0, struct SVECTOR *v1, struct SVECTOR *v2, long *sxy0, long *sxy1, long *sxy2, long *p, long *otz, long *flag); extern long RotAverageNclip4(struct SVECTOR *v0, struct SVECTOR *v1, struct SVECTOR *v2, struct SVECTOR *v3, long *sxy0, long *sxy1, long *sxy2, long *sxy3, long *p, long *otz, long *flag); extern long RotColorDpq(struct SVECTOR *v0, struct SVECTOR *v1, struct CVECTOR *v2, long *sxy, struct CVECTOR *v3, long *flag); extern long RotColorDpq3(struct SVECTOR *v0, struct SVECTOR *v1, struct SVECTOR *v2, struct SVECTOR *v3, struct SVECTOR *v4, struct SVECTOR *v5, struct CVECTOR *v6, long *sxy0, long *sxy1, long *sxy2, struct CVECTOR *v7, struct CVECTOR *v8, struct CVECTOR *v9, long *flag); extern long RotAverageNclipColorDpq3(struct SVECTOR *v0, struct SVECTOR *v1, struct SVECTOR *v2, struct SVECTOR *v3, struct SVECTOR *v4, struct SVECTOR *v5, struct CVECTOR *v6, long *sxy0, long *sxy1, long *sxy2, struct CVECTOR *v7, struct CVECTOR *v8, struct CVECTOR *v9, long *otz, long *flag); extern long RotAverageNclipColorCol3(struct SVECTOR *v0, struct SVECTOR *v1, struct SVECTOR *v2, struct SVECTOR *v3, struct SVECTOR *v4, struct SVECTOR *v5, struct CVECTOR *v6, long *sxy0, long *sxy1, long *sxy2, struct CVECTOR *v7, struct CVECTOR *v8, struct CVECTOR *v9, long *otz, long *flag); extern long RotColorMatDpq(struct SVECTOR *v0, struct SVECTOR *v1, struct CVECTOR *v2, long *sxy, struct CVECTOR *v3, long matc, long flag); extern void ColorMatDpq(struct SVECTOR *v0, struct CVECTOR *v1, long p, struct CVECTOR *v2, long matc); extern void ColorMatCol(struct SVECTOR *v0, struct CVECTOR *v1, struct CVECTOR *v2, long matc); extern void LoadAverage12(struct VECTOR *v0, struct VECTOR *v1, long p0, long p1, struct VECTOR *v2); extern void LoadAverageShort12(struct SVECTOR *v0, struct SVECTOR *v1, long p0, long p1, struct SVECTOR *v2); extern void LoadAverage0(struct VECTOR *v0, struct VECTOR *v1, long p0, long p1, struct VECTOR *v2); extern void LoadAverageShort0(struct SVECTOR *v0, struct SVECTOR *v1, long p0, long p1, struct SVECTOR *v2); extern void LoadAverageByte(unsigned char *v0, unsigned char *v1, long p0, long p1, unsigned char *v2); extern void LoadAverageCol(unsigned char *v0, unsigned char *v1, long p0, long p1, unsigned char *v2); extern long VectorNormal(struct VECTOR *v0, struct VECTOR *v1); extern long VectorNormalS(struct VECTOR *v0, struct SVECTOR *v1); extern long VectorNormalSS(struct SVECTOR *v0, struct SVECTOR *v1); extern long SquareRoot0(long a); extern long SquareRoot12(long a); extern void InvSquareRoot(long a, long *b, long *c); extern void gteMIMefunc(struct SVECTOR *otp, struct SVECTOR *dfp, long n, long p); extern void SetFogFar(long a, long h); extern void SetFogNear(long a, long h); extern void SetFogNearFar(long a, long b, long h); extern void SubPol4(struct POL4 *p, struct SPOL *sp, int ndiv); extern void SubPol3(struct POL3 *p, struct SPOL *sp, int ndiv); extern int rcos(int a); extern int rsin(int a); extern int ccos(int a); extern int csin(int a); extern int cln(int a); extern int csqrt(int a); extern int catan(int a); extern long ratan2(long y, long x); extern void RotPMD_F3(long *pa, unsigned long *ot, int otlen, int id, int backc); extern void RotPMD_G3(long *pa, unsigned long *ot, int otlen, int id, int backc); extern void RotPMD_FT3(long *pa, unsigned long *ot, int otlen, int id, int backc); extern void RotPMD_GT3(long *pa, unsigned long *ot, int otlen, int id, int backc); extern void RotPMD_F4(long *pa, unsigned long *ot, int otlen, int id, int backc); extern void RotPMD_G4(long *pa, unsigned long *ot, int otlen, int id, int backc); extern void RotPMD_FT4(long *pa, unsigned long *ot, int otlen, int id, int backc); extern void RotPMD_GT4(long *pa, unsigned long *ot, int otlen, int id, int backc); extern void RotPMD_SV_F3(long *pa, long *va, unsigned long *ot, int otlen, int id, int backc); extern void RotPMD_SV_G3(long *pa, long *va, unsigned long *ot, int otlen, int id, int backc); extern void RotPMD_SV_FT3(long *pa, long *va, unsigned long *ot, int otlen, int id, int backc); extern void RotPMD_SV_GT3(long *pa, long *va, unsigned long *ot, int otlen, int id, int backc); extern void RotPMD_SV_F4(long *pa, long *va, unsigned long *ot, int otlen, int id, int backc); extern void RotPMD_SV_G4(long *pa, long *va, unsigned long *ot, int otlen, int id, int backc); extern void RotPMD_SV_FT4(long *pa, long *va, unsigned long *ot, int otlen, int id, int backc); extern void RotPMD_SV_GT4(long *pa, long *va, unsigned long *ot, int otlen, int id, int backc); extern void InitClip(struct EVECTOR *evbfad, long hw, long vw, long h, long near, long far); extern long Clip3F(struct SVECTOR *v0, struct SVECTOR *v1, struct SVECTOR *v2, struct EVECTOR **evmx); extern long Clip3FP(struct SVECTOR *v0, struct SVECTOR *v1, struct SVECTOR *v2, struct EVECTOR **evmx); extern long Clip4F(struct SVECTOR *v0, struct SVECTOR *v1, struct SVECTOR *v2, struct SVECTOR *v3, struct EVECTOR **evmx); extern long Clip4FP(struct SVECTOR *v0, struct SVECTOR *v1, struct SVECTOR *v2, struct SVECTOR *v3, struct EVECTOR **evmx); extern long Clip3FT(struct SVECTOR *v0, struct SVECTOR *v1, struct SVECTOR *v2, short *uv0, short *uv1, short *uv2, struct EVECTOR **evmx); extern long Clip3FTP(struct SVECTOR *v0, struct SVECTOR *v1, struct SVECTOR *v2, short *uv0, short *uv1, short *uv2, struct EVECTOR **evmx); extern long Clip4FT(struct SVECTOR *v0, struct SVECTOR *v1, struct SVECTOR *v2, struct SVECTOR *v3, short *uv0, short *uv1, short *uv2, short *uv3, struct EVECTOR **evmx); extern long Clip4FTP(struct SVECTOR *v0, struct SVECTOR *v1, struct SVECTOR *v2, struct SVECTOR *v3, short *uv0, short *uv1, short *uv2, short *uv3, struct EVECTOR **evmx); extern long Clip3G(struct SVECTOR *v0, struct SVECTOR *v1, struct SVECTOR *v2, struct CVECTOR *rgb0, struct CVECTOR *rgb1, struct CVECTOR *rgb2, struct EVECTOR **evmx); extern long Clip3GP(struct SVECTOR *v0, struct SVECTOR *v1, struct SVECTOR *v2, struct CVECTOR *rgb0, struct CVECTOR *rgb1, struct CVECTOR *rgb2, struct EVECTOR **evmx); extern long Clip4G(struct SVECTOR *v0, struct SVECTOR *v1, struct SVECTOR *v2, struct SVECTOR *v3, struct CVECTOR *rgb0, struct CVECTOR *rgb1, struct CVECTOR *rgb2, struct CVECTOR *rgb3, struct EVECTOR **evmx); extern long Clip4GP(struct SVECTOR *v0, struct SVECTOR *v1, struct SVECTOR *v2, struct SVECTOR *v3, struct CVECTOR *rgb0, struct CVECTOR *rgb1, struct CVECTOR *rgb2, struct CVECTOR *rgb3, struct EVECTOR **evmx); extern long Clip3GT(struct SVECTOR *v0, struct SVECTOR *v1, struct SVECTOR *v2, short *uv0, short *uv1, short *uv2, struct CVECTOR *rgb0, struct CVECTOR *rgb1, struct CVECTOR *rgb2, struct EVECTOR **evmx); extern long Clip3GTP(struct SVECTOR *v0, struct SVECTOR *v1, struct SVECTOR *v2, short *uv0, short *uv1, short *uv2, struct CVECTOR *rgb0, struct CVECTOR *rgb1, struct CVECTOR *rgb2, struct EVECTOR **evmx); extern long Clip4GT(struct SVECTOR *v0, struct SVECTOR *v1, struct SVECTOR *v2, struct SVECTOR *v3, short *uv0, short *uv1, short *uv2, short *uv3, struct CVECTOR *rgb0, struct CVECTOR *rgb1, struct CVECTOR *rgb2, struct CVECTOR *rgb3, struct EVECTOR **evmx); extern long Clip4GTP(struct SVECTOR *v0, struct SVECTOR *v1, struct SVECTOR *v2, struct SVECTOR *v3, short *uv0, short *uv1, short *uv2, short *uv3, struct CVECTOR *rgb0, struct CVECTOR *rgb1, struct CVECTOR *rgb2, struct CVECTOR *rgb3, struct EVECTOR **evmx); extern void RotTransPers_nom(struct SVECTOR *v0); extern void RotTransPers3_nom(struct SVECTOR *v0, struct SVECTOR *v1, struct SVECTOR *v2); extern void RotTransPers4_nom(struct SVECTOR *v0, struct SVECTOR *v1, struct SVECTOR *v2, struct SVECTOR *v3); extern void RotTrans_nom(struct SVECTOR *v0); extern void RotAverage3_nom(struct SVECTOR *v0, struct SVECTOR *v1, struct SVECTOR *v2); extern void RotNclip3_nom(struct SVECTOR *v0, struct SVECTOR *v1, struct SVECTOR *v2); extern void RotAverageNclip3_nom(struct SVECTOR *v0, struct SVECTOR *v1, struct SVECTOR *v2); extern void RotAverageNclipColorDpq3_nom(struct SVECTOR *v0, struct SVECTOR *v1, struct SVECTOR *v2, struct SVECTOR *v3, struct SVECTOR *v4, struct SVECTOR *v5, struct CVECTOR *v6); extern void RotAverageNclipColorCol3_nom(struct SVECTOR *v0, struct SVECTOR *v1, struct SVECTOR *v2, struct SVECTOR *v3, struct SVECTOR *v4, struct SVECTOR *v5, struct CVECTOR *v6); extern void RotColorDpq_nom(struct SVECTOR *v0, struct SVECTOR *v1, struct CVECTOR *v2); extern long RotColorDpq3_nom(struct SVECTOR *v0, struct SVECTOR *v1, struct SVECTOR *v2, struct SVECTOR *v3, struct SVECTOR *v4, struct SVECTOR *v5, struct CVECTOR *v6); extern void NormalColor_nom(struct SVECTOR *v0); extern void NormalColor3_nom(struct SVECTOR *v0, struct SVECTOR *v1, struct SVECTOR *v2); extern void NormalColorDpq_nom(struct SVECTOR *v0, struct CVECTOR *v1, long p); extern void NormalColorDpq3_nom(struct SVECTOR *v0, struct SVECTOR *v1, struct SVECTOR *v2, struct CVECTOR *v3, long p); extern void NormalColorCol_nom(struct SVECTOR *v0, struct CVECTOR *v1); extern void NormalColorCol3_nom(struct SVECTOR *v0, struct SVECTOR *v1, struct SVECTOR *v2, struct CVECTOR *v3); /* extern unsigned long *DivideF3(struct SVECTOR *v0,struct SVECTOR *v1,struct SVECTOR *v2,struct CVECTOR *rgbc, POLY *otp); extern unsigned long *GsPrng n,unsigned long shift,GsOT *otp); extern unsigned long *GsTMDfastTG3LB(TMD_P_TG3 *primtop,struct SVECTOR *vertop,struct SVECTOR *nortop, POLY_GT3 *s,unsigned long n,unsigned long shift,GsOT *otp); extern unsigned long *GsTMDfastTG3LFGB(TMD_P_TG3 *primtop,struct SVECTOR *vertop, struct SVECTOR *nortop,POLY_GT3 *s,unsigned long n,unsigned long shift,GsOT *otp); extern unsigned long *GsTMDfastTG3NLB(TMD_P_TG3 *primtop,struct SVECTOR *vertop, struct SVECTOR *nortop,POLY_GT3 *s,unsigned long n,unsigned long shift,GsOT *otp); extern unsigned long *GsTMDfastTNG3B(TMD_P_TNG3 *primtop,struct SVECTOR *vertop, POLY_GT3 *s,unsigned long n,unsigned long shift,GsOT *otp); extern unsigned long *GsTMDfastTG4LB(TMD_P_TG4 *primtop,struct SVECTOR *vertop,struct SVECTOR *nortop, POLY_GT4 *s,unsigned long n,unsigned long shift,GsOT *otp); extern unsigned long *GsTMDfastTG4LFGB(TMD_P_TG4 *primtop,struct SVECTOR *vertop, struct SVECTOR *nortop,POLY_GT4 *s,unsigned long n,unsigned long shift,GsOT *otp); extern unsigned long *GsTMDfastTG4NLB(TMD_P_TG4 *primtop,struct SVECTOR *vertop, struct SVECTOR *nortop,POLY_GT4 *s,unsigned long n,unsigned long shift,GsOT *otp); extern unsigned long *GsTMDfastTNG4B(TMD_P_TNG4 *primtop,struct SVECTOR *vertop, POLY_GT4 *s,unsigned long n,unsigned long shift,GsOT *otp); extern unsigned long *GsTMDdivF3LB(TMD_P_F3 *primtop,struct SVECTOR *vertop,struct SVECTOR *nortop, POLY_F3 *s,unsigned long n,unsigned long shift,GsOT *otp,DIVPOLYGON3 *divp); extern unsigned long *GsTMDdivF3LFGB(TMD_P_F3 *primtop,struct SVECTOR *vertop,struct SVECTOR *nortop, POLY_F3 *s,unsigned long n,unsigned long shift,GsOT *otp,DIVPOLYGON3 *divp); extern unsigned long *GsTMDdivF3NLB(TMD_P_F3 *primtop,struct SVECTOR *vertop,struct SVECTOR *nortop, POLY_F3 *s,unsigned long n,unsigned long shift,GsOT *otp,DIVPOLYGON3 *divp); extern unsigned long *GsTMDdivNF3B(TMD_P_NF3 *primtop,struct SVECTOR *vertop, POLY_F3 *s,unsigned long n,unsigned long shift,GsOT *otp,DIVPOLYGON3 *divp); extern unsigned long *GsTMDdivF4LB(TMD_P_F4 *primtop,struct SVECTOR *vertop,struct SVECTOR *nortop, POLY_F4 *s,unsigned long n,unsigned long shift,GsOT *otp,DIVPOLYGON4 *divp); extern unsigned long *GsTMDdivF4LFGB(TMD_P_F4 *primtop,struct SVECTOR *vertop,struct SVECTOR *nortop, POLY_F4 *s,unsigned long n,unsigned long shift,GsOT *otp,DIVPOLYGON4 *divp); extern unsigned long *GsTMDdivF4NLB(TMD_P_F4 *primtop,struct SVECTOR *vertop,struct SVECTOR *nortop, POLY_F4 *s,unsigned long n,unsigned long shift,GsOT *otp,DIVPOLYGON4 *divp); extern unsigned long *GsTMDdivNF4B(TMD_P_NF4 *primtop,struct SVECTOR *vertop, POLY_F4 *s,unsigned long n,unsigned long shift,GsOT *otp,DIVPOLYGON4 *divp); extern unsigned long *GsTMDdivTF3LB(TMD_P_TF3 *primtop,struct SVECTOR *vertop,struct SVECTOR *nortop, POLY_FT3 *s,unsigned long n,unsigned long shift,GsOT *otp,DIVPOLYGON3 *divp); extern unsigned long *GsTMDdivTF3LFGB(TMD_P_TF3 *primtop,struct SVECTOR *vertop, struct SVECTOR *nortop,POLY_FT3 *s,unsigned long n,unsigned long shift, GsOT *otp,DIVPOLYGON3 *divp); extern unsigned long *GsTMDdivTF3NLB(TMD_P_TF3 *primtop,struct SVECTOR *vertop,struct SVECTOR *nortop, POLY_FT3 *s,unsigned long n,unsigned long shift,GsOT *otp,DIVPOLYGON3 *divp); extern unsigned long *GsTMDdivTNF3B(TMD_P_TNF3 *primtop,struct SVECTOR *vertop, POLY_FT3 *s,unsigned long n,unsigned long shift,GsOT *otp,DIVPOLYGON3 *divp); extern unsigned long *GsTMDdivTF4LB(TMD_P_TF4 *primtop,struct SVECTOR *vertop,struct SVECTOR *nortop, POLY_FT4 *s,unsigned long n,unsigned long shift,GsOT *otp,DIVPOLYGON4 *divp); extern unsigned long *GsTMDdivTF4LFGB(TMD_P_TF4 *primtop,struct SVECTOR *vertop, struct SVECTOR *nortop,POLY_FT4 *s,unsigned long n,unsigned long shift, GsOT *otp,DIVPOLYGON4 *divp); extern unsigned long *GsTMDdivTF4NLB(TMD_P_TF4 *primtop,struct SVECTOR *vertop,struct SVECTOR *nortop, POLY_FT4 *s,unsigned long n,unsigned long shift,GsOT *otp,DIVPOLYGON4 *divp); extern unsigned long *GsTMDdivTNF4B(TMD_P_TNF4 *primtop,struct SVECTOR *vertop, POLY_FT4 *s,unsigned long n,unsigned long shift,GsOT *otp,DIVPOLYGON4 *divp); extern unsigned long *GsTMDdivG3LB(TMD_P_G3 *primtop,struct SVECTOR *vertop,struct SVECTOR *nortop, POLY_G3 *s,unsigned long n,unsigned long shift,GsOT *otp,DIVPOLYGON3 *divp); extern unsigned long *GsTMDdivG3LFGB(TMD_P_G3 *primtop,struct SVECTOR *vertop,struct SVECTOR *nortop, POLY_G3 *s,unsigned long n,unsigned long shift,GsOT *otp,DIVPOLYGON3 *divp); extern unsigned long *GsTMDdivG3NLB(TMD_P_G3 *primtop,struct SVECTOR *vertop,struct SVECTOR *nortop, POLY_G3 *s,unsigned long n,unsigned long shift,GsOT *otp,DIVPOLYGON3 *divp); extern unsigned long *GsTMDdivNG3B(TMD_P_NG3 *primtop,struct SVECTOR *vertop, POLY_G3 *s,unsigned long n,unsigned long shift,GsOT *otp,DIVPOLYGON3 *divp); extern unsigned long *GsTMDdivG4LB(TMD_P_G4 *primtop,struct SVECTOR *vertop,struct SVECTOR *nortop, POLY_G4 *s,unsigned long n,unsigned long shift,GsOT *otp,DIVPOLYGON4 *divp); extern unsigned long *GsTMDdivG4LFGB(TMD_P_G4 *primtop,struct SVECTOR *vertop,struct SVECTOR *nortop, POLY_G4 *s,unsigned long n,unsigned long shift,GsOT *otp,DIVPOLYGON4 *divp); extern unsigned long *GsTMDdivG4NLB(TMD_P_G4 *primtop,struct SVECTOR *vertop,struct SVECTOR *nortop, POLY_G4 *s,unsigned long n,unsigned long shift,GsOT *otp,DIVPOLYGON4 *divp); extern unsigned long *GsTMDdivNG4B(TMD_P_NG4 *primtop,struct SVECTOR *vertop, POLY_G4 *s,unsigned long n,unsigned long shift,GsOT *otp,DIVPOLYGON4 *divp); extern unsigned long *GsTMDdivTG3LB(TMD_P_TG3 *primtop,struct SVECTOR *vertop,struct SVECTOR *nortop, POLY_GT3 *s,unsigned long n,unsigned long shift,GsOT *otp,DIVPOLYGON3 *divp); extern unsigned long *GsTMDdivTG3LFGB(TMD_P_TG3 *primtop,struct SVECTOR *vertop, struct SVECTOR *nortop,POLY_GT3 *s,unsigned long n,unsigned long shift, GsOT *otp,DIVPOLYGON3 *divp); extern unsigned long *GsTMDdivTG3NLB(TMD_P_TG3 *primtop,struct SVECTOR *vertop,struct SVECTOR *nortop, POLY_GT3 *s,unsigned long n,unsigned long shift,GsOT *otp,DIVPOLYGON3 *divp); extern unsigned long *GsTMDdivTNG3B(TMD_P_TNG3 *primtop,struct SVECTOR *vertop, POLY_GT3 *s,unsigned long n,unsigned long shift,GsOT *otp,DIVPOLYGON3 *divp); extern unsigned long *GsTMDdivTG4LB(TMD_P_TG4 *primtop,struct SVECTOR *vertop,struct SVECTOR *nortop, POLY_GT4 *s,unsigned long n,unsigned long shift,GsOT *otp,DIVPOLYGON4 *divp); extern unsigned long *GsTMDdivTG4LFGB(TMD_P_TG4 *primtop,struct SVECTOR *vertop, struct SVECTOR *nortop,POLY_GT4 *s,unsigned long n,unsigned long shift, GsOT *otp,DIVPOLYGON4 *divp); extern unsigned long *GsTMDdivTG4NLB(TMD_P_TG4 *primtop,struct SVECTOR *vertop,struct SVECTOR *nortop, POLY_GT4 *s,unsigned long n,unsigned long shift,GsOT *otp,DIVPOLYGON4 *divp); extern unsigned long *GsTMDdivTNG4B(TMD_P_TNG4 *primtop,struct SVECTOR *vertop, POLY_GT4 *s,unsigned long n,unsigned long shift,GsOT *otp,DIVPOLYGON4 *divp); */ extern void RotSMD_F3(long *pa, unsigned long *ot, int otlen, int id, int sclip, int hclip, int vclip, int nclipmode); extern void RotSMD_G3(long *pa, unsigned long *ot, int otlen, int id, int sclip, int hclip, int vclip, int nclipmode); extern void RotSMD_FT3(long *pa, unsigned long *ot, int otlen, int id, int sclip, int hclip, int vclip, int nclipmode); extern void RotSMD_GT3(long *pa, unsigned long *ot, int otlen, int id, int sclip, int hclip, int vclip, int nclipmode); extern void RotSMD_F4(long *pa, unsigned long *ot, int otlen, int id, int sclip, int hclip, int vclip, int nclipmode); extern void RotSMD_G4(long *pa, unsigned long *ot, int otlen, int id, int sclip, int hclip, int vclip, int nclipmode); extern void RotSMD_FT4(long *pa, unsigned long *ot, int otlen, int id, int sclip, int hclip, int vclip, int nclipmode); extern void RotSMD_GT4(long *pa, unsigned long *ot, int otlen, int id, int sclip, int hclip, int vclip, int nclipmode); extern void RotSMD_SV_F3(long *pa, long *va, unsigned long *ot, int otlen, int id, int sclip, int hclip, int vclip, int nclipmode); extern void RotSMD_SV_G3(long *pa, long *va, unsigned long *ot, int otlen, int id, int sclip, int hclip, int vclip, int nclipmode); extern void RotSMD_SV_FT3(long *pa, long *va, unsigned long *ot, int otlen, int id, int sclip, int hclip, int vclip, int nclipmode); extern void RotSMD_SV_GT3(long *pa, long *va, unsigned long *ot, int otlen, int id, int sclip, int hclip, int vclip, int nclipmode); extern void RotSMD_SV_F4(long *pa, long *va, unsigned long *ot, int otlen, int id, int sclip, int hclip, int vclip, int nclipmode); extern void RotSMD_SV_G4(long *pa, long *va, unsigned long *ot, int otlen, int id, int sclip, int hclip, int vclip, int nclipmode); extern void RotSMD_SV_FT4(long *pa, long *va, unsigned long *ot, int otlen, int id, int sclip, int hclip, int vclip, int nclipmode); extern void RotSMD_SV_GT4(long *pa, long *va, unsigned long *ot, int otlen, int id, int sclip, int hclip, int vclip, int nclipmode); extern void RotRMD_F3(long *pa, unsigned long *ot, int otlen, int id, int sclip, int hclip, int vclip, int nclipmode); extern void RotRMD_G3(long *pa, unsigned long *ot, int otlen, int id, int sclip, int hclip, int vclip, int nclipmode); extern void RotRMD_FT3(long *pa, unsigned long *ot, int otlen, int id, int sclip, int hclip, int vclip, int nclipmode); extern void RotRMD_GT3(long *pa, unsigned long *ot, int otlen, int id, int sclip, int hclip, int vclip, int nclipmode); extern void RotRMD_F4(long *pa, unsigned long *ot, int otlen, int id, int sclip, int hclip, int vclip, int nclipmode); extern void RotRMD_G4(long *pa, unsigned long *ot, int otlen, int id, int sclip, int hclip, int vclip, int nclipmode); extern void RotRMD_FT4(long *pa, unsigned long *ot, int otlen, int id, int sclip, int hclip, int vclip, int nclipmode); extern void RotRMD_GT4(long *pa, unsigned long *ot, int otlen, int id, int sclip, int hclip, int vclip, int nclipmode); extern void RotRMD_SV_F3(long *pa, long *va, unsigned long *ot, int otlen, int id, int sclip, int hclip, int vclip, int nclipmode); extern void RotRMD_SV_G3(long *pa, long *va, unsigned long *ot, int otlen, int id, int sclip, int hclip, int vclip, int nclipmode); extern void RotRMD_SV_FT3(long *pa, long *va, unsigned long *ot, int otlen, int id, int sclip, int hclip, int vclip, int nclipmode); extern void RotRMD_SV_GT3(long *pa, long *va, unsigned long *ot, int otlen, int id, int sclip, int hclip, int vclip, int nclipmode); extern void RotRMD_SV_F4(long *pa, long *va, unsigned long *ot, int otlen, int id, int sclip, int hclip, int vclip, int nclipmode); extern void RotRMD_SV_G4(long *pa, long *va, unsigned long *ot, int otlen, int id, int sclip, int hclip, int vclip, int nclipmode); extern void RotRMD_SV_FT4(long *pa, long *va, unsigned long *ot, int otlen, int id, int sclip, int hclip, int vclip, int nclipmode); extern void RotRMD_SV_GT4(long *pa, long *va, unsigned long *ot, int otlen, int id, int sclip, int hclip, int vclip, int nclipmode); extern long p2otz(long p, long projection); extern long otz2p(long otz, long projection); /* extern void RotMeshPrimS_F3(TMESH *msh,POLY_F3 *prim,u_long *ot, u_long otlen,long dpq,u_long backc); extern void RotMeshPrimS_G3(TMESH *msh,POLY_G3 *prim,u_long *ot, u_long otlen,long dpq,u_long backc); extern void RotMeshPrimS_FC3(TMESH *msh,POLY_F3 *prim,u_long *ot, u_long otlen,long dpq,u_long backc); extern void RotMeshPrimS_GC3(TMESH *msh,POLY_G3 *prim,u_long *ot, u_long otlen,long dpq,u_long backc); extern void RotMeshPrimS_FT3(TMESH *msh,POLY_FT3 *prim,u_long *ot, u_long otlen,long dpq,u_long backc); extern void RotMeshPrimS_GT3(TMESH *msh,POLY_GT3 *prim,u_long *ot, u_long otlen,long dpq,u_long backc); extern void RotMeshPrimS_FCT3(TMESH *msh,POLY_FT3 *prim,u_long *ot, u_long otlen,long dpq,u_long backc); extern void RotMeshPrimS_GCT3(TMESH *msh,POLY_GT3 *prim,u_long *ot, u_long otlen,long dpq,u_long backc); extern void RotMeshPrimS_T3(TMESH *msh,POLY_FT3 *prim,u_long *ot, u_long otlen,long dpq,u_long backc); extern void RotMeshPrimR_F3(TMESH *msh,POLY_F3 *prim,u_long *ot, u_long otlen,long dpq,u _long backc); extern void RotMeshPrimR_G3(TMESH *msh,POLY_G3 *prim,u_long *ot, u_long otlen,long dpq,u_long backc); extern void RotMeshPrimR_FC3(TMESH *msh,POLY_F3 *prim,u_long *ot, u_long otlen,long dpq,u_long backc); extern void RotMeshPrimR_GC3(TMESH *msh,POLY_G3 *prim,u_long *ot, u_long otlen,long dpq,u_long backc); extern void RotMeshPrimR_FT3(TMESH *msh,POLY_FT3 *prim,u_long *ot, u_long otlen,long dpq,u_long backc); extern void RotMeshPrimR_GT3(TMESH *msh,POLY_GT3 *prim,u_long *ot, u_long otlen,long dpq,u_long backc); extern void RotMeshPrimR_FCT3(TMESH *msh,POLY_FT3 *prim,u_long *ot, u_long otlen,long dpq,u_long backc); extern void RotMeshPrimR_GCT3(TMESH *msh,POLY_GT3 *prim,u_long *ot, u_long otlen,long dpq,u_long backc); extern void RotMeshPrimR_T3(TMESH *msh,POLY_FT3 *prim,u_long *ot, u_long otlen,long dpq,u_long backc); extern void RotMeshPrimQ_T(QMESH *msh,POLY_FT4 *prim,u_long *ot, u_long otlen,long dpq,long backc); */ #if defined(_LANGUAGE_C_PLUS_PLUS)||defined(__cplusplus)||defined(c_plusplus) } #endif #else #define INLINE_H <INLINE_C.H> #endif #include <sys/types.h> #include <LIBGTE.H> #include <LIBGPU.H> struct DB_STRUCT { int current_buffer; unsigned long* ot; char* polyptr; char* curpolybuf; char* polybuf_limit; int nOTSize; int nPBSize; unsigned long* order_table[2]; unsigned long* poly_buffer[2]; unsigned long* pickup_ot; unsigned long* pickup_order_table[2]; DRAWENV draw[2]; DISPENV disp[2]; }; struct room_info { short* data; // size=0, offset=0 short* door; // size=0, offset=4 struct FLOOR_INFO* floor; // size=8, offset=8 struct LIGHTINFO* light; // size=32, offset=12 struct MESH_INFO* mesh; // size=20, offset=16 long x; // size=0, offset=20 long y; // size=0, offset=24 long z; // size=0, offset=28 long minfloor; // size=0, offset=32 long maxceiling; // size=0, offset=36 short x_size; // size=0, offset=40 short y_size; // size=0, offset=42 CVECTOR ambient; // size=4, offset=44 short num_lights; // size=0, offset=48 short num_meshes; // size=0, offset=50 unsigned char ReverbType; // size=0, offset=52 unsigned char FlipNumber; // size=0, offset=53 char MeshEffect; // size=0, offset=54 char bound_active; // size=0, offset=55 short left; // size=0, offset=56 short right; // size=0, offset=58 short top; // size=0, offset=60 short bottom; // size=0, offset=62 short test_left; // size=0, offset=64 short test_right; short test_top; short test_bottom; short item_number; short fx_number; short flipped_room; unsigned short flags; }; struct object_info { short nmeshes; // size=0, offset=0 short mesh_index; // size=0, offset=2 long bone_index; // size=0, offset=4 short *frame_base; // size=0, offset=8 void(*initialise)(short item_number); // size=0, offset=12 void(*control)(short item_number); // size=0, offset=16 void(*floor)(struct ITEM_INFO* item, int x, int y, int z, int* height); // size=0, offset=20 void(*ceiling)(struct ITEM_INFO* item, int x, int y, int z, int* height); // size=0, offset=24 void(*draw_routine)(struct ITEM_INFO* item); // size=0, offset=28 void(*collision)(short item_num, struct ITEM_INFO* laraitem, struct COLL_INFO* coll); // size=0, offset=32 short object_mip; // size=0, offset=36 short anim_index; // size=0, offset=38 short hit_points; // size=0, offset=40 short pivot_length; // size=0, offset=42 short radius; // size=0, offset=44 short shadow_size; // size=0, offset=46 unsigned short bite_offset; // size=0, offset=48 unsigned short loaded : 1; // offset=50.0 unsigned short intelligent : 1; // offset=50.1 unsigned short non_lot : 1; // offset=50.2 unsigned short save_position : 1; // offset=50.3 unsigned short save_hitpoints : 1; // offset=50.4 unsigned short save_flags : 1; // offset=50.5 unsigned short save_anim : 1; // offset=50.6 unsigned short semi_transparent : 1; // offset=50.7 unsigned short water_creature : 1; // offset=51.0 unsigned short using_drawanimating_item : 1; // offset=51.1 unsigned short HitEffect : 2; // offset=51.2 unsigned short undead : 1; // offset=51.4 unsigned short save_mesh : 1; // offset=51.5 void(*draw_routine_extra)(struct ITEM_INFO* item); // size=0, offset=52 unsigned long explodable_meshbits; // size=0, offset=56 unsigned long padfuck; // size=0, offset=60 }; struct TEXTURE { unsigned char u0; unsigned char v0; unsigned short clut; unsigned char u1; unsigned char v1; unsigned short tpage; unsigned char u2; unsigned char v2; unsigned char id[2]; unsigned char u3; unsigned char v3; unsigned short wclut; }; struct static_info { short mesh_number; short flags; short x_minp; short x_maxp; short y_minp; short y_maxp; short z_minp; short z_maxp; short x_minc; short x_maxc; short y_minc; short y_maxc; short z_minc; short z_maxc; }; struct PSXTEXTI { unsigned char u0; unsigned char v0; unsigned short clut; unsigned char u1; unsigned char v1; unsigned short tpage; unsigned char u2; unsigned char v2; unsigned char codeGT4; unsigned char codeGT3; unsigned char u3; unsigned char v3; unsigned short pad3; }; struct VECTOR3D { long x; long y; long z; }; struct PSXTEXTSTRUCT { unsigned long u0v0clut; unsigned long u1v1tpage; unsigned long u2v2pad; unsigned long u3v3pad; }; struct PSXSPRITESTRUCT { short x1; short y1; short x2; short y2; unsigned short clut; unsigned short tpage; unsigned char u1; unsigned char v1; unsigned char u2; unsigned char v2; }; struct MMTEXTURE { struct TEXTURE t[3]; }; struct TSV { unsigned long xy; unsigned long rgz; }; typedef unsigned short PadData; typedef struct { unsigned short buttons; char xOffset; char yOffset; } MouseData; typedef struct { unsigned short digitalButtons; char centralTwist; char buttonI; char buttonII; char topLeft; } NegconData; typedef struct { unsigned char transStatus; unsigned char dataFormat; union { PadData pad; NegconData negcon; } data; } TapCtrllerData; typedef struct { TapCtrllerData ctrllers[4]; } MultiTapData; typedef struct { unsigned char transStatus; unsigned char dataFormat; union { PadData pad; MouseData mouse; NegconData negcon; MultiTapData tap; } data; } ControllerPacket; struct pad_configs { unsigned long pad_L2; unsigned long pad_R2; unsigned long pad_L1; unsigned long pad_R1; unsigned long pad_triangle; unsigned long pad_square; unsigned long pad_circle; unsigned long pad_cross; }; struct GouraudBarColourSet { unsigned char abLeftRed[5]; unsigned char abLeftGreen[5]; unsigned char abLeftBlue[5]; unsigned char abRightRed[5]; unsigned char abRightGreen[5]; unsigned char abRightBlue[5]; }; struct STASHEDOBJ { short clip; short numnodestodraw; struct ITEM_INFO* item; short* frmptr0; }; struct STASHEDDAT { short* mesh; char matrix[32]; }; struct WATERTAB { char shimmer; char choppy; unsigned char random; unsigned char abs; }; struct VIBRATION { short Rate; short Len; short Lev; short Acc; short Dec; short Sus; short Flag; short Vib; }; struct REQUESTER { unsigned short TitleTxt; unsigned short TitleCol : 5; unsigned short nOptions : 3; unsigned short CursorPos : 3; unsigned short OptionCol : 5; unsigned long JustifyL : 5; unsigned long JustifyR : 5; unsigned long Arrows : 5; unsigned long Ignore : 5; unsigned short OptionTxt[5]; }; struct SCALE { short xgrid; char scalefactor; char nummarks; }; struct COCKSUCK { unsigned char r; unsigned char g; unsigned char b; unsigned char pad; short finalcnt; short profile_xcnt; }; struct PACKEDNAME { char Name[12]; unsigned char Days; unsigned char Hours; unsigned char Min; unsigned char Sec; unsigned short Slot; unsigned char Level; unsigned char Pad; }; struct ILIGHT { short x; short y; short z; short pad1; unsigned char r; unsigned char g; unsigned char b; unsigned char pad; }; struct ITEM_LIGHT { struct ILIGHT Light[4]; }; struct ITEM_INFO { long floor; // size=0, offset=0 unsigned long touch_bits; // size=0, offset=4 unsigned long mesh_bits; // size=0, offset=8 short object_number; // size=0, offset=12 short current_anim_state; // size=0, offset=14 short goal_anim_state; // size=0, offset=16 short required_anim_state; // size=0, offset=18 short anim_number; // size=0, offset=20 short frame_number; // size=0, offset=22 short room_number; // size=0, offset=24 short next_item; // size=0, offset=26 short next_active; // size=0, offset=28 short speed; // size=0, offset=30 short fallspeed; // size=0, offset=32 short hit_points; // size=0, offset=34 unsigned short box_number; // size=0, offset=36 short timer; // size=0, offset=38 short flags; // size=0, offset=40 short shade; // size=0, offset=42 short trigger_flags; // size=0, offset=44 short carried_item; // size=0, offset=46 short after_death; // size=0, offset=48 unsigned short fired_weapon; // size=0, offset=50 short item_flags[4]; // size=8, offset=52 void* data; // size=0, offset=60 struct PHD_3DPOS pos; // size=20, offset=64 struct ITEM_LIGHT il; // size=48, offset=84 unsigned long active : 1; // offset=132.0 unsigned long status : 2; // offset=132.1 unsigned long gravity_status : 1; // offset=132.3 unsigned long hit_status : 1; // offset=132.4 unsigned long collidable : 1; // offset=132.5 unsigned long looked_at : 1; // offset=132.6 unsigned long dynamic_light : 1; // offset=132.7 unsigned long poisoned : 1; // offset=133.0 unsigned long ai_bits : 5; // offset=133.1 unsigned long really_active : 1; // offset=133.6 unsigned long InDrawRoom : 1; // offset=133.7 unsigned long meshswap_meshbits; // size=0, offset=136 short draw_room; // size=0, offset=140 short TOSSPAD; // size=0, offset=142 }; struct creature_info { short joint_rotation[4]; // size=8, offset=0 short maximum_turn; // size=0, offset=8 short flags; // size=0, offset=10 unsigned short alerted : 1; // offset=12.0 unsigned short head_left : 1; // offset=12.1 unsigned short head_right : 1; // offset=12.2 unsigned short reached_goal : 1; // offset=12.3 unsigned short hurt_by_lara : 1; // offset=12.4 unsigned short patrol2 : 1; // offset=12.5 unsigned short jump_ahead : 1; // offset=12.6 unsigned short monkey_ahead : 1; // offset=12.7 enum mood_type mood; // size=4, offset=16 struct ITEM_INFO* enemy; // size=144, offset=20 struct ITEM_INFO ai_target; // size=144, offset=24 short pad; // size=0, offset=168 short item_num; // size=0, offset=170 struct PHD_VECTOR target; // size=12, offset=172 struct lot_info LOT; // size=44, offset=184 }; struct DRIP_STRUCT { long x; // size=0, offset=0 long y; // size=0, offset=4 long z; // size=0, offset=8 unsigned char On; // size=0, offset=12 unsigned char R; // size=0, offset=13 unsigned char G; // size=0, offset=14 unsigned char B; // size=0, offset=15 short Yvel; // size=0, offset=16 unsigned char Gravity; // size=0, offset=18 unsigned char Life; // size=0, offset=19 short RoomNumber; // size=0, offset=20 unsigned char Outside; // size=0, offset=22 unsigned char Pad; // size=0, offset=23 }; #endif
// Copyright (C) 2017 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and University of // of Connecticut School of Medicine. // All rights reserved. // Copyright (C) 2010 - 2016 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and The University // of Manchester. // All rights reserved. #ifdef SWIGPERL #undef NORMAL #endif // SWIGPERL #include "CopasiDataModel/CDataModel.h" #include "utilities/CCopasiMethod.h" #include "utilities/CCopasiProblem.h" #include "utilities/CCopasiTask.h" #include "function/CEvaluationTree.h" #include "function/CFunction.h" #include "function/CFunctionDB.h" #include "function/CFunctionParameter.h" #include "function/CFunctionParameters.h" #include "MIRIAM/CBiologicalDescription.h" #include "MIRIAM/CReference.h" #include "MIRIAM/CModified.h" #include "MIRIAM/CModelMIRIAMInfo.h" #include "model/CModelValue.h" #include "model/CMetab.h" #include "model/CModel.h" #include "model/CChemEq.h" #include "model/CChemEqElement.h" #include "model/CReaction.h" #include "model/CMoiety.h" #include "model/CEvent.h" #include "core/CDataString.h" #include "report/CReportDefinition.h" #include "core/CDataArray.h" #include "copasi/../core/CMatrix.h" #include "steadystate/CSteadyStateTask.h" #include "steadystate/CSteadyStateProblem.h" #include "steadystate/CSteadyStateMethod.h" #include "steadystate/CNewtonMethod.h" #include "trajectory/CTrajectoryTask.h" #include "trajectory/CTrajectoryProblem.h" #include "trajectory/CTrajectoryMethod.h" #include "scan/CScanTask.h" #include "scan/CScanProblem.h" #include "scan/CScanMethod.h" #include "lyap/CLyapTask.h" #include "lyap/CLyapProblem.h" #include "lyap/CLyapMethod.h" #include "optimization/COptItem.h" #include "optimization/COptTask.h" #include "optimization/COptProblem.h" #include "optimization/COptMethod.h" #include "parameterFitting/CExperiment.h" #include "parameterFitting/CExperimentFileInfo.h" #include "parameterFitting/CExperimentObjectMap.h" #include "parameterFitting/CExperimentSet.h" #include "parameterFitting/CFitItem.h" #include "optimization/COptMethod.h" #include "parameterFitting/CFitProblem.h" #include "parameterFitting/CFitTask.h" // since COPASI undefines TRUE from swig, we have to redefine it here // if needed #ifndef TRUE #define TRUE #endif //#include <iostream> typedef CDataVector<CEvent> EventVector; typedef CDataVectorN<CEvent> EventVectorN; typedef CDataVector<CEventAssignment> EventAssignmentVector; typedef CDataVectorN<CEventAssignment> EventAssignmentVectorN; typedef CDataVector<CCopasiTask> TaskVector; typedef CDataVectorN<CCopasiTask> TaskVectorN; typedef CDataVectorN<CModelValue> ModelValueVectorN; typedef CDataVector<CMoiety> MoietyVector; typedef CDataVector<CMetab> MetabVector; typedef CDataVectorNS<CMetab> MetabVectorNS; typedef CDataVectorNS<CCompartment> CompartmentVectorNS; typedef CDataVectorNS<CReaction> ReactionVectorNS; typedef std::vector<CRegisteredCommonName> ReportItemVector; typedef std::vector<CCopasiParameter*> ParameterVector; typedef CDataVectorN<CEvaluationTree> CEvaluationTreeVectorN; typedef CDataVectorN<CDataModel> CDataModelVectorN; typedef std::vector<CFunction> CFunctionStdVector; typedef CDataVector<CChemEqElement> CChemEqElementVector; typedef CDataVector<CModelValue> ModelValueVector; typedef CDataVectorN<CReportDefinition> CReportDefinitionVectorN; typedef CDataVectorN<CMetab> MetabVectorN; typedef CDataVector<CCompartment> CompartmentVector; typedef CDataVectorN<CCompartment> CompartmentVectorN; typedef CDataVectorN<CReaction> ReactionVectorN; typedef CDataVector<CReaction> ReactionVector; typedef CDataVector<CEvaluationTree> CEvaluationTreeVector; typedef CMatrixInterface<CMatrix<C_FLOAT64> > AnnotatedFloatMatrix; /** * @return the most specific Swig type for the given CExperimentSet object. struct swig_type_info* GetDowncastSwigTypeForCExperimentSet (CExperimentSet* experimentSet) { if (array == NULL) return SWIGTYPE_p_CExperimentSet; struct swig_type_info* pInfo = SWIGTYPE_p_CExperimentSet; if (dynamic_cast<CCrossValidationSet*>(experimentSet)) { pInfo = SWIGTYPE_p_CCrossValidationSet; } return pInfo; } */ /** * @return the most specific Swig type for the given CFitItem object. */ struct swig_type_info* GetDowncastSwigTypeForCFitItem(CFitItem* fitItem) { if (fitItem == NULL) return SWIGTYPE_p_CFitItem; struct swig_type_info* pInfo = SWIGTYPE_p_CFitItem; if (dynamic_cast<CFitConstraint*>(fitItem)) { pInfo = SWIGTYPE_p_CFitConstraint; } return pInfo; } /** * @return the most specific Swig type for the given COptItem object. */ struct swig_type_info* GetDowncastSwigTypeForCOptItem(COptItem* optItem) { if (optItem == NULL) return SWIGTYPE_p_COptItem; struct swig_type_info* pInfo = SWIGTYPE_p_COptItem; if (dynamic_cast<CFitItem*>(optItem)) { pInfo = GetDowncastSwigTypeForCFitItem(static_cast<CFitItem*>(optItem)); } return pInfo; } /** * @return the most specific Swig type for the given COptProblem object. */ struct swig_type_info* GetDowncastSwigTypeForCOptProblem(COptProblem* optProblem) { if (optProblem == NULL) return SWIGTYPE_p_COptProblem; struct swig_type_info* pInfo = SWIGTYPE_p_COptProblem; if (dynamic_cast<CFitProblem*>(optProblem)) { pInfo = SWIGTYPE_p_CFitProblem; } return pInfo; } /** * @return the most specific Swig type for the given COptMethod object. */ struct swig_type_info* GetDowncastSwigTypeForCOptMethod(COptMethod* optMethod) { return SWIGTYPE_p_COptMethod; } /** * @return the most specific Swig type for the given COptTask object. */ struct swig_type_info* GetDowncastSwigTypeForCOptTask(COptTask* optTask) { if (optTask == NULL) return SWIGTYPE_p_COptTask; struct swig_type_info* pInfo = SWIGTYPE_p_COptTask; if (dynamic_cast<CFitTask*>(optTask)) { pInfo = SWIGTYPE_p_CFitTask; } return pInfo; } /** * @return the most specific Swig type for the given CArrayInterface object. */ struct swig_type_info* GetDowncastSwigTypeForCArrayInterface(CArrayInterface* array) { if (array == NULL) return SWIGTYPE_p_CArrayInterface; struct swig_type_info* pInfo = SWIGTYPE_p_CArrayInterface; if (dynamic_cast<CArray*>(array)) { pInfo = SWIGTYPE_p_CArray; } /* The following code no longer compiles out of some reason else if (dynamic_cast<CCopasiMatrixInterface<CMatrix<C_FLOAT64> >*>(array)) { pInfo = SWIGTYPE_p_CCopasiMatrixInterfaceTCMatrixTdouble_t_t; } */ return pInfo; } /** * @return the most specific Swig type for the given Task object. */ struct swig_type_info* GetDowncastSwigTypeForTask(CCopasiTask* task) { if (task == NULL) return SWIGTYPE_p_CCopasiTask; struct swig_type_info* pInfo = SWIGTYPE_p_CCopasiTask; if (dynamic_cast<COptTask*>(task)) { pInfo = GetDowncastSwigTypeForCOptTask(static_cast<COptTask*>(task)); } else if (dynamic_cast<CTrajectoryTask*>(task)) { pInfo = SWIGTYPE_p_CTrajectoryTask; } else if (dynamic_cast<CScanTask*>(task)) { pInfo = SWIGTYPE_p_CScanTask; } else if (dynamic_cast<CSteadyStateTask*>(task)) { pInfo = SWIGTYPE_p_CSteadyStateTask; } else if (dynamic_cast<CLyapTask*>(task)) { pInfo = SWIGTYPE_p_CLyapTask; } return pInfo; } /** * @return the most specific Swig type for the given Method object. */ struct swig_type_info* GetDowncastSwigTypeForMethod(CCopasiMethod* method) { if (method == NULL) return SWIGTYPE_p_CCopasiMethod; struct swig_type_info* pInfo = SWIGTYPE_p_CCopasiMethod; if (dynamic_cast<COptMethod*>(method)) { pInfo = GetDowncastSwigTypeForCOptMethod(static_cast<COptMethod*>(method)); } else if (dynamic_cast<CTrajectoryMethod*>(method)) { pInfo = SWIGTYPE_p_CTrajectoryMethod; } else if (dynamic_cast<CScanMethod*>(method)) { pInfo = SWIGTYPE_p_CScanMethod; } else if (dynamic_cast<CSteadyStateMethod*>(method)) { pInfo = SWIGTYPE_p_CSteadyStateMethod; } else if (dynamic_cast<CLyapMethod*>(method)) { pInfo = SWIGTYPE_p_CLyapMethod; } return pInfo; } /** * @return the most specific Swig type for the given Problem object. */ struct swig_type_info* GetDowncastSwigTypeForProblem(CCopasiProblem* problem) { if (problem == NULL) return SWIGTYPE_p_CCopasiProblem; struct swig_type_info* pInfo = SWIGTYPE_p_CCopasiProblem; if (dynamic_cast<COptProblem*>(problem)) { pInfo = GetDowncastSwigTypeForCOptProblem(static_cast<COptProblem*>(problem)); } else if (dynamic_cast<CTrajectoryProblem*>(problem)) { pInfo = SWIGTYPE_p_CTrajectoryProblem; } else if (dynamic_cast<CScanProblem*>(problem)) { pInfo = SWIGTYPE_p_CScanProblem; } else if (dynamic_cast<CSteadyStateProblem*>(problem)) { pInfo = SWIGTYPE_p_CSteadyStateProblem; } else if (dynamic_cast<CLyapProblem*>(problem)) { pInfo = SWIGTYPE_p_CLyapProblem; } return pInfo; } /** * @return the most specific Swig type for the given CEvaluationTree object. */ struct swig_type_info* GetDowncastSwigTypeForCEvaluationTree(CEvaluationTree* tree) { if (tree == NULL) return SWIGTYPE_p_CEvaluationTree; struct swig_type_info* pInfo = SWIGTYPE_p_CEvaluationTree; if (dynamic_cast<CFunction*>(tree)) { pInfo = SWIGTYPE_p_CFunction; } return pInfo; } struct swig_type_info* GetDowncastSwigTypeForCCopasiParameterGroup(CCopasiParameterGroup* group) { if (group == NULL) return SWIGTYPE_p_CCopasiParameterGroup; struct swig_type_info* pInfo = SWIGTYPE_p_CCopasiParameterGroup; if (dynamic_cast<CCopasiMethod*>(group)) { pInfo = GetDowncastSwigTypeForMethod(static_cast<CCopasiMethod*>(group)); } else if (dynamic_cast<CCopasiProblem*>(group)) { pInfo = GetDowncastSwigTypeForProblem(static_cast<CCopasiProblem*>(group)); } else if (dynamic_cast<CExperiment*>(group)) { pInfo = SWIGTYPE_p_CExperiment; } else if (dynamic_cast<CExperimentObjectMap*>(group)) { pInfo = SWIGTYPE_p_CExperimentObjectMap; } else if (dynamic_cast<CExperimentSet*>(group)) { pInfo = SWIGTYPE_p_CExperimentSet; //GetDowncastSwigTypeForCExperimentSet(static_cast<CExperimentSet*>(group)); } else if (dynamic_cast<COptItem*>(group)) { pInfo = GetDowncastSwigTypeForCOptItem(static_cast<COptItem*>(group)); } return pInfo; } struct swig_type_info* GetDowncastSwigTypeForCCopasiParameter(CCopasiParameter* parameter) { if (parameter == NULL) return SWIGTYPE_p_CCopasiParameter; struct swig_type_info* pInfo = SWIGTYPE_p_CCopasiParameter; if (dynamic_cast<CCopasiParameterGroup*>(parameter)) { pInfo = GetDowncastSwigTypeForCCopasiParameterGroup(static_cast<CCopasiParameterGroup*>(parameter)); } return pInfo; } struct swig_type_info* GetDowncastSwigTypeForCModelEntity(CModelEntity* entity) { if (entity == NULL) return SWIGTYPE_p_CModelEntity; struct swig_type_info* pInfo = SWIGTYPE_p_CModelEntity; if (dynamic_cast<CCompartment*>(entity)) { pInfo = SWIGTYPE_p_CCompartment; } else if (dynamic_cast<CMetab*>(entity)) { pInfo = SWIGTYPE_p_CMetab; } else if (dynamic_cast<CModelValue*>(entity)) { pInfo = SWIGTYPE_p_CModelValue; } else if (dynamic_cast<CModel*>(entity)) { pInfo = SWIGTYPE_p_CModel; } return pInfo; } struct swig_type_info* GetDowncastSwigTypeForCDataContainer(CDataContainer* container) { if (container == NULL) return SWIGTYPE_p_CDataContainer; struct swig_type_info* pInfo = SWIGTYPE_p_CDataContainer; if (dynamic_cast<CRootContainer*>(container)) { pInfo = SWIGTYPE_p_CRootContainer; } else if (dynamic_cast<CDataModel*>(container)) { pInfo = SWIGTYPE_p_CDataModel; } else if (dynamic_cast<CModelEntity*>(container)) { pInfo = GetDowncastSwigTypeForCModelEntity(static_cast<CModelEntity*>(container)); } else if (dynamic_cast<CCopasiParameter*>(container)) { pInfo = GetDowncastSwigTypeForCCopasiParameter(static_cast<CCopasiParameter*>(container)); } else if (dynamic_cast<CEvent*>(container)) { pInfo = SWIGTYPE_p_CEvent; } else if (dynamic_cast<CEventAssignment*>(container)) { pInfo = SWIGTYPE_p_CEventAssignment; } else if (dynamic_cast<CReference*>(container)) { pInfo = SWIGTYPE_p_CReference; } else if (dynamic_cast<CBiologicalDescription*>(container)) { pInfo = SWIGTYPE_p_CBiologicalDescription; } else if (dynamic_cast<CModification*>(container)) { pInfo = SWIGTYPE_p_CModification; } else if (dynamic_cast<CCreator*>(container)) { pInfo = SWIGTYPE_p_CCreator; } else if (dynamic_cast<CMIRIAMInfo*>(container)) { pInfo = SWIGTYPE_p_CMIRIAMInfo; } else if (container->isNameVector()) { if (dynamic_cast<CDataModelVectorN*>(container)) { pInfo = SWIGTYPE_p_CDataVectorT_CDataModel_t; } else if (dynamic_cast<TaskVectorN*>(container)) { pInfo = SWIGTYPE_p_CDataVectorNT_CCopasiTask_t; } else if (dynamic_cast<ModelValueVectorN*>(container)) { pInfo = SWIGTYPE_p_CDataVectorNT_CModelValue_t; } else if (dynamic_cast<MetabVectorNS*>(container)) { pInfo = SWIGTYPE_p_CDataVectorNST_CMetab_t; } else if (dynamic_cast<CompartmentVectorNS*>(container)) { pInfo = SWIGTYPE_p_CDataVectorNST_CCompartment_t; } else if (dynamic_cast<ReactionVectorNS*>(container)) { pInfo = SWIGTYPE_p_CDataVectorNST_CReaction_t; } else if (dynamic_cast<CEvaluationTreeVectorN*>(container)) { pInfo = SWIGTYPE_p_CDataVectorNT_CEvaluationTree_t; } else if (dynamic_cast<EventVectorN*>(container)) { pInfo = SWIGTYPE_p_CDataVectorNT_CEvent_t; } else if (dynamic_cast<EventAssignmentVectorN*>(container)) { pInfo = SWIGTYPE_p_CDataVectorNT_CEventAssignment_t; } } else if (container->isVector()) { if (dynamic_cast<MoietyVector*>(container)) { pInfo = SWIGTYPE_p_CDataVectorT_CMoiety_t; } else if (dynamic_cast<MetabVector*>(container)) { pInfo = SWIGTYPE_p_CDataVectorT_CMetab_t; } else if (dynamic_cast<ReportItemVector*>(container)) { pInfo = SWIGTYPE_p_std__vectorT_CRegisteredCommonName_t; } else if (dynamic_cast<ParameterVector*>(container)) { pInfo = SWIGTYPE_p_std__vectorT_CCopasiParameter_p_t; } else if (dynamic_cast<CFunctionStdVector*>(container)) { pInfo = SWIGTYPE_p_std__vectorT_CFunction_p_t; } else if (dynamic_cast<CChemEqElementVector*>(container)) { pInfo = SWIGTYPE_p_CDataVectorT_CChemEqElement_t; } } else if (dynamic_cast<CEvaluationTree*>(container)) { pInfo = GetDowncastSwigTypeForCEvaluationTree(static_cast<CEvaluationTree*>(container)); } else if (dynamic_cast<CCopasiTask*>(container)) { pInfo = GetDowncastSwigTypeForTask(static_cast<CCopasiTask*>(container)); } else if (dynamic_cast<CChemEq*>(container)) { pInfo = SWIGTYPE_p_CChemEq; } else if (dynamic_cast<CChemEqElement*>(container)) { pInfo = SWIGTYPE_p_CChemEqElement; } else if (dynamic_cast<CFunctionDB*>(container)) { pInfo = SWIGTYPE_p_CFunctionDB; } else if (dynamic_cast<CFunctionParameter*>(container)) { pInfo = SWIGTYPE_p_CFunctionParameter; } else if (dynamic_cast<CFunctionParameters*>(container)) { pInfo = SWIGTYPE_p_CFunctionParameters; } else if (dynamic_cast<CMoiety*>(container)) { pInfo = SWIGTYPE_p_CMoiety; } else if (dynamic_cast<CReaction*>(container)) { pInfo = SWIGTYPE_p_CReaction; } else if (dynamic_cast<CDataArray*>(container)) { pInfo = SWIGTYPE_p_CDataArray; } else if (dynamic_cast<CFittingPoint*>(container)) { pInfo = SWIGTYPE_p_CFittingPoint; } return pInfo; } struct swig_type_info* GetDowncastSwigTypeForCDataObject(CDataObject* object) { if (object == NULL) return SWIGTYPE_p_CDataObject; struct swig_type_info* pInfo = SWIGTYPE_p_CDataObject; if (dynamic_cast<CDataContainer*>(object)) { pInfo = GetDowncastSwigTypeForCDataContainer(static_cast<CDataContainer*>(object)); } else if (dynamic_cast<CReportDefinition*>(object)) { pInfo = SWIGTYPE_p_CReportDefinition; } else if (dynamic_cast<CDataString*>(object)) { if (dynamic_cast<CCopasiReportSeparator*>(object)) { pInfo = SWIGTYPE_p_CCopasiReportSeparator; } else { pInfo = SWIGTYPE_p_CDataString; } } return pInfo; } - fix include path // Copyright (C) 2017 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and University of // of Connecticut School of Medicine. // All rights reserved. // Copyright (C) 2010 - 2016 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and The University // of Manchester. // All rights reserved. #ifdef SWIGPERL #undef NORMAL #endif // SWIGPERL #include "CopasiDataModel/CDataModel.h" #include "utilities/CCopasiMethod.h" #include "utilities/CCopasiProblem.h" #include "utilities/CCopasiTask.h" #include "function/CEvaluationTree.h" #include "function/CFunction.h" #include "function/CFunctionDB.h" #include "function/CFunctionParameter.h" #include "function/CFunctionParameters.h" #include "MIRIAM/CBiologicalDescription.h" #include "MIRIAM/CReference.h" #include "MIRIAM/CModified.h" #include "MIRIAM/CModelMIRIAMInfo.h" #include "model/CModelValue.h" #include "model/CMetab.h" #include "model/CModel.h" #include "model/CChemEq.h" #include "model/CChemEqElement.h" #include "model/CReaction.h" #include "model/CMoiety.h" #include "model/CEvent.h" #include "core/CDataString.h" #include "report/CReportDefinition.h" #include "core/CDataArray.h" #include "copasi/core/CMatrix.h" #include "steadystate/CSteadyStateTask.h" #include "steadystate/CSteadyStateProblem.h" #include "steadystate/CSteadyStateMethod.h" #include "steadystate/CNewtonMethod.h" #include "trajectory/CTrajectoryTask.h" #include "trajectory/CTrajectoryProblem.h" #include "trajectory/CTrajectoryMethod.h" #include "scan/CScanTask.h" #include "scan/CScanProblem.h" #include "scan/CScanMethod.h" #include "lyap/CLyapTask.h" #include "lyap/CLyapProblem.h" #include "lyap/CLyapMethod.h" #include "optimization/COptItem.h" #include "optimization/COptTask.h" #include "optimization/COptProblem.h" #include "optimization/COptMethod.h" #include "parameterFitting/CExperiment.h" #include "parameterFitting/CExperimentFileInfo.h" #include "parameterFitting/CExperimentObjectMap.h" #include "parameterFitting/CExperimentSet.h" #include "parameterFitting/CFitItem.h" #include "optimization/COptMethod.h" #include "parameterFitting/CFitProblem.h" #include "parameterFitting/CFitTask.h" // since COPASI undefines TRUE from swig, we have to redefine it here // if needed #ifndef TRUE #define TRUE #endif //#include <iostream> typedef CDataVector<CEvent> EventVector; typedef CDataVectorN<CEvent> EventVectorN; typedef CDataVector<CEventAssignment> EventAssignmentVector; typedef CDataVectorN<CEventAssignment> EventAssignmentVectorN; typedef CDataVector<CCopasiTask> TaskVector; typedef CDataVectorN<CCopasiTask> TaskVectorN; typedef CDataVectorN<CModelValue> ModelValueVectorN; typedef CDataVector<CMoiety> MoietyVector; typedef CDataVector<CMetab> MetabVector; typedef CDataVectorNS<CMetab> MetabVectorNS; typedef CDataVectorNS<CCompartment> CompartmentVectorNS; typedef CDataVectorNS<CReaction> ReactionVectorNS; typedef std::vector<CRegisteredCommonName> ReportItemVector; typedef std::vector<CCopasiParameter*> ParameterVector; typedef CDataVectorN<CEvaluationTree> CEvaluationTreeVectorN; typedef CDataVectorN<CDataModel> CDataModelVectorN; typedef std::vector<CFunction> CFunctionStdVector; typedef CDataVector<CChemEqElement> CChemEqElementVector; typedef CDataVector<CModelValue> ModelValueVector; typedef CDataVectorN<CReportDefinition> CReportDefinitionVectorN; typedef CDataVectorN<CMetab> MetabVectorN; typedef CDataVector<CCompartment> CompartmentVector; typedef CDataVectorN<CCompartment> CompartmentVectorN; typedef CDataVectorN<CReaction> ReactionVectorN; typedef CDataVector<CReaction> ReactionVector; typedef CDataVector<CEvaluationTree> CEvaluationTreeVector; typedef CMatrixInterface<CMatrix<C_FLOAT64> > AnnotatedFloatMatrix; /** * @return the most specific Swig type for the given CExperimentSet object. struct swig_type_info* GetDowncastSwigTypeForCExperimentSet (CExperimentSet* experimentSet) { if (array == NULL) return SWIGTYPE_p_CExperimentSet; struct swig_type_info* pInfo = SWIGTYPE_p_CExperimentSet; if (dynamic_cast<CCrossValidationSet*>(experimentSet)) { pInfo = SWIGTYPE_p_CCrossValidationSet; } return pInfo; } */ /** * @return the most specific Swig type for the given CFitItem object. */ struct swig_type_info* GetDowncastSwigTypeForCFitItem(CFitItem* fitItem) { if (fitItem == NULL) return SWIGTYPE_p_CFitItem; struct swig_type_info* pInfo = SWIGTYPE_p_CFitItem; if (dynamic_cast<CFitConstraint*>(fitItem)) { pInfo = SWIGTYPE_p_CFitConstraint; } return pInfo; } /** * @return the most specific Swig type for the given COptItem object. */ struct swig_type_info* GetDowncastSwigTypeForCOptItem(COptItem* optItem) { if (optItem == NULL) return SWIGTYPE_p_COptItem; struct swig_type_info* pInfo = SWIGTYPE_p_COptItem; if (dynamic_cast<CFitItem*>(optItem)) { pInfo = GetDowncastSwigTypeForCFitItem(static_cast<CFitItem*>(optItem)); } return pInfo; } /** * @return the most specific Swig type for the given COptProblem object. */ struct swig_type_info* GetDowncastSwigTypeForCOptProblem(COptProblem* optProblem) { if (optProblem == NULL) return SWIGTYPE_p_COptProblem; struct swig_type_info* pInfo = SWIGTYPE_p_COptProblem; if (dynamic_cast<CFitProblem*>(optProblem)) { pInfo = SWIGTYPE_p_CFitProblem; } return pInfo; } /** * @return the most specific Swig type for the given COptMethod object. */ struct swig_type_info* GetDowncastSwigTypeForCOptMethod(COptMethod* optMethod) { return SWIGTYPE_p_COptMethod; } /** * @return the most specific Swig type for the given COptTask object. */ struct swig_type_info* GetDowncastSwigTypeForCOptTask(COptTask* optTask) { if (optTask == NULL) return SWIGTYPE_p_COptTask; struct swig_type_info* pInfo = SWIGTYPE_p_COptTask; if (dynamic_cast<CFitTask*>(optTask)) { pInfo = SWIGTYPE_p_CFitTask; } return pInfo; } /** * @return the most specific Swig type for the given CArrayInterface object. */ struct swig_type_info* GetDowncastSwigTypeForCArrayInterface(CArrayInterface* array) { if (array == NULL) return SWIGTYPE_p_CArrayInterface; struct swig_type_info* pInfo = SWIGTYPE_p_CArrayInterface; if (dynamic_cast<CArray*>(array)) { pInfo = SWIGTYPE_p_CArray; } /* The following code no longer compiles out of some reason else if (dynamic_cast<CCopasiMatrixInterface<CMatrix<C_FLOAT64> >*>(array)) { pInfo = SWIGTYPE_p_CCopasiMatrixInterfaceTCMatrixTdouble_t_t; } */ return pInfo; } /** * @return the most specific Swig type for the given Task object. */ struct swig_type_info* GetDowncastSwigTypeForTask(CCopasiTask* task) { if (task == NULL) return SWIGTYPE_p_CCopasiTask; struct swig_type_info* pInfo = SWIGTYPE_p_CCopasiTask; if (dynamic_cast<COptTask*>(task)) { pInfo = GetDowncastSwigTypeForCOptTask(static_cast<COptTask*>(task)); } else if (dynamic_cast<CTrajectoryTask*>(task)) { pInfo = SWIGTYPE_p_CTrajectoryTask; } else if (dynamic_cast<CScanTask*>(task)) { pInfo = SWIGTYPE_p_CScanTask; } else if (dynamic_cast<CSteadyStateTask*>(task)) { pInfo = SWIGTYPE_p_CSteadyStateTask; } else if (dynamic_cast<CLyapTask*>(task)) { pInfo = SWIGTYPE_p_CLyapTask; } return pInfo; } /** * @return the most specific Swig type for the given Method object. */ struct swig_type_info* GetDowncastSwigTypeForMethod(CCopasiMethod* method) { if (method == NULL) return SWIGTYPE_p_CCopasiMethod; struct swig_type_info* pInfo = SWIGTYPE_p_CCopasiMethod; if (dynamic_cast<COptMethod*>(method)) { pInfo = GetDowncastSwigTypeForCOptMethod(static_cast<COptMethod*>(method)); } else if (dynamic_cast<CTrajectoryMethod*>(method)) { pInfo = SWIGTYPE_p_CTrajectoryMethod; } else if (dynamic_cast<CScanMethod*>(method)) { pInfo = SWIGTYPE_p_CScanMethod; } else if (dynamic_cast<CSteadyStateMethod*>(method)) { pInfo = SWIGTYPE_p_CSteadyStateMethod; } else if (dynamic_cast<CLyapMethod*>(method)) { pInfo = SWIGTYPE_p_CLyapMethod; } return pInfo; } /** * @return the most specific Swig type for the given Problem object. */ struct swig_type_info* GetDowncastSwigTypeForProblem(CCopasiProblem* problem) { if (problem == NULL) return SWIGTYPE_p_CCopasiProblem; struct swig_type_info* pInfo = SWIGTYPE_p_CCopasiProblem; if (dynamic_cast<COptProblem*>(problem)) { pInfo = GetDowncastSwigTypeForCOptProblem(static_cast<COptProblem*>(problem)); } else if (dynamic_cast<CTrajectoryProblem*>(problem)) { pInfo = SWIGTYPE_p_CTrajectoryProblem; } else if (dynamic_cast<CScanProblem*>(problem)) { pInfo = SWIGTYPE_p_CScanProblem; } else if (dynamic_cast<CSteadyStateProblem*>(problem)) { pInfo = SWIGTYPE_p_CSteadyStateProblem; } else if (dynamic_cast<CLyapProblem*>(problem)) { pInfo = SWIGTYPE_p_CLyapProblem; } return pInfo; } /** * @return the most specific Swig type for the given CEvaluationTree object. */ struct swig_type_info* GetDowncastSwigTypeForCEvaluationTree(CEvaluationTree* tree) { if (tree == NULL) return SWIGTYPE_p_CEvaluationTree; struct swig_type_info* pInfo = SWIGTYPE_p_CEvaluationTree; if (dynamic_cast<CFunction*>(tree)) { pInfo = SWIGTYPE_p_CFunction; } return pInfo; } struct swig_type_info* GetDowncastSwigTypeForCCopasiParameterGroup(CCopasiParameterGroup* group) { if (group == NULL) return SWIGTYPE_p_CCopasiParameterGroup; struct swig_type_info* pInfo = SWIGTYPE_p_CCopasiParameterGroup; if (dynamic_cast<CCopasiMethod*>(group)) { pInfo = GetDowncastSwigTypeForMethod(static_cast<CCopasiMethod*>(group)); } else if (dynamic_cast<CCopasiProblem*>(group)) { pInfo = GetDowncastSwigTypeForProblem(static_cast<CCopasiProblem*>(group)); } else if (dynamic_cast<CExperiment*>(group)) { pInfo = SWIGTYPE_p_CExperiment; } else if (dynamic_cast<CExperimentObjectMap*>(group)) { pInfo = SWIGTYPE_p_CExperimentObjectMap; } else if (dynamic_cast<CExperimentSet*>(group)) { pInfo = SWIGTYPE_p_CExperimentSet; //GetDowncastSwigTypeForCExperimentSet(static_cast<CExperimentSet*>(group)); } else if (dynamic_cast<COptItem*>(group)) { pInfo = GetDowncastSwigTypeForCOptItem(static_cast<COptItem*>(group)); } return pInfo; } struct swig_type_info* GetDowncastSwigTypeForCCopasiParameter(CCopasiParameter* parameter) { if (parameter == NULL) return SWIGTYPE_p_CCopasiParameter; struct swig_type_info* pInfo = SWIGTYPE_p_CCopasiParameter; if (dynamic_cast<CCopasiParameterGroup*>(parameter)) { pInfo = GetDowncastSwigTypeForCCopasiParameterGroup(static_cast<CCopasiParameterGroup*>(parameter)); } return pInfo; } struct swig_type_info* GetDowncastSwigTypeForCModelEntity(CModelEntity* entity) { if (entity == NULL) return SWIGTYPE_p_CModelEntity; struct swig_type_info* pInfo = SWIGTYPE_p_CModelEntity; if (dynamic_cast<CCompartment*>(entity)) { pInfo = SWIGTYPE_p_CCompartment; } else if (dynamic_cast<CMetab*>(entity)) { pInfo = SWIGTYPE_p_CMetab; } else if (dynamic_cast<CModelValue*>(entity)) { pInfo = SWIGTYPE_p_CModelValue; } else if (dynamic_cast<CModel*>(entity)) { pInfo = SWIGTYPE_p_CModel; } return pInfo; } struct swig_type_info* GetDowncastSwigTypeForCDataContainer(CDataContainer* container) { if (container == NULL) return SWIGTYPE_p_CDataContainer; struct swig_type_info* pInfo = SWIGTYPE_p_CDataContainer; if (dynamic_cast<CRootContainer*>(container)) { pInfo = SWIGTYPE_p_CRootContainer; } else if (dynamic_cast<CDataModel*>(container)) { pInfo = SWIGTYPE_p_CDataModel; } else if (dynamic_cast<CModelEntity*>(container)) { pInfo = GetDowncastSwigTypeForCModelEntity(static_cast<CModelEntity*>(container)); } else if (dynamic_cast<CCopasiParameter*>(container)) { pInfo = GetDowncastSwigTypeForCCopasiParameter(static_cast<CCopasiParameter*>(container)); } else if (dynamic_cast<CEvent*>(container)) { pInfo = SWIGTYPE_p_CEvent; } else if (dynamic_cast<CEventAssignment*>(container)) { pInfo = SWIGTYPE_p_CEventAssignment; } else if (dynamic_cast<CReference*>(container)) { pInfo = SWIGTYPE_p_CReference; } else if (dynamic_cast<CBiologicalDescription*>(container)) { pInfo = SWIGTYPE_p_CBiologicalDescription; } else if (dynamic_cast<CModification*>(container)) { pInfo = SWIGTYPE_p_CModification; } else if (dynamic_cast<CCreator*>(container)) { pInfo = SWIGTYPE_p_CCreator; } else if (dynamic_cast<CMIRIAMInfo*>(container)) { pInfo = SWIGTYPE_p_CMIRIAMInfo; } else if (container->isNameVector()) { if (dynamic_cast<CDataModelVectorN*>(container)) { pInfo = SWIGTYPE_p_CDataVectorT_CDataModel_t; } else if (dynamic_cast<TaskVectorN*>(container)) { pInfo = SWIGTYPE_p_CDataVectorNT_CCopasiTask_t; } else if (dynamic_cast<ModelValueVectorN*>(container)) { pInfo = SWIGTYPE_p_CDataVectorNT_CModelValue_t; } else if (dynamic_cast<MetabVectorNS*>(container)) { pInfo = SWIGTYPE_p_CDataVectorNST_CMetab_t; } else if (dynamic_cast<CompartmentVectorNS*>(container)) { pInfo = SWIGTYPE_p_CDataVectorNST_CCompartment_t; } else if (dynamic_cast<ReactionVectorNS*>(container)) { pInfo = SWIGTYPE_p_CDataVectorNST_CReaction_t; } else if (dynamic_cast<CEvaluationTreeVectorN*>(container)) { pInfo = SWIGTYPE_p_CDataVectorNT_CEvaluationTree_t; } else if (dynamic_cast<EventVectorN*>(container)) { pInfo = SWIGTYPE_p_CDataVectorNT_CEvent_t; } else if (dynamic_cast<EventAssignmentVectorN*>(container)) { pInfo = SWIGTYPE_p_CDataVectorNT_CEventAssignment_t; } } else if (container->isVector()) { if (dynamic_cast<MoietyVector*>(container)) { pInfo = SWIGTYPE_p_CDataVectorT_CMoiety_t; } else if (dynamic_cast<MetabVector*>(container)) { pInfo = SWIGTYPE_p_CDataVectorT_CMetab_t; } else if (dynamic_cast<ReportItemVector*>(container)) { pInfo = SWIGTYPE_p_std__vectorT_CRegisteredCommonName_t; } else if (dynamic_cast<ParameterVector*>(container)) { pInfo = SWIGTYPE_p_std__vectorT_CCopasiParameter_p_t; } else if (dynamic_cast<CFunctionStdVector*>(container)) { pInfo = SWIGTYPE_p_std__vectorT_CFunction_p_t; } else if (dynamic_cast<CChemEqElementVector*>(container)) { pInfo = SWIGTYPE_p_CDataVectorT_CChemEqElement_t; } } else if (dynamic_cast<CEvaluationTree*>(container)) { pInfo = GetDowncastSwigTypeForCEvaluationTree(static_cast<CEvaluationTree*>(container)); } else if (dynamic_cast<CCopasiTask*>(container)) { pInfo = GetDowncastSwigTypeForTask(static_cast<CCopasiTask*>(container)); } else if (dynamic_cast<CChemEq*>(container)) { pInfo = SWIGTYPE_p_CChemEq; } else if (dynamic_cast<CChemEqElement*>(container)) { pInfo = SWIGTYPE_p_CChemEqElement; } else if (dynamic_cast<CFunctionDB*>(container)) { pInfo = SWIGTYPE_p_CFunctionDB; } else if (dynamic_cast<CFunctionParameter*>(container)) { pInfo = SWIGTYPE_p_CFunctionParameter; } else if (dynamic_cast<CFunctionParameters*>(container)) { pInfo = SWIGTYPE_p_CFunctionParameters; } else if (dynamic_cast<CMoiety*>(container)) { pInfo = SWIGTYPE_p_CMoiety; } else if (dynamic_cast<CReaction*>(container)) { pInfo = SWIGTYPE_p_CReaction; } else if (dynamic_cast<CDataArray*>(container)) { pInfo = SWIGTYPE_p_CDataArray; } else if (dynamic_cast<CFittingPoint*>(container)) { pInfo = SWIGTYPE_p_CFittingPoint; } return pInfo; } struct swig_type_info* GetDowncastSwigTypeForCDataObject(CDataObject* object) { if (object == NULL) return SWIGTYPE_p_CDataObject; struct swig_type_info* pInfo = SWIGTYPE_p_CDataObject; if (dynamic_cast<CDataContainer*>(object)) { pInfo = GetDowncastSwigTypeForCDataContainer(static_cast<CDataContainer*>(object)); } else if (dynamic_cast<CReportDefinition*>(object)) { pInfo = SWIGTYPE_p_CReportDefinition; } else if (dynamic_cast<CDataString*>(object)) { if (dynamic_cast<CCopasiReportSeparator*>(object)) { pInfo = SWIGTYPE_p_CCopasiReportSeparator; } else { pInfo = SWIGTYPE_p_CDataString; } } return pInfo; }
/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: DAVResourceAccess.cxx,v $ * $Revision: 1.28 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_ucb.hxx" #include "osl/diagnose.h" #include "com/sun/star/task/XInteractionAbort.hpp" #include "com/sun/star/ucb/XWebDAVCommandEnvironment.hpp" #include "ucbhelper/simpleauthenticationrequest.hxx" #include "comphelper/seekableinput.hxx" #include "DAVAuthListenerImpl.hxx" #include "DAVResourceAccess.hxx" using namespace webdav_ucp; using namespace com::sun::star; //========================================================================= //========================================================================= // // DAVAuthListener_Impl Implementation. // //========================================================================= //========================================================================= //========================================================================= // virtual int DAVAuthListener_Impl::authenticate( const ::rtl::OUString & inRealm, const ::rtl::OUString & inHostName, ::rtl::OUString & inoutUserName, ::rtl::OUString & outPassWord ) { if ( m_xEnv.is() ) { uno::Reference< task::XInteractionHandler > xIH = m_xEnv->getInteractionHandler(); if ( xIH.is() ) { // #102871# - Supply username and password from previous try. // Password container service depends on this! if ( inoutUserName.getLength() == 0 ) inoutUserName = m_aPrevUsername; if ( outPassWord.getLength() == 0 ) outPassWord = m_aPrevPassword; rtl::Reference< ucbhelper::SimpleAuthenticationRequest > xRequest = new ucbhelper::SimpleAuthenticationRequest( inHostName, inRealm, inoutUserName, outPassWord ); xIH->handle( xRequest.get() ); rtl::Reference< ucbhelper::InteractionContinuation > xSelection = xRequest->getSelection(); if ( xSelection.is() ) { // Handler handled the request. uno::Reference< task::XInteractionAbort > xAbort( xSelection.get(), uno::UNO_QUERY ); if ( !xAbort.is() ) { const rtl::Reference< ucbhelper::InteractionSupplyAuthentication > & xSupp = xRequest->getAuthenticationSupplier(); inoutUserName = xSupp->getUserName(); outPassWord = xSupp->getPassword(); // #102871# - Remember username and password. m_aPrevUsername = inoutUserName; m_aPrevPassword = outPassWord; // go on. return 0; } } } } // Abort. return -1; } //========================================================================= //========================================================================= // // DAVResourceAccess Implementation. // //========================================================================= //========================================================================= //========================================================================= DAVResourceAccess::DAVResourceAccess( const uno::Reference< lang::XMultiServiceFactory > & rSMgr, rtl::Reference< DAVSessionFactory > const & rSessionFactory, const rtl::OUString & rURL ) : m_aURL( rURL ), m_xSessionFactory( rSessionFactory ), m_xSMgr( rSMgr ) { } //========================================================================= DAVResourceAccess::DAVResourceAccess( const DAVResourceAccess & rOther ) : m_aURL( rOther.m_aURL ), m_aPath( rOther.m_aPath ), m_xSession( rOther.m_xSession ), m_xSessionFactory( rOther.m_xSessionFactory ), m_xSMgr( rOther.m_xSMgr ), m_aRedirectURIs( rOther.m_aRedirectURIs ) { } //========================================================================= DAVResourceAccess & DAVResourceAccess::operator=( const DAVResourceAccess & rOther ) { m_aURL = rOther.m_aURL; m_aPath = rOther.m_aPath; m_xSession = rOther.m_xSession; m_xSessionFactory = rOther.m_xSessionFactory; m_xSMgr = rOther.m_xSMgr; m_aRedirectURIs = rOther.m_aRedirectURIs; return *this; } //========================================================================= void DAVResourceAccess::OPTIONS( DAVCapabilities & rCapabilities, const uno::Reference< ucb::XCommandEnvironment > & xEnv ) throw( DAVException ) { initialize(); bool bRetry; do { bRetry = false; try { DAVRequestHeaders aHeaders; getUserRequestHeaders( xEnv, getRequestURI(), rtl::OUString::createFromAscii( "OPTIONS" ), aHeaders ); m_xSession->OPTIONS( getRequestURI(), rCapabilities, DAVRequestEnvironment( getRequestURI(), new DAVAuthListener_Impl( xEnv ), aHeaders, xEnv) ); } catch ( DAVException & e ) { bRetry = handleException( e ); if ( !bRetry ) throw; } } while ( bRetry ); } //========================================================================= void DAVResourceAccess::PROPFIND( const Depth nDepth, const std::vector< rtl::OUString > & rPropertyNames, std::vector< DAVResource > & rResources, const uno::Reference< ucb::XCommandEnvironment > & xEnv ) throw( DAVException ) { initialize(); bool bRetry; do { bRetry = false; try { DAVRequestHeaders aHeaders; getUserRequestHeaders( xEnv, getRequestURI(), rtl::OUString::createFromAscii( "PROPFIND" ), aHeaders ); m_xSession->PROPFIND( getRequestURI(), nDepth, rPropertyNames, rResources, DAVRequestEnvironment( getRequestURI(), new DAVAuthListener_Impl( xEnv ), aHeaders, xEnv ) ); } catch ( DAVException & e ) { bRetry = handleException( e ); if ( !bRetry ) throw; } } while ( bRetry ); } //========================================================================= void DAVResourceAccess::PROPFIND( const Depth nDepth, std::vector< DAVResourceInfo > & rResInfo, const uno::Reference< ucb::XCommandEnvironment > & xEnv ) throw( DAVException ) { initialize(); bool bRetry; do { bRetry = false; try { DAVRequestHeaders aHeaders; getUserRequestHeaders( xEnv, getRequestURI(), rtl::OUString::createFromAscii( "PROPFIND" ), aHeaders ); m_xSession->PROPFIND( getRequestURI(), nDepth, rResInfo, DAVRequestEnvironment( getRequestURI(), new DAVAuthListener_Impl( xEnv ), aHeaders, xEnv ) ) ; } catch ( DAVException & e ) { bRetry = handleException( e ); if ( !bRetry ) throw; } } while ( bRetry ); } //========================================================================= void DAVResourceAccess::PROPPATCH( const std::vector< ProppatchValue >& rValues, const uno::Reference< ucb::XCommandEnvironment >& xEnv ) throw( DAVException ) { initialize(); bool bRetry; do { bRetry = false; try { DAVRequestHeaders aHeaders; getUserRequestHeaders( xEnv, getRequestURI(), rtl::OUString::createFromAscii( "PROPPATCH" ), aHeaders ); m_xSession->PROPPATCH( getRequestURI(), rValues, DAVRequestEnvironment( getRequestURI(), new DAVAuthListener_Impl( xEnv ), aHeaders, xEnv ) ); } catch ( DAVException & e ) { bRetry = handleException( e ); if ( !bRetry ) throw; } } while ( bRetry ); } //========================================================================= void DAVResourceAccess::HEAD( const std::vector< rtl::OUString > & rHeaderNames, DAVResource & rResource, const uno::Reference< ucb::XCommandEnvironment >& xEnv ) throw( DAVException ) { initialize(); bool bRetry; do { bRetry = false; try { DAVRequestHeaders aHeaders; getUserRequestHeaders( xEnv, getRequestURI(), rtl::OUString::createFromAscii( "HEAD" ), aHeaders ); m_xSession->HEAD( getRequestURI(), rHeaderNames, rResource, DAVRequestEnvironment( getRequestURI(), new DAVAuthListener_Impl( xEnv ), aHeaders, xEnv ) ); } catch ( DAVException & e ) { bRetry = handleException( e ); if ( !bRetry ) throw; } } while ( bRetry ); } //========================================================================= uno::Reference< io::XInputStream > DAVResourceAccess::GET( const uno::Reference< ucb::XCommandEnvironment > & xEnv ) throw( DAVException ) { initialize(); uno::Reference< io::XInputStream > xStream; bool bRetry; do { bRetry = false; try { DAVRequestHeaders aHeaders; getUserRequestHeaders( xEnv, getRequestURI(), rtl::OUString::createFromAscii( "GET" ), aHeaders ); xStream = m_xSession->GET( getRequestURI(), DAVRequestEnvironment( getRequestURI(), new DAVAuthListener_Impl( xEnv ), aHeaders, xEnv ) ); } catch ( DAVException & e ) { bRetry = handleException( e ); if ( !bRetry ) throw; } } while ( bRetry ); return xStream; } //========================================================================= void DAVResourceAccess::GET( uno::Reference< io::XOutputStream > & rStream, const uno::Reference< ucb::XCommandEnvironment > & xEnv ) throw( DAVException ) { initialize(); bool bRetry; do { bRetry = false; try { DAVRequestHeaders aHeaders; getUserRequestHeaders( xEnv, getRequestURI(), rtl::OUString::createFromAscii( "GET" ), aHeaders ); m_xSession->GET( getRequestURI(), rStream, DAVRequestEnvironment( getRequestURI(), new DAVAuthListener_Impl( xEnv ), aHeaders, xEnv ) ); } catch ( DAVException & e ) { bRetry = handleException( e ); if ( !bRetry ) throw; } } while ( bRetry ); } //========================================================================= uno::Reference< io::XInputStream > DAVResourceAccess::GET( const std::vector< rtl::OUString > & rHeaderNames, DAVResource & rResource, const uno::Reference< ucb::XCommandEnvironment > & xEnv ) throw( DAVException ) { initialize(); uno::Reference< io::XInputStream > xStream; bool bRetry; do { bRetry = false; try { DAVRequestHeaders aHeaders; getUserRequestHeaders( xEnv, getRequestURI(), rtl::OUString::createFromAscii( "GET" ), aHeaders ); xStream = m_xSession->GET( getRequestURI(), rHeaderNames, rResource, DAVRequestEnvironment( getRequestURI(), new DAVAuthListener_Impl( xEnv ), aHeaders, xEnv ) ); } catch ( DAVException & e ) { bRetry = handleException( e ); if ( !bRetry ) throw; } } while ( bRetry ); return xStream; } //========================================================================= void DAVResourceAccess::GET( uno::Reference< io::XOutputStream > & rStream, const std::vector< rtl::OUString > & rHeaderNames, DAVResource & rResource, const uno::Reference< ucb::XCommandEnvironment > & xEnv ) throw( DAVException ) { initialize(); bool bRetry; do { bRetry = false; try { DAVRequestHeaders aHeaders; getUserRequestHeaders( xEnv, getRequestURI(), rtl::OUString::createFromAscii( "GET" ), aHeaders ); m_xSession->GET( getRequestURI(), rStream, rHeaderNames, rResource, DAVRequestEnvironment( getRequestURI(), new DAVAuthListener_Impl( xEnv ), aHeaders, xEnv ) ); } catch ( DAVException & e ) { bRetry = handleException( e ); if ( !bRetry ) throw; } } while ( bRetry ); } //========================================================================= namespace { void resetInputStream( const uno::Reference< io::XInputStream > & rStream ) throw( DAVException ) { try { uno::Reference< io::XSeekable > xSeekable( rStream, uno::UNO_QUERY ); if ( xSeekable.is() ) { xSeekable->seek( 0 ); return; } } catch ( lang::IllegalArgumentException const & ) { } catch ( io::IOException const & ) { } throw DAVException( DAVException::DAV_INVALID_ARG ); } } // namespace //========================================================================= void DAVResourceAccess::PUT( const uno::Reference< io::XInputStream > & rStream, const uno::Reference< ucb::XCommandEnvironment > & xEnv ) throw( DAVException ) { initialize(); // Make stream seekable, if it not. Needed, if request must be retried. uno::Reference< io::XInputStream > xSeekableStream = comphelper::OSeekableInputWrapper::CheckSeekableCanWrap( rStream, m_xSMgr ); bool bRetry = false; do { if ( bRetry ) resetInputStream( xSeekableStream ); bRetry = false; try { DAVRequestHeaders aHeaders; getUserRequestHeaders( xEnv, getRequestURI(), rtl::OUString::createFromAscii( "PUT" ), aHeaders ); m_xSession->PUT( getRequestURI(), xSeekableStream, DAVRequestEnvironment( getRequestURI(), new DAVAuthListener_Impl( xEnv ), aHeaders, xEnv ) ); } catch ( DAVException & e ) { bRetry = handleException( e ); if ( !bRetry ) throw; } } while ( bRetry ); } //========================================================================= uno::Reference< io::XInputStream > DAVResourceAccess::POST( const rtl::OUString & rContentType, const rtl::OUString & rReferer, const uno::Reference< io::XInputStream > & rInputStream, const uno::Reference< ucb::XCommandEnvironment >& xEnv ) throw ( DAVException ) { initialize(); // Make stream seekable, if it not. Needed, if request must be retried. uno::Reference< io::XInputStream > xSeekableStream = comphelper::OSeekableInputWrapper::CheckSeekableCanWrap( rInputStream, m_xSMgr ); uno::Reference< io::XInputStream > xStream; bool bRetry = false; do { if ( bRetry ) { resetInputStream( xSeekableStream ); bRetry = false; } try { DAVRequestHeaders aHeaders; getUserRequestHeaders( xEnv, getRequestURI(), rtl::OUString::createFromAscii( "POST" ), aHeaders ); xStream = m_xSession->POST( getRequestURI(), rContentType, rReferer, xSeekableStream, DAVRequestEnvironment( getRequestURI(), new DAVAuthListener_Impl( xEnv ), aHeaders, xEnv ) ); } catch ( DAVException & e ) { bRetry = handleException( e ); if ( !bRetry ) throw; if ( e.getError() == DAVException::DAV_HTTP_REDIRECT ) { // #i74980# - Upon POST redirect, do a GET. return GET( xEnv ); } } } while ( bRetry ); return xStream; } //========================================================================= void DAVResourceAccess::POST( const rtl::OUString & rContentType, const rtl::OUString & rReferer, const uno::Reference< io::XInputStream > & rInputStream, uno::Reference< io::XOutputStream > & rOutputStream, const uno::Reference< ucb::XCommandEnvironment >& xEnv ) throw ( DAVException ) { initialize(); // Make stream seekable, if it not. Needed, if request must be retried. uno::Reference< io::XInputStream > xSeekableStream = comphelper::OSeekableInputWrapper::CheckSeekableCanWrap( rInputStream, m_xSMgr ); bool bRetry = false; do { if ( bRetry ) { resetInputStream( xSeekableStream ); bRetry = false; } try { DAVRequestHeaders aHeaders; getUserRequestHeaders( xEnv, getRequestURI(), rtl::OUString::createFromAscii( "POST" ), aHeaders ); m_xSession->POST( getRequestURI(), rContentType, rReferer, xSeekableStream, rOutputStream, DAVRequestEnvironment( getRequestURI(), new DAVAuthListener_Impl( xEnv ), aHeaders, xEnv ) ); } catch ( DAVException & e ) { bRetry = handleException( e ); if ( !bRetry ) throw; if ( e.getError() == DAVException::DAV_HTTP_REDIRECT ) { // #i74980# - Upon POST redirect, do a GET. GET( rOutputStream, xEnv ); return; } } } while ( bRetry ); } //========================================================================= void DAVResourceAccess::MKCOL( const uno::Reference< ucb::XCommandEnvironment > & xEnv ) throw( DAVException ) { initialize(); bool bRetry; do { bRetry = false; try { DAVRequestHeaders aHeaders; getUserRequestHeaders( xEnv, getRequestURI(), rtl::OUString::createFromAscii( "MKCOL" ), aHeaders ); m_xSession->MKCOL( getRequestURI(), DAVRequestEnvironment( getRequestURI(), new DAVAuthListener_Impl( xEnv ), aHeaders, xEnv ) ); } catch ( DAVException & e ) { bRetry = handleException( e ); if ( !bRetry ) throw; } } while ( bRetry ); } //========================================================================= void DAVResourceAccess::COPY( const ::rtl::OUString & rSourcePath, const ::rtl::OUString & rDestinationURI, sal_Bool bOverwrite, const uno::Reference< ucb::XCommandEnvironment > & xEnv ) throw( DAVException ) { initialize(); bool bRetry; do { bRetry = false; try { DAVRequestHeaders aHeaders; getUserRequestHeaders( xEnv, getRequestURI(), rtl::OUString::createFromAscii( "COPY" ), aHeaders ); m_xSession->COPY( rSourcePath, rDestinationURI, DAVRequestEnvironment( getRequestURI(), new DAVAuthListener_Impl( xEnv ), aHeaders, xEnv ), bOverwrite ); } catch ( DAVException & e ) { bRetry = handleException( e ); if ( !bRetry ) throw; } } while ( bRetry ); } //========================================================================= void DAVResourceAccess::MOVE( const ::rtl::OUString & rSourcePath, const ::rtl::OUString & rDestinationURI, sal_Bool bOverwrite, const uno::Reference< ucb::XCommandEnvironment > & xEnv ) throw( DAVException ) { initialize(); bool bRetry; do { bRetry = false; try { DAVRequestHeaders aHeaders; getUserRequestHeaders( xEnv, getRequestURI(), rtl::OUString::createFromAscii( "MOVE" ), aHeaders ); m_xSession->MOVE( rSourcePath, rDestinationURI, DAVRequestEnvironment( getRequestURI(), new DAVAuthListener_Impl( xEnv ), aHeaders, xEnv ), bOverwrite ); } catch ( DAVException & e ) { bRetry = handleException( e ); if ( !bRetry ) throw; } } while ( bRetry ); } //========================================================================= void DAVResourceAccess::DESTROY( const uno::Reference< ucb::XCommandEnvironment > & xEnv ) throw( DAVException ) { initialize(); bool bRetry; do { bRetry = false; try { DAVRequestHeaders aHeaders; getUserRequestHeaders( xEnv, getRequestURI(), rtl::OUString::createFromAscii( "DESTROY" ), aHeaders ); m_xSession->DESTROY( getRequestURI(), DAVRequestEnvironment( getRequestURI(), new DAVAuthListener_Impl( xEnv ), aHeaders, xEnv ) ); } catch ( DAVException & e ) { bRetry = handleException( e ); if ( !bRetry ) throw; } } while ( bRetry ); } //========================================================================= void DAVResourceAccess::LOCK ( const ucb::Lock & /*rLock*/, const uno::Reference< ucb::XCommandEnvironment > & /*xEnv*/ ) throw( DAVException ) { // initialize(); OSL_ENSURE( sal_False, "DAVResourceAccess::LOCK - NYI" ); } //========================================================================= void DAVResourceAccess::UNLOCK ( const ucb::Lock & /*rLock*/, const uno::Reference< ucb::XCommandEnvironment > & /*xEnv*/ ) throw( DAVException ) { // initialize(); OSL_ENSURE( sal_False, "DAVResourceAccess::UNLOCK - NYI" ); } //========================================================================= void DAVResourceAccess::setURL( const rtl::OUString & rNewURL ) throw( DAVException ) { osl::Guard< osl::Mutex > aGuard( m_aMutex ); m_aURL = rNewURL; m_aPath = rtl::OUString(); // Next initialize() will create new session. } //========================================================================= // init dav session and path void DAVResourceAccess::initialize() throw ( DAVException ) { if ( m_aPath.getLength() == 0 ) { osl::Guard< osl::Mutex > aGuard( m_aMutex ); if ( m_aPath.getLength() == 0 ) { NeonUri aURI( m_aURL ); rtl::OUString aPath( aURI.GetPath() ); /* #134089# - Check URI */ if ( !aPath.getLength() ) throw DAVException( DAVException::DAV_INVALID_ARG ); /* #134089# - Check URI */ if ( !aURI.GetHost().getLength() ) throw DAVException( DAVException::DAV_INVALID_ARG ); if ( !m_xSession.is() || !m_xSession->CanUse( m_aURL ) ) { m_xSession.clear(); // create new webdav session m_xSession = m_xSessionFactory->createDAVSession( m_aURL, m_xSMgr ); if ( !m_xSession.is() ) return; } // Own URI is needed for redirect cycle detection. m_aRedirectURIs.push_back( aURI ); // Success. m_aPath = aPath; // Not only the path has to be encoded m_aURL = aURI.GetURI(); } } } //========================================================================= const rtl::OUString & DAVResourceAccess::getRequestURI() const { OSL_ENSURE( m_xSession.is(), "DAVResourceAccess::getRequestURI - Not initialized!" ); // In case a proxy is used we have to use the absolute URI for a request. if ( m_xSession->UsesProxy() ) return m_aURL; return m_aPath; } //========================================================================= // static void DAVResourceAccess::getUserRequestHeaders( const uno::Reference< ucb::XCommandEnvironment > & xEnv, const rtl::OUString & rURI, const rtl::OUString & rMethod, DAVRequestHeaders & rRequestHeaders ) { if ( xEnv.is() ) { uno::Reference< ucb::XWebDAVCommandEnvironment > xDAVEnv( xEnv, uno::UNO_QUERY ); if ( xDAVEnv.is() ) { uno::Sequence< beans::NamedValue > aRequestHeaders = xDAVEnv->getUserRequestHeaders( rURI, rMethod ); for ( sal_Int32 n = 0; n < aRequestHeaders.getLength(); ++n ) { rtl::OUString aValue; sal_Bool isString = aRequestHeaders[ n ].Value >>= aValue; if ( !isString ) { OSL_ENSURE( isString, "DAVResourceAccess::getUserRequestHeaders :" "Value is not a string! Ignoring..." ); } rRequestHeaders.push_back( DAVRequestHeader( aRequestHeaders[ n ].Name, aValue ) ); } } } } //========================================================================= sal_Bool DAVResourceAccess::detectRedirectCycle( const rtl::OUString& rRedirectURL ) throw ( DAVException ) { osl::Guard< osl::Mutex > aGuard( m_aMutex ); NeonUri aUri( rRedirectURL ); std::vector< NeonUri >::const_iterator it = m_aRedirectURIs.begin(); std::vector< NeonUri >::const_iterator end = m_aRedirectURIs.end(); while ( it != end ) { if ( aUri == (*it) ) return sal_True; it++; } return sal_False; } //========================================================================= sal_Bool DAVResourceAccess::handleException( DAVException & e ) throw ( DAVException ) { switch ( e.getError() ) { case DAVException::DAV_HTTP_REDIRECT: if ( !detectRedirectCycle( e.getData() ) ) { // set new URL and path. setURL( e.getData() ); initialize(); return sal_True; } return sal_False; default: return sal_False; // Abort } } INTEGRATION: CWS tkr14 (1.28.8); FILE MERGED 2008/06/11 14:28:18 tkr 1.28.8.3: #67048# copy & paste connection errors 2008/06/09 14:11:33 tkr 1.28.8.2: #67048# copy & paste connection errors 2008/06/05 09:41:47 tkr 1.28.8.1: #i78894# helper function for type detection /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: DAVResourceAccess.cxx,v $ * $Revision: 1.29 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_ucb.hxx" #include "osl/diagnose.h" #include "com/sun/star/task/XInteractionAbort.hpp" #include "com/sun/star/ucb/XWebDAVCommandEnvironment.hpp" #include "ucbhelper/simpleauthenticationrequest.hxx" #include "comphelper/seekableinput.hxx" #include "DAVAuthListenerImpl.hxx" #include "DAVResourceAccess.hxx" using namespace webdav_ucp; using namespace com::sun::star; //========================================================================= //========================================================================= // // DAVAuthListener_Impl Implementation. // //========================================================================= //========================================================================= //========================================================================= // virtual int DAVAuthListener_Impl::authenticate( const ::rtl::OUString & inRealm, const ::rtl::OUString & inHostName, ::rtl::OUString & inoutUserName, ::rtl::OUString & outPassWord ) { if ( m_xEnv.is() ) { uno::Reference< task::XInteractionHandler > xIH = m_xEnv->getInteractionHandler(); if ( xIH.is() ) { // #102871# - Supply username and password from previous try. // Password container service depends on this! if ( inoutUserName.getLength() == 0 ) inoutUserName = m_aPrevUsername; if ( outPassWord.getLength() == 0 ) outPassWord = m_aPrevPassword; rtl::Reference< ucbhelper::SimpleAuthenticationRequest > xRequest = new ucbhelper::SimpleAuthenticationRequest( inHostName, inRealm, inoutUserName, outPassWord ); xIH->handle( xRequest.get() ); rtl::Reference< ucbhelper::InteractionContinuation > xSelection = xRequest->getSelection(); if ( xSelection.is() ) { // Handler handled the request. uno::Reference< task::XInteractionAbort > xAbort( xSelection.get(), uno::UNO_QUERY ); if ( !xAbort.is() ) { const rtl::Reference< ucbhelper::InteractionSupplyAuthentication > & xSupp = xRequest->getAuthenticationSupplier(); inoutUserName = xSupp->getUserName(); outPassWord = xSupp->getPassword(); // #102871# - Remember username and password. m_aPrevUsername = inoutUserName; m_aPrevPassword = outPassWord; // go on. return 0; } } } } // Abort. return -1; } //========================================================================= //========================================================================= // // DAVResourceAccess Implementation. // //========================================================================= //========================================================================= //========================================================================= DAVResourceAccess::DAVResourceAccess( const uno::Reference< lang::XMultiServiceFactory > & rSMgr, rtl::Reference< DAVSessionFactory > const & rSessionFactory, const rtl::OUString & rURL ) : m_aURL( rURL ), m_xSessionFactory( rSessionFactory ), m_xSMgr( rSMgr ) { } //========================================================================= DAVResourceAccess::DAVResourceAccess( const DAVResourceAccess & rOther ) : m_aURL( rOther.m_aURL ), m_aPath( rOther.m_aPath ), m_xSession( rOther.m_xSession ), m_xSessionFactory( rOther.m_xSessionFactory ), m_xSMgr( rOther.m_xSMgr ), m_aRedirectURIs( rOther.m_aRedirectURIs ) { } //========================================================================= DAVResourceAccess & DAVResourceAccess::operator=( const DAVResourceAccess & rOther ) { m_aURL = rOther.m_aURL; m_aPath = rOther.m_aPath; m_xSession = rOther.m_xSession; m_xSessionFactory = rOther.m_xSessionFactory; m_xSMgr = rOther.m_xSMgr; m_aRedirectURIs = rOther.m_aRedirectURIs; return *this; } //========================================================================= void DAVResourceAccess::OPTIONS( DAVCapabilities & rCapabilities, const uno::Reference< ucb::XCommandEnvironment > & xEnv ) throw( DAVException ) { initialize(); bool bRetry; int errorCount = 0; do { bRetry = false; try { DAVRequestHeaders aHeaders; getUserRequestHeaders( xEnv, getRequestURI(), rtl::OUString::createFromAscii( "OPTIONS" ), aHeaders ); m_xSession->OPTIONS( getRequestURI(), rCapabilities, DAVRequestEnvironment( getRequestURI(), new DAVAuthListener_Impl( xEnv ), aHeaders, xEnv) ); } catch ( DAVException & e ) { errorCount++; bRetry = handleException( e, errorCount ); if ( !bRetry ) throw; } } while ( bRetry ); } //========================================================================= void DAVResourceAccess::PROPFIND( const Depth nDepth, const std::vector< rtl::OUString > & rPropertyNames, std::vector< DAVResource > & rResources, const uno::Reference< ucb::XCommandEnvironment > & xEnv ) throw( DAVException ) { initialize(); int errorCount = 0; bool bRetry; do { bRetry = false; try { DAVRequestHeaders aHeaders; getUserRequestHeaders( xEnv, getRequestURI(), rtl::OUString::createFromAscii( "PROPFIND" ), aHeaders ); m_xSession->PROPFIND( getRequestURI(), nDepth, rPropertyNames, rResources, DAVRequestEnvironment( getRequestURI(), new DAVAuthListener_Impl( xEnv ), aHeaders, xEnv ) ); } catch ( DAVException & e ) { errorCount++; bRetry = handleException( e, errorCount ); if ( !bRetry ) throw; } } while ( bRetry ); } //========================================================================= void DAVResourceAccess::PROPFIND( const Depth nDepth, std::vector< DAVResourceInfo > & rResInfo, const uno::Reference< ucb::XCommandEnvironment > & xEnv ) throw( DAVException ) { initialize(); int errorCount = 0; bool bRetry; do { bRetry = false; try { DAVRequestHeaders aHeaders; getUserRequestHeaders( xEnv, getRequestURI(), rtl::OUString::createFromAscii( "PROPFIND" ), aHeaders ); m_xSession->PROPFIND( getRequestURI(), nDepth, rResInfo, DAVRequestEnvironment( getRequestURI(), new DAVAuthListener_Impl( xEnv ), aHeaders, xEnv ) ) ; } catch ( DAVException & e ) { errorCount++; bRetry = handleException( e, errorCount ); if ( !bRetry ) throw; } } while ( bRetry ); } //========================================================================= void DAVResourceAccess::PROPPATCH( const std::vector< ProppatchValue >& rValues, const uno::Reference< ucb::XCommandEnvironment >& xEnv ) throw( DAVException ) { initialize(); int errorCount = 0; bool bRetry; do { bRetry = false; try { DAVRequestHeaders aHeaders; getUserRequestHeaders( xEnv, getRequestURI(), rtl::OUString::createFromAscii( "PROPPATCH" ), aHeaders ); m_xSession->PROPPATCH( getRequestURI(), rValues, DAVRequestEnvironment( getRequestURI(), new DAVAuthListener_Impl( xEnv ), aHeaders, xEnv ) ); } catch ( DAVException & e ) { errorCount++; bRetry = handleException( e, errorCount ); if ( !bRetry ) throw; } } while ( bRetry ); } //========================================================================= void DAVResourceAccess::HEAD( const std::vector< rtl::OUString > & rHeaderNames, DAVResource & rResource, const uno::Reference< ucb::XCommandEnvironment >& xEnv ) throw( DAVException ) { initialize(); int errorCount = 0; bool bRetry; do { bRetry = false; try { DAVRequestHeaders aHeaders; getUserRequestHeaders( xEnv, getRequestURI(), rtl::OUString::createFromAscii( "HEAD" ), aHeaders ); m_xSession->HEAD( getRequestURI(), rHeaderNames, rResource, DAVRequestEnvironment( getRequestURI(), new DAVAuthListener_Impl( xEnv ), aHeaders, xEnv ) ); } catch ( DAVException & e ) { errorCount++; bRetry = handleException( e, errorCount ); if ( !bRetry ) throw; } } while ( bRetry ); } //========================================================================= uno::Reference< io::XInputStream > DAVResourceAccess::GET( const uno::Reference< ucb::XCommandEnvironment > & xEnv ) throw( DAVException ) { initialize(); uno::Reference< io::XInputStream > xStream; int errorCount = 0; bool bRetry; do { bRetry = false; try { DAVRequestHeaders aHeaders; getUserRequestHeaders( xEnv, getRequestURI(), rtl::OUString::createFromAscii( "GET" ), aHeaders ); xStream = m_xSession->GET( getRequestURI(), DAVRequestEnvironment( getRequestURI(), new DAVAuthListener_Impl( xEnv ), aHeaders, xEnv ) ); } catch ( DAVException & e ) { errorCount++; bRetry = handleException( e, errorCount ); if ( !bRetry ) throw; } } while ( bRetry ); return xStream; } //========================================================================= void DAVResourceAccess::GET( uno::Reference< io::XOutputStream > & rStream, const uno::Reference< ucb::XCommandEnvironment > & xEnv ) throw( DAVException ) { initialize(); int errorCount = 0; bool bRetry; do { bRetry = false; try { DAVRequestHeaders aHeaders; getUserRequestHeaders( xEnv, getRequestURI(), rtl::OUString::createFromAscii( "GET" ), aHeaders ); m_xSession->GET( getRequestURI(), rStream, DAVRequestEnvironment( getRequestURI(), new DAVAuthListener_Impl( xEnv ), aHeaders, xEnv ) ); } catch ( DAVException & e ) { errorCount++; bRetry = handleException( e, errorCount ); if ( !bRetry ) throw; } } while ( bRetry ); } //========================================================================= uno::Reference< io::XInputStream > DAVResourceAccess::GET( const std::vector< rtl::OUString > & rHeaderNames, DAVResource & rResource, const uno::Reference< ucb::XCommandEnvironment > & xEnv ) throw( DAVException ) { initialize(); uno::Reference< io::XInputStream > xStream; int errorCount = 0; bool bRetry; do { bRetry = false; try { DAVRequestHeaders aHeaders; getUserRequestHeaders( xEnv, getRequestURI(), rtl::OUString::createFromAscii( "GET" ), aHeaders ); xStream = m_xSession->GET( getRequestURI(), rHeaderNames, rResource, DAVRequestEnvironment( getRequestURI(), new DAVAuthListener_Impl( xEnv ), aHeaders, xEnv ) ); } catch ( DAVException & e ) { errorCount++; bRetry = handleException( e, errorCount ); if ( !bRetry ) throw; } } while ( bRetry ); return xStream; } //========================================================================= void DAVResourceAccess::GET( uno::Reference< io::XOutputStream > & rStream, const std::vector< rtl::OUString > & rHeaderNames, DAVResource & rResource, const uno::Reference< ucb::XCommandEnvironment > & xEnv ) throw( DAVException ) { initialize(); bool bRetry; int errorCount = 0; do { bRetry = false; try { DAVRequestHeaders aHeaders; getUserRequestHeaders( xEnv, getRequestURI(), rtl::OUString::createFromAscii( "GET" ), aHeaders ); m_xSession->GET( getRequestURI(), rStream, rHeaderNames, rResource, DAVRequestEnvironment( getRequestURI(), new DAVAuthListener_Impl( xEnv ), aHeaders, xEnv ) ); } catch ( DAVException & e ) { errorCount++; bRetry = handleException( e, errorCount ); if ( !bRetry ) throw; } } while ( bRetry ); } //========================================================================= namespace { void resetInputStream( const uno::Reference< io::XInputStream > & rStream ) throw( DAVException ) { try { uno::Reference< io::XSeekable > xSeekable( rStream, uno::UNO_QUERY ); if ( xSeekable.is() ) { xSeekable->seek( 0 ); return; } } catch ( lang::IllegalArgumentException const & ) { } catch ( io::IOException const & ) { } throw DAVException( DAVException::DAV_INVALID_ARG ); } } // namespace //========================================================================= void DAVResourceAccess::PUT( const uno::Reference< io::XInputStream > & rStream, const uno::Reference< ucb::XCommandEnvironment > & xEnv ) throw( DAVException ) { initialize(); // Make stream seekable, if it not. Needed, if request must be retried. uno::Reference< io::XInputStream > xSeekableStream = comphelper::OSeekableInputWrapper::CheckSeekableCanWrap( rStream, m_xSMgr ); int errorCount = 0; bool bRetry = false; do { if ( bRetry ) resetInputStream( xSeekableStream ); bRetry = false; try { DAVRequestHeaders aHeaders; getUserRequestHeaders( xEnv, getRequestURI(), rtl::OUString::createFromAscii( "PUT" ), aHeaders ); m_xSession->PUT( getRequestURI(), xSeekableStream, DAVRequestEnvironment( getRequestURI(), new DAVAuthListener_Impl( xEnv ), aHeaders, xEnv ) ); } catch ( DAVException & e ) { errorCount++; bRetry = handleException( e, errorCount ); if ( !bRetry ) throw; } } while ( bRetry ); } //========================================================================= uno::Reference< io::XInputStream > DAVResourceAccess::POST( const rtl::OUString & rContentType, const rtl::OUString & rReferer, const uno::Reference< io::XInputStream > & rInputStream, const uno::Reference< ucb::XCommandEnvironment >& xEnv ) throw ( DAVException ) { initialize(); // Make stream seekable, if it not. Needed, if request must be retried. uno::Reference< io::XInputStream > xSeekableStream = comphelper::OSeekableInputWrapper::CheckSeekableCanWrap( rInputStream, m_xSMgr ); uno::Reference< io::XInputStream > xStream; int errorCount = 0; bool bRetry = false; do { if ( bRetry ) { resetInputStream( xSeekableStream ); bRetry = false; } try { DAVRequestHeaders aHeaders; getUserRequestHeaders( xEnv, getRequestURI(), rtl::OUString::createFromAscii( "POST" ), aHeaders ); xStream = m_xSession->POST( getRequestURI(), rContentType, rReferer, xSeekableStream, DAVRequestEnvironment( getRequestURI(), new DAVAuthListener_Impl( xEnv ), aHeaders, xEnv ) ); } catch ( DAVException & e ) { errorCount++; bRetry = handleException( e, errorCount ); if ( !bRetry ) throw; if ( e.getError() == DAVException::DAV_HTTP_REDIRECT ) { // #i74980# - Upon POST redirect, do a GET. return GET( xEnv ); } } } while ( bRetry ); return xStream; } //========================================================================= void DAVResourceAccess::POST( const rtl::OUString & rContentType, const rtl::OUString & rReferer, const uno::Reference< io::XInputStream > & rInputStream, uno::Reference< io::XOutputStream > & rOutputStream, const uno::Reference< ucb::XCommandEnvironment >& xEnv ) throw ( DAVException ) { initialize(); // Make stream seekable, if it not. Needed, if request must be retried. uno::Reference< io::XInputStream > xSeekableStream = comphelper::OSeekableInputWrapper::CheckSeekableCanWrap( rInputStream, m_xSMgr ); int errorCount = 0; bool bRetry = false; do { if ( bRetry ) { resetInputStream( xSeekableStream ); bRetry = false; } try { DAVRequestHeaders aHeaders; getUserRequestHeaders( xEnv, getRequestURI(), rtl::OUString::createFromAscii( "POST" ), aHeaders ); m_xSession->POST( getRequestURI(), rContentType, rReferer, xSeekableStream, rOutputStream, DAVRequestEnvironment( getRequestURI(), new DAVAuthListener_Impl( xEnv ), aHeaders, xEnv ) ); } catch ( DAVException & e ) { errorCount++; bRetry = handleException( e, errorCount ); if ( !bRetry ) throw; if ( e.getError() == DAVException::DAV_HTTP_REDIRECT ) { // #i74980# - Upon POST redirect, do a GET. GET( rOutputStream, xEnv ); return; } } } while ( bRetry ); } //========================================================================= void DAVResourceAccess::MKCOL( const uno::Reference< ucb::XCommandEnvironment > & xEnv ) throw( DAVException ) { initialize(); int errorCount = 0; bool bRetry; do { bRetry = false; try { DAVRequestHeaders aHeaders; getUserRequestHeaders( xEnv, getRequestURI(), rtl::OUString::createFromAscii( "MKCOL" ), aHeaders ); m_xSession->MKCOL( getRequestURI(), DAVRequestEnvironment( getRequestURI(), new DAVAuthListener_Impl( xEnv ), aHeaders, xEnv ) ); } catch ( DAVException & e ) { errorCount++; bRetry = handleException( e, errorCount ); if ( !bRetry ) throw; } } while ( bRetry ); } //========================================================================= void DAVResourceAccess::COPY( const ::rtl::OUString & rSourcePath, const ::rtl::OUString & rDestinationURI, sal_Bool bOverwrite, const uno::Reference< ucb::XCommandEnvironment > & xEnv ) throw( DAVException ) { initialize(); int errorCount = 0; bool bRetry; do { bRetry = false; try { DAVRequestHeaders aHeaders; getUserRequestHeaders( xEnv, getRequestURI(), rtl::OUString::createFromAscii( "COPY" ), aHeaders ); m_xSession->COPY( rSourcePath, rDestinationURI, DAVRequestEnvironment( getRequestURI(), new DAVAuthListener_Impl( xEnv ), aHeaders, xEnv ), bOverwrite ); } catch ( DAVException & e ) { errorCount++; bRetry = handleException( e, errorCount ); if ( !bRetry ) throw; } } while ( bRetry ); } //========================================================================= void DAVResourceAccess::MOVE( const ::rtl::OUString & rSourcePath, const ::rtl::OUString & rDestinationURI, sal_Bool bOverwrite, const uno::Reference< ucb::XCommandEnvironment > & xEnv ) throw( DAVException ) { initialize(); int errorCount = 0; bool bRetry; do { bRetry = false; try { DAVRequestHeaders aHeaders; getUserRequestHeaders( xEnv, getRequestURI(), rtl::OUString::createFromAscii( "MOVE" ), aHeaders ); m_xSession->MOVE( rSourcePath, rDestinationURI, DAVRequestEnvironment( getRequestURI(), new DAVAuthListener_Impl( xEnv ), aHeaders, xEnv ), bOverwrite ); } catch ( DAVException & e ) { errorCount++; bRetry = handleException( e, errorCount ); if ( !bRetry ) throw; } } while ( bRetry ); } //========================================================================= void DAVResourceAccess::DESTROY( const uno::Reference< ucb::XCommandEnvironment > & xEnv ) throw( DAVException ) { initialize(); int errorCount = 0; bool bRetry; do { bRetry = false; try { DAVRequestHeaders aHeaders; getUserRequestHeaders( xEnv, getRequestURI(), rtl::OUString::createFromAscii( "DESTROY" ), aHeaders ); m_xSession->DESTROY( getRequestURI(), DAVRequestEnvironment( getRequestURI(), new DAVAuthListener_Impl( xEnv ), aHeaders, xEnv ) ); } catch ( DAVException & e ) { errorCount++; bRetry = handleException( e, errorCount ); if ( !bRetry ) throw; } } while ( bRetry ); } //========================================================================= void DAVResourceAccess::LOCK ( const ucb::Lock & /*rLock*/, const uno::Reference< ucb::XCommandEnvironment > & /*xEnv*/ ) throw( DAVException ) { // initialize(); OSL_ENSURE( sal_False, "DAVResourceAccess::LOCK - NYI" ); } //========================================================================= void DAVResourceAccess::UNLOCK ( const ucb::Lock & /*rLock*/, const uno::Reference< ucb::XCommandEnvironment > & /*xEnv*/ ) throw( DAVException ) { // initialize(); OSL_ENSURE( sal_False, "DAVResourceAccess::UNLOCK - NYI" ); } //========================================================================= void DAVResourceAccess::setURL( const rtl::OUString & rNewURL ) throw( DAVException ) { osl::Guard< osl::Mutex > aGuard( m_aMutex ); m_aURL = rNewURL; m_aPath = rtl::OUString(); // Next initialize() will create new session. } //========================================================================= // init dav session and path void DAVResourceAccess::initialize() throw ( DAVException ) { osl::Guard< osl::Mutex > aGuard( m_aMutex ); if ( m_aPath.getLength() == 0 ) { NeonUri aURI( m_aURL ); rtl::OUString aPath( aURI.GetPath() ); /* #134089# - Check URI */ if ( !aPath.getLength() ) throw DAVException( DAVException::DAV_INVALID_ARG ); /* #134089# - Check URI */ if ( !aURI.GetHost().getLength() ) throw DAVException( DAVException::DAV_INVALID_ARG ); if ( !m_xSession.is() || !m_xSession->CanUse( m_aURL ) ) { m_xSession.clear(); // create new webdav session m_xSession = m_xSessionFactory->createDAVSession( m_aURL, m_xSMgr ); if ( !m_xSession.is() ) return; } // Own URI is needed for redirect cycle detection. m_aRedirectURIs.push_back( aURI ); // Success. m_aPath = aPath; // Not only the path has to be encoded m_aURL = aURI.GetURI(); } } //========================================================================= const rtl::OUString & DAVResourceAccess::getRequestURI() const { OSL_ENSURE( m_xSession.is(), "DAVResourceAccess::getRequestURI - Not initialized!" ); // In case a proxy is used we have to use the absolute URI for a request. if ( m_xSession->UsesProxy() ) return m_aURL; return m_aPath; } //========================================================================= // static void DAVResourceAccess::getUserRequestHeaders( const uno::Reference< ucb::XCommandEnvironment > & xEnv, const rtl::OUString & rURI, const rtl::OUString & rMethod, DAVRequestHeaders & rRequestHeaders ) { if ( xEnv.is() ) { uno::Reference< ucb::XWebDAVCommandEnvironment > xDAVEnv( xEnv, uno::UNO_QUERY ); if ( xDAVEnv.is() ) { uno::Sequence< beans::NamedValue > aRequestHeaders = xDAVEnv->getUserRequestHeaders( rURI, rMethod ); for ( sal_Int32 n = 0; n < aRequestHeaders.getLength(); ++n ) { rtl::OUString aValue; sal_Bool isString = aRequestHeaders[ n ].Value >>= aValue; if ( !isString ) { OSL_ENSURE( isString, "DAVResourceAccess::getUserRequestHeaders :" "Value is not a string! Ignoring..." ); } rRequestHeaders.push_back( DAVRequestHeader( aRequestHeaders[ n ].Name, aValue ) ); } } } } //========================================================================= sal_Bool DAVResourceAccess::detectRedirectCycle( const rtl::OUString& rRedirectURL ) throw ( DAVException ) { osl::Guard< osl::Mutex > aGuard( m_aMutex ); NeonUri aUri( rRedirectURL ); std::vector< NeonUri >::const_iterator it = m_aRedirectURIs.begin(); std::vector< NeonUri >::const_iterator end = m_aRedirectURIs.end(); while ( it != end ) { if ( aUri == (*it) ) return sal_True; it++; } return sal_False; } //========================================================================= void DAVResourceAccess::resetUri() { osl::Guard< osl::Mutex > aGuard( m_aMutex ); if ( m_aRedirectURIs.size() > 0 ) { std::vector< NeonUri >::const_iterator it = m_aRedirectURIs.begin(); NeonUri aUri( (*it) ); m_aRedirectURIs.clear(); setURL ( aUri.GetURI() ); initialize(); } } //========================================================================= sal_Bool DAVResourceAccess::handleException( DAVException & e, int errorCount ) throw ( DAVException ) { switch ( e.getError() ) { case DAVException::DAV_HTTP_REDIRECT: if ( !detectRedirectCycle( e.getData() ) ) { // set new URL and path. setURL( e.getData() ); initialize(); return sal_True; } return sal_False; // --> tkr #67048# copy & paste images doesn't display. // if we have a bad connection try again. Up to three times. case DAVException::DAV_HTTP_ERROR: if (errorCount < 3) { return sal_True; } return sal_False; // <-- // --> tkr: if connection has said retry then retry! case DAVException::DAV_HTTP_RETRY: return sal_True; // <-- default: return sal_False; // Abort } }
#include "Base.h" #include "TTFFontEncoder.h" #include "GPBFile.h" #include "StringUtil.h" #include "Image.h" #ifdef WIN32 #include <windows.h> #include <wingdi.h> #endif namespace gameplay { static void drawBitmap(unsigned char* dstBitmap, int x, int y, int dstWidth, unsigned char* srcBitmap, int srcWidth, int srcHeight) { // offset dst bitmap by x,y. dstBitmap += (x + (y * dstWidth)); for (int i = 0; i < srcHeight; ++i) { memcpy(dstBitmap, (const void*)srcBitmap, srcWidth); srcBitmap += srcWidth; dstBitmap += dstWidth; } } static void writeUint(FILE* fp, unsigned int i) { fwrite(&i, sizeof(unsigned int), 1, fp); } static void writeString(FILE* fp, const char* str) { unsigned int len = strlen(str); fwrite(&len, sizeof(unsigned int), 1, fp); if (len > 0) { fwrite(str, 1, len, fp); } } unsigned char* createDistanceFields(unsigned char* img, unsigned int width, unsigned int height) { short* xDistance = (short*)malloc(width * height * sizeof(short)); short* yDistance = (short*)malloc(width * height * sizeof(short)); double* gx = (double*)calloc(width * height, sizeof(double)); double* gy = (double*)calloc(width * height, sizeof(double)); double* data = (double*)calloc(width * height, sizeof(double)); double* outside = (double*)calloc(width * height, sizeof(double)); double* inside = (double*)calloc(width * height, sizeof(double)); unsigned int i; // Convert img into double (data) double imgMin = 255; double imgMax = -255; for (i = 0; i < width * height; ++i) { double v = img[i]; data[i] = v; if (v > imgMax) imgMax = v; if (v < imgMin) imgMin = v; } // Rescale image levels between 0 and 1 for (i = 0; i < width * height; ++i) { data[i] = (img[i] - imgMin) / imgMax; } // Compute outside = edtaa3(bitmap); % Transform background (0's) computegradient(data, width, height, gx, gy); edtaa3(data, gx, gy, height, width, xDistance, yDistance, outside); for (i = 0; i < width * height; ++i) { if (outside[i] < 0 ) outside[i] = 0.0; } // Compute inside = edtaa3(1-bitmap); % Transform foreground (1's) memset(gx, 0, sizeof(double) * width * height); memset(gy, 0, sizeof(double) * width * height); for (i = 0; i < width * height; ++i) { data[i] = 1 - data[i]; } computegradient(data, width, height, gx, gy); edtaa3(data, gx, gy, height, width, xDistance, yDistance, inside); for (i = 0; i < width * height; ++i) { if( inside[i] < 0 ) inside[i] = 0.0; } // distmap = outside - inside; % Bipolar distance field unsigned char* out = (unsigned char*)malloc(sizeof(unsigned char) * width * height); for (i = 0; i < width * height; ++i) { outside[i] -= inside[i]; outside[i] = 128 + outside[i] * 16; if (outside[i] < 0) outside[i] = 0; if (outside[i] > 255) outside[i] = 255; out[i] = 255 - (unsigned char) outside[i]; } free(xDistance); free(yDistance); free(gx); free(gy); free(data); free(outside); free(inside); return out; } struct KerningPair { wchar_t left; wchar_t right; int kerning; }; // Stores a single genreated font size to be written into the GPB struct FontData { // Array of glyphs for a font TTFGlyph * glyphArray; int fontSize; // Actual size of the underlying glyphs (may be different from fontSize) int glyphSize; // Font texture unsigned char* imageBuffer; unsigned int imageWidth; unsigned int imageHeight; // Kerning pairs std::vector<KerningPair> kerningPairs; FontData() : fontSize(0), glyphSize(0), imageBuffer(NULL), imageWidth(0), imageHeight(0) { } ~FontData() { if (imageBuffer) free(imageBuffer); } }; int writeFont(const char* inFilePath, const char* outFilePath, std::vector<unsigned int>& fontSizes, const char* id, bool fontpreview = false, Font::FontFormat fontFormat = Font::BITMAP, const wchar_t * characterSet = NULL) { // Initialize freetype library. FT_Library library; FT_Error error = FT_Init_FreeType(&library); if (error) { LOG(1, "FT_Init_FreeType error: %d \n", error); return -1; } // Initialize font face. FT_Face face; error = FT_New_Face(library, inFilePath, 0, &face); if (error) { LOG(1, "FT_New_Face error: %d \n", error); return -1; } std::vector<FontData*> fonts; if( characterSet == NULL || wcslen( characterSet ) == 0 ) { wchar_t * defaultSet = reinterpret_cast< wchar_t * >( calloc( END_INDEX - START_INDEX + 1, sizeof( wchar_t ) ) ); for( wchar_t ch = START_INDEX; ch < END_INDEX; ch++ ) defaultSet[ ch - START_INDEX ] = ch; defaultSet[ END_INDEX - START_INDEX] = NULL; characterSet = defaultSet; } // retrieve kerning pairs // freetype has no API to access kerning pairs table, // use brute-force attempt to retrieve all pair for current characters set std::vector<std::pair<wchar_t, wchar_t> > kerningPairs; // freetype has limited support processing kerning table for OTF fonts, it // retrieve data from the outdated 'kern' table instead of GPOS table. // Use MSDN functions to retrieve full kerning pairs and offsets #if 0//def WIN32 AddFontResourceExA(inFilePath, FR_PRIVATE, 0); #else for (const wchar_t * ascii1 = characterSet; *ascii1; ++ascii1) { for (const wchar_t * ascii2 = characterSet; *ascii2; ++ascii2) { FT_Vector out; if (FT_Get_Kerning(face, *ascii1, *ascii2, FT_KERNING_UNSCALED, &out) == 0 && out.x != 0) kerningPairs.push_back(std::make_pair(*ascii1, *ascii2)); } } #endif for (size_t fontIndex = 0, count = fontSizes.size(); fontIndex < count; ++fontIndex) { unsigned int fontSize = fontSizes[fontIndex]; FontData* font = new FontData(); font->fontSize = fontSize; font->glyphArray = reinterpret_cast<TTFGlyph *>(malloc(wcslen(characterSet) * sizeof(TTFGlyph))); if (!font->glyphArray) { LOG(1, "Not enough memory to allocate glyphs."); return -1; } TTFGlyph* glyphArray = font->glyphArray; int rowSize = 0; int glyphSize = 0; int actualfontHeight = 0; FT_GlyphSlot slot = NULL; FT_Int32 loadFlags = FT_LOAD_RENDER; // We want to generate fonts that fit exactly the requested pixels size. // Since free type (due to modern fonts) does not directly correlate requested // size to glyph size, we'll brute-force attempt to set the largest font size // possible that will fit within the requested pixel size. for (unsigned int requestedSize = fontSize; requestedSize > 0; --requestedSize) { // Set the pixel size. error = FT_Set_Char_Size(face, 0, requestedSize * 64, 0, 0); if (error) { LOG(1, "FT_Set_Pixel_Sizes error: %d \n", error); return -1; } // Save glyph information (slot contains the actual glyph bitmap). slot = face->glyph; rowSize = 0; glyphSize = 0; actualfontHeight = 0; // Find the width of the image. for (const wchar_t * ascii = characterSet; *ascii; ++ascii) { // Load glyph image into the slot (erase previous one) error = FT_Load_Char(face, *ascii, loadFlags); if (error) { LOG(1, "FT_Load_Char error : %d \n", error); } int bitmapRows = slot->bitmap.rows; actualfontHeight = (actualfontHeight < bitmapRows) ? bitmapRows : actualfontHeight; if (slot->bitmap.rows > slot->bitmap_top) { bitmapRows += (slot->bitmap.rows - slot->bitmap_top); } rowSize = (rowSize < bitmapRows) ? bitmapRows : rowSize; } // Have we found a pixel size that fits? if (rowSize <= (int)fontSize) { glyphSize = rowSize; rowSize = fontSize; break; } } if (slot == NULL || glyphSize == 0) { LOG(1, "Cannot generate a font of the requested size: %d\n", fontSize); return -1; } // Include padding in the rowSize. rowSize += GLYPH_PADDING; // Initialize with padding. int penX = 0; int penY = 0; int row = 0; double powerOf2 = 2; unsigned int imageWidth = 0; unsigned int imageHeight = 0; bool textureSizeFound = false; int advance; int i; while (textureSizeFound == false) { imageWidth = (unsigned int)pow(2.0, powerOf2); imageHeight = (unsigned int)pow(2.0, powerOf2); penX = 0; penY = 0; row = 0; // Find out the squared texture size that would fit all the require font glyphs. i = 0; // Find the width of the image. for (const wchar_t * ascii = characterSet; *ascii; ++ascii) { // Load glyph image into the slot (erase the previous one). error = FT_Load_Char(face, *ascii, loadFlags); if (error) { LOG(1, "FT_Load_Char error : %d \n", error); } // Glyph image. int glyphWidth = slot->bitmap.pitch; int glyphHeight = slot->bitmap.rows; advance = glyphWidth + GLYPH_PADDING; // If we reach the end of the image wrap aroud to the next row. if ((penX + advance) > (int)imageWidth) { penX = 0; row += 1; penY = row * rowSize; if (penY + rowSize > (int)imageHeight) { powerOf2++; break; } } // penY should include the glyph offsets. penY += (actualfontHeight - glyphHeight) + (glyphHeight - slot->bitmap_top); // Set the pen position for the next glyph penX += advance; // Move X to next glyph position // Move Y back to the top of the row. penY = row * rowSize; if (*(ascii + 1) == L'\0') { textureSizeFound = true; } i++; } } // Try further to find a tighter texture size. powerOf2 = 1; for (;;) { if ((penY + rowSize) >= pow(2.0, powerOf2)) { powerOf2++; } else { imageHeight = (int)pow(2.0, powerOf2); break; } } // Allocate temporary image buffer to draw the glyphs into. unsigned char* imageBuffer = (unsigned char*)malloc(imageWidth * imageHeight); memset(imageBuffer, 0, imageWidth * imageHeight); penX = 1; penY = 0; row = 0; i = 0; for (const wchar_t * ascii = characterSet; *ascii; ++ascii) { // Load glyph image into the slot (erase the previous one). error = FT_Load_Char(face, *ascii, loadFlags); if (error) { LOG(1, "FT_Load_Char error : %d \n", error); } // Glyph image. unsigned char* glyphBuffer = slot->bitmap.buffer; int glyphWidth = slot->bitmap.pitch; int glyphHeight = slot->bitmap.rows; advance = glyphWidth + GLYPH_PADDING; // If we reach the end of the image wrap aroud to the next row. if ((penX + advance) > (int)imageWidth) { penX = 1; row += 1; penY = row * rowSize; if (penY + rowSize > (int)imageHeight) { free(imageBuffer); LOG(1, "Image size exceeded!"); return -1; } } // penY should include the glyph offsets. penY += (actualfontHeight - glyphHeight) + (glyphHeight - slot->bitmap_top); // Draw the glyph to the bitmap with a one pixel padding. drawBitmap(imageBuffer, penX, penY, imageWidth, glyphBuffer, glyphWidth, glyphHeight); // Move Y back to the top of the row. penY = row * rowSize; glyphArray[i].index = *ascii; glyphArray[i].width = advance - GLYPH_PADDING; glyphArray[i].bearingX = slot->metrics.horiBearingX >> 6; glyphArray[i].advance = slot->metrics.horiAdvance >> 6; // Generate UV coords. glyphArray[i].uvCoords[0] = (float)penX / (float)imageWidth; glyphArray[i].uvCoords[1] = (float)penY / (float)imageHeight; glyphArray[i].uvCoords[2] = (float)(penX + advance - GLYPH_PADDING) / (float)imageWidth; glyphArray[i].uvCoords[3] = (float)(penY + rowSize - GLYPH_PADDING) / (float)imageHeight; // Set the pen position for the next glyph penX += advance; i++; } font->glyphSize = glyphSize; font->imageBuffer = imageBuffer; font->imageWidth = imageWidth; font->imageHeight = imageHeight; // get kerning pairs for font of specific size #if 0//def WIN32 HDC hDC = GetDC(NULL); //CreateDCA("DISPLAY", NULL, NULL, NULL); LOGFONTA fontStruct; memset(&fontStruct, 0, sizeof(fontStruct)); fontStruct.lfHeight = -(int)fontSize;// -MulDiv(actualfontHeight, GetDeviceCaps(hDC, LOGPIXELSY), 72); fontStruct.lfWeight = FW_DONTCARE; fontStruct.lfOutPrecision = OUT_OUTLINE_PRECIS; fontStruct.lfCharSet = DEFAULT_CHARSET; strcpy_s(fontStruct.lfFaceName, face->family_name); HFONT fnt = CreateFontIndirectA(&fontStruct); SelectObject(hDC, fnt); GetTextFaceA(hDC, 32, fontStruct.lfFaceName); DWORD numberOfKerningPairs = GetKerningPairs(hDC, INT_MAX, NULL); KERNINGPAIR * pairs = new KERNINGPAIR[numberOfKerningPairs]; GetKerningPairs(hDC, numberOfKerningPairs, pairs); for (unsigned int i = 0; i < numberOfKerningPairs; i++) { if (pairs[i].iKernAmount != 0 && wcschr(characterSet, pairs[i].wFirst) != NULL && wcschr(characterSet, pairs[i].wSecond) != NULL) font->kerningPairs.push_back(KerningPair{ pairs[i].wFirst, pairs[i].wSecond, pairs[i].iKernAmount }); } delete[] pairs; DeleteObject(fnt); //DeleteDC(hDC); #else for (const std::pair<wchar_t, wchar_t>& kernPair : kerningPairs) { FT_Vector kerning; if (FT_Get_Kerning(face, kernPair.first, kernPair.second, FT_KERNING_DEFAULT, &kerning) == 0 && (kerning.x >> 6) != 0) font->kerningPairs.push_back(KerningPair{ kernPair.first, kernPair.second, kerning.x >> 6 }); } #endif fonts.push_back(font); } #if 0//def WIN32 RemoveFontResourceExA(inFilePath, FR_PRIVATE, 0); #endif // File header and version. FILE *gpbFp = fopen(outFilePath, "wb"); char fileHeader[9] = {'\xAB', 'G', 'P', 'B', '\xBB', '\r', '\n', '\x1A', '\n'}; fwrite(fileHeader, sizeof(char), 9, gpbFp); fwrite(gameplay::GPB_VERSION, sizeof(char), 2, gpbFp); // Write Ref table (for a single font) writeUint(gpbFp, 1); // Ref[] count writeString(gpbFp, id); // Ref id writeUint(gpbFp, 128); // Ref type writeUint(gpbFp, ftell(gpbFp) + 4); // Ref offset (current pos + 4 bytes) // Family name. writeString(gpbFp, face->family_name); // Style. // TODO: Switch based on TTF style name and write appropriate font style unsigned int for now just hardcoding to 0 = PLAIN. writeUint(gpbFp, 0); // Number of included font sizes (GPB version 1.3+) writeUint(gpbFp, (unsigned int)fonts.size()); for (size_t i = 0, count = fonts.size(); i < count; ++i) { FontData* font = fonts[i]; // Font size (pixels). writeUint(gpbFp, font->fontSize); // Character set. TODO: Empty for now writeString(gpbFp, ""); // Glyphs. unsigned int glyphSetSize = wcslen( characterSet ); writeUint(gpbFp, glyphSetSize); for (unsigned int j = 0; j < glyphSetSize; j++) { writeUint(gpbFp, font->glyphArray[j].index); writeUint(gpbFp, font->glyphArray[j].width); fwrite(&font->glyphArray[j].bearingX, sizeof(int), 1, gpbFp); writeUint(gpbFp, font->glyphArray[j].advance); fwrite(&font->glyphArray[j].uvCoords, sizeof(float), 4, gpbFp); } // Image dimensions unsigned int imageSize = font->imageWidth * font->imageHeight; writeUint(gpbFp, font->imageWidth); writeUint(gpbFp, font->imageHeight); writeUint(gpbFp, imageSize); FILE* previewFp = NULL; std::string pgmFilePath; if (fontpreview) { // Save out a pgm monochome image file for preview std::ostringstream pgmFilePathStream; pgmFilePathStream << getFilenameNoExt(outFilePath) << "-" << font->fontSize << ".pgm"; pgmFilePath = pgmFilePathStream.str(); previewFp = fopen(pgmFilePath.c_str(), "wb"); fprintf(previewFp, "P5 %u %u 255\n", font->imageWidth, font->imageHeight); } if (fontFormat == Font::DISTANCE_FIELD) { // Flip height and width since the distance field map generator is column-wise. unsigned char* distanceFieldBuffer = createDistanceFields(font->imageBuffer, font->imageHeight, font->imageWidth); fwrite(distanceFieldBuffer, sizeof(unsigned char), imageSize, gpbFp); writeUint(gpbFp, Font::DISTANCE_FIELD); if (previewFp) { fwrite((const char*)distanceFieldBuffer, sizeof(unsigned char), imageSize, previewFp); fclose(previewFp); } free(distanceFieldBuffer); } else { fwrite(font->imageBuffer, sizeof(unsigned char), imageSize, gpbFp); writeUint(gpbFp, Font::BITMAP); if (previewFp) { fwrite((const char*)font->imageBuffer, sizeof(unsigned char), font->imageWidth * font->imageHeight, previewFp); fclose(previewFp); } } if (previewFp) { fclose(previewFp); LOG(1, "%s.pgm preview image created successfully. \n", getBaseName(pgmFilePath).c_str()); } } // Close file. fclose(gpbFp); LOG(1, "%s.gpb created successfully. \n", getBaseName(outFilePath).c_str()); for (size_t i = 0, count = fonts.size(); i < count; ++i) { delete fonts[i]; } FT_Done_Face(face); FT_Done_FreeType(library); return 0; } int writeFontFromImage(const char* inFilePath, const char* outFilePath, unsigned int fontSize, const char* id, const wchar_t * characterSet) { Image * image = Image::create( inFilePath ); if( image == NULL ) { LOG( 1, "Can't load image file: %s", inFilePath ); return -1; } Glyph * glyphArray = reinterpret_cast< Glyph * >( calloc( wcslen( characterSet ), sizeof( Glyph ) ) ); if( !glyphArray ) { LOG( 1, "Not enough stack memory to allocate glyphs." ); return -1; } if( image->getFormat( ) != Image::RGBA || image->getBpp( ) != 4 ) { delete image; LOG( 1, "Only RGBA images are supported." ); return -1; } unsigned width = image->getWidth( ); unsigned height = image->getHeight( ); unsigned charHeight = fontSize; unsigned long * data = reinterpret_cast< unsigned long * >( image->getData( ) ); unsigned long * scanline = data; unsigned long * oldscanline = scanline; unsigned long breakcolor = *scanline & 0x00ffffff; unsigned x = 0; unsigned y = 0; int glyphsCount = 0; while( *characterSet ) { wchar_t ch = *characterSet++; if( ch == L'\n' ) { scanline += width * charHeight; x = 0; y += charHeight; if( y >= height ) { delete image; LOG( 1, "Invalid image pixels data or character set." ); return -1; } oldscanline = scanline; } else if( ch != L'\r' ) { unsigned long * newscanline = oldscanline + 1; unsigned charWidth = 1; while( ( *newscanline & 0x00ffffff ) != breakcolor && x + charWidth < width ) { newscanline++; charWidth++; } oldscanline = newscanline; glyphArray[glyphsCount].index = ch; glyphArray[glyphsCount].width = charWidth; // Generate UV coords. glyphArray[glyphsCount].uvCoords[0] = (float)x / (float)width; glyphArray[glyphsCount].uvCoords[1] = (float)( y + 1 ) / (float)height; glyphArray[glyphsCount].uvCoords[2] = (float)( x + charWidth ) / (float)width; glyphArray[glyphsCount].uvCoords[3] = (float)( y + charHeight + 1 ) / (float)height; x += charWidth; glyphsCount++; } } FILE *gpbFp = fopen(outFilePath, "wb"); // File header and version. char fileHeader[9] = {'', 'G', 'P', 'B', '', '\r', '\n', '\x1A', '\n'}; fwrite(fileHeader, sizeof(char), 9, gpbFp); fwrite(gameplay::GPB_VERSION, sizeof(char), 2, gpbFp); // Write Ref table (for a single font) writeUint(gpbFp, 1); // Ref[] count writeString(gpbFp, id); // Ref id writeUint(gpbFp, 128); // Ref type writeUint(gpbFp, ftell(gpbFp) + 4); // Ref offset (current pos + 4 bytes) // Write Font object. // Family name. writeString(gpbFp, id); // Style. // TODO: Switch based on TTF style name and write appropriate font style unsigned int // For now just hardcoding to 0. //char* style = face->style_name; writeUint(gpbFp, 5); // 5 == TEXTURED // Font size. writeUint(gpbFp, charHeight); // Character set. // TODO: Empty for now writeString(gpbFp, "");//characterSet); // Glyphs. writeUint(gpbFp, glyphsCount); fwrite(glyphArray, sizeof(Glyph), glyphsCount, gpbFp); // Texture. unsigned int textureSize = width * height * 4; writeUint(gpbFp, width); writeUint(gpbFp, height); writeUint(gpbFp, textureSize); fwrite(image->getData( ), sizeof(unsigned char), textureSize, gpbFp); // Close file. fclose(gpbFp); delete image; LOG(1, "%s.gpb created successfully. \n", getBaseName(outFilePath).c_str()); return 0; } } fixed incorrect font's height calculation in encoder. the height was overestimated #include "Base.h" #include "TTFFontEncoder.h" #include "GPBFile.h" #include "StringUtil.h" #include "Image.h" #ifdef WIN32 #include <windows.h> #include <wingdi.h> #endif namespace gameplay { static void drawBitmap(unsigned char* dstBitmap, int x, int y, int dstWidth, unsigned char* srcBitmap, int srcWidth, int srcHeight) { // offset dst bitmap by x,y. dstBitmap += (x + (y * dstWidth)); for (int i = 0; i < srcHeight; ++i) { memcpy(dstBitmap, (const void*)srcBitmap, srcWidth); srcBitmap += srcWidth; dstBitmap += dstWidth; } } static void writeUint(FILE* fp, unsigned int i) { fwrite(&i, sizeof(unsigned int), 1, fp); } static void writeString(FILE* fp, const char* str) { unsigned int len = strlen(str); fwrite(&len, sizeof(unsigned int), 1, fp); if (len > 0) { fwrite(str, 1, len, fp); } } unsigned char* createDistanceFields(unsigned char* img, unsigned int width, unsigned int height) { short* xDistance = (short*)malloc(width * height * sizeof(short)); short* yDistance = (short*)malloc(width * height * sizeof(short)); double* gx = (double*)calloc(width * height, sizeof(double)); double* gy = (double*)calloc(width * height, sizeof(double)); double* data = (double*)calloc(width * height, sizeof(double)); double* outside = (double*)calloc(width * height, sizeof(double)); double* inside = (double*)calloc(width * height, sizeof(double)); unsigned int i; // Convert img into double (data) double imgMin = 255; double imgMax = -255; for (i = 0; i < width * height; ++i) { double v = img[i]; data[i] = v; if (v > imgMax) imgMax = v; if (v < imgMin) imgMin = v; } // Rescale image levels between 0 and 1 for (i = 0; i < width * height; ++i) { data[i] = (img[i] - imgMin) / imgMax; } // Compute outside = edtaa3(bitmap); % Transform background (0's) computegradient(data, width, height, gx, gy); edtaa3(data, gx, gy, height, width, xDistance, yDistance, outside); for (i = 0; i < width * height; ++i) { if (outside[i] < 0 ) outside[i] = 0.0; } // Compute inside = edtaa3(1-bitmap); % Transform foreground (1's) memset(gx, 0, sizeof(double) * width * height); memset(gy, 0, sizeof(double) * width * height); for (i = 0; i < width * height; ++i) { data[i] = 1 - data[i]; } computegradient(data, width, height, gx, gy); edtaa3(data, gx, gy, height, width, xDistance, yDistance, inside); for (i = 0; i < width * height; ++i) { if( inside[i] < 0 ) inside[i] = 0.0; } // distmap = outside - inside; % Bipolar distance field unsigned char* out = (unsigned char*)malloc(sizeof(unsigned char) * width * height); for (i = 0; i < width * height; ++i) { outside[i] -= inside[i]; outside[i] = 128 + outside[i] * 16; if (outside[i] < 0) outside[i] = 0; if (outside[i] > 255) outside[i] = 255; out[i] = 255 - (unsigned char) outside[i]; } free(xDistance); free(yDistance); free(gx); free(gy); free(data); free(outside); free(inside); return out; } struct KerningPair { wchar_t left; wchar_t right; int kerning; }; // Stores a single genreated font size to be written into the GPB struct FontData { // Array of glyphs for a font TTFGlyph * glyphArray; int fontSize; // Actual size of the underlying glyphs (may be different from fontSize) int glyphSize; // Font texture unsigned char* imageBuffer; unsigned int imageWidth; unsigned int imageHeight; // Kerning pairs std::vector<KerningPair> kerningPairs; FontData() : fontSize(0), glyphSize(0), imageBuffer(NULL), imageWidth(0), imageHeight(0) { } ~FontData() { if (imageBuffer) free(imageBuffer); } }; int writeFont(const char* inFilePath, const char* outFilePath, std::vector<unsigned int>& fontSizes, const char* id, bool fontpreview = false, Font::FontFormat fontFormat = Font::BITMAP, const wchar_t * characterSet = NULL) { // Initialize freetype library. FT_Library library; FT_Error error = FT_Init_FreeType(&library); if (error) { LOG(1, "FT_Init_FreeType error: %d \n", error); return -1; } // Initialize font face. FT_Face face; error = FT_New_Face(library, inFilePath, 0, &face); if (error) { LOG(1, "FT_New_Face error: %d \n", error); return -1; } std::vector<FontData*> fonts; if( characterSet == NULL || wcslen( characterSet ) == 0 ) { wchar_t * defaultSet = reinterpret_cast< wchar_t * >( calloc( END_INDEX - START_INDEX + 1, sizeof( wchar_t ) ) ); for( wchar_t ch = START_INDEX; ch < END_INDEX; ch++ ) defaultSet[ ch - START_INDEX ] = ch; defaultSet[ END_INDEX - START_INDEX] = NULL; characterSet = defaultSet; } // retrieve kerning pairs // freetype has no API to access kerning pairs table, // use brute-force attempt to retrieve all pair for current characters set std::vector<std::pair<wchar_t, wchar_t> > kerningPairs; // freetype has limited support processing kerning table for OTF fonts, it // retrieve data from the outdated 'kern' table instead of GPOS table. // Use MSDN functions to retrieve full kerning pairs and offsets #if 0//def WIN32 AddFontResourceExA(inFilePath, FR_PRIVATE, 0); #else for (const wchar_t * ascii1 = characterSet; *ascii1; ++ascii1) { for (const wchar_t * ascii2 = characterSet; *ascii2; ++ascii2) { FT_Vector out; if (FT_Get_Kerning(face, *ascii1, *ascii2, FT_KERNING_UNSCALED, &out) == 0 && out.x != 0) kerningPairs.push_back(std::make_pair(*ascii1, *ascii2)); } } #endif for (size_t fontIndex = 0, count = fontSizes.size(); fontIndex < count; ++fontIndex) { unsigned int fontSize = fontSizes[fontIndex]; FontData* font = new FontData(); font->fontSize = fontSize; font->glyphArray = reinterpret_cast<TTFGlyph *>(malloc(wcslen(characterSet) * sizeof(TTFGlyph))); if (!font->glyphArray) { LOG(1, "Not enough memory to allocate glyphs."); return -1; } TTFGlyph* glyphArray = font->glyphArray; int rowSize = 0; int glyphSize = 0; int actualfontHeight = 0; int maxTopY = 0; int minBottomY = 0; FT_GlyphSlot slot = NULL; FT_Int32 loadFlags = FT_LOAD_RENDER; // We want to generate fonts that fit exactly the requested pixels size. // Since free type (due to modern fonts) does not directly correlate requested // size to glyph size, we'll brute-force attempt to set the largest font size // possible that will fit within the requested pixel size. for (unsigned int requestedSize = fontSize; requestedSize > 0; --requestedSize) { // Set the pixel size. error = FT_Set_Char_Size(face, 0, requestedSize * 64, 0, 0); if (error) { LOG(1, "FT_Set_Pixel_Sizes error: %d \n", error); return -1; } // Save glyph information (slot contains the actual glyph bitmap). slot = face->glyph; rowSize = 0; glyphSize = 0; actualfontHeight = 0; maxTopY = 0; minBottomY = 0; // Find the width of the image. for (const wchar_t * ascii = characterSet; *ascii; ++ascii) { // Load glyph image into the slot (erase previous one) error = FT_Load_Char(face, *ascii, loadFlags); if (error) { LOG(1, "FT_Load_Char error : %d \n", error); } int bitmapRows = slot->bitmap.rows; actualfontHeight = (actualfontHeight < bitmapRows) ? bitmapRows : actualfontHeight; int topY = slot->bitmap_top; int bottomY = topY - bitmapRows; if (topY > maxTopY) maxTopY = topY; if (bottomY < minBottomY) minBottomY = bottomY; } rowSize = maxTopY - minBottomY; // Have we found a pixel size that fits? if (rowSize <= (int)fontSize) { glyphSize = rowSize; rowSize = fontSize; break; } } if (slot == NULL || glyphSize == 0) { LOG(1, "Cannot generate a font of the requested size: %d\n", fontSize); return -1; } // Include padding in the rowSize. rowSize += GLYPH_PADDING; // Initialize with padding. int penX = 0; int penY = 0; int row = 0; double powerOf2 = 2; unsigned int imageWidth = 0; unsigned int imageHeight = 0; bool textureSizeFound = false; int advance; int i; while (textureSizeFound == false) { imageWidth = (unsigned int)pow(2.0, powerOf2); imageHeight = (unsigned int)pow(2.0, powerOf2); penX = 0; penY = 0; row = 0; // Find out the squared texture size that would fit all the require font glyphs. i = 0; // Find the width of the image. for (const wchar_t * ascii = characterSet; *ascii; ++ascii) { // Load glyph image into the slot (erase the previous one). error = FT_Load_Char(face, *ascii, loadFlags); if (error) { LOG(1, "FT_Load_Char error : %d \n", error); } // Glyph image. int glyphWidth = slot->bitmap.pitch; int glyphHeight = slot->bitmap.rows; advance = glyphWidth + GLYPH_PADDING; // If we reach the end of the image wrap aroud to the next row. if ((penX + advance) > (int)imageWidth) { penX = 0; row += 1; penY = row * rowSize; if (penY + rowSize > (int)imageHeight) { powerOf2++; break; } } // Set the pen position for the next glyph penX += advance; // Move X to next glyph position // Move Y back to the top of the row. penY = row * rowSize; if (*(ascii + 1) == L'\0') { textureSizeFound = true; } i++; } } // Try further to find a tighter texture size. powerOf2 = 1; for (;;) { if ((penY + rowSize) >= pow(2.0, powerOf2)) { powerOf2++; } else { imageHeight = (int)pow(2.0, powerOf2); break; } } // Allocate temporary image buffer to draw the glyphs into. unsigned char* imageBuffer = (unsigned char*)malloc(imageWidth * imageHeight); memset(imageBuffer, 0, imageWidth * imageHeight); penX = 1; penY = 0; row = 0; i = 0; for (const wchar_t * ascii = characterSet; *ascii; ++ascii) { // Load glyph image into the slot (erase the previous one). error = FT_Load_Char(face, *ascii, loadFlags); if (error) { LOG(1, "FT_Load_Char error : %d \n", error); } // Glyph image. unsigned char* glyphBuffer = slot->bitmap.buffer; int glyphWidth = slot->bitmap.pitch; int glyphHeight = slot->bitmap.rows; advance = glyphWidth + GLYPH_PADDING; // If we reach the end of the image wrap aroud to the next row. if ((penX + advance) > (int)imageWidth) { penX = 1; row += 1; penY = row * rowSize; if (penY + rowSize > (int)imageHeight) { free(imageBuffer); LOG(1, "Image size exceeded!"); return -1; } } // move pen to baseline penY += maxTopY; // set pen now to the appropriate height of the drawn glyph penY -= slot->bitmap_top; // Draw the glyph to the bitmap with a one pixel padding. drawBitmap(imageBuffer, penX, penY, imageWidth, glyphBuffer, glyphWidth, glyphHeight); // Move Y back to the top of the row. penY = row * rowSize; glyphArray[i].index = *ascii; glyphArray[i].width = advance - GLYPH_PADDING; glyphArray[i].bearingX = slot->metrics.horiBearingX >> 6; glyphArray[i].advance = slot->metrics.horiAdvance >> 6; // Generate UV coords. glyphArray[i].uvCoords[0] = (float)penX / (float)imageWidth; glyphArray[i].uvCoords[1] = (float)penY / (float)imageHeight; glyphArray[i].uvCoords[2] = (float)(penX + advance - GLYPH_PADDING) / (float)imageWidth; glyphArray[i].uvCoords[3] = (float)(penY + rowSize - GLYPH_PADDING) / (float)imageHeight; // Set the pen position for the next glyph penX += advance; i++; } font->glyphSize = glyphSize; font->imageBuffer = imageBuffer; font->imageWidth = imageWidth; font->imageHeight = imageHeight; // get kerning pairs for font of specific size #if 0//def WIN32 HDC hDC = GetDC(NULL); //CreateDCA("DISPLAY", NULL, NULL, NULL); LOGFONTA fontStruct; memset(&fontStruct, 0, sizeof(fontStruct)); fontStruct.lfHeight = -(int)fontSize;// -MulDiv(actualfontHeight, GetDeviceCaps(hDC, LOGPIXELSY), 72); fontStruct.lfWeight = FW_DONTCARE; fontStruct.lfOutPrecision = OUT_OUTLINE_PRECIS; fontStruct.lfCharSet = DEFAULT_CHARSET; strcpy_s(fontStruct.lfFaceName, face->family_name); HFONT fnt = CreateFontIndirectA(&fontStruct); SelectObject(hDC, fnt); GetTextFaceA(hDC, 32, fontStruct.lfFaceName); DWORD numberOfKerningPairs = GetKerningPairs(hDC, INT_MAX, NULL); KERNINGPAIR * pairs = new KERNINGPAIR[numberOfKerningPairs]; GetKerningPairs(hDC, numberOfKerningPairs, pairs); for (unsigned int i = 0; i < numberOfKerningPairs; i++) { if (pairs[i].iKernAmount != 0 && wcschr(characterSet, pairs[i].wFirst) != NULL && wcschr(characterSet, pairs[i].wSecond) != NULL) font->kerningPairs.push_back(KerningPair{ pairs[i].wFirst, pairs[i].wSecond, pairs[i].iKernAmount }); } delete[] pairs; DeleteObject(fnt); //DeleteDC(hDC); #else for (const std::pair<wchar_t, wchar_t>& kernPair : kerningPairs) { FT_Vector kerning; if (FT_Get_Kerning(face, kernPair.first, kernPair.second, FT_KERNING_DEFAULT, &kerning) == 0 && (kerning.x >> 6) != 0) font->kerningPairs.push_back(KerningPair{ kernPair.first, kernPair.second, kerning.x >> 6 }); } #endif fonts.push_back(font); } #if 0//def WIN32 RemoveFontResourceExA(inFilePath, FR_PRIVATE, 0); #endif // File header and version. FILE *gpbFp = fopen(outFilePath, "wb"); char fileHeader[9] = {'\xAB', 'G', 'P', 'B', '\xBB', '\r', '\n', '\x1A', '\n'}; fwrite(fileHeader, sizeof(char), 9, gpbFp); fwrite(gameplay::GPB_VERSION, sizeof(char), 2, gpbFp); // Write Ref table (for a single font) writeUint(gpbFp, 1); // Ref[] count writeString(gpbFp, id); // Ref id writeUint(gpbFp, 128); // Ref type writeUint(gpbFp, ftell(gpbFp) + 4); // Ref offset (current pos + 4 bytes) // Family name. writeString(gpbFp, face->family_name); // Style. // TODO: Switch based on TTF style name and write appropriate font style unsigned int for now just hardcoding to 0 = PLAIN. writeUint(gpbFp, 0); // Number of included font sizes (GPB version 1.3+) writeUint(gpbFp, (unsigned int)fonts.size()); for (size_t i = 0, count = fonts.size(); i < count; ++i) { FontData* font = fonts[i]; // Font size (pixels). writeUint(gpbFp, font->fontSize); // Character set. TODO: Empty for now writeString(gpbFp, ""); // Glyphs. unsigned int glyphSetSize = wcslen( characterSet ); writeUint(gpbFp, glyphSetSize); for (unsigned int j = 0; j < glyphSetSize; j++) { writeUint(gpbFp, font->glyphArray[j].index); writeUint(gpbFp, font->glyphArray[j].width); fwrite(&font->glyphArray[j].bearingX, sizeof(int), 1, gpbFp); writeUint(gpbFp, font->glyphArray[j].advance); fwrite(&font->glyphArray[j].uvCoords, sizeof(float), 4, gpbFp); } // Image dimensions unsigned int imageSize = font->imageWidth * font->imageHeight; writeUint(gpbFp, font->imageWidth); writeUint(gpbFp, font->imageHeight); writeUint(gpbFp, imageSize); FILE* previewFp = NULL; std::string pgmFilePath; if (fontpreview) { // Save out a pgm monochome image file for preview std::ostringstream pgmFilePathStream; pgmFilePathStream << getFilenameNoExt(outFilePath) << "-" << font->fontSize << ".pgm"; pgmFilePath = pgmFilePathStream.str(); previewFp = fopen(pgmFilePath.c_str(), "wb"); fprintf(previewFp, "P5 %u %u 255\n", font->imageWidth, font->imageHeight); } if (fontFormat == Font::DISTANCE_FIELD) { // Flip height and width since the distance field map generator is column-wise. unsigned char* distanceFieldBuffer = createDistanceFields(font->imageBuffer, font->imageHeight, font->imageWidth); fwrite(distanceFieldBuffer, sizeof(unsigned char), imageSize, gpbFp); writeUint(gpbFp, Font::DISTANCE_FIELD); if (previewFp) { fwrite((const char*)distanceFieldBuffer, sizeof(unsigned char), imageSize, previewFp); fclose(previewFp); } free(distanceFieldBuffer); } else { fwrite(font->imageBuffer, sizeof(unsigned char), imageSize, gpbFp); writeUint(gpbFp, Font::BITMAP); if (previewFp) { fwrite((const char*)font->imageBuffer, sizeof(unsigned char), font->imageWidth * font->imageHeight, previewFp); fclose(previewFp); } } if (previewFp) { fclose(previewFp); LOG(1, "%s.pgm preview image created successfully. \n", getBaseName(pgmFilePath).c_str()); } } // Close file. fclose(gpbFp); LOG(1, "%s.gpb created successfully. \n", getBaseName(outFilePath).c_str()); for (size_t i = 0, count = fonts.size(); i < count; ++i) { delete fonts[i]; } FT_Done_Face(face); FT_Done_FreeType(library); return 0; } int writeFontFromImage(const char* inFilePath, const char* outFilePath, unsigned int fontSize, const char* id, const wchar_t * characterSet) { Image * image = Image::create( inFilePath ); if( image == NULL ) { LOG( 1, "Can't load image file: %s", inFilePath ); return -1; } Glyph * glyphArray = reinterpret_cast< Glyph * >( calloc( wcslen( characterSet ), sizeof( Glyph ) ) ); if( !glyphArray ) { LOG( 1, "Not enough stack memory to allocate glyphs." ); return -1; } if( image->getFormat( ) != Image::RGBA || image->getBpp( ) != 4 ) { delete image; LOG( 1, "Only RGBA images are supported." ); return -1; } unsigned width = image->getWidth( ); unsigned height = image->getHeight( ); unsigned charHeight = fontSize; unsigned long * data = reinterpret_cast< unsigned long * >( image->getData( ) ); unsigned long * scanline = data; unsigned long * oldscanline = scanline; unsigned long breakcolor = *scanline & 0x00ffffff; unsigned x = 0; unsigned y = 0; int glyphsCount = 0; while( *characterSet ) { wchar_t ch = *characterSet++; if( ch == L'\n' ) { scanline += width * charHeight; x = 0; y += charHeight; if( y >= height ) { delete image; LOG( 1, "Invalid image pixels data or character set." ); return -1; } oldscanline = scanline; } else if( ch != L'\r' ) { unsigned long * newscanline = oldscanline + 1; unsigned charWidth = 1; while( ( *newscanline & 0x00ffffff ) != breakcolor && x + charWidth < width ) { newscanline++; charWidth++; } oldscanline = newscanline; glyphArray[glyphsCount].index = ch; glyphArray[glyphsCount].width = charWidth; // Generate UV coords. glyphArray[glyphsCount].uvCoords[0] = (float)x / (float)width; glyphArray[glyphsCount].uvCoords[1] = (float)( y + 1 ) / (float)height; glyphArray[glyphsCount].uvCoords[2] = (float)( x + charWidth ) / (float)width; glyphArray[glyphsCount].uvCoords[3] = (float)( y + charHeight + 1 ) / (float)height; x += charWidth; glyphsCount++; } } FILE *gpbFp = fopen(outFilePath, "wb"); // File header and version. char fileHeader[9] = {'', 'G', 'P', 'B', '', '\r', '\n', '\x1A', '\n'}; fwrite(fileHeader, sizeof(char), 9, gpbFp); fwrite(gameplay::GPB_VERSION, sizeof(char), 2, gpbFp); // Write Ref table (for a single font) writeUint(gpbFp, 1); // Ref[] count writeString(gpbFp, id); // Ref id writeUint(gpbFp, 128); // Ref type writeUint(gpbFp, ftell(gpbFp) + 4); // Ref offset (current pos + 4 bytes) // Write Font object. // Family name. writeString(gpbFp, id); // Style. // TODO: Switch based on TTF style name and write appropriate font style unsigned int // For now just hardcoding to 0. //char* style = face->style_name; writeUint(gpbFp, 5); // 5 == TEXTURED // Font size. writeUint(gpbFp, charHeight); // Character set. // TODO: Empty for now writeString(gpbFp, "");//characterSet); // Glyphs. writeUint(gpbFp, glyphsCount); fwrite(glyphArray, sizeof(Glyph), glyphsCount, gpbFp); // Texture. unsigned int textureSize = width * height * 4; writeUint(gpbFp, width); writeUint(gpbFp, height); writeUint(gpbFp, textureSize); fwrite(image->getData( ), sizeof(unsigned char), textureSize, gpbFp); // Close file. fclose(gpbFp); delete image; LOG(1, "%s.gpb created successfully. \n", getBaseName(outFilePath).c_str()); return 0; } }
//////////////////////////////////////////////////////////////////////////////////////////////// /// /// @file /// @author Kuba Sejdak /// @date 21.07.2016 /// /// @copyright This file is a part of cosmos OS. All rights reserved. /// //////////////////////////////////////////////////////////////////////////////////////////////// #include "buddy_allocator.h" #include "pagepool_dynamic.h" #include "pagepool_static.h" #include <hal/mmu.h> #include <os/assert.h> using namespace HAL; namespace Memory { static const uint32_t MEMORY_CHUNK_MAGIC = 0x08081990; MemoryChunk::MemoryChunk() : m_magic(0) , m_virtualAddress(0) , m_size(0) , m_parentPage(nullptr) { } bool MemoryChunk::checkMagic() { return (m_magic == MEMORY_CHUNK_MAGIC); } uint32_t MemoryChunk::virtualAddress() { return m_virtualAddress; } void* MemoryChunk::data() { return reinterpret_cast<void*>(m_virtualAddress + sizeof(MemoryChunk)); } uint16_t MemoryChunk::size() { return m_size; } Page* MemoryChunk::parentPage() { return m_parentPage; } void MemoryChunk::init(Page* parentPage) { m_magic = MEMORY_CHUNK_MAGIC; m_parentPage = parentPage; } void MemoryChunk::setVirtualAddress(uint32_t virtualAddress) { m_virtualAddress = virtualAddress; } void MemoryChunk::setSize(uint32_t size) { m_size = size; } os::pair<MemoryChunk, MemoryChunk> MemoryChunk::split() { uint32_t newSize = m_size / 2; MemoryChunk* first = reinterpret_cast<MemoryChunk*>(m_virtualAddress); first->init(m_parentPage); first->setVirtualAddress(m_virtualAddress); first->setSize(newSize); MemoryChunk* second = reinterpret_cast<MemoryChunk*>(m_virtualAddress + newSize); second->init(m_parentPage); first->setVirtualAddress(m_virtualAddress + newSize); second->setSize(newSize); return os::pair<MemoryChunk, MemoryChunk>(first, second); } void IAllocator::init() { static StaticPagePool staticPool; static BuddyAllocator staticBuddy(&staticPool); staticAllocator = &staticBuddy; static DynamicPagePool dynamicPool; static BuddyAllocator dynamicBuddy(&dynamicPool); dynamicAllocator = &dynamicBuddy; } BuddyAllocator::BuddyAllocator(IPagePool* pagePool) : IAllocator(pagePool) { } void* BuddyAllocator::allocate(uint32_t size) { if (size == 0) return nullptr; uint32_t requiredSize = size + sizeof(MemoryChunk); int factor = sizeToFactor(requiredSize); while (true) { // Find proper chunk from the free chunks list. bool chunkAvailable = false; for (int i = factor; i < MEMORY_CHUNK_FACTOR; ++i) { if (m_freeChunks[i].size() == 0) { // There is no chunk with given factor. continue; } if (factorToSize(i) / 2 >= requiredSize) { // Smallest suitable chunk can be splitted to avoid fragmentation. splitChunk(m_freeChunks[i].front()); chunkAvailable = true; break; } // Proper chunk found. return m_freeChunks[i].pop_front()->data(); } if (chunkAvailable) continue; // No suitable chunk was found. Allocate new page. if (!allocatePage()) return nullptr; } return nullptr; } void BuddyAllocator::release(void *memoryChunk) { if (memoryChunk == nullptr) return; MemoryChunk* chunk = reinterpret_cast<MemoryChunk*>((char*) memoryChunk - sizeof(MemoryChunk)); assert(chunk->checkMagic()); } bool BuddyAllocator::allocatePage() { auto page = m_pagePool->allocatePages(1); if (page.size() == 0) return false; /// @todo Map this page into kernel address space. // void* pageVirtualAddress = IMMU::map(page.front()); void* pageVirtualAddress = reinterpret_cast<void*>(page.front()->physicalAddress()); MemoryChunk* newChunk = reinterpret_cast<MemoryChunk*>(pageVirtualAddress); newChunk->init(page.front()); newChunk->setVirtualAddress((uint32_t) pageVirtualAddress); newChunk->setSize(IMMU::pageSize()); // Insert this chunk to the list of free chunks. m_freeChunks[sizeToFactor(newChunk->size())].push_back(newChunk); return true; } int BuddyAllocator::sizeToFactor(uint32_t size) { for (int i = 0; i < MEMORY_CHUNK_FACTOR; ++i) { if (factorToSize(i) >= size) return i; } return -1; } uint32_t BuddyAllocator::factorToSize(int factor) { return (1 << factor); } void BuddyAllocator::splitChunk(MemoryChunk* chunk) { int factor = sizeToFactor(chunk->size()); int index = m_freeChunks[factor].indexOf(chunk); assert(index != -1); auto chunkHalfs = chunk->split(); m_freeChunks[factor].remove(index); m_freeChunks[factor - 1].push_back(chunkHalfs.first()); m_freeChunks[factor - 1].push_back(chunkHalfs.second()); } } // namespace Memory Add initializing page pools when allocator is itnialized. //////////////////////////////////////////////////////////////////////////////////////////////// /// /// @file /// @author Kuba Sejdak /// @date 21.07.2016 /// /// @copyright This file is a part of cosmos OS. All rights reserved. /// //////////////////////////////////////////////////////////////////////////////////////////////// #include "buddy_allocator.h" #include "pagepool_dynamic.h" #include "pagepool_static.h" #include <hal/mmu.h> #include <os/assert.h> using namespace HAL; namespace Memory { static const uint32_t MEMORY_CHUNK_MAGIC = 0x08081990; MemoryChunk::MemoryChunk() : m_magic(0) , m_virtualAddress(0) , m_size(0) , m_parentPage(nullptr) { } bool MemoryChunk::checkMagic() { return (m_magic == MEMORY_CHUNK_MAGIC); } uint32_t MemoryChunk::virtualAddress() { return m_virtualAddress; } void* MemoryChunk::data() { return reinterpret_cast<void*>(m_virtualAddress + sizeof(MemoryChunk)); } uint16_t MemoryChunk::size() { return m_size; } Page* MemoryChunk::parentPage() { return m_parentPage; } void MemoryChunk::init(Page* parentPage) { m_magic = MEMORY_CHUNK_MAGIC; m_parentPage = parentPage; } void MemoryChunk::setVirtualAddress(uint32_t virtualAddress) { m_virtualAddress = virtualAddress; } void MemoryChunk::setSize(uint32_t size) { m_size = size; } os::pair<MemoryChunk, MemoryChunk> MemoryChunk::split() { uint32_t newSize = m_size / 2; MemoryChunk* first = reinterpret_cast<MemoryChunk*>(m_virtualAddress); first->init(m_parentPage); first->setVirtualAddress(m_virtualAddress); first->setSize(newSize); MemoryChunk* second = reinterpret_cast<MemoryChunk*>(m_virtualAddress + newSize); second->init(m_parentPage); first->setVirtualAddress(m_virtualAddress + newSize); second->setSize(newSize); return os::pair<MemoryChunk, MemoryChunk>(first, second); } void IAllocator::init() { static StaticPagePool staticPool; staticPool.init(); static BuddyAllocator staticBuddy(&staticPool); staticAllocator = &staticBuddy; static DynamicPagePool dynamicPool; dynamicPool.init(); static BuddyAllocator dynamicBuddy(&dynamicPool); dynamicAllocator = &dynamicBuddy; } BuddyAllocator::BuddyAllocator(IPagePool* pagePool) : IAllocator(pagePool) { } void* BuddyAllocator::allocate(uint32_t size) { if (size == 0) return nullptr; uint32_t requiredSize = size + sizeof(MemoryChunk); int factor = sizeToFactor(requiredSize); while (true) { // Find proper chunk from the free chunks list. bool chunkAvailable = false; for (int i = factor; i < MEMORY_CHUNK_FACTOR; ++i) { if (m_freeChunks[i].size() == 0) { // There is no chunk with given factor. continue; } if (factorToSize(i) / 2 >= requiredSize) { // Smallest suitable chunk can be splitted to avoid fragmentation. splitChunk(m_freeChunks[i].front()); chunkAvailable = true; break; } // Proper chunk found. return m_freeChunks[i].pop_front()->data(); } if (chunkAvailable) continue; // No suitable chunk was found. Allocate new page. if (!allocatePage()) return nullptr; } return nullptr; } void BuddyAllocator::release(void *memoryChunk) { if (memoryChunk == nullptr) return; MemoryChunk* chunk = reinterpret_cast<MemoryChunk*>((char*) memoryChunk - sizeof(MemoryChunk)); assert(chunk->checkMagic()); } bool BuddyAllocator::allocatePage() { auto page = m_pagePool->allocatePages(1); if (page.size() == 0) return false; /// @todo Map this page into kernel address space. // void* pageVirtualAddress = IMMU::map(page.front()); void* pageVirtualAddress = reinterpret_cast<void*>(page.front()->physicalAddress()); MemoryChunk* newChunk = reinterpret_cast<MemoryChunk*>(pageVirtualAddress); newChunk->init(page.front()); newChunk->setVirtualAddress((uint32_t) pageVirtualAddress); newChunk->setSize(IMMU::pageSize()); // Insert this chunk to the list of free chunks. m_freeChunks[sizeToFactor(newChunk->size())].push_back(newChunk); return true; } int BuddyAllocator::sizeToFactor(uint32_t size) { for (int i = 0; i < MEMORY_CHUNK_FACTOR; ++i) { if (factorToSize(i) >= size) return i; } return -1; } uint32_t BuddyAllocator::factorToSize(int factor) { return (1 << factor); } void BuddyAllocator::splitChunk(MemoryChunk* chunk) { int factor = sizeToFactor(chunk->size()); int index = m_freeChunks[factor].indexOf(chunk); assert(index != -1); auto chunkHalfs = chunk->split(); m_freeChunks[factor].remove(index); m_freeChunks[factor - 1].push_back(chunkHalfs.first()); m_freeChunks[factor - 1].push_back(chunkHalfs.second()); } } // namespace Memory
/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkHistogramImageToImageMetricTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #include "itkGaussianImageSource.h" #include "itkImage.h" #include "itkLinearInterpolateImageFunction.h" #include "itkMeanSquaresHistogramImageToImageMetric.h" #include "itkTranslationTransform.h" int itkHistogramImageToImageMetricTest(int , char*[] ) { // Create two simple images. const unsigned int ImageDimension = 2; typedef double PixelType; typedef double CoordinateRepresentationType; //Allocate Images typedef itk::Image<PixelType,ImageDimension> MovingImageType; typedef itk::Image<PixelType,ImageDimension> FixedImageType; // Declare Gaussian Sources typedef itk::GaussianImageSource<MovingImageType> MovingImageSourceType; typedef itk::GaussianImageSource<FixedImageType> FixedImageSourceType; typedef MovingImageSourceType::Pointer MovingImageSourcePointer; typedef FixedImageSourceType::Pointer FixedImageSourcePointer; // Note: the following declarations are classical arrays unsigned long fixedImageSize[] = {100, 100}; unsigned long movingImageSize[] = {100, 100}; float fixedImageSpacing[] = {1.0f, 1.0f}; float movingImageSpacing[] = {1.0f, 1.0f}; float fixedImageOrigin[] = {0.0f, 0.0f}; float movingImageOrigin[] = {0.0f, 0.0f}; MovingImageSourceType::Pointer movingImageSource = MovingImageSourceType::New(); FixedImageSourceType::Pointer fixedImageSource = FixedImageSourceType::New(); movingImageSource->SetSize(movingImageSize); movingImageSource->SetOrigin(movingImageOrigin); movingImageSource->SetSpacing(movingImageSpacing); movingImageSource->SetNormalized(false); movingImageSource->SetScale(250.0f); fixedImageSource->SetSize(fixedImageSize); fixedImageSource->SetOrigin(fixedImageOrigin); fixedImageSource->SetSpacing(fixedImageSpacing); fixedImageSource->SetNormalized(false); fixedImageSource->SetScale(250.0f); movingImageSource->Update(); // Force the filter to run fixedImageSource->Update(); // Force the filter to run MovingImageType::Pointer movingImage = movingImageSource->GetOutput(); FixedImageType::Pointer fixedImage = fixedImageSource->GetOutput(); // Set up the metric. typedef itk::MeanSquaresHistogramImageToImageMetric<FixedImageType, MovingImageType> MetricType; typedef MetricType::TransformType TransformBaseType; typedef MetricType::ScalesType ScalesType; typedef MetricType::DerivativeType DerivativeType; typedef TransformBaseType::ParametersType ParametersType; MetricType::Pointer metric = MetricType::New(); unsigned int nBins = 256; MetricType::HistogramType::SizeType histSize; histSize[0] = nBins; histSize[1] = nBins; metric->SetHistogramSize(histSize); // Plug the images into the metric. metric->SetFixedImage(fixedImage); metric->SetMovingImage(movingImage); // Set up a transform. typedef itk::TranslationTransform<CoordinateRepresentationType, ImageDimension> TransformType; TransformType::Pointer transform = TransformType::New(); metric->SetTransform(transform.GetPointer()); // Set up an interpolator. typedef itk::LinearInterpolateImageFunction<MovingImageType, double> InterpolatorType; InterpolatorType::Pointer interpolator = InterpolatorType::New(); interpolator->SetInputImage(movingImage.GetPointer()); metric->SetInterpolator(interpolator.GetPointer()); // Define the region over which the metric will be computed. metric->SetFixedImageRegion(fixedImage->GetBufferedRegion()); // Set up transform parameters. const unsigned int numberOfParameters = transform->GetNumberOfParameters(); ParametersType parameters( numberOfParameters ); for (unsigned int k = 0; k < numberOfParameters; k++) { parameters[k] = 0.0; } // Set scales for derivative calculation. ScalesType scales( numberOfParameters ); for (unsigned int k = 0; k < numberOfParameters; k++) { scales[k] = 1; } const double STEP_LENGTH = 0.001; metric->SetDerivativeStepLength(STEP_LENGTH); metric->SetDerivativeStepLengthScales(scales); try { // Initialize the metric. metric->Initialize(); // Test SetPaddingValue() and GetPaddingValue(). metric->SetPaddingValue(-1); metric->SetUsePaddingValue(true); if (metric->GetPaddingValue() != -1) { std::cerr << "Incorrect padding value." << std::endl; return EXIT_FAILURE; } // Check to make sure the returned histogram size is the same as histSize. if (histSize != metric->GetHistogramSize()) { std::cout << "Incorrect histogram size." << std::endl; return EXIT_FAILURE; } // Check GetDerivativeStepLength(). if (metric->GetDerivativeStepLength() != STEP_LENGTH) { std::cout << "Incorrect derivative step length." << std::endl; return EXIT_FAILURE; } // Check GetDerivativeStepLengthScales(). if (metric->GetDerivativeStepLengthScales() != scales) { std::cout << "Incorrect scales." << std::endl; return EXIT_FAILURE; } // Do some work DerivativeType derivatives( numberOfParameters ); MetricType::MeasureType value; for (double y = -50.0; y <= 50.0; y += 25.0) { parameters[1] = y; for (double x = -50.0; x <= 50.0; x += 25.0) { parameters[0] = x; metric->GetValueAndDerivative (parameters, value, derivatives); std::cout << "Parameters: " << parameters << ", Value: " << value << ", Derivatives: " << derivatives << std::endl; } } // Exercise Print() method. metric->Print(std::cout); std::cout << "Test passed." << std::endl; } catch (itk::ExceptionObject& ex) { std::cerr << "Exception caught!" << std::endl; std::cerr << ex << std::endl; return EXIT_FAILURE; } // Force an exception try { ParametersType parameters( 2 ); DerivativeType derivatives( 2 ); ScalesType badScales( 1 ); metric->SetDerivativeStepLengthScales(badScales); metric->Initialize(); metric->GetDerivative (parameters, derivatives); } catch (itk::ExceptionObject &ex) { std::cerr << "Expected exception caught!" << std::endl; std::cerr << ex << std::endl; return EXIT_SUCCESS; } return EXIT_FAILURE; } ENH: Exposing the Lower and Upper bounds of the Histogram as options to be set from the API of the metric. This allows to focus the registration on regions having pixels with a particular range of intensities. /*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkHistogramImageToImageMetricTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #include "itkGaussianImageSource.h" #include "itkImage.h" #include "itkLinearInterpolateImageFunction.h" #include "itkMeanSquaresHistogramImageToImageMetric.h" #include "itkTranslationTransform.h" int itkHistogramImageToImageMetricTest(int , char*[] ) { // Create two simple images. const unsigned int ImageDimension = 2; typedef double PixelType; typedef double CoordinateRepresentationType; //Allocate Images typedef itk::Image<PixelType,ImageDimension> MovingImageType; typedef itk::Image<PixelType,ImageDimension> FixedImageType; // Declare Gaussian Sources typedef itk::GaussianImageSource<MovingImageType> MovingImageSourceType; typedef itk::GaussianImageSource<FixedImageType> FixedImageSourceType; typedef MovingImageSourceType::Pointer MovingImageSourcePointer; typedef FixedImageSourceType::Pointer FixedImageSourcePointer; // Note: the following declarations are classical arrays unsigned long fixedImageSize[] = {100, 100}; unsigned long movingImageSize[] = {100, 100}; float fixedImageSpacing[] = {1.0f, 1.0f}; float movingImageSpacing[] = {1.0f, 1.0f}; float fixedImageOrigin[] = {0.0f, 0.0f}; float movingImageOrigin[] = {0.0f, 0.0f}; MovingImageSourceType::Pointer movingImageSource = MovingImageSourceType::New(); FixedImageSourceType::Pointer fixedImageSource = FixedImageSourceType::New(); movingImageSource->SetSize(movingImageSize); movingImageSource->SetOrigin(movingImageOrigin); movingImageSource->SetSpacing(movingImageSpacing); movingImageSource->SetNormalized(false); movingImageSource->SetScale(250.0f); fixedImageSource->SetSize(fixedImageSize); fixedImageSource->SetOrigin(fixedImageOrigin); fixedImageSource->SetSpacing(fixedImageSpacing); fixedImageSource->SetNormalized(false); fixedImageSource->SetScale(250.0f); movingImageSource->Update(); // Force the filter to run fixedImageSource->Update(); // Force the filter to run MovingImageType::Pointer movingImage = movingImageSource->GetOutput(); FixedImageType::Pointer fixedImage = fixedImageSource->GetOutput(); // Set up the metric. typedef itk::MeanSquaresHistogramImageToImageMetric<FixedImageType, MovingImageType> MetricType; typedef MetricType::TransformType TransformBaseType; typedef MetricType::ScalesType ScalesType; typedef MetricType::DerivativeType DerivativeType; typedef TransformBaseType::ParametersType ParametersType; MetricType::Pointer metric = MetricType::New(); unsigned int nBins = 256; MetricType::HistogramType::SizeType histSize; histSize[0] = nBins; histSize[1] = nBins; metric->SetHistogramSize(histSize); // Plug the images into the metric. metric->SetFixedImage(fixedImage); metric->SetMovingImage(movingImage); // Set up a transform. typedef itk::TranslationTransform<CoordinateRepresentationType, ImageDimension> TransformType; TransformType::Pointer transform = TransformType::New(); metric->SetTransform(transform.GetPointer()); // Set up an interpolator. typedef itk::LinearInterpolateImageFunction<MovingImageType, double> InterpolatorType; InterpolatorType::Pointer interpolator = InterpolatorType::New(); interpolator->SetInputImage(movingImage.GetPointer()); metric->SetInterpolator(interpolator.GetPointer()); // Define the region over which the metric will be computed. metric->SetFixedImageRegion(fixedImage->GetBufferedRegion()); // Set up transform parameters. const unsigned int numberOfParameters = transform->GetNumberOfParameters(); ParametersType parameters( numberOfParameters ); for (unsigned int k = 0; k < numberOfParameters; k++) { parameters[k] = 0.0; } // Set scales for derivative calculation. ScalesType scales( numberOfParameters ); for (unsigned int k = 0; k < numberOfParameters; k++) { scales[k] = 1; } const double STEP_LENGTH = 0.001; metric->SetDerivativeStepLength(STEP_LENGTH); metric->SetDerivativeStepLengthScales(scales); try { // Initialize the metric. metric->Initialize(); // Test SetPaddingValue() and GetPaddingValue(). metric->SetPaddingValue(-1); metric->SetUsePaddingValue(true); if (metric->GetPaddingValue() != -1) { std::cerr << "Incorrect padding value." << std::endl; return EXIT_FAILURE; } // Check to make sure the returned histogram size is the same as histSize. if (histSize != metric->GetHistogramSize()) { std::cout << "Incorrect histogram size." << std::endl; return EXIT_FAILURE; } // Check GetDerivativeStepLength(). if (metric->GetDerivativeStepLength() != STEP_LENGTH) { std::cout << "Incorrect derivative step length." << std::endl; return EXIT_FAILURE; } // Check GetDerivativeStepLengthScales(). if (metric->GetDerivativeStepLengthScales() != scales) { std::cout << "Incorrect scales." << std::endl; return EXIT_FAILURE; } // Do some work DerivativeType derivatives( numberOfParameters ); MetricType::MeasureType value; for (double y = -50.0; y <= 50.0; y += 25.0) { parameters[1] = y; for (double x = -50.0; x <= 50.0; x += 25.0) { parameters[0] = x; metric->GetValueAndDerivative (parameters, value, derivatives); std::cout << "Parameters: " << parameters << ", Value: " << value << ", Derivatives: " << derivatives << std::endl; } } // Exercise Print() method. metric->Print(std::cout); std::cout << "Test passed." << std::endl; } catch (itk::ExceptionObject& ex) { std::cerr << "Exception caught!" << std::endl; std::cerr << ex << std::endl; return EXIT_FAILURE; } std::cout << "Exercise the SetLowerBound() and SetUpperBound() methods " << std::endl; MetricType::MeasurementVectorType lowerBound; MetricType::MeasurementVectorType upperBound; metric->SetLowerBound( lowerBound ); metric->SetUpperBound( upperBound ); try { // Initialize the metric. metric->Initialize(); // Exercise Print() method. metric->Print(std::cout); std::cout << "Test passed." << std::endl; } catch (itk::ExceptionObject& ex) { std::cerr << "Exception caught!" << std::endl; std::cerr << ex << std::endl; return EXIT_FAILURE; } // Force an exception try { ParametersType parameters( 2 ); DerivativeType derivatives( 2 ); ScalesType badScales( 1 ); metric->SetDerivativeStepLengthScales(badScales); metric->Initialize(); metric->GetDerivative (parameters, derivatives); } catch (itk::ExceptionObject &ex) { std::cerr << "Expected exception caught!" << std::endl; std::cerr << ex << std::endl; return EXIT_SUCCESS; } return EXIT_FAILURE; }
#include "ride/project.h" #include <wx/utils.h> #include <wx/process.h> #include <wx/txtstrm.h> #include <wx/filename.h> #include "ride/wxutils.h" #include "ride/mainwindow.h" #include "settings.pb.h" #include "ride/proto.h" #include <wx/choicdlg.h> Project::Project(MainWindow* output, const wxString& root_folder) : main_(output), root_folder_(root_folder) { if (root_folder_.IsEmpty() == false) { if (LoadProto(&project_, GetProjectFile()) == false) { } if (project_.build_settings_size() == 0) { // add default build settings to the project ride::BuildSetting* debug = project_.add_build_settings(); debug->set_name("Debug"); debug->set_release(false); ride::BuildSetting* release = project_.add_build_settings(); release->set_name("Release"); release->set_release(true); } if (LoadProto(&user_, GetUserFile()) == false) { } // validate project file GetCurrentBuildSetting(); } } Project::~Project() { Save(); } const wxString& Project::root_folder() const { return root_folder_; } bool Project::Save() { if (root_folder_.IsEmpty() ) return false; bool project_saved = SaveProto(&project_, GetProjectFile()); bool user_saved = SaveUser(); return project_saved && user_saved; } int Project::tabwidth() const { return project_.tabwidth(); } bool Project::usetabs() const { return project_.usetabs(); } void Project::set_tabwidth(int tabwidth) { project_.set_tabwidth(tabwidth); } void Project::set_usetabs(bool usetabs) { project_.set_usetabs(usetabs); } const wxString Project::GetCargoFile() const { if (root_folder_.IsEmpty()) return ""; wxFileName cargo(root_folder_, "cargo.toml"); return cargo.GetFullPath(); } const wxString Project::GetProjectFile() const { if (root_folder_.IsEmpty()) return ""; wxFileName cargo(root_folder_, "project.ride"); return cargo.GetFullPath(); } const wxString Project::GetUserFile() const { if (root_folder_.IsEmpty()) return ""; wxFileName cargo(root_folder_, "project.ride.user"); return cargo.GetFullPath(); } bool Project::IsPartOfProject(const wxString& filename) { // todo: implement a better logic for checking if the file is part of the project return true; } void Project::Settings() { // todo: implement me } void Project::SelectActiveBuild() { std::vector<wxString> names; names.reserve(project_.build_settings_size()); for (const ride::BuildSetting& setting : project_.build_settings()) { names.push_back(setting.name()); } wxSingleChoiceDialog dlg(NULL, "Select build", "Build", names.size(), &names[0]); dlg.SetSelection( user_.build_setting() ); const int dialog_result = dlg.ShowModal(); if (dialog_result != wxID_OK) return; user_.set_build_setting(dlg.GetSelection()); SaveUser(); SetMainStatusbarText(); } void Project::SaveAllFiles() { main_->SaveAllChangedProjectFiles(); Save(); } void Project::Build(bool origin_main) { if (origin_main) { CleanOutput(); SaveAllFiles(); } // todo: expand commandline with arguments RunCmd("cargo build"); } void Project::Clean(bool origin_main) { if (origin_main) { CleanOutput(); SaveAllFiles(); } // todo: expand commandline with arguments RunCmd("cargo clean"); } void Project::Rebuild(bool origin_main) { if (origin_main) { CleanOutput(); SaveAllFiles(); } Clean(false); Build(false); } void Project::Doc(bool origin_main) { if (origin_main) { CleanOutput(); SaveAllFiles(); } // todo: expand commandline with arguments RunCmd("cargo doc"); } void Project::Run(bool origin_main) { if (origin_main) { CleanOutput(); SaveAllFiles(); } Build(false); //todo: run the application } void Project::Test(bool origin_main) { if (origin_main) { CleanOutput(); SaveAllFiles(); } // todo: expand commandline with arguments RunCmd("cargo test"); } void Project::Bench(bool origin_main) { if (origin_main) { CleanOutput(); SaveAllFiles(); } // todo: expand commandline with arguments RunCmd("cargo bench"); } void Project::Update(bool origin_main) { if (origin_main) { CleanOutput(); SaveAllFiles(); } // todo: expand commandline with arguments RunCmd("cargo update"); } ////////////////////////////////////////////////////////////////////////// void Project::CleanOutput() { main_->build_output().Clear(); } void Project::Append(const wxString& str) { main_->build_output().Append(str); } void Project::RunCmd(const wxString& cmd) { if (root_folder_.IsEmpty()) { ShowInfo(main_, "No project open, you need to open a cargo project first!", "No project open!"); return; } MultiRunner::RunCmd(Command(root_folder_, cmd)); } bool Project::SaveUser() { return SaveProto(&user_, GetUserFile()); } int Project::GetSelectedBuildIndex() { if (project_.build_settings_size() <= 0) return -1; if (user_.build_setting() < 0 || user_.build_setting() >= project_.build_settings_size()) { user_.set_build_setting(0); SaveUser(); SetMainStatusbarText(); } return user_.build_setting(); } const ride::BuildSetting& Project::GetCurrentBuildSetting() { int index = GetSelectedBuildIndex(); if (index == -1) return ride::BuildSetting::default_instance(); else return project_.build_settings(index); } void Project::SetMainStatusbarText() { main_->SetStatusText(GetCurrentBuildSetting().name(), STATUSBAR_BUILD_CONF); main_->SetStatusText("Run", STATUSBAR_RUN_CONF); } generate the build command from settings #include "ride/project.h" #include <wx/utils.h> #include <wx/process.h> #include <wx/txtstrm.h> #include <wx/filename.h> #include "ride/wxutils.h" #include "ride/mainwindow.h" #include "settings.pb.h" #include "ride/proto.h" #include <wx/choicdlg.h> Project::Project(MainWindow* output, const wxString& root_folder) : main_(output), root_folder_(root_folder) { if (root_folder_.IsEmpty() == false) { if (LoadProto(&project_, GetProjectFile()) == false) { } if (project_.build_settings_size() == 0) { // add default build settings to the project ride::BuildSetting* debug = project_.add_build_settings(); debug->set_name("Debug"); debug->set_release(false); ride::BuildSetting* release = project_.add_build_settings(); release->set_name("Release"); release->set_release(true); } if (LoadProto(&user_, GetUserFile()) == false) { } // validate project file GetCurrentBuildSetting(); } } Project::~Project() { Save(); } const wxString& Project::root_folder() const { return root_folder_; } bool Project::Save() { if (root_folder_.IsEmpty() ) return false; bool project_saved = SaveProto(&project_, GetProjectFile()); bool user_saved = SaveUser(); return project_saved && user_saved; } int Project::tabwidth() const { return project_.tabwidth(); } bool Project::usetabs() const { return project_.usetabs(); } void Project::set_tabwidth(int tabwidth) { project_.set_tabwidth(tabwidth); } void Project::set_usetabs(bool usetabs) { project_.set_usetabs(usetabs); } const wxString Project::GetCargoFile() const { if (root_folder_.IsEmpty()) return ""; wxFileName cargo(root_folder_, "cargo.toml"); return cargo.GetFullPath(); } const wxString Project::GetProjectFile() const { if (root_folder_.IsEmpty()) return ""; wxFileName cargo(root_folder_, "project.ride"); return cargo.GetFullPath(); } const wxString Project::GetUserFile() const { if (root_folder_.IsEmpty()) return ""; wxFileName cargo(root_folder_, "project.ride.user"); return cargo.GetFullPath(); } bool Project::IsPartOfProject(const wxString& filename) { // todo: implement a better logic for checking if the file is part of the project return true; } void Project::Settings() { // todo: implement me } void Project::SelectActiveBuild() { std::vector<wxString> names; names.reserve(project_.build_settings_size()); for (const ride::BuildSetting& setting : project_.build_settings()) { names.push_back(setting.name()); } wxSingleChoiceDialog dlg(NULL, "Select build", "Build", names.size(), &names[0]); dlg.SetSelection( user_.build_setting() ); const int dialog_result = dlg.ShowModal(); if (dialog_result != wxID_OK) return; user_.set_build_setting(dlg.GetSelection()); SaveUser(); SetMainStatusbarText(); } void Project::SaveAllFiles() { main_->SaveAllChangedProjectFiles(); Save(); } void Project::Build(bool origin_main) { if (origin_main) { CleanOutput(); SaveAllFiles(); } const ride::BuildSetting& build = GetCurrentBuildSetting(); wxString cmd = "cargo build"; if (build.release()) { cmd += " --release"; } if (build.features_size() > 0) { cmd += " --features"; for (const std::string& f : build.features()) { cmd += " " + f; } } if (build.default_features() == false) { cmd += " --no-default-features"; } if (build.target().empty() == false) { cmd += " --target " + build.target(); } if (build.verbose()) { cmd += " --verbose"; } if (build.custom_arguments().empty() == false) { cmd += " " + build.custom_arguments(); } RunCmd(cmd); } void Project::Clean(bool origin_main) { if (origin_main) { CleanOutput(); SaveAllFiles(); } // todo: expand commandline with arguments RunCmd("cargo clean"); } void Project::Rebuild(bool origin_main) { if (origin_main) { CleanOutput(); SaveAllFiles(); } Clean(false); Build(false); } void Project::Doc(bool origin_main) { if (origin_main) { CleanOutput(); SaveAllFiles(); } // todo: expand commandline with arguments RunCmd("cargo doc"); } void Project::Run(bool origin_main) { if (origin_main) { CleanOutput(); SaveAllFiles(); } Build(false); //todo: run the application } void Project::Test(bool origin_main) { if (origin_main) { CleanOutput(); SaveAllFiles(); } // todo: expand commandline with arguments RunCmd("cargo test"); } void Project::Bench(bool origin_main) { if (origin_main) { CleanOutput(); SaveAllFiles(); } // todo: expand commandline with arguments RunCmd("cargo bench"); } void Project::Update(bool origin_main) { if (origin_main) { CleanOutput(); SaveAllFiles(); } // todo: expand commandline with arguments RunCmd("cargo update"); } ////////////////////////////////////////////////////////////////////////// void Project::CleanOutput() { main_->build_output().Clear(); } void Project::Append(const wxString& str) { main_->build_output().Append(str); } void Project::RunCmd(const wxString& cmd) { if (root_folder_.IsEmpty()) { ShowInfo(main_, "No project open, you need to open a cargo project first!", "No project open!"); return; } MultiRunner::RunCmd(Command(root_folder_, cmd)); } bool Project::SaveUser() { return SaveProto(&user_, GetUserFile()); } int Project::GetSelectedBuildIndex() { if (project_.build_settings_size() <= 0) return -1; if (user_.build_setting() < 0 || user_.build_setting() >= project_.build_settings_size()) { user_.set_build_setting(0); SaveUser(); SetMainStatusbarText(); } return user_.build_setting(); } const ride::BuildSetting& Project::GetCurrentBuildSetting() { int index = GetSelectedBuildIndex(); if (index == -1) return ride::BuildSetting::default_instance(); else return project_.build_settings(index); } void Project::SetMainStatusbarText() { main_->SetStatusText(GetCurrentBuildSetting().name(), STATUSBAR_BUILD_CONF); main_->SetStatusText("Run", STATUSBAR_RUN_CONF); }
// // This source file is part of appleseed. // Visit http://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited // Copyright (c) 2014-2017 Francois Beaune, The appleseedhq Organization // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // // Interface header. #include "mainwindow.h" // UI definition header. #include "ui_mainwindow.h" // appleseed.studio headers. #include "help/about/aboutwindow.h" #include "mainwindow/logwidget.h" #include "mainwindow/minimizebutton.h" #include "mainwindow/project/attributeeditor.h" #include "mainwindow/project/projectexplorer.h" #include "mainwindow/pythonconsole/pythonconsolewidget.h" #include "utility/interop.h" #include "utility/miscellaneous.h" #include "utility/settingskeys.h" // appleseed.shared headers. #include "application/application.h" // appleseed.renderer headers. #include "renderer/api/aov.h" #include "renderer/api/frame.h" #include "renderer/api/log.h" #include "renderer/api/project.h" #include "renderer/api/rendering.h" #include "renderer/api/surfaceshader.h" // appleseed.foundation headers. #include "foundation/core/appleseed.h" #include "foundation/math/aabb.h" #include "foundation/math/vector.h" #include "foundation/platform/compiler.h" #include "foundation/platform/system.h" #include "foundation/platform/types.h" #include "foundation/utility/containers/dictionary.h" #include "foundation/utility/foreach.h" #include "foundation/utility/log/logmessage.h" #include "foundation/utility/path.h" #include "foundation/utility/settings.h" // Qt headers. #include <QAction> #include <QActionGroup> #include <QApplication> #include <QCloseEvent> #include <QDir> #include <QFileInfo> #include <QFileSystemWatcher> #include <QIcon> #include <QLabel> #include <QLayout> #include <QLineEdit> #include <QMenu> #include <QMessageBox> #include <QRect> #include <QSettings> #include <QStatusBar> #include <QString> #include <QStringList> #include <Qt> #include <QToolButton> #include <QUrl> // Boost headers. #include "boost/filesystem/path.hpp" // Standard headers. #include <algorithm> #include <cassert> #include <cstdlib> using namespace appleseed::shared; using namespace foundation; using namespace renderer; using namespace std; namespace bf = boost::filesystem; namespace appleseed { namespace studio { // // MainWindow class implementation. // namespace { const int MaxRecentlyOpenedFiles = 15; } MainWindow::MainWindow(QWidget* parent) : QMainWindow(parent) , m_ui(new Ui::MainWindow()) , m_rendering_manager(m_status_bar) , m_project_explorer(nullptr) , m_attribute_editor(nullptr) , m_project_file_watcher(nullptr) { initialize_ocio(); m_ui->setupUi(this); statusBar()->addWidget(&m_status_bar); build_menus(); build_toolbar(); build_log_panel(); build_python_console_panel(); build_project_explorer(); build_connections(); const QSettings settings(SETTINGS_ORGANIZATION, SETTINGS_APPLICATION); restoreGeometry(settings.value("main_window_geometry").toByteArray()); restoreState(settings.value("main_window_state").toByteArray()); m_ui->treewidget_project_explorer_scene->header()->restoreGeometry( settings.value("main_window_project_explorer_geometry").toByteArray()); m_ui->treewidget_project_explorer_scene->header()->restoreState( settings.value("main_window_project_explorer_state").toByteArray()); print_startup_information(); slot_load_settings(); update_project_explorer(); remove_render_widgets(); update_workspace(); build_minimize_buttons(); setAcceptDrops(true); } MainWindow::~MainWindow() { delete m_project_explorer; delete m_ui; } namespace { class CustomSignalMapper : public QObject { Q_OBJECT public: CustomSignalMapper(QObject* parent, const QString& configuration) : QObject(parent) , m_configuration(configuration) { } signals: void mapped(const QString& filepath, const QString& config, const bool success); public slots: void map(const QString& filepath, const bool success) { emit mapped(filepath, m_configuration, success); } private: const QString m_configuration; }; } void MainWindow::new_project() { m_project_manager.create_project(); on_project_change(); } bool MainWindow::open_project(const QString& filepath) { save_state_before_project_open(); if (m_rendering_manager.is_rendering()) { m_rendering_manager.abort_rendering(); m_rendering_manager.wait_until_rendering_end(); } remove_render_widgets(); set_file_widgets_enabled(false, NotRendering); set_project_explorer_enabled(false); set_rendering_widgets_enabled(false, NotRendering); const bool successful = m_project_manager.load_project(filepath.toAscii().constData()); if (successful) { on_project_change(); } else { recreate_render_widgets(); update_workspace(); } return successful; } void MainWindow::open_project_async(const QString& filepath) { save_state_before_project_open(); if (m_rendering_manager.is_rendering()) { m_rendering_manager.abort_rendering(); m_rendering_manager.wait_until_rendering_end(); } remove_render_widgets(); set_file_widgets_enabled(false, NotRendering); set_project_explorer_enabled(false); set_rendering_widgets_enabled(false, NotRendering); m_project_manager.load_project_async(filepath.toAscii().constData()); } void MainWindow::open_and_render_project(const QString& filepath, const QString& configuration) { CustomSignalMapper* mapper = new CustomSignalMapper(this, configuration); connect( &m_project_manager, SIGNAL(signal_load_project_async_complete(const QString&, const bool)), mapper, SLOT(map(const QString&, const bool))); connect( mapper, SIGNAL(mapped(const QString&, const QString&, const bool)), SLOT(slot_start_rendering_once(const QString&, const QString&, const bool))); open_project_async(filepath); } bool MainWindow::save_project(QString filepath) { if (!m_project_manager.is_project_open()) return false; const QString Extension = "appleseed"; if (QFileInfo(filepath).suffix() != Extension) filepath += "." + Extension; if (m_project_file_watcher) stop_monitoring_project_file(); const bool successful = m_project_manager.save_project_as(filepath.toAscii().constData()); if (m_project_file_watcher) start_monitoring_project_file(); update_workspace(); return successful; } bool MainWindow::pack_project(QString filepath) { if (!m_project_manager.is_project_open()) return false; const QString Extension = "appleseedz"; if (QFileInfo(filepath).suffix() != Extension) filepath += "." + Extension; return m_project_manager.pack_project_as(filepath.toAscii().constData()); } void MainWindow::close_project() { m_project_manager.close_project(); on_project_change(); } ProjectManager* MainWindow::get_project_manager() { return &m_project_manager; } ParamArray& MainWindow::get_settings() { return m_settings; } QDockWidget* MainWindow::create_dock_widget(const char* dock_name) { QDockWidget* dock_widget = new QDockWidget(this); const QString object_name = QString(dock_name).toLower().split(' ').join("_"); dock_widget->setObjectName(object_name); dock_widget->setWindowTitle(dock_name); const auto& actions = m_ui->menu_view->actions(); QAction* menu_separator = actions.last(); for (int i = actions.size() - 2; i != 0; --i) { if (actions[i]->isSeparator()) { menu_separator = actions[i]; break; } } m_ui->menu_view->insertAction(menu_separator, dock_widget->toggleViewAction()); m_minimize_buttons.push_back(new MinimizeButton(dock_widget)); statusBar()->insertPermanentWidget( static_cast<int>(m_minimize_buttons.size()), m_minimize_buttons.back()); return dock_widget; } void MainWindow::build_menus() { // // File menu. // m_ui->action_file_new_project->setShortcut(QKeySequence::New); connect(m_ui->action_file_new_project, SIGNAL(triggered()), SLOT(slot_new_project())); m_ui->action_file_open_project->setShortcut(QKeySequence::Open); connect(m_ui->action_file_open_project, SIGNAL(triggered()), SLOT(slot_open_project())); build_recent_files_menu(); connect(m_ui->action_file_open_builtin_project_cornellbox, SIGNAL(triggered()), SLOT(slot_open_cornellbox_builtin_project())); connect(m_ui->action_file_reload_project, SIGNAL(triggered()), SLOT(slot_reload_project())); connect(m_ui->action_file_monitor_project, SIGNAL(toggled(bool)), SLOT(slot_toggle_project_file_monitoring(const bool))); m_ui->action_file_save_project->setShortcut(QKeySequence::Save); connect(m_ui->action_file_save_project, SIGNAL(triggered()), SLOT(slot_save_project())); m_ui->action_file_save_project_as->setShortcut(QKeySequence::SaveAs); connect(m_ui->action_file_save_project_as, SIGNAL(triggered()), SLOT(slot_save_project_as())); connect(m_ui->action_file_pack_project_as, SIGNAL(triggered()), SLOT(slot_pack_project_as())); m_ui->action_file_close_project->setShortcut(QKeySequence::Close); connect(m_ui->action_file_close_project, SIGNAL(triggered()), SLOT(slot_close_project())); m_ui->action_file_exit->setShortcut(QKeySequence::Quit); connect(m_ui->action_file_exit, SIGNAL(triggered()), SLOT(close())); // // View menu. // m_ui->menu_view->addAction(m_ui->project_explorer->toggleViewAction()); m_ui->menu_view->addAction(m_ui->attribute_editor->toggleViewAction()); m_ui->menu_view->addAction(m_ui->log->toggleViewAction()); m_ui->menu_view->addAction(m_ui->python_console->toggleViewAction()); m_ui->menu_view->addSeparator(); QAction* fullscreen_action = m_ui->menu_view->addAction("Fullscreen"); fullscreen_action->setShortcut(Qt::Key_F11); connect(fullscreen_action, SIGNAL(triggered()), SLOT(slot_fullscreen())); // // Rendering menu. // connect(m_ui->action_rendering_start_interactive_rendering, SIGNAL(triggered()), SLOT(slot_start_interactive_rendering())); connect(m_ui->action_rendering_start_final_rendering, SIGNAL(triggered()), SLOT(slot_start_final_rendering())); connect(m_ui->action_rendering_stop_rendering, SIGNAL(triggered()), &m_rendering_manager, SLOT(slot_abort_rendering())); connect(m_ui->action_rendering_rendering_settings, SIGNAL(triggered()), SLOT(slot_show_rendering_settings_window())); // // Diagnostics menu. // build_override_shading_menu_item(); // // Debug menu. // connect(m_ui->action_debug_tests, SIGNAL(triggered()), SLOT(slot_show_test_window())); connect(m_ui->action_debug_benchmarks, SIGNAL(triggered()), SLOT(slot_show_benchmark_window())); // // Tools menu. // connect(m_ui->action_tools_settings, SIGNAL(triggered()), SLOT(slot_show_settings_window())); connect(m_ui->action_tools_save_settings, SIGNAL(triggered()), SLOT(slot_save_settings())); connect(m_ui->action_tools_reload_settings, SIGNAL(triggered()), SLOT(slot_load_settings())); // // Help menu. // connect(m_ui->action_help_about, SIGNAL(triggered()), SLOT(slot_show_about_window())); } void MainWindow::build_override_shading_menu_item() { QActionGroup* action_group = new QActionGroup(this); connect( m_ui->action_diagnostics_override_shading_no_override, SIGNAL(triggered()), SLOT(slot_clear_shading_override())); action_group->addAction(m_ui->action_diagnostics_override_shading_no_override); for (int i = 0; i < DiagnosticSurfaceShader::ShadingModeCount; ++i) { const char* shading_mode_value = DiagnosticSurfaceShader::ShadingModeNames[i].m_key; const char* shading_mode_name = DiagnosticSurfaceShader::ShadingModeNames[i].m_value; QAction* action = new QAction(this); action->setCheckable(true); action->setObjectName( QString::fromAscii("action_diagnostics_override_shading_") + shading_mode_value); action->setText( QApplication::translate( objectName().toAscii().constData(), shading_mode_name, nullptr, QApplication::UnicodeUTF8)); const int shortcut_number = i + 1; if (shortcut_number <= 9) { const QString shortcut = QApplication::translate( objectName().toAscii().constData(), QString::fromAscii("Ctrl+Shift+%1").arg(shortcut_number).toAscii().constData(), nullptr, QApplication::UnicodeUTF8); action->setShortcut(shortcut); } action->setData(shading_mode_value); connect( action, SIGNAL(triggered()), SLOT(slot_set_shading_override())); m_ui->menu_diagnostics_override_shading->addAction(action); action_group->addAction(action); } } void MainWindow::update_override_shading_menu_item() { const ParamArray project_params = get_project_params("interactive"); const ParamArray shading_engine_params = project_params.child("shading_engine"); if (shading_engine_params.dictionaries().exist("override_shading")) { const string shading_mode = shading_engine_params.child("override_shading").get_optional<string>("mode", "coverage"); for (const_each<QList<QAction*>> i = m_ui->menu_diagnostics_override_shading->actions(); i; ++i) { QAction* action = *i; if (action->data().toString().toStdString() == shading_mode) { action->activate(QAction::Trigger); break; } } } else { m_ui->action_diagnostics_override_shading_no_override->activate(QAction::Trigger); } } void MainWindow::build_recent_files_menu() { assert(m_recently_opened.empty()); m_recently_opened.reserve(MaxRecentlyOpenedFiles); for (int i = 0; i < MaxRecentlyOpenedFiles; ++i) { QAction* action = new QAction(this); action->setVisible(false); connect(action, SIGNAL(triggered()), SLOT(slot_open_recent())); m_ui->menu_open_recent->addAction(action); m_recently_opened.push_back(action); } QSettings settings(SETTINGS_ORGANIZATION, SETTINGS_APPLICATION); QStringList files = settings.value("recent_file_list").toStringList(); update_recent_files_menu(files); m_ui->menu_open_recent->addSeparator(); QAction* clear_open_recent_menu = new QAction(this); clear_open_recent_menu->setText("&Clear Menu"); connect(clear_open_recent_menu, SIGNAL(triggered()), SLOT(slot_clear_open_recent_files_menu())); m_ui->menu_open_recent->addAction(clear_open_recent_menu); } void MainWindow::update_recent_files_menu(const QString& filepath) { QSettings settings(SETTINGS_ORGANIZATION, SETTINGS_APPLICATION); QStringList files = settings.value("recent_file_list").toStringList(); files.removeAll(filepath); files.prepend(filepath); while (files.size() > MaxRecentlyOpenedFiles) files.removeLast(); update_recent_files_menu(files); settings.setValue("recent_file_list", files); } void MainWindow::update_recent_files_menu(const QStringList& files) { const int recent_file_count = min(files.size(), MaxRecentlyOpenedFiles); for (int i = 0; i < recent_file_count; ++i) { const int number = i + 1; const QString filepath = files[i]; const QString format = number < 10 ? "&%1 %2" : "%1 %2"; const QString text = format.arg(number).arg(filepath); m_recently_opened[i]->setText(text); m_recently_opened[i]->setData(filepath); m_recently_opened[i]->setVisible(true); } for (int i = recent_file_count; i < MaxRecentlyOpenedFiles; ++i) m_recently_opened[i]->setVisible(false); } void MainWindow::build_toolbar() { // // File actions. // m_action_new_project = new QAction(load_icons("project_new"), combine_name_and_shortcut("New Project", m_ui->action_file_new_project->shortcut()), this); connect(m_action_new_project, SIGNAL(triggered()), SLOT(slot_new_project())); m_ui->main_toolbar->addAction(m_action_new_project); m_action_open_project = new QAction(load_icons("project_open"), combine_name_and_shortcut("Open Project...", m_ui->action_file_open_project->shortcut()), this); connect(m_action_open_project, SIGNAL(triggered()), SLOT(slot_open_project())); m_ui->main_toolbar->addAction(m_action_open_project); m_action_save_project = new QAction(load_icons("project_save") , combine_name_and_shortcut("Save Project", m_ui->action_file_save_project->shortcut()), this); connect(m_action_save_project, SIGNAL(triggered()), SLOT(slot_save_project())); m_ui->main_toolbar->addAction(m_action_save_project); m_action_reload_project = new QAction(load_icons("project_reload"), combine_name_and_shortcut("Reload Project", m_ui->action_file_reload_project->shortcut()), this); connect(m_action_reload_project, SIGNAL(triggered()), SLOT(slot_reload_project())); m_ui->main_toolbar->addAction(m_action_reload_project); m_action_monitor_project_file = new QAction(load_icons("project_monitor"), "Toggle Project File Monitoring", this); m_action_monitor_project_file->setCheckable(true); connect(m_action_monitor_project_file, SIGNAL(toggled(bool)), SLOT(slot_toggle_project_file_monitoring(const bool))); m_ui->main_toolbar->addAction(m_action_monitor_project_file); m_ui->main_toolbar->addSeparator(); // // Rendering actions. // m_action_start_interactive_rendering = new QAction(load_icons("rendering_start_interactive"), combine_name_and_shortcut("Start Interactive Rendering", m_ui->action_rendering_start_interactive_rendering->shortcut()), this); connect(m_action_start_interactive_rendering, SIGNAL(triggered()), SLOT(slot_start_interactive_rendering())); m_ui->main_toolbar->addAction(m_action_start_interactive_rendering); m_action_start_final_rendering = new QAction(load_icons("rendering_start_final"), combine_name_and_shortcut("Start Final Rendering", m_ui->action_rendering_start_final_rendering->shortcut()), this); connect(m_action_start_final_rendering, SIGNAL(triggered()), SLOT(slot_start_final_rendering())); m_ui->main_toolbar->addAction(m_action_start_final_rendering); m_action_stop_rendering = new QAction(load_icons("rendering_stop"), combine_name_and_shortcut("Stop Rendering", m_ui->action_rendering_stop_rendering->shortcut()), this); connect(m_action_stop_rendering, SIGNAL(triggered()), &m_rendering_manager, SLOT(slot_abort_rendering())); m_ui->main_toolbar->addAction(m_action_stop_rendering); m_action_rendering_settings = new QAction(load_icons("rendering_settings"), combine_name_and_shortcut("Rendering Settings...", m_ui->action_rendering_rendering_settings->shortcut()), this); connect(m_action_rendering_settings, SIGNAL(triggered()), SLOT(slot_show_rendering_settings_window())); m_ui->main_toolbar->addAction(m_action_rendering_settings); } void MainWindow::build_log_panel() { LogWidget* log_widget = new LogWidget(m_ui->log_contents); m_ui->log_contents->layout()->addWidget(log_widget); log_widget->setObjectName("textedit_log"); log_widget->setUndoRedoEnabled(false); log_widget->setLineWrapMode(QTextEdit::NoWrap); log_widget->setReadOnly(true); log_widget->setTextInteractionFlags(Qt::TextSelectableByMouse); m_log_target.reset(new QtLogTarget(log_widget)); global_logger().add_target(m_log_target.get()); } void MainWindow::build_python_console_panel() { PythonConsoleWidget* console_widget = new PythonConsoleWidget(m_ui->python_console_contents); m_ui->python_console_contents->layout()->addWidget(console_widget); console_widget->setObjectName("textedit_console"); } void MainWindow::build_project_explorer() { m_ui->treewidget_project_explorer_scene->setColumnWidth(0, 295); // name disable_osx_focus_rect(m_ui->treewidget_project_explorer_scene); connect( m_ui->lineedit_filter, SIGNAL(textChanged(const QString&)), SLOT(slot_filter_text_changed(const QString&))); connect( m_ui->pushbutton_clear_filter, SIGNAL(clicked()), SLOT(slot_clear_filter())); m_ui->pushbutton_clear_filter->setEnabled(false); } void MainWindow::build_minimize_buttons() { m_minimize_buttons.push_back(new MinimizeButton(m_ui->project_explorer)); m_minimize_buttons.push_back(new MinimizeButton(m_ui->attribute_editor)); m_minimize_buttons.push_back(new MinimizeButton(m_ui->log)); m_minimize_buttons.push_back(new MinimizeButton(m_ui->python_console)); for (size_t i = 0; i < m_minimize_buttons.size(); ++i) { statusBar()->insertPermanentWidget( static_cast<int>(i + 1), m_minimize_buttons[i]); } } void MainWindow::build_connections() { connect( m_action_monitor_project_file, SIGNAL(toggled(bool)), m_ui->action_file_monitor_project, SLOT(setChecked(bool))); connect( m_ui->action_file_monitor_project, SIGNAL(toggled(bool)), m_action_monitor_project_file, SLOT(setChecked(bool))); connect( &m_project_manager, SIGNAL(signal_load_project_async_complete(const QString&, const bool)), SLOT(slot_open_project_complete(const QString&, const bool))); connect( &m_rendering_manager, SIGNAL(signal_rendering_end()), SLOT(slot_rendering_end())); connect( &m_rendering_manager, SIGNAL(signal_camera_changed()), SLOT(slot_camera_changed())); } void MainWindow::update_workspace() { update_window_title(); set_file_widgets_enabled(true, NotRendering); set_project_explorer_enabled(true); set_rendering_widgets_enabled(true, NotRendering); m_ui->attribute_editor_scrollarea_contents->setEnabled(true); } void MainWindow::update_project_explorer() { delete m_project_explorer; m_project_explorer = nullptr; delete m_attribute_editor; m_attribute_editor = nullptr; if (m_project_manager.is_project_open()) { m_attribute_editor = new AttributeEditor( m_ui->attribute_editor_scrollarea_contents, *m_project_manager.get_project(), m_settings); m_project_explorer = new ProjectExplorer( m_ui->treewidget_project_explorer_scene, m_attribute_editor, *m_project_manager.get_project(), m_rendering_manager, m_settings); connect( m_project_explorer, SIGNAL(signal_project_modified()), SLOT(slot_project_modified())); connect( m_project_explorer, SIGNAL(signal_frame_modified()), SLOT(slot_frame_modified())); } m_ui->lineedit_filter->clear(); } void MainWindow::update_window_title() { QString title; if (m_project_manager.is_project_open()) { if (m_project_manager.is_project_dirty()) title.append("* "); title.append(QString::fromStdString(m_project_manager.get_project_display_name())); title.append(" - "); } title.append("appleseed.studio"); setWindowTitle(title); } void MainWindow::set_file_widgets_enabled(const bool is_enabled, const RenderingMode rendering_mode) { const bool is_project_open = m_project_manager.is_project_open(); const bool project_has_path = is_project_open && m_project_manager.get_project()->has_path(); // File -> New Project. m_ui->action_file_new_project->setEnabled(is_enabled); m_action_new_project->setEnabled(is_enabled); // File -> Open Project. m_ui->action_file_open_project->setEnabled(is_enabled); m_action_open_project->setEnabled(is_enabled); // File -> Open Recent. m_ui->menu_open_recent->setEnabled(is_enabled); // File -> Open Built-in Project. m_ui->menu_file_open_builtin_project->setEnabled(is_enabled); // File -> Reload Project. const bool allow_reload = (is_enabled || rendering_mode == InteractiveRendering) && project_has_path; m_ui->action_file_reload_project->setEnabled(allow_reload); m_action_reload_project->setEnabled(allow_reload); // File -> Monitor Project. const bool allow_monitor = (is_enabled || rendering_mode == InteractiveRendering) && project_has_path; m_ui->action_file_monitor_project->setEnabled(allow_monitor); m_action_monitor_project_file->setEnabled(allow_monitor); // File -> Save Project, Save Project As and Pack Project As. const bool allow_save = is_enabled && is_project_open; m_ui->action_file_save_project->setEnabled(allow_save); m_action_save_project->setEnabled(allow_save); m_ui->action_file_save_project_as->setEnabled(allow_save); m_ui->action_file_pack_project_as->setEnabled(allow_save); // File -> Close Project. const bool allow_close = is_enabled && is_project_open; m_ui->action_file_close_project->setEnabled(allow_close); // File -> Exit. m_ui->action_file_exit->setEnabled(is_enabled); } void MainWindow::set_project_explorer_enabled(const bool is_enabled) { const bool is_project_open = m_project_manager.is_project_open(); m_ui->label_filter->setEnabled(is_enabled && is_project_open); m_ui->lineedit_filter->setEnabled(is_enabled && is_project_open); m_ui->pushbutton_clear_filter->setEnabled(is_enabled && is_project_open && !m_ui->lineedit_filter->text().isEmpty()); m_ui->treewidget_project_explorer_scene->setEnabled(is_enabled && is_project_open); } void MainWindow::set_rendering_widgets_enabled(const bool is_enabled, const RenderingMode rendering_mode) { const bool is_project_open = m_project_manager.is_project_open(); const bool allow_start = is_enabled && is_project_open && rendering_mode == NotRendering; const bool allow_stop = is_enabled && is_project_open && rendering_mode != NotRendering; // Rendering -> Rendering Settings. m_ui->action_rendering_rendering_settings->setEnabled(allow_start); m_action_rendering_settings->setEnabled(allow_start); // Rendering -> Start Interactive Rendering. m_ui->action_rendering_start_interactive_rendering->setEnabled(allow_start); m_action_start_interactive_rendering->setEnabled(allow_start); // Rendering -> Start Final Rendering. m_ui->action_rendering_start_final_rendering->setEnabled(allow_start); m_action_start_final_rendering->setEnabled(allow_start); // Rendering -> Stop Rendering. m_ui->action_rendering_stop_rendering->setEnabled(allow_stop); m_action_stop_rendering->setEnabled(allow_stop); // Rendering -> Render Settings. m_ui->action_rendering_rendering_settings->setEnabled(allow_start); // Render tab buttons. const int current_tab_index = m_ui->tab_render_channels->currentIndex(); if (current_tab_index != -1) { RenderTab* render_tab = m_tab_index_to_render_tab[current_tab_index]; // Clear frame. render_tab->set_clear_frame_button_enabled( is_enabled && is_project_open && rendering_mode == NotRendering); // Set/clear rendering region. render_tab->set_render_region_buttons_enabled( is_enabled && is_project_open && rendering_mode != FinalRendering); // Scene picker. render_tab->get_scene_picking_handler()->set_enabled( is_enabled && is_project_open && rendering_mode != FinalRendering); } } void MainWindow::save_state_before_project_open() { m_state_before_project_open.reset(new StateBeforeProjectOpen()); m_state_before_project_open->m_is_rendering = m_rendering_manager.is_rendering(); for (const_each<RenderTabCollection> i = m_render_tabs; i; ++i) m_state_before_project_open->m_render_tab_states[i->first] = i->second->save_state(); } void MainWindow::restore_state_after_project_open() { if (m_state_before_project_open.get()) { for (const_each<RenderTabCollection> i = m_render_tabs; i; ++i) { const RenderTabStateCollection& tab_states = m_state_before_project_open->m_render_tab_states; const RenderTabStateCollection::const_iterator tab_state_it = tab_states.find(i->first); if (tab_state_it != tab_states.end()) i->second->load_state(tab_state_it->second); } if (m_state_before_project_open->m_is_rendering) start_rendering(InteractiveRendering); } } void MainWindow::recreate_render_widgets() { remove_render_widgets(); if (m_project_manager.is_project_open()) add_render_widget("RGB"); } void MainWindow::remove_render_widgets() { for (const_each<RenderTabCollection> i = m_render_tabs; i; ++i) delete i->second; m_render_tabs.clear(); m_tab_index_to_render_tab.clear(); while (m_ui->tab_render_channels->count() > 0) m_ui->tab_render_channels->removeTab(0); } void MainWindow::add_render_widget(const QString& label) { // Create the render tab. RenderTab* render_tab = new RenderTab( *m_project_explorer, *m_project_manager.get_project(), m_ocio_config); connect( render_tab, SIGNAL(signal_render_widget_context_menu(const QPoint&)), SLOT(slot_render_widget_context_menu(const QPoint&))); connect( render_tab, SIGNAL(signal_set_render_region(const QRect&)), SLOT(slot_set_render_region(const QRect&))); connect( render_tab, SIGNAL(signal_clear_render_region()), SLOT(slot_clear_render_region())); connect( render_tab, SIGNAL(signal_save_all_aovs()), SLOT(slot_save_all_aovs())); connect( render_tab, SIGNAL(signal_quicksave_all_aovs()), SLOT(slot_quicksave_all_aovs())); connect( render_tab, SIGNAL(signal_reset_zoom()), SLOT(slot_reset_zoom())); connect( render_tab, SIGNAL(signal_clear_frame()), SLOT(slot_clear_frame())); connect( render_tab, SIGNAL(signal_entity_picked(renderer::ScenePicker::PickingResult)), SLOT(slot_clear_filter())); connect( render_tab, SIGNAL(signal_camera_change_begin()), &m_rendering_manager, SLOT(slot_camera_change_begin())); connect( render_tab, SIGNAL(signal_camera_change_end()), &m_rendering_manager, SLOT(slot_camera_change_end())); connect( render_tab, SIGNAL(signal_camera_changed()), &m_rendering_manager, SLOT(slot_camera_changed())); connect( render_tab, SIGNAL(signal_camera_changed()), &m_rendering_manager, SIGNAL(signal_camera_changed())); // Add the render tab to the tab bar. const int tab_index = m_ui->tab_render_channels->addTab(render_tab, label); // Update the mappings. m_render_tabs[label.toStdString()] = render_tab; m_tab_index_to_render_tab[tab_index] = render_tab; } ParamArray MainWindow::get_project_params(const char* configuration_name) const { ParamArray params; Configuration* configuration = m_project_manager.is_project_open() ? m_project_manager.get_project()->configurations().get_by_name(configuration_name) : nullptr; if (configuration && configuration->get_base()) params = configuration->get_base()->get_parameters(); params.merge(m_settings); if (configuration) params.merge(configuration->get_parameters()); return params; } namespace { int show_modified_project_message_box(QWidget* parent) { QMessageBox msgbox(parent); msgbox.setWindowTitle("Save Changes?"); msgbox.setIcon(QMessageBox::Question); msgbox.setText("The project has been modified."); msgbox.setInformativeText("Do you want to save your changes?"); msgbox.setStandardButtons(QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel); msgbox.setDefaultButton(QMessageBox::Save); return msgbox.exec(); } } bool MainWindow::can_close_project() { // Project being loaded: can't close. if (m_project_manager.is_project_loading()) return false; // No project open: no problem. if (!m_project_manager.is_project_open()) return true; // Unmodified project: no problem. if (!m_project_manager.is_project_dirty()) return true; // The current project has been modified, ask the user what to do. switch (show_modified_project_message_box(this)) { case QMessageBox::Save: slot_save_project(); return true; case QMessageBox::Discard: return true; case QMessageBox::Cancel: return false; } assert(!"Should never be reached."); return false; } void MainWindow::on_project_change() { update_project_explorer(); recreate_render_widgets(); update_override_shading_menu_item(); if (m_rendering_settings_window.get() != nullptr && m_project_manager.get_project() != nullptr) m_rendering_settings_window->reload(); m_status_bar.clear(); update_workspace(); restore_state_after_project_open(); if (m_project_file_watcher) start_monitoring_project_file(); } void MainWindow::enable_project_file_monitoring() { if (m_project_file_watcher == nullptr) { m_project_file_watcher = new QFileSystemWatcher(this); connect( m_project_file_watcher, SIGNAL(fileChanged(const QString&)), SLOT(slot_project_file_changed(const QString&))); RENDERER_LOG_INFO("project file monitoring is now enabled."); start_monitoring_project_file(); } } void MainWindow::disable_project_file_monitoring() { if (m_project_file_watcher) { delete m_project_file_watcher; m_project_file_watcher = nullptr; RENDERER_LOG_INFO("project file monitoring is now disabled."); } } void MainWindow::start_monitoring_project_file() { assert(m_project_file_watcher); if (m_project_manager.is_project_open() && m_project_manager.get_project()->has_path()) { m_project_file_watcher->addPath(m_project_manager.get_project()->get_path()); } } void MainWindow::stop_monitoring_project_file() { assert(m_project_file_watcher); if (m_project_manager.is_project_open() && m_project_manager.get_project()->has_path()) { m_project_file_watcher->removePath(m_project_manager.get_project()->get_path()); } } void MainWindow::dragEnterEvent(QDragEnterEvent* event) { if (event->mimeData()->hasFormat("text/plain") || event->mimeData()->hasFormat("text/uri-list")) event->acceptProposedAction(); } void MainWindow::dropEvent(QDropEvent* event) { if (event->mimeData()->hasFormat("text/uri-list")) { const QList<QUrl> urls = event->mimeData()->urls(); QApplication::sendEvent(this, new QCloseEvent()); open_project_async(urls[0].toLocalFile()); } else { const QString text = event->mimeData()->text(); QApplication::sendEvent(this, new QCloseEvent()); open_project_async(text); } event->accept(); } void MainWindow::start_rendering(const RenderingMode rendering_mode) { assert(m_project_manager.is_project_open()); // Enable/disable widgets appropriately. set_file_widgets_enabled(false, rendering_mode); set_rendering_widgets_enabled(true, rendering_mode); set_project_explorer_enabled(rendering_mode == InteractiveRendering); m_ui->attribute_editor_scrollarea_contents->setEnabled(rendering_mode == InteractiveRendering); // Stop monitoring the project file in Final rendering mode. if (rendering_mode == FinalRendering) { if (m_project_file_watcher) stop_monitoring_project_file(); } Project* project = m_project_manager.get_project(); Frame* frame = project->get_frame(); frame->clear_main_and_aov_images(); // In the UI, darken all render widgets. for (const_each<RenderTabCollection> i = m_render_tabs; i; ++i) { i->second->darken(); i->second->update(); } // Retrieve the right configuration. const char* configuration_name = rendering_mode == InteractiveRendering ? "interactive" : "final"; const ParamArray params = get_project_params(configuration_name); // Effectively start rendering. m_rendering_manager.start_rendering( project, params, rendering_mode == InteractiveRendering ? RenderingManager::InteractiveRendering : RenderingManager::FinalRendering, m_render_tabs["RGB"]); } void MainWindow::print_startup_information() { RENDERER_LOG_INFO( "%s, %s configuration\n" "compiled on %s at %s using %s version %s", Appleseed::get_synthetic_version_string(), Appleseed::get_lib_configuration(), Appleseed::get_lib_compilation_date(), Appleseed::get_lib_compilation_time(), Compiler::get_compiler_name(), Compiler::get_compiler_version()); System::print_information(global_logger()); } namespace { int ask_abort_rendering_confirmation(QWidget* parent) { QMessageBox msgbox(parent); msgbox.setWindowTitle("Abort Rendering?"); msgbox.setIcon(QMessageBox::Question); msgbox.setText("Rendering is in progress."); msgbox.setInformativeText("Do you want to abort rendering?"); msgbox.setStandardButtons(QMessageBox::Yes | QMessageBox::No); msgbox.setDefaultButton(QMessageBox::No); return msgbox.exec(); } } void MainWindow::closeEvent(QCloseEvent* event) { if (m_rendering_manager.is_rendering()) { if (ask_abort_rendering_confirmation(this) != QMessageBox::Yes) { event->ignore(); return; } m_rendering_manager.abort_rendering(); m_rendering_manager.wait_until_rendering_end(); } if (!can_close_project()) { event->ignore(); return; } QSettings settings(SETTINGS_ORGANIZATION, SETTINGS_APPLICATION); settings.setValue("main_window_geometry", saveGeometry()); settings.setValue("main_window_state", saveState()); settings.setValue("main_window_project_explorer_geometry", m_ui->treewidget_project_explorer_scene->header()->saveGeometry()); settings.setValue("main_window_project_explorer_state", m_ui->treewidget_project_explorer_scene->header()->saveState()); slot_save_settings(); if (m_test_window.get()) m_test_window->close(); if (m_benchmark_window.get()) m_benchmark_window->close(); remove_render_widgets(); m_project_manager.close_project(); event->accept(); } void MainWindow::slot_new_project() { if (!can_close_project()) return; new_project(); } void MainWindow::slot_open_project() { if (!can_close_project()) return; QString filepath = get_open_filename( this, "Open...", get_project_files_filter(), m_settings, SETTINGS_FILE_DIALOG_PROJECTS); if (!filepath.isEmpty()) { filepath = QDir::toNativeSeparators(filepath); open_project_async(filepath); update_recent_files_menu(filepath); } } void MainWindow::slot_open_recent() { if (!can_close_project()) return; QAction* action = qobject_cast<QAction*>(sender()); if (action) { const QString filepath = action->data().toString(); open_project_async(filepath); } } void MainWindow::slot_clear_open_recent_files_menu() { QSettings settings(SETTINGS_ORGANIZATION, SETTINGS_APPLICATION); settings.setValue("recent_file_list", QStringList()); update_recent_files_menu(QStringList()); } void MainWindow::slot_open_cornellbox_builtin_project() { if (!can_close_project()) return; APPLESEED_UNUSED const bool successful = m_project_manager.load_builtin_project("cornell_box"); assert(successful); on_project_change(); } void MainWindow::slot_reload_project() { assert(m_project_manager.is_project_open()); assert(m_project_manager.get_project()->has_path()); if (!can_close_project()) return; open_project_async(m_project_manager.get_project()->get_path()); } namespace { void show_project_file_loading_failed_message_box(QWidget* parent, const QString& filepath) { QMessageBox msgbox(parent); msgbox.setWindowTitle("Loading Error"); msgbox.setIcon(QMessageBox::Critical); msgbox.setText("Failed to load the project file " + filepath + "."); msgbox.setInformativeText( "The project file may be invalid, corrupted or missing. " "Please look at the Log window for details."); msgbox.setStandardButtons(QMessageBox::Ok); msgbox.exec(); } } void MainWindow::slot_open_project_complete(const QString& filepath, const bool successful) { if (successful) { on_project_change(); } else { show_project_file_loading_failed_message_box(this, filepath); recreate_render_widgets(); update_workspace(); } } void MainWindow::slot_save_project() { assert(m_project_manager.is_project_open()); if (!m_project_manager.get_project()->has_path()) slot_save_project_as(); else save_project(m_project_manager.get_project()->get_path()); } void MainWindow::slot_save_project_as() { assert(m_project_manager.is_project_open()); QString filepath = get_save_filename( this, "Save As...", get_project_files_filter(ProjectFilesFilterPlainProjects), m_settings, SETTINGS_FILE_DIALOG_PROJECTS); if (!filepath.isEmpty()) { filepath = QDir::toNativeSeparators(filepath); save_project(filepath); update_recent_files_menu(filepath); } } void MainWindow::slot_pack_project_as() { assert(m_project_manager.is_project_open()); QString filepath = get_save_filename( this, "Pack As...", get_project_files_filter(ProjectFilesFilterPackedProjects), m_settings, SETTINGS_FILE_DIALOG_PROJECTS); if (!filepath.isEmpty()) { filepath = QDir::toNativeSeparators(filepath); pack_project(filepath); // Don't update the Recent Files menu. } } void MainWindow::slot_close_project() { if (!can_close_project()) return; close_project(); } void MainWindow::initialize_ocio() { // Try first a user specified OCIO config. if (getenv("OCIO")) { try { m_ocio_config = OCIO::GetCurrentConfig(); RENDERER_LOG_INFO("using ocio configuration: %s", getenv("OCIO")); return; } catch (const OCIO::Exception&) { } } // Try the bundled default OCIO config. const bf::path root_path(Application::get_root_path()); const string default_ocio_config = (root_path / "ocio" / "config.ocio").string(); try { m_ocio_config = OCIO::Config::CreateFromFile(default_ocio_config.c_str()); RENDERER_LOG_INFO("using ocio configuration: %s", default_ocio_config.c_str()); OCIO::SetCurrentConfig(m_ocio_config); return; } catch (const OCIO::Exception&) { } // Default to an empty OCIO config if everything else fails. m_ocio_config = OCIO::GetCurrentConfig(); RENDERER_LOG_ERROR("Could not initialize OCIO config."); } void MainWindow::slot_project_modified() { assert(m_project_manager.is_project_open()); m_project_manager.set_project_dirty_flag(); update_window_title(); } void MainWindow::slot_toggle_project_file_monitoring(const bool checked) { if (checked) enable_project_file_monitoring(); else disable_project_file_monitoring(); m_settings.insert_path( SETTINGS_WATCH_FILE_CHANGES, m_project_file_watcher != nullptr); } void MainWindow::slot_project_file_changed(const QString& filepath) { RENDERER_LOG_INFO("project file changed on disk, reloading it."); assert(m_project_file_watcher); m_project_file_watcher->removePath(filepath); slot_reload_project(); } void MainWindow::slot_load_settings() { Dictionary settings; if (!Application::load_settings("appleseed.studio.xml", settings, global_logger(), LogMessage::Info)) return; m_settings = settings; slot_apply_settings(); } void MainWindow::slot_save_settings() { SettingsFileWriter writer; // First try to save the settings to the user path. if (const char* p = Application::get_user_settings_path()) { try { const bf::path user_settings_path(p); bf::create_directories(user_settings_path); const string user_settings_file_path = (user_settings_path / "appleseed.studio.xml").string(); if (writer.write(user_settings_file_path.c_str(), m_settings)) { RENDERER_LOG_INFO("successfully saved settings to %s.", user_settings_file_path.c_str()); return; } } catch (const bf::filesystem_error&) { } } // As a fallback, try to save the settings to the appleseed's installation directory. const bf::path root_path(Application::get_root_path()); const string settings_file_path = (root_path / "settings" / "appleseed.studio.xml").string(); if (writer.write(settings_file_path.c_str(), m_settings)) { RENDERER_LOG_INFO("successfully saved settings to %s.", settings_file_path.c_str()); return; } RENDERER_LOG_ERROR("failed to save settings to %s.", settings_file_path.c_str()); } void MainWindow::slot_apply_settings() { if (m_settings.strings().exist(SETTINGS_MESSAGE_VERBOSITY)) { const char* level_name = m_settings.get(SETTINGS_MESSAGE_VERBOSITY); const LogMessage::Category level = LogMessage::get_category_value(level_name); if (level < LogMessage::NumMessageCategories) global_logger().set_verbosity_level(level); else RENDERER_LOG_ERROR("invalid message verbosity level \"%s\".", level_name); } if (m_settings.get_optional<bool>(SETTINGS_WATCH_FILE_CHANGES)) { m_action_monitor_project_file->setChecked(true); enable_project_file_monitoring(); } else { m_action_monitor_project_file->setChecked(false); disable_project_file_monitoring(); } } void MainWindow::slot_start_interactive_rendering() { start_rendering(InteractiveRendering); } void MainWindow::slot_start_final_rendering() { start_rendering(FinalRendering); } void MainWindow::slot_start_rendering_once(const QString& filepath, const QString& configuration, const bool successful) { sender()->deleteLater(); if (successful) { if (configuration == "interactive") start_rendering(InteractiveRendering); else start_rendering(FinalRendering); } } void MainWindow::slot_rendering_end() { update_workspace(); // Restart monitoring the project file if monitoring was enabled // (monitoring would have been stopped if rendering in Final mode). if (m_project_file_watcher) start_monitoring_project_file(); } void MainWindow::slot_camera_changed() { m_project_manager.set_project_dirty_flag(); } namespace { class ClearShadingOverrideAction : public RenderingManager::IStickyAction { public: void operator()( MasterRenderer& master_renderer, Project& project) override { master_renderer.get_parameters() .push("shading_engine") .dictionaries().remove("override_shading"); } }; class SetShadingOverrideAction : public RenderingManager::IStickyAction { public: explicit SetShadingOverrideAction(const string& shading_mode) : m_shading_mode(shading_mode) { } void operator()( MasterRenderer& master_renderer, Project& project) override { master_renderer.get_parameters() .push("shading_engine") .push("override_shading") .insert("mode", m_shading_mode); } private: const string m_shading_mode; }; } void MainWindow::slot_clear_shading_override() { m_rendering_manager.set_sticky_action( "override_shading", unique_ptr<RenderingManager::IStickyAction>( new ClearShadingOverrideAction())); m_rendering_manager.reinitialize_rendering(); } void MainWindow::slot_set_shading_override() { QAction* action = qobject_cast<QAction*>(sender()); const string shading_mode = action->data().toString().toStdString(); m_rendering_manager.set_sticky_action( "override_shading", unique_ptr<RenderingManager::IStickyAction>( new SetShadingOverrideAction(shading_mode))); m_rendering_manager.reinitialize_rendering(); } namespace { class ClearRenderRegionAction : public RenderingManager::IScheduledAction { public: explicit ClearRenderRegionAction(const AttributeEditor* attribute_editor) : m_attribute_editor(attribute_editor) { } void operator()( Project& project) override { project.get_frame()->reset_crop_window(); m_attribute_editor->refresh(); } private: const AttributeEditor* m_attribute_editor; }; class SetRenderRegionAction : public RenderingManager::IScheduledAction { public: SetRenderRegionAction( const QRect& rect, const AttributeEditor* attribute_editor) : m_rect(rect), m_attribute_editor(attribute_editor) { } void operator()( Project& project) override { const int w = m_rect.width(); const int h = m_rect.height(); const int x0 = m_rect.x(); const int y0 = m_rect.y(); const int x1 = x0 + w - 1; const int y1 = y0 + h - 1; assert(x0 >= 0); assert(y0 >= 0); assert(x0 <= x1); assert(y0 <= y1); project.get_frame()->set_crop_window( AABB2i( Vector2i(x0, y0), Vector2i(x1, y1))); m_attribute_editor->refresh(); } private: const QRect m_rect; const AttributeEditor* m_attribute_editor; }; } void MainWindow::slot_clear_render_region() { unique_ptr<RenderingManager::IScheduledAction> clear_render_region_action( new ClearRenderRegionAction(m_attribute_editor)); if (m_rendering_manager.is_rendering()) m_rendering_manager.schedule(std::move(clear_render_region_action)); else clear_render_region_action.get()->operator()( *m_project_manager.get_project()); m_rendering_manager.reinitialize_rendering(); } void MainWindow::slot_set_render_region(const QRect& rect) { unique_ptr<RenderingManager::IScheduledAction> set_render_region_action( new SetRenderRegionAction(rect, m_attribute_editor)); if (!m_rendering_manager.is_rendering()) { set_render_region_action.get()->operator()( *m_project_manager.get_project()); if (m_settings.get_path_optional<bool>(SETTINGS_RENDER_REGION_TRIGGERS_RENDERING)) start_rendering(InteractiveRendering); } else { m_rendering_manager.schedule(std::move(set_render_region_action)); m_rendering_manager.reinitialize_rendering(); } } void MainWindow::slot_render_widget_context_menu(const QPoint& point) { if (!(QApplication::keyboardModifiers() & Qt::ShiftModifier)) return; if (m_rendering_manager.is_rendering()) return; QMenu* menu = new QMenu(this); menu->addAction("Save Frame...", this, SLOT(slot_save_frame())); menu->addAction("Save All AOVs...", this, SLOT(slot_save_all_aovs())); menu->addSeparator(); menu->addAction("Clear Frame", this, SLOT(slot_clear_frame())); menu->exec(point); } namespace { QString ask_frame_save_file_path( QWidget* parent, const QString& caption, ParamArray& settings) { QString filepath = get_save_filename( parent, caption, g_appleseed_image_files_filter, settings, SETTINGS_FILE_DIALOG_FRAMES); if (!filepath.isEmpty()) { if (QFileInfo(filepath).suffix().isEmpty()) filepath += ".exr"; filepath = QDir::toNativeSeparators(filepath); } return filepath; } } void MainWindow::slot_save_frame() { assert(m_project_manager.is_project_open()); assert(!m_rendering_manager.is_rendering()); const QString filepath = ask_frame_save_file_path(this, "Save Frame As...", m_settings); if (filepath.isEmpty()) return; const Frame* frame = m_project_manager.get_project()->get_frame(); frame->write_main_image(filepath.toAscii().constData()); } void MainWindow::slot_save_all_aovs() { assert(m_project_manager.is_project_open()); assert(!m_rendering_manager.is_rendering()); const QString filepath = ask_frame_save_file_path(this, "Save All AOVs As...", m_settings); if (filepath.isEmpty()) return; const Frame* frame = m_project_manager.get_project()->get_frame(); frame->write_main_image(filepath.toAscii().constData()); frame->write_aov_images(filepath.toAscii().constData()); } namespace { void write_all_aovs( const Project& project, const bf::path& image_path) { bf::create_directories(image_path.parent_path()); const Frame* frame = project.get_frame(); frame->write_main_image(image_path.string().c_str()); frame->write_aov_images(image_path.string().c_str()); } } void MainWindow::slot_quicksave_all_aovs() { assert(m_project_manager.is_project_open()); assert(!m_rendering_manager.is_rendering()); const Project& project = *m_project_manager.get_project(); const bf::path project_path(project.get_path()); const bf::path quicksave_dir = project_path.parent_path() / "quicksaves"; write_all_aovs( project, bf::absolute( quicksave_dir / "quicksave.exr")); write_all_aovs( project, bf::absolute( find_next_available_path(quicksave_dir / "quicksave####.exr"))); } void MainWindow::slot_clear_frame() { Frame* frame = m_project_manager.get_project()->get_frame(); frame->clear_main_and_aov_images(); // In the UI, clear all render widgets to black. for (const_each<RenderTabCollection> i = m_render_tabs; i; ++i) i->second->clear(); } void MainWindow::slot_reset_zoom() { const int current_tab_index = m_ui->tab_render_channels->currentIndex(); m_tab_index_to_render_tab[current_tab_index]->reset_zoom(); } void MainWindow::slot_filter_text_changed(const QString& pattern) { m_ui->pushbutton_clear_filter->setEnabled(!pattern.isEmpty()); m_project_explorer->filter_items(pattern); } void MainWindow::slot_clear_filter() { m_ui->lineedit_filter->clear(); } void MainWindow::slot_frame_modified() { for (each<RenderTabCollection> i = m_render_tabs; i; ++i) i->second->update_size(); } void MainWindow::slot_fullscreen() { m_fullscreen = !m_fullscreen; bool all_minimized = true; bool not_minimized = false; for (each<vector<MinimizeButton*>> button = m_minimize_buttons; button; ++button) { all_minimized = all_minimized && (*button)->is_on(); not_minimized = not_minimized || !(*button)->is_on(); } // All were manually minimized, exit full screen mode if (all_minimized) m_fullscreen = false; // At least one is on screen, enter full screen mode if (not_minimized) m_fullscreen = true; for (each<vector<MinimizeButton*>> button = m_minimize_buttons; button; ++button) (*button)->set_fullscreen(m_fullscreen); } void MainWindow::slot_show_settings_window() { if (m_settings_window.get() == nullptr) { m_settings_window.reset(new SettingsWindow(m_settings, this)); connect( m_settings_window.get(), SIGNAL(signal_settings_modified()), SLOT(slot_save_settings())); connect( m_settings_window.get(), SIGNAL(signal_settings_modified()), SLOT(slot_apply_settings())); } m_settings_window->showNormal(); m_settings_window->activateWindow(); } void MainWindow::slot_show_rendering_settings_window() { assert(m_project_manager.is_project_open()); if (m_rendering_settings_window.get() == nullptr) { m_rendering_settings_window.reset( new RenderingSettingsWindow(m_project_manager, this)); connect( m_rendering_settings_window.get(), SIGNAL(signal_settings_modified()), SLOT(slot_project_modified())); } m_rendering_settings_window->showNormal(); m_rendering_settings_window->activateWindow(); } void MainWindow::slot_show_test_window() { if (m_test_window.get() == nullptr) m_test_window.reset(new TestWindow(this)); m_test_window->showNormal(); m_test_window->activateWindow(); } void MainWindow::slot_show_benchmark_window() { if (m_benchmark_window.get() == nullptr) m_benchmark_window.reset(new BenchmarkWindow(this)); m_benchmark_window->showNormal(); m_benchmark_window->activateWindow(); } void MainWindow::slot_show_about_window() { AboutWindow* about_window = new AboutWindow(this); about_window->showNormal(); about_window->activateWindow(); } } // namespace studio } // namespace appleseed #include "mainwindow/moc_cpp_mainwindow.cxx" Change Clear Frame to Clear All in render context menu // // This source file is part of appleseed. // Visit http://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited // Copyright (c) 2014-2017 Francois Beaune, The appleseedhq Organization // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // // Interface header. #include "mainwindow.h" // UI definition header. #include "ui_mainwindow.h" // appleseed.studio headers. #include "help/about/aboutwindow.h" #include "mainwindow/logwidget.h" #include "mainwindow/minimizebutton.h" #include "mainwindow/project/attributeeditor.h" #include "mainwindow/project/projectexplorer.h" #include "mainwindow/pythonconsole/pythonconsolewidget.h" #include "utility/interop.h" #include "utility/miscellaneous.h" #include "utility/settingskeys.h" // appleseed.shared headers. #include "application/application.h" // appleseed.renderer headers. #include "renderer/api/aov.h" #include "renderer/api/frame.h" #include "renderer/api/log.h" #include "renderer/api/project.h" #include "renderer/api/rendering.h" #include "renderer/api/surfaceshader.h" // appleseed.foundation headers. #include "foundation/core/appleseed.h" #include "foundation/math/aabb.h" #include "foundation/math/vector.h" #include "foundation/platform/compiler.h" #include "foundation/platform/system.h" #include "foundation/platform/types.h" #include "foundation/utility/containers/dictionary.h" #include "foundation/utility/foreach.h" #include "foundation/utility/log/logmessage.h" #include "foundation/utility/path.h" #include "foundation/utility/settings.h" // Qt headers. #include <QAction> #include <QActionGroup> #include <QApplication> #include <QCloseEvent> #include <QDir> #include <QFileInfo> #include <QFileSystemWatcher> #include <QIcon> #include <QLabel> #include <QLayout> #include <QLineEdit> #include <QMenu> #include <QMessageBox> #include <QRect> #include <QSettings> #include <QStatusBar> #include <QString> #include <QStringList> #include <Qt> #include <QToolButton> #include <QUrl> // Boost headers. #include "boost/filesystem/path.hpp" // Standard headers. #include <algorithm> #include <cassert> #include <cstdlib> using namespace appleseed::shared; using namespace foundation; using namespace renderer; using namespace std; namespace bf = boost::filesystem; namespace appleseed { namespace studio { // // MainWindow class implementation. // namespace { const int MaxRecentlyOpenedFiles = 15; } MainWindow::MainWindow(QWidget* parent) : QMainWindow(parent) , m_ui(new Ui::MainWindow()) , m_rendering_manager(m_status_bar) , m_project_explorer(nullptr) , m_attribute_editor(nullptr) , m_project_file_watcher(nullptr) { initialize_ocio(); m_ui->setupUi(this); statusBar()->addWidget(&m_status_bar); build_menus(); build_toolbar(); build_log_panel(); build_python_console_panel(); build_project_explorer(); build_connections(); const QSettings settings(SETTINGS_ORGANIZATION, SETTINGS_APPLICATION); restoreGeometry(settings.value("main_window_geometry").toByteArray()); restoreState(settings.value("main_window_state").toByteArray()); m_ui->treewidget_project_explorer_scene->header()->restoreGeometry( settings.value("main_window_project_explorer_geometry").toByteArray()); m_ui->treewidget_project_explorer_scene->header()->restoreState( settings.value("main_window_project_explorer_state").toByteArray()); print_startup_information(); slot_load_settings(); update_project_explorer(); remove_render_widgets(); update_workspace(); build_minimize_buttons(); setAcceptDrops(true); } MainWindow::~MainWindow() { delete m_project_explorer; delete m_ui; } namespace { class CustomSignalMapper : public QObject { Q_OBJECT public: CustomSignalMapper(QObject* parent, const QString& configuration) : QObject(parent) , m_configuration(configuration) { } signals: void mapped(const QString& filepath, const QString& config, const bool success); public slots: void map(const QString& filepath, const bool success) { emit mapped(filepath, m_configuration, success); } private: const QString m_configuration; }; } void MainWindow::new_project() { m_project_manager.create_project(); on_project_change(); } bool MainWindow::open_project(const QString& filepath) { save_state_before_project_open(); if (m_rendering_manager.is_rendering()) { m_rendering_manager.abort_rendering(); m_rendering_manager.wait_until_rendering_end(); } remove_render_widgets(); set_file_widgets_enabled(false, NotRendering); set_project_explorer_enabled(false); set_rendering_widgets_enabled(false, NotRendering); const bool successful = m_project_manager.load_project(filepath.toAscii().constData()); if (successful) { on_project_change(); } else { recreate_render_widgets(); update_workspace(); } return successful; } void MainWindow::open_project_async(const QString& filepath) { save_state_before_project_open(); if (m_rendering_manager.is_rendering()) { m_rendering_manager.abort_rendering(); m_rendering_manager.wait_until_rendering_end(); } remove_render_widgets(); set_file_widgets_enabled(false, NotRendering); set_project_explorer_enabled(false); set_rendering_widgets_enabled(false, NotRendering); m_project_manager.load_project_async(filepath.toAscii().constData()); } void MainWindow::open_and_render_project(const QString& filepath, const QString& configuration) { CustomSignalMapper* mapper = new CustomSignalMapper(this, configuration); connect( &m_project_manager, SIGNAL(signal_load_project_async_complete(const QString&, const bool)), mapper, SLOT(map(const QString&, const bool))); connect( mapper, SIGNAL(mapped(const QString&, const QString&, const bool)), SLOT(slot_start_rendering_once(const QString&, const QString&, const bool))); open_project_async(filepath); } bool MainWindow::save_project(QString filepath) { if (!m_project_manager.is_project_open()) return false; const QString Extension = "appleseed"; if (QFileInfo(filepath).suffix() != Extension) filepath += "." + Extension; if (m_project_file_watcher) stop_monitoring_project_file(); const bool successful = m_project_manager.save_project_as(filepath.toAscii().constData()); if (m_project_file_watcher) start_monitoring_project_file(); update_workspace(); return successful; } bool MainWindow::pack_project(QString filepath) { if (!m_project_manager.is_project_open()) return false; const QString Extension = "appleseedz"; if (QFileInfo(filepath).suffix() != Extension) filepath += "." + Extension; return m_project_manager.pack_project_as(filepath.toAscii().constData()); } void MainWindow::close_project() { m_project_manager.close_project(); on_project_change(); } ProjectManager* MainWindow::get_project_manager() { return &m_project_manager; } ParamArray& MainWindow::get_settings() { return m_settings; } QDockWidget* MainWindow::create_dock_widget(const char* dock_name) { QDockWidget* dock_widget = new QDockWidget(this); const QString object_name = QString(dock_name).toLower().split(' ').join("_"); dock_widget->setObjectName(object_name); dock_widget->setWindowTitle(dock_name); const auto& actions = m_ui->menu_view->actions(); QAction* menu_separator = actions.last(); for (int i = actions.size() - 2; i != 0; --i) { if (actions[i]->isSeparator()) { menu_separator = actions[i]; break; } } m_ui->menu_view->insertAction(menu_separator, dock_widget->toggleViewAction()); m_minimize_buttons.push_back(new MinimizeButton(dock_widget)); statusBar()->insertPermanentWidget( static_cast<int>(m_minimize_buttons.size()), m_minimize_buttons.back()); return dock_widget; } void MainWindow::build_menus() { // // File menu. // m_ui->action_file_new_project->setShortcut(QKeySequence::New); connect(m_ui->action_file_new_project, SIGNAL(triggered()), SLOT(slot_new_project())); m_ui->action_file_open_project->setShortcut(QKeySequence::Open); connect(m_ui->action_file_open_project, SIGNAL(triggered()), SLOT(slot_open_project())); build_recent_files_menu(); connect(m_ui->action_file_open_builtin_project_cornellbox, SIGNAL(triggered()), SLOT(slot_open_cornellbox_builtin_project())); connect(m_ui->action_file_reload_project, SIGNAL(triggered()), SLOT(slot_reload_project())); connect(m_ui->action_file_monitor_project, SIGNAL(toggled(bool)), SLOT(slot_toggle_project_file_monitoring(const bool))); m_ui->action_file_save_project->setShortcut(QKeySequence::Save); connect(m_ui->action_file_save_project, SIGNAL(triggered()), SLOT(slot_save_project())); m_ui->action_file_save_project_as->setShortcut(QKeySequence::SaveAs); connect(m_ui->action_file_save_project_as, SIGNAL(triggered()), SLOT(slot_save_project_as())); connect(m_ui->action_file_pack_project_as, SIGNAL(triggered()), SLOT(slot_pack_project_as())); m_ui->action_file_close_project->setShortcut(QKeySequence::Close); connect(m_ui->action_file_close_project, SIGNAL(triggered()), SLOT(slot_close_project())); m_ui->action_file_exit->setShortcut(QKeySequence::Quit); connect(m_ui->action_file_exit, SIGNAL(triggered()), SLOT(close())); // // View menu. // m_ui->menu_view->addAction(m_ui->project_explorer->toggleViewAction()); m_ui->menu_view->addAction(m_ui->attribute_editor->toggleViewAction()); m_ui->menu_view->addAction(m_ui->log->toggleViewAction()); m_ui->menu_view->addAction(m_ui->python_console->toggleViewAction()); m_ui->menu_view->addSeparator(); QAction* fullscreen_action = m_ui->menu_view->addAction("Fullscreen"); fullscreen_action->setShortcut(Qt::Key_F11); connect(fullscreen_action, SIGNAL(triggered()), SLOT(slot_fullscreen())); // // Rendering menu. // connect(m_ui->action_rendering_start_interactive_rendering, SIGNAL(triggered()), SLOT(slot_start_interactive_rendering())); connect(m_ui->action_rendering_start_final_rendering, SIGNAL(triggered()), SLOT(slot_start_final_rendering())); connect(m_ui->action_rendering_stop_rendering, SIGNAL(triggered()), &m_rendering_manager, SLOT(slot_abort_rendering())); connect(m_ui->action_rendering_rendering_settings, SIGNAL(triggered()), SLOT(slot_show_rendering_settings_window())); // // Diagnostics menu. // build_override_shading_menu_item(); // // Debug menu. // connect(m_ui->action_debug_tests, SIGNAL(triggered()), SLOT(slot_show_test_window())); connect(m_ui->action_debug_benchmarks, SIGNAL(triggered()), SLOT(slot_show_benchmark_window())); // // Tools menu. // connect(m_ui->action_tools_settings, SIGNAL(triggered()), SLOT(slot_show_settings_window())); connect(m_ui->action_tools_save_settings, SIGNAL(triggered()), SLOT(slot_save_settings())); connect(m_ui->action_tools_reload_settings, SIGNAL(triggered()), SLOT(slot_load_settings())); // // Help menu. // connect(m_ui->action_help_about, SIGNAL(triggered()), SLOT(slot_show_about_window())); } void MainWindow::build_override_shading_menu_item() { QActionGroup* action_group = new QActionGroup(this); connect( m_ui->action_diagnostics_override_shading_no_override, SIGNAL(triggered()), SLOT(slot_clear_shading_override())); action_group->addAction(m_ui->action_diagnostics_override_shading_no_override); for (int i = 0; i < DiagnosticSurfaceShader::ShadingModeCount; ++i) { const char* shading_mode_value = DiagnosticSurfaceShader::ShadingModeNames[i].m_key; const char* shading_mode_name = DiagnosticSurfaceShader::ShadingModeNames[i].m_value; QAction* action = new QAction(this); action->setCheckable(true); action->setObjectName( QString::fromAscii("action_diagnostics_override_shading_") + shading_mode_value); action->setText( QApplication::translate( objectName().toAscii().constData(), shading_mode_name, nullptr, QApplication::UnicodeUTF8)); const int shortcut_number = i + 1; if (shortcut_number <= 9) { const QString shortcut = QApplication::translate( objectName().toAscii().constData(), QString::fromAscii("Ctrl+Shift+%1").arg(shortcut_number).toAscii().constData(), nullptr, QApplication::UnicodeUTF8); action->setShortcut(shortcut); } action->setData(shading_mode_value); connect( action, SIGNAL(triggered()), SLOT(slot_set_shading_override())); m_ui->menu_diagnostics_override_shading->addAction(action); action_group->addAction(action); } } void MainWindow::update_override_shading_menu_item() { const ParamArray project_params = get_project_params("interactive"); const ParamArray shading_engine_params = project_params.child("shading_engine"); if (shading_engine_params.dictionaries().exist("override_shading")) { const string shading_mode = shading_engine_params.child("override_shading").get_optional<string>("mode", "coverage"); for (const_each<QList<QAction*>> i = m_ui->menu_diagnostics_override_shading->actions(); i; ++i) { QAction* action = *i; if (action->data().toString().toStdString() == shading_mode) { action->activate(QAction::Trigger); break; } } } else { m_ui->action_diagnostics_override_shading_no_override->activate(QAction::Trigger); } } void MainWindow::build_recent_files_menu() { assert(m_recently_opened.empty()); m_recently_opened.reserve(MaxRecentlyOpenedFiles); for (int i = 0; i < MaxRecentlyOpenedFiles; ++i) { QAction* action = new QAction(this); action->setVisible(false); connect(action, SIGNAL(triggered()), SLOT(slot_open_recent())); m_ui->menu_open_recent->addAction(action); m_recently_opened.push_back(action); } QSettings settings(SETTINGS_ORGANIZATION, SETTINGS_APPLICATION); QStringList files = settings.value("recent_file_list").toStringList(); update_recent_files_menu(files); m_ui->menu_open_recent->addSeparator(); QAction* clear_open_recent_menu = new QAction(this); clear_open_recent_menu->setText("&Clear Menu"); connect(clear_open_recent_menu, SIGNAL(triggered()), SLOT(slot_clear_open_recent_files_menu())); m_ui->menu_open_recent->addAction(clear_open_recent_menu); } void MainWindow::update_recent_files_menu(const QString& filepath) { QSettings settings(SETTINGS_ORGANIZATION, SETTINGS_APPLICATION); QStringList files = settings.value("recent_file_list").toStringList(); files.removeAll(filepath); files.prepend(filepath); while (files.size() > MaxRecentlyOpenedFiles) files.removeLast(); update_recent_files_menu(files); settings.setValue("recent_file_list", files); } void MainWindow::update_recent_files_menu(const QStringList& files) { const int recent_file_count = min(files.size(), MaxRecentlyOpenedFiles); for (int i = 0; i < recent_file_count; ++i) { const int number = i + 1; const QString filepath = files[i]; const QString format = number < 10 ? "&%1 %2" : "%1 %2"; const QString text = format.arg(number).arg(filepath); m_recently_opened[i]->setText(text); m_recently_opened[i]->setData(filepath); m_recently_opened[i]->setVisible(true); } for (int i = recent_file_count; i < MaxRecentlyOpenedFiles; ++i) m_recently_opened[i]->setVisible(false); } void MainWindow::build_toolbar() { // // File actions. // m_action_new_project = new QAction(load_icons("project_new"), combine_name_and_shortcut("New Project", m_ui->action_file_new_project->shortcut()), this); connect(m_action_new_project, SIGNAL(triggered()), SLOT(slot_new_project())); m_ui->main_toolbar->addAction(m_action_new_project); m_action_open_project = new QAction(load_icons("project_open"), combine_name_and_shortcut("Open Project...", m_ui->action_file_open_project->shortcut()), this); connect(m_action_open_project, SIGNAL(triggered()), SLOT(slot_open_project())); m_ui->main_toolbar->addAction(m_action_open_project); m_action_save_project = new QAction(load_icons("project_save") , combine_name_and_shortcut("Save Project", m_ui->action_file_save_project->shortcut()), this); connect(m_action_save_project, SIGNAL(triggered()), SLOT(slot_save_project())); m_ui->main_toolbar->addAction(m_action_save_project); m_action_reload_project = new QAction(load_icons("project_reload"), combine_name_and_shortcut("Reload Project", m_ui->action_file_reload_project->shortcut()), this); connect(m_action_reload_project, SIGNAL(triggered()), SLOT(slot_reload_project())); m_ui->main_toolbar->addAction(m_action_reload_project); m_action_monitor_project_file = new QAction(load_icons("project_monitor"), "Toggle Project File Monitoring", this); m_action_monitor_project_file->setCheckable(true); connect(m_action_monitor_project_file, SIGNAL(toggled(bool)), SLOT(slot_toggle_project_file_monitoring(const bool))); m_ui->main_toolbar->addAction(m_action_monitor_project_file); m_ui->main_toolbar->addSeparator(); // // Rendering actions. // m_action_start_interactive_rendering = new QAction(load_icons("rendering_start_interactive"), combine_name_and_shortcut("Start Interactive Rendering", m_ui->action_rendering_start_interactive_rendering->shortcut()), this); connect(m_action_start_interactive_rendering, SIGNAL(triggered()), SLOT(slot_start_interactive_rendering())); m_ui->main_toolbar->addAction(m_action_start_interactive_rendering); m_action_start_final_rendering = new QAction(load_icons("rendering_start_final"), combine_name_and_shortcut("Start Final Rendering", m_ui->action_rendering_start_final_rendering->shortcut()), this); connect(m_action_start_final_rendering, SIGNAL(triggered()), SLOT(slot_start_final_rendering())); m_ui->main_toolbar->addAction(m_action_start_final_rendering); m_action_stop_rendering = new QAction(load_icons("rendering_stop"), combine_name_and_shortcut("Stop Rendering", m_ui->action_rendering_stop_rendering->shortcut()), this); connect(m_action_stop_rendering, SIGNAL(triggered()), &m_rendering_manager, SLOT(slot_abort_rendering())); m_ui->main_toolbar->addAction(m_action_stop_rendering); m_action_rendering_settings = new QAction(load_icons("rendering_settings"), combine_name_and_shortcut("Rendering Settings...", m_ui->action_rendering_rendering_settings->shortcut()), this); connect(m_action_rendering_settings, SIGNAL(triggered()), SLOT(slot_show_rendering_settings_window())); m_ui->main_toolbar->addAction(m_action_rendering_settings); } void MainWindow::build_log_panel() { LogWidget* log_widget = new LogWidget(m_ui->log_contents); m_ui->log_contents->layout()->addWidget(log_widget); log_widget->setObjectName("textedit_log"); log_widget->setUndoRedoEnabled(false); log_widget->setLineWrapMode(QTextEdit::NoWrap); log_widget->setReadOnly(true); log_widget->setTextInteractionFlags(Qt::TextSelectableByMouse); m_log_target.reset(new QtLogTarget(log_widget)); global_logger().add_target(m_log_target.get()); } void MainWindow::build_python_console_panel() { PythonConsoleWidget* console_widget = new PythonConsoleWidget(m_ui->python_console_contents); m_ui->python_console_contents->layout()->addWidget(console_widget); console_widget->setObjectName("textedit_console"); } void MainWindow::build_project_explorer() { m_ui->treewidget_project_explorer_scene->setColumnWidth(0, 295); // name disable_osx_focus_rect(m_ui->treewidget_project_explorer_scene); connect( m_ui->lineedit_filter, SIGNAL(textChanged(const QString&)), SLOT(slot_filter_text_changed(const QString&))); connect( m_ui->pushbutton_clear_filter, SIGNAL(clicked()), SLOT(slot_clear_filter())); m_ui->pushbutton_clear_filter->setEnabled(false); } void MainWindow::build_minimize_buttons() { m_minimize_buttons.push_back(new MinimizeButton(m_ui->project_explorer)); m_minimize_buttons.push_back(new MinimizeButton(m_ui->attribute_editor)); m_minimize_buttons.push_back(new MinimizeButton(m_ui->log)); m_minimize_buttons.push_back(new MinimizeButton(m_ui->python_console)); for (size_t i = 0; i < m_minimize_buttons.size(); ++i) { statusBar()->insertPermanentWidget( static_cast<int>(i + 1), m_minimize_buttons[i]); } } void MainWindow::build_connections() { connect( m_action_monitor_project_file, SIGNAL(toggled(bool)), m_ui->action_file_monitor_project, SLOT(setChecked(bool))); connect( m_ui->action_file_monitor_project, SIGNAL(toggled(bool)), m_action_monitor_project_file, SLOT(setChecked(bool))); connect( &m_project_manager, SIGNAL(signal_load_project_async_complete(const QString&, const bool)), SLOT(slot_open_project_complete(const QString&, const bool))); connect( &m_rendering_manager, SIGNAL(signal_rendering_end()), SLOT(slot_rendering_end())); connect( &m_rendering_manager, SIGNAL(signal_camera_changed()), SLOT(slot_camera_changed())); } void MainWindow::update_workspace() { update_window_title(); set_file_widgets_enabled(true, NotRendering); set_project_explorer_enabled(true); set_rendering_widgets_enabled(true, NotRendering); m_ui->attribute_editor_scrollarea_contents->setEnabled(true); } void MainWindow::update_project_explorer() { delete m_project_explorer; m_project_explorer = nullptr; delete m_attribute_editor; m_attribute_editor = nullptr; if (m_project_manager.is_project_open()) { m_attribute_editor = new AttributeEditor( m_ui->attribute_editor_scrollarea_contents, *m_project_manager.get_project(), m_settings); m_project_explorer = new ProjectExplorer( m_ui->treewidget_project_explorer_scene, m_attribute_editor, *m_project_manager.get_project(), m_rendering_manager, m_settings); connect( m_project_explorer, SIGNAL(signal_project_modified()), SLOT(slot_project_modified())); connect( m_project_explorer, SIGNAL(signal_frame_modified()), SLOT(slot_frame_modified())); } m_ui->lineedit_filter->clear(); } void MainWindow::update_window_title() { QString title; if (m_project_manager.is_project_open()) { if (m_project_manager.is_project_dirty()) title.append("* "); title.append(QString::fromStdString(m_project_manager.get_project_display_name())); title.append(" - "); } title.append("appleseed.studio"); setWindowTitle(title); } void MainWindow::set_file_widgets_enabled(const bool is_enabled, const RenderingMode rendering_mode) { const bool is_project_open = m_project_manager.is_project_open(); const bool project_has_path = is_project_open && m_project_manager.get_project()->has_path(); // File -> New Project. m_ui->action_file_new_project->setEnabled(is_enabled); m_action_new_project->setEnabled(is_enabled); // File -> Open Project. m_ui->action_file_open_project->setEnabled(is_enabled); m_action_open_project->setEnabled(is_enabled); // File -> Open Recent. m_ui->menu_open_recent->setEnabled(is_enabled); // File -> Open Built-in Project. m_ui->menu_file_open_builtin_project->setEnabled(is_enabled); // File -> Reload Project. const bool allow_reload = (is_enabled || rendering_mode == InteractiveRendering) && project_has_path; m_ui->action_file_reload_project->setEnabled(allow_reload); m_action_reload_project->setEnabled(allow_reload); // File -> Monitor Project. const bool allow_monitor = (is_enabled || rendering_mode == InteractiveRendering) && project_has_path; m_ui->action_file_monitor_project->setEnabled(allow_monitor); m_action_monitor_project_file->setEnabled(allow_monitor); // File -> Save Project, Save Project As and Pack Project As. const bool allow_save = is_enabled && is_project_open; m_ui->action_file_save_project->setEnabled(allow_save); m_action_save_project->setEnabled(allow_save); m_ui->action_file_save_project_as->setEnabled(allow_save); m_ui->action_file_pack_project_as->setEnabled(allow_save); // File -> Close Project. const bool allow_close = is_enabled && is_project_open; m_ui->action_file_close_project->setEnabled(allow_close); // File -> Exit. m_ui->action_file_exit->setEnabled(is_enabled); } void MainWindow::set_project_explorer_enabled(const bool is_enabled) { const bool is_project_open = m_project_manager.is_project_open(); m_ui->label_filter->setEnabled(is_enabled && is_project_open); m_ui->lineedit_filter->setEnabled(is_enabled && is_project_open); m_ui->pushbutton_clear_filter->setEnabled(is_enabled && is_project_open && !m_ui->lineedit_filter->text().isEmpty()); m_ui->treewidget_project_explorer_scene->setEnabled(is_enabled && is_project_open); } void MainWindow::set_rendering_widgets_enabled(const bool is_enabled, const RenderingMode rendering_mode) { const bool is_project_open = m_project_manager.is_project_open(); const bool allow_start = is_enabled && is_project_open && rendering_mode == NotRendering; const bool allow_stop = is_enabled && is_project_open && rendering_mode != NotRendering; // Rendering -> Rendering Settings. m_ui->action_rendering_rendering_settings->setEnabled(allow_start); m_action_rendering_settings->setEnabled(allow_start); // Rendering -> Start Interactive Rendering. m_ui->action_rendering_start_interactive_rendering->setEnabled(allow_start); m_action_start_interactive_rendering->setEnabled(allow_start); // Rendering -> Start Final Rendering. m_ui->action_rendering_start_final_rendering->setEnabled(allow_start); m_action_start_final_rendering->setEnabled(allow_start); // Rendering -> Stop Rendering. m_ui->action_rendering_stop_rendering->setEnabled(allow_stop); m_action_stop_rendering->setEnabled(allow_stop); // Rendering -> Render Settings. m_ui->action_rendering_rendering_settings->setEnabled(allow_start); // Render tab buttons. const int current_tab_index = m_ui->tab_render_channels->currentIndex(); if (current_tab_index != -1) { RenderTab* render_tab = m_tab_index_to_render_tab[current_tab_index]; // Clear frame. render_tab->set_clear_frame_button_enabled( is_enabled && is_project_open && rendering_mode == NotRendering); // Set/clear rendering region. render_tab->set_render_region_buttons_enabled( is_enabled && is_project_open && rendering_mode != FinalRendering); // Scene picker. render_tab->get_scene_picking_handler()->set_enabled( is_enabled && is_project_open && rendering_mode != FinalRendering); } } void MainWindow::save_state_before_project_open() { m_state_before_project_open.reset(new StateBeforeProjectOpen()); m_state_before_project_open->m_is_rendering = m_rendering_manager.is_rendering(); for (const_each<RenderTabCollection> i = m_render_tabs; i; ++i) m_state_before_project_open->m_render_tab_states[i->first] = i->second->save_state(); } void MainWindow::restore_state_after_project_open() { if (m_state_before_project_open.get()) { for (const_each<RenderTabCollection> i = m_render_tabs; i; ++i) { const RenderTabStateCollection& tab_states = m_state_before_project_open->m_render_tab_states; const RenderTabStateCollection::const_iterator tab_state_it = tab_states.find(i->first); if (tab_state_it != tab_states.end()) i->second->load_state(tab_state_it->second); } if (m_state_before_project_open->m_is_rendering) start_rendering(InteractiveRendering); } } void MainWindow::recreate_render_widgets() { remove_render_widgets(); if (m_project_manager.is_project_open()) add_render_widget("RGB"); } void MainWindow::remove_render_widgets() { for (const_each<RenderTabCollection> i = m_render_tabs; i; ++i) delete i->second; m_render_tabs.clear(); m_tab_index_to_render_tab.clear(); while (m_ui->tab_render_channels->count() > 0) m_ui->tab_render_channels->removeTab(0); } void MainWindow::add_render_widget(const QString& label) { // Create the render tab. RenderTab* render_tab = new RenderTab( *m_project_explorer, *m_project_manager.get_project(), m_ocio_config); connect( render_tab, SIGNAL(signal_render_widget_context_menu(const QPoint&)), SLOT(slot_render_widget_context_menu(const QPoint&))); connect( render_tab, SIGNAL(signal_set_render_region(const QRect&)), SLOT(slot_set_render_region(const QRect&))); connect( render_tab, SIGNAL(signal_clear_render_region()), SLOT(slot_clear_render_region())); connect( render_tab, SIGNAL(signal_save_all_aovs()), SLOT(slot_save_all_aovs())); connect( render_tab, SIGNAL(signal_quicksave_all_aovs()), SLOT(slot_quicksave_all_aovs())); connect( render_tab, SIGNAL(signal_reset_zoom()), SLOT(slot_reset_zoom())); connect( render_tab, SIGNAL(signal_clear_frame()), SLOT(slot_clear_frame())); connect( render_tab, SIGNAL(signal_entity_picked(renderer::ScenePicker::PickingResult)), SLOT(slot_clear_filter())); connect( render_tab, SIGNAL(signal_camera_change_begin()), &m_rendering_manager, SLOT(slot_camera_change_begin())); connect( render_tab, SIGNAL(signal_camera_change_end()), &m_rendering_manager, SLOT(slot_camera_change_end())); connect( render_tab, SIGNAL(signal_camera_changed()), &m_rendering_manager, SLOT(slot_camera_changed())); connect( render_tab, SIGNAL(signal_camera_changed()), &m_rendering_manager, SIGNAL(signal_camera_changed())); // Add the render tab to the tab bar. const int tab_index = m_ui->tab_render_channels->addTab(render_tab, label); // Update the mappings. m_render_tabs[label.toStdString()] = render_tab; m_tab_index_to_render_tab[tab_index] = render_tab; } ParamArray MainWindow::get_project_params(const char* configuration_name) const { ParamArray params; Configuration* configuration = m_project_manager.is_project_open() ? m_project_manager.get_project()->configurations().get_by_name(configuration_name) : nullptr; if (configuration && configuration->get_base()) params = configuration->get_base()->get_parameters(); params.merge(m_settings); if (configuration) params.merge(configuration->get_parameters()); return params; } namespace { int show_modified_project_message_box(QWidget* parent) { QMessageBox msgbox(parent); msgbox.setWindowTitle("Save Changes?"); msgbox.setIcon(QMessageBox::Question); msgbox.setText("The project has been modified."); msgbox.setInformativeText("Do you want to save your changes?"); msgbox.setStandardButtons(QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel); msgbox.setDefaultButton(QMessageBox::Save); return msgbox.exec(); } } bool MainWindow::can_close_project() { // Project being loaded: can't close. if (m_project_manager.is_project_loading()) return false; // No project open: no problem. if (!m_project_manager.is_project_open()) return true; // Unmodified project: no problem. if (!m_project_manager.is_project_dirty()) return true; // The current project has been modified, ask the user what to do. switch (show_modified_project_message_box(this)) { case QMessageBox::Save: slot_save_project(); return true; case QMessageBox::Discard: return true; case QMessageBox::Cancel: return false; } assert(!"Should never be reached."); return false; } void MainWindow::on_project_change() { update_project_explorer(); recreate_render_widgets(); update_override_shading_menu_item(); if (m_rendering_settings_window.get() != nullptr && m_project_manager.get_project() != nullptr) m_rendering_settings_window->reload(); m_status_bar.clear(); update_workspace(); restore_state_after_project_open(); if (m_project_file_watcher) start_monitoring_project_file(); } void MainWindow::enable_project_file_monitoring() { if (m_project_file_watcher == nullptr) { m_project_file_watcher = new QFileSystemWatcher(this); connect( m_project_file_watcher, SIGNAL(fileChanged(const QString&)), SLOT(slot_project_file_changed(const QString&))); RENDERER_LOG_INFO("project file monitoring is now enabled."); start_monitoring_project_file(); } } void MainWindow::disable_project_file_monitoring() { if (m_project_file_watcher) { delete m_project_file_watcher; m_project_file_watcher = nullptr; RENDERER_LOG_INFO("project file monitoring is now disabled."); } } void MainWindow::start_monitoring_project_file() { assert(m_project_file_watcher); if (m_project_manager.is_project_open() && m_project_manager.get_project()->has_path()) { m_project_file_watcher->addPath(m_project_manager.get_project()->get_path()); } } void MainWindow::stop_monitoring_project_file() { assert(m_project_file_watcher); if (m_project_manager.is_project_open() && m_project_manager.get_project()->has_path()) { m_project_file_watcher->removePath(m_project_manager.get_project()->get_path()); } } void MainWindow::dragEnterEvent(QDragEnterEvent* event) { if (event->mimeData()->hasFormat("text/plain") || event->mimeData()->hasFormat("text/uri-list")) event->acceptProposedAction(); } void MainWindow::dropEvent(QDropEvent* event) { if (event->mimeData()->hasFormat("text/uri-list")) { const QList<QUrl> urls = event->mimeData()->urls(); QApplication::sendEvent(this, new QCloseEvent()); open_project_async(urls[0].toLocalFile()); } else { const QString text = event->mimeData()->text(); QApplication::sendEvent(this, new QCloseEvent()); open_project_async(text); } event->accept(); } void MainWindow::start_rendering(const RenderingMode rendering_mode) { assert(m_project_manager.is_project_open()); // Enable/disable widgets appropriately. set_file_widgets_enabled(false, rendering_mode); set_rendering_widgets_enabled(true, rendering_mode); set_project_explorer_enabled(rendering_mode == InteractiveRendering); m_ui->attribute_editor_scrollarea_contents->setEnabled(rendering_mode == InteractiveRendering); // Stop monitoring the project file in Final rendering mode. if (rendering_mode == FinalRendering) { if (m_project_file_watcher) stop_monitoring_project_file(); } Project* project = m_project_manager.get_project(); Frame* frame = project->get_frame(); frame->clear_main_and_aov_images(); // In the UI, darken all render widgets. for (const_each<RenderTabCollection> i = m_render_tabs; i; ++i) { i->second->darken(); i->second->update(); } // Retrieve the right configuration. const char* configuration_name = rendering_mode == InteractiveRendering ? "interactive" : "final"; const ParamArray params = get_project_params(configuration_name); // Effectively start rendering. m_rendering_manager.start_rendering( project, params, rendering_mode == InteractiveRendering ? RenderingManager::InteractiveRendering : RenderingManager::FinalRendering, m_render_tabs["RGB"]); } void MainWindow::print_startup_information() { RENDERER_LOG_INFO( "%s, %s configuration\n" "compiled on %s at %s using %s version %s", Appleseed::get_synthetic_version_string(), Appleseed::get_lib_configuration(), Appleseed::get_lib_compilation_date(), Appleseed::get_lib_compilation_time(), Compiler::get_compiler_name(), Compiler::get_compiler_version()); System::print_information(global_logger()); } namespace { int ask_abort_rendering_confirmation(QWidget* parent) { QMessageBox msgbox(parent); msgbox.setWindowTitle("Abort Rendering?"); msgbox.setIcon(QMessageBox::Question); msgbox.setText("Rendering is in progress."); msgbox.setInformativeText("Do you want to abort rendering?"); msgbox.setStandardButtons(QMessageBox::Yes | QMessageBox::No); msgbox.setDefaultButton(QMessageBox::No); return msgbox.exec(); } } void MainWindow::closeEvent(QCloseEvent* event) { if (m_rendering_manager.is_rendering()) { if (ask_abort_rendering_confirmation(this) != QMessageBox::Yes) { event->ignore(); return; } m_rendering_manager.abort_rendering(); m_rendering_manager.wait_until_rendering_end(); } if (!can_close_project()) { event->ignore(); return; } QSettings settings(SETTINGS_ORGANIZATION, SETTINGS_APPLICATION); settings.setValue("main_window_geometry", saveGeometry()); settings.setValue("main_window_state", saveState()); settings.setValue("main_window_project_explorer_geometry", m_ui->treewidget_project_explorer_scene->header()->saveGeometry()); settings.setValue("main_window_project_explorer_state", m_ui->treewidget_project_explorer_scene->header()->saveState()); slot_save_settings(); if (m_test_window.get()) m_test_window->close(); if (m_benchmark_window.get()) m_benchmark_window->close(); remove_render_widgets(); m_project_manager.close_project(); event->accept(); } void MainWindow::slot_new_project() { if (!can_close_project()) return; new_project(); } void MainWindow::slot_open_project() { if (!can_close_project()) return; QString filepath = get_open_filename( this, "Open...", get_project_files_filter(), m_settings, SETTINGS_FILE_DIALOG_PROJECTS); if (!filepath.isEmpty()) { filepath = QDir::toNativeSeparators(filepath); open_project_async(filepath); update_recent_files_menu(filepath); } } void MainWindow::slot_open_recent() { if (!can_close_project()) return; QAction* action = qobject_cast<QAction*>(sender()); if (action) { const QString filepath = action->data().toString(); open_project_async(filepath); } } void MainWindow::slot_clear_open_recent_files_menu() { QSettings settings(SETTINGS_ORGANIZATION, SETTINGS_APPLICATION); settings.setValue("recent_file_list", QStringList()); update_recent_files_menu(QStringList()); } void MainWindow::slot_open_cornellbox_builtin_project() { if (!can_close_project()) return; APPLESEED_UNUSED const bool successful = m_project_manager.load_builtin_project("cornell_box"); assert(successful); on_project_change(); } void MainWindow::slot_reload_project() { assert(m_project_manager.is_project_open()); assert(m_project_manager.get_project()->has_path()); if (!can_close_project()) return; open_project_async(m_project_manager.get_project()->get_path()); } namespace { void show_project_file_loading_failed_message_box(QWidget* parent, const QString& filepath) { QMessageBox msgbox(parent); msgbox.setWindowTitle("Loading Error"); msgbox.setIcon(QMessageBox::Critical); msgbox.setText("Failed to load the project file " + filepath + "."); msgbox.setInformativeText( "The project file may be invalid, corrupted or missing. " "Please look at the Log window for details."); msgbox.setStandardButtons(QMessageBox::Ok); msgbox.exec(); } } void MainWindow::slot_open_project_complete(const QString& filepath, const bool successful) { if (successful) { on_project_change(); } else { show_project_file_loading_failed_message_box(this, filepath); recreate_render_widgets(); update_workspace(); } } void MainWindow::slot_save_project() { assert(m_project_manager.is_project_open()); if (!m_project_manager.get_project()->has_path()) slot_save_project_as(); else save_project(m_project_manager.get_project()->get_path()); } void MainWindow::slot_save_project_as() { assert(m_project_manager.is_project_open()); QString filepath = get_save_filename( this, "Save As...", get_project_files_filter(ProjectFilesFilterPlainProjects), m_settings, SETTINGS_FILE_DIALOG_PROJECTS); if (!filepath.isEmpty()) { filepath = QDir::toNativeSeparators(filepath); save_project(filepath); update_recent_files_menu(filepath); } } void MainWindow::slot_pack_project_as() { assert(m_project_manager.is_project_open()); QString filepath = get_save_filename( this, "Pack As...", get_project_files_filter(ProjectFilesFilterPackedProjects), m_settings, SETTINGS_FILE_DIALOG_PROJECTS); if (!filepath.isEmpty()) { filepath = QDir::toNativeSeparators(filepath); pack_project(filepath); // Don't update the Recent Files menu. } } void MainWindow::slot_close_project() { if (!can_close_project()) return; close_project(); } void MainWindow::initialize_ocio() { // Try first a user specified OCIO config. if (getenv("OCIO")) { try { m_ocio_config = OCIO::GetCurrentConfig(); RENDERER_LOG_INFO("using ocio configuration: %s", getenv("OCIO")); return; } catch (const OCIO::Exception&) { } } // Try the bundled default OCIO config. const bf::path root_path(Application::get_root_path()); const string default_ocio_config = (root_path / "ocio" / "config.ocio").string(); try { m_ocio_config = OCIO::Config::CreateFromFile(default_ocio_config.c_str()); RENDERER_LOG_INFO("using ocio configuration: %s", default_ocio_config.c_str()); OCIO::SetCurrentConfig(m_ocio_config); return; } catch (const OCIO::Exception&) { } // Default to an empty OCIO config if everything else fails. m_ocio_config = OCIO::GetCurrentConfig(); RENDERER_LOG_ERROR("Could not initialize OCIO config."); } void MainWindow::slot_project_modified() { assert(m_project_manager.is_project_open()); m_project_manager.set_project_dirty_flag(); update_window_title(); } void MainWindow::slot_toggle_project_file_monitoring(const bool checked) { if (checked) enable_project_file_monitoring(); else disable_project_file_monitoring(); m_settings.insert_path( SETTINGS_WATCH_FILE_CHANGES, m_project_file_watcher != nullptr); } void MainWindow::slot_project_file_changed(const QString& filepath) { RENDERER_LOG_INFO("project file changed on disk, reloading it."); assert(m_project_file_watcher); m_project_file_watcher->removePath(filepath); slot_reload_project(); } void MainWindow::slot_load_settings() { Dictionary settings; if (!Application::load_settings("appleseed.studio.xml", settings, global_logger(), LogMessage::Info)) return; m_settings = settings; slot_apply_settings(); } void MainWindow::slot_save_settings() { SettingsFileWriter writer; // First try to save the settings to the user path. if (const char* p = Application::get_user_settings_path()) { try { const bf::path user_settings_path(p); bf::create_directories(user_settings_path); const string user_settings_file_path = (user_settings_path / "appleseed.studio.xml").string(); if (writer.write(user_settings_file_path.c_str(), m_settings)) { RENDERER_LOG_INFO("successfully saved settings to %s.", user_settings_file_path.c_str()); return; } } catch (const bf::filesystem_error&) { } } // As a fallback, try to save the settings to the appleseed's installation directory. const bf::path root_path(Application::get_root_path()); const string settings_file_path = (root_path / "settings" / "appleseed.studio.xml").string(); if (writer.write(settings_file_path.c_str(), m_settings)) { RENDERER_LOG_INFO("successfully saved settings to %s.", settings_file_path.c_str()); return; } RENDERER_LOG_ERROR("failed to save settings to %s.", settings_file_path.c_str()); } void MainWindow::slot_apply_settings() { if (m_settings.strings().exist(SETTINGS_MESSAGE_VERBOSITY)) { const char* level_name = m_settings.get(SETTINGS_MESSAGE_VERBOSITY); const LogMessage::Category level = LogMessage::get_category_value(level_name); if (level < LogMessage::NumMessageCategories) global_logger().set_verbosity_level(level); else RENDERER_LOG_ERROR("invalid message verbosity level \"%s\".", level_name); } if (m_settings.get_optional<bool>(SETTINGS_WATCH_FILE_CHANGES)) { m_action_monitor_project_file->setChecked(true); enable_project_file_monitoring(); } else { m_action_monitor_project_file->setChecked(false); disable_project_file_monitoring(); } } void MainWindow::slot_start_interactive_rendering() { start_rendering(InteractiveRendering); } void MainWindow::slot_start_final_rendering() { start_rendering(FinalRendering); } void MainWindow::slot_start_rendering_once(const QString& filepath, const QString& configuration, const bool successful) { sender()->deleteLater(); if (successful) { if (configuration == "interactive") start_rendering(InteractiveRendering); else start_rendering(FinalRendering); } } void MainWindow::slot_rendering_end() { update_workspace(); // Restart monitoring the project file if monitoring was enabled // (monitoring would have been stopped if rendering in Final mode). if (m_project_file_watcher) start_monitoring_project_file(); } void MainWindow::slot_camera_changed() { m_project_manager.set_project_dirty_flag(); } namespace { class ClearShadingOverrideAction : public RenderingManager::IStickyAction { public: void operator()( MasterRenderer& master_renderer, Project& project) override { master_renderer.get_parameters() .push("shading_engine") .dictionaries().remove("override_shading"); } }; class SetShadingOverrideAction : public RenderingManager::IStickyAction { public: explicit SetShadingOverrideAction(const string& shading_mode) : m_shading_mode(shading_mode) { } void operator()( MasterRenderer& master_renderer, Project& project) override { master_renderer.get_parameters() .push("shading_engine") .push("override_shading") .insert("mode", m_shading_mode); } private: const string m_shading_mode; }; } void MainWindow::slot_clear_shading_override() { m_rendering_manager.set_sticky_action( "override_shading", unique_ptr<RenderingManager::IStickyAction>( new ClearShadingOverrideAction())); m_rendering_manager.reinitialize_rendering(); } void MainWindow::slot_set_shading_override() { QAction* action = qobject_cast<QAction*>(sender()); const string shading_mode = action->data().toString().toStdString(); m_rendering_manager.set_sticky_action( "override_shading", unique_ptr<RenderingManager::IStickyAction>( new SetShadingOverrideAction(shading_mode))); m_rendering_manager.reinitialize_rendering(); } namespace { class ClearRenderRegionAction : public RenderingManager::IScheduledAction { public: explicit ClearRenderRegionAction(const AttributeEditor* attribute_editor) : m_attribute_editor(attribute_editor) { } void operator()( Project& project) override { project.get_frame()->reset_crop_window(); m_attribute_editor->refresh(); } private: const AttributeEditor* m_attribute_editor; }; class SetRenderRegionAction : public RenderingManager::IScheduledAction { public: SetRenderRegionAction( const QRect& rect, const AttributeEditor* attribute_editor) : m_rect(rect), m_attribute_editor(attribute_editor) { } void operator()( Project& project) override { const int w = m_rect.width(); const int h = m_rect.height(); const int x0 = m_rect.x(); const int y0 = m_rect.y(); const int x1 = x0 + w - 1; const int y1 = y0 + h - 1; assert(x0 >= 0); assert(y0 >= 0); assert(x0 <= x1); assert(y0 <= y1); project.get_frame()->set_crop_window( AABB2i( Vector2i(x0, y0), Vector2i(x1, y1))); m_attribute_editor->refresh(); } private: const QRect m_rect; const AttributeEditor* m_attribute_editor; }; } void MainWindow::slot_clear_render_region() { unique_ptr<RenderingManager::IScheduledAction> clear_render_region_action( new ClearRenderRegionAction(m_attribute_editor)); if (m_rendering_manager.is_rendering()) m_rendering_manager.schedule(std::move(clear_render_region_action)); else clear_render_region_action.get()->operator()( *m_project_manager.get_project()); m_rendering_manager.reinitialize_rendering(); } void MainWindow::slot_set_render_region(const QRect& rect) { unique_ptr<RenderingManager::IScheduledAction> set_render_region_action( new SetRenderRegionAction(rect, m_attribute_editor)); if (!m_rendering_manager.is_rendering()) { set_render_region_action.get()->operator()( *m_project_manager.get_project()); if (m_settings.get_path_optional<bool>(SETTINGS_RENDER_REGION_TRIGGERS_RENDERING)) start_rendering(InteractiveRendering); } else { m_rendering_manager.schedule(std::move(set_render_region_action)); m_rendering_manager.reinitialize_rendering(); } } void MainWindow::slot_render_widget_context_menu(const QPoint& point) { if (!(QApplication::keyboardModifiers() & Qt::ShiftModifier)) return; if (m_rendering_manager.is_rendering()) return; QMenu* menu = new QMenu(this); menu->addAction("Save Frame...", this, SLOT(slot_save_frame())); menu->addAction("Save All AOVs...", this, SLOT(slot_save_all_aovs())); menu->addSeparator(); menu->addAction("Clear All", this, SLOT(slot_clear_frame())); menu->exec(point); } namespace { QString ask_frame_save_file_path( QWidget* parent, const QString& caption, ParamArray& settings) { QString filepath = get_save_filename( parent, caption, g_appleseed_image_files_filter, settings, SETTINGS_FILE_DIALOG_FRAMES); if (!filepath.isEmpty()) { if (QFileInfo(filepath).suffix().isEmpty()) filepath += ".exr"; filepath = QDir::toNativeSeparators(filepath); } return filepath; } } void MainWindow::slot_save_frame() { assert(m_project_manager.is_project_open()); assert(!m_rendering_manager.is_rendering()); const QString filepath = ask_frame_save_file_path(this, "Save Frame As...", m_settings); if (filepath.isEmpty()) return; const Frame* frame = m_project_manager.get_project()->get_frame(); frame->write_main_image(filepath.toAscii().constData()); } void MainWindow::slot_save_all_aovs() { assert(m_project_manager.is_project_open()); assert(!m_rendering_manager.is_rendering()); const QString filepath = ask_frame_save_file_path(this, "Save All AOVs As...", m_settings); if (filepath.isEmpty()) return; const Frame* frame = m_project_manager.get_project()->get_frame(); frame->write_main_image(filepath.toAscii().constData()); frame->write_aov_images(filepath.toAscii().constData()); } namespace { void write_all_aovs( const Project& project, const bf::path& image_path) { bf::create_directories(image_path.parent_path()); const Frame* frame = project.get_frame(); frame->write_main_image(image_path.string().c_str()); frame->write_aov_images(image_path.string().c_str()); } } void MainWindow::slot_quicksave_all_aovs() { assert(m_project_manager.is_project_open()); assert(!m_rendering_manager.is_rendering()); const Project& project = *m_project_manager.get_project(); const bf::path project_path(project.get_path()); const bf::path quicksave_dir = project_path.parent_path() / "quicksaves"; write_all_aovs( project, bf::absolute( quicksave_dir / "quicksave.exr")); write_all_aovs( project, bf::absolute( find_next_available_path(quicksave_dir / "quicksave####.exr"))); } void MainWindow::slot_clear_frame() { Frame* frame = m_project_manager.get_project()->get_frame(); frame->clear_main_and_aov_images(); // In the UI, clear all render widgets to black. for (const_each<RenderTabCollection> i = m_render_tabs; i; ++i) i->second->clear(); } void MainWindow::slot_reset_zoom() { const int current_tab_index = m_ui->tab_render_channels->currentIndex(); m_tab_index_to_render_tab[current_tab_index]->reset_zoom(); } void MainWindow::slot_filter_text_changed(const QString& pattern) { m_ui->pushbutton_clear_filter->setEnabled(!pattern.isEmpty()); m_project_explorer->filter_items(pattern); } void MainWindow::slot_clear_filter() { m_ui->lineedit_filter->clear(); } void MainWindow::slot_frame_modified() { for (each<RenderTabCollection> i = m_render_tabs; i; ++i) i->second->update_size(); } void MainWindow::slot_fullscreen() { m_fullscreen = !m_fullscreen; bool all_minimized = true; bool not_minimized = false; for (each<vector<MinimizeButton*>> button = m_minimize_buttons; button; ++button) { all_minimized = all_minimized && (*button)->is_on(); not_minimized = not_minimized || !(*button)->is_on(); } // All were manually minimized, exit full screen mode if (all_minimized) m_fullscreen = false; // At least one is on screen, enter full screen mode if (not_minimized) m_fullscreen = true; for (each<vector<MinimizeButton*>> button = m_minimize_buttons; button; ++button) (*button)->set_fullscreen(m_fullscreen); } void MainWindow::slot_show_settings_window() { if (m_settings_window.get() == nullptr) { m_settings_window.reset(new SettingsWindow(m_settings, this)); connect( m_settings_window.get(), SIGNAL(signal_settings_modified()), SLOT(slot_save_settings())); connect( m_settings_window.get(), SIGNAL(signal_settings_modified()), SLOT(slot_apply_settings())); } m_settings_window->showNormal(); m_settings_window->activateWindow(); } void MainWindow::slot_show_rendering_settings_window() { assert(m_project_manager.is_project_open()); if (m_rendering_settings_window.get() == nullptr) { m_rendering_settings_window.reset( new RenderingSettingsWindow(m_project_manager, this)); connect( m_rendering_settings_window.get(), SIGNAL(signal_settings_modified()), SLOT(slot_project_modified())); } m_rendering_settings_window->showNormal(); m_rendering_settings_window->activateWindow(); } void MainWindow::slot_show_test_window() { if (m_test_window.get() == nullptr) m_test_window.reset(new TestWindow(this)); m_test_window->showNormal(); m_test_window->activateWindow(); } void MainWindow::slot_show_benchmark_window() { if (m_benchmark_window.get() == nullptr) m_benchmark_window.reset(new BenchmarkWindow(this)); m_benchmark_window->showNormal(); m_benchmark_window->activateWindow(); } void MainWindow::slot_show_about_window() { AboutWindow* about_window = new AboutWindow(this); about_window->showNormal(); about_window->activateWindow(); } } // namespace studio } // namespace appleseed #include "mainwindow/moc_cpp_mainwindow.cxx"
#include "LIGHT.H" #include "EFFECT2.H" #include "DRAW.H" #include "MATHS.H" #include "LOAD_LEV.H" #include "GTEREG.H" #include "MISC.H" #include "DRAWSPKS.H" void mNormaliseXYZ_L(int* x, int* y, int* z)//86500 (F) { IR1 = *x; IR2 = *y; IR3 = *z; int a3 = 0x1F; docop2(0xA00428); int v0 = MAC1; int v1 = MAC2; int at = MAC3; v0 += v1; v0 += at; LZCR = gte_leadingzerocount(v0); LZCS = v0; IR1 = *x; IR2 = *y; v1 = LZCR; at = -2; v1 &= at; a3 -= v1; a3 >>= 1; at = v1 - 24; if (at >= 0) { v0 <<= at; } else { //loc_8655C at = 24; at -= v1; v0 >>= at; } //loc_86568 v0 -= 64; v0 = ScalarTable[v0]; IR3 = *z; IR0 = v0; docop2(0x190003D); *x = MAC1; *y = MAC2; *z = MAC3; *x >>= a3; *y >>= a3; *z >>= a3; } int mSqrt_L(int a0)//8649C (F) { LZCR = gte_leadingzerocount(a0); LZCS = a0; int v0 = 0x1F; if (a0 != 0) { int v1 = LZCR; int at = -2; v1 &= at; v0 -= v1; v0 >>= 1; at = v1 - 24; if (at >= 0) { a0 <<= at; } else { at = 24; at -= v1; a0 >>= at; } //loc_864DC a0 -= 64; a0 = SqrtTable[a0]; a0 <<= v0; } //locret_864F8 return a0 >> 12; } void S_CalculateStaticMeshLight(long floor, long touch_bits, long mesh_bits, int anim_state)//8669C(<) { int t5 = 0; int t4 = 0; int t3 = 0; int t7; int t6; int t0; int a0; int a1; int a2; int v1; int at; int v0; int i; if (number_dynamics > 0) { t7 = floor; t6 = touch_bits; t0 = mesh_bits; //loc_866C4 for(i = 0; i < number_dynamics; i++) { IR1 = floor - dynamics[i].x; //loc_866E4 if (ABS(IR1) < 0x2001) { IR2 = touch_bits - dynamics[i].y; if (ABS(IR1) < 0x2001) { IR2 = mesh_bits - dynamics[i].z; if (ABS(IR2) < 0x2001) { docop2(0xA00428); a0 = MAC1; a1 = MAC2; a2 = MAC3; a0 += a1; a0 += a2; a0 = gte_leadingzerocount(a0); v0 = 0x1F; if (a0 != 0) { v1 = LZCR; at = -2; v1 &= at; v0 -= v1; v0 >>= 1; at = v1 - 0x18; if (at >= 0) { a0 <<= at; }//loc_86774 else { at = 0x18; at -= v1; a0 >>= at; } //loc_86780 a0 -= 0x40; a0 = SqrtTable[a0]; a0 <<= v0; } //loc_8679C v0 = a0 >> 12; v1 = dynamics[i].falloff >> 1; a0 = v0; v0 = a0 << 13; if (v1 >= a0) { v0 -= a0; v0 = v0 / v1; v1 = 0x1FFF; a0 = dynamics[i].r; v1 -= v0; at = a0 * v1; v0 = dynamics[i].g; a0 = v0 * v1; v0 = dynamics[i].b; v1 = v0 * v1; v0 = at >> 13; t3 += v0; v0 = a0 >> 13; t4 += v0; v0 = v1 >> 13; t5 += v0; } }//loc_86810 }//loc_86810 }//loc_86810 } }//loc_8681C v0 = t3 + t4; v0 += t5; a0 = anim_state; if (v0 != 0) { v0 = anim_state & 0x1F; v0 <<= 3; t3 += v0; v1 = anim_state & 0x3E0; v1 >>= 2; t4 += v1; v1 = anim_state & 0x7C00; v1 >>= 7; t5 += v1; if (t3 >= 0x100) { t3 = 0xFF; }//loc_86860 if (t4 >= 0x100) { t4 = 0xFF; }//loc_8686C if (t5 >= 0x100) { t5 = 0xFF; }//loc_86878 t4 <<= 8; t5 <<= 16; a0 = t3 | t4 | t5; } else { //loc_8688C v1 = a0 & 0x3E0; v0 = a0 & 0x7C00; a0 &= 0x1F; a0 <<= 3; v1 <<= 6; v0 <<= 9; a0 |= v1; a0 |= v0; } R = (a0 & 0xFF); G = (a0 & 0xFF00) >> 8; B = (a0 & 0xFF0000) >> 16; CODE = (a0 & 0xFF000000) >> 24; } void CalculateObjectLighting(struct ITEM_INFO* item/*a0*/, short* frmptr/*a1*/, struct STASHEDOBJ* sobject/*s0*/, short numnodestodraw/*s1*/) { if (item->shade < 0) { R11 = 4096; R12 = 0; R13 = 0; R21 = 0; R22 = 4096; R23 = 0; R31 = 0; R32 = 0; R33 = 4096; TRX = 0; TRY = 0; TRZ = 0; Matrix++; mRotYXZ(item->pos.y_rot, item->pos.x_rot, item->pos.z_rot); mTranslateXYZ((frmptr[0] + frmptr[1]) >> 1, (frmptr[2] + frmptr[4]) >> 1, (frmptr[3] + frmptr[5]) >> 1); mPopMatrix(); //S_CalculateLight(item->pos.x_pos + TRX, item->pos.y_pos + TRY, item->pos.z_pos + TRZ, item->room_number, &item->il); } else { //loc_8668C S_CalculateStaticMeshLight(item->pos.x_pos, item->pos.y_pos, item->pos.z_pos, 0x7FFF); } } void S_CalculateLight(long x, long y, long z, short room_num, struct ITEM_LIGHT* light) { struct room_info* r;//$t0 int scratchPad[256]; int t3; int t4; int t5; int t6; S_MemSet((char*)&scratchPad[0], 0, 1024); int* s1 = &scratchPad[21]; //at = 0x1000 s1[3] = 0; s1[4] = 0; ((short*)s1)[10] = 0x1000; int* s2 = &s1[8]; s2[3] = 0; s2[4] = 0; ((short*)s2)[10] = 0x1000; int* s3 = &s2[8]; s3[3] = 0; s3[4] = 0; ((short*)s3)[10] = 0x1000; int s4 = 0; int s5 = 0; int s6 = 0; int s7 = 4096; int t7 = x; int t8 = y; int t9 = z; //t0 = &room[0]; //s0 = gp r = &room[room_num]; struct LIGHTINFO* gp = r->light; int v0 = ((int*)&r->ambient)[0]; unsigned short fp = r->num_lights; int t2 = (v0 >> 12) & 0xFF0; int t1 = (v0 >> 4) & 0xFF0; int t0 = (v0 << 4) & 0xFF0; SXY0 = t0; SXY1 = t1; SXY2 = t2; loc_85D34: if (fp-- != 0) { int t3 = gp->Type; int t2 = ((int*)&gp->Inner)[0]; int t0 = t2 & 0xFF00; if (gp->Type == 0) { s4 |= 0x2000; int a0 = ((int*)&gp->nx)[0]; int a1 = ((int*)&gp->nz)[0]; int a2 = ((int*)&gp->Type)[0]; s1[4] = a0; s1[5] = a1; s1[3] = a2; gp++; goto loc_85D34; } else { //loc_85D70 t4 = gp->x; t5 = gp->y; t6 = gp->z; t4 -= t7; t5 -= t8; t6 -= t9; IR1 = t4; IR2 = t5; IR3 = t6; t0 >>= 1; docop2(0xA00428); t1 = (t2 & 0xFF) << 7; t2 >>= 16; int a3 = t3 & 1; int a0 = MAC1; int a1 = MAC2; int a2 = MAC3; a0 += a1; a0 += a2; int v0 = mSqrt_L(a0); a0 = t4; if (v0 < t0) { a1 = t5; a2 = t6; if (a3 != 0) { t4 = v0; mNormaliseXYZ_L(&a0, &a1, &a2); t5 = gp->Intensity; a3 = t5; if (t4 >= t1) { t4 -= t1; t5 = t0 - t1; t5 -= t4; a3 = (t5 * t2) >> 8; } //loc_85E0C int at = 4096; if (t3 - 3 == 0) { a3 = at - a3; if (a3 < s7) { gp++; s7 = a3; } goto loc_85D34; } goto loc_85ED0; } else { //loc_85E30 t4 = v0; mNormaliseXYZ_L(&a0, &a1, &a2); v0 = (R11 & 0xFFFF) | ((R12 & 0xFFFF) << 16); int v1 = (R13 & 0xFFFF) | ((R21 & 0xFFFF) << 16); VX0 = ((int*)&gp->nx)[0] & 0xFFFF; VY0 = (((int*)&gp->nx)[0] >> 16) & 0xFFFF; VZ0 = ((int*)&gp->nz)[0] & 0xFFFF; a1 <<= 16; a0 &= 0xFFFF; a0 |= a1; R11 = a0 & 0xFFFF; R12 = (a0 >> 16) & 0xFFFF; R13 = a2 & 0xFFFF; R21 = (a2 >> 16) & 0xFFFF; t3 = t4 - t1; docop2(0x486012); t5 = t0 - t1; t5 -= t3; t1 = t5 * t2; t5 = ((int*)&gp->Length)[0]; t3 = ((unsigned short*)&gp->Intensity)[0]; t6 = t5 >> 16; t0 = IR1; R11 = v0 & 0xFFFF; R12 = (v0 >> 16) & 0xFFFF; R13 = v1 & 0xFFFF; R21 = (v1 >> 16) & 0xFFFF; t5 &= 0xFFFF; if (t0 >= t6) { if (t0 >= t5) { t0 = 4096; } //loc_85EA4 t1 >>= 8; a0 = (VX0 & 0xFFFF) | ((VY0 & 0xFFFF) << 16); if (t1 >= t3) { t1 = t3; } //loc_85EB8 a3 = t0 * t1; a2 = VZ0; a1 = a0 >> 16; a0 &= 0xFFFF; a3 >>= 12; loc_85ED0: int at = s5 - a3; if (s4 - a3 < 0) { s6 = s5; s5 = s4; s4 = a3; at = (int)s3; s3 = s2; s2 = s1; s1 = (int*)at; //j loc_85F2C } else if (s5 - a3 < 0) { //loc_85EFC s6 = s5; s5 = a3; at = (int)s3; s3 = s2; s2 = (int*)at; //j loc_85F2C } else if (s6 - a3 < 0) { //loc_85F1C s6 = a3; at = (int)s3; } else { goto loc_85F40; } loc_85F2C:///@TODO expand (implant) into ifs then let it all fall through. t0 = ((int*)&gp->Type)[0]; ((short*)at)[8] = a0; ((short*)at)[9] = a1; ((short*)at)[10] = a2; ((int*)at)[3] = t0; }//loc_85F40 } } loc_85F40: gp++; goto loc_85D34; } } //loc_85F48 int at = 4096; if (s4 != 0 || s7 - 4096 != 0) { IR0 = s7; IR1 = s4; IR2 = s5; IR3 = s6; t0 = (at - s7) + 4096; docop2(0x198003D); t1 = SXY0; t2 = SXY1; int t3 = SXY2; at = s4 < 4096 ? 1 : 0; s4 = IR1; s5 = IR2; s6 = IR3; IR1 = t1; IR2 = t2; IR3 = t3; docop2(0x198003D); t1 = IR1; t2 = IR2; t3 = IR3; SXY0 = t1; SXY1 = t2; SXY2 = t3; if (at == 0) { s4 = t0; } } //loc_85FCC fp = number_dynamics; struct DYNAMIC* gpp = &dynamics[0]; loc_85FD4: if (fp--) { t4 = gpp->x; t5 = gpp->y; t6 = gpp->z; t4 -= t7; t5 -= t8; t6 -= t9; IR1 = t4; IR2 = t5; IR3 = t6; int a0 = t4; if (t4 < 0) { a0 = -t4; } //loc_8600C docop2(0xA00428); int a1 = t5; if (t5 < 0) { a1 = -t5; } //loc_8601C int a2 = t6; if (t6 < 0) { a2 = -t6; } //loc_86028 if ((unsigned)a0 < 0x2000 && (unsigned)a1 < 0x2000 && (unsigned)a2 < 0x2000) { t0 = ((int*)&gpp->falloff)[0] >> 1; t1 = gpp->FalloffScale; a0 = MAC1; a1 = MAC2; a2 = MAC3; a0 += a1; a0 += a2; if (mSqrt_L(a0) < t0) { v0 = (v0 * t1) >> 8; a0 = t4; a1 = t5; a2 = t6; mNormaliseXYZ_L(&a0, &a1, &a2); int a3 = 4096 - v0; //at = s5 - a3 if (s4 - a3 < 0) { s6 = s5; s5 = s4; s4 = a3; at = (int)s3; s3 = s2; s2 = s1; s1 = (int*)at; //goto loc_860EC; }//loc_860BC else if (s5 - a3 < 0) { s6 = s5; s5 = a3; at = (int)s3; s3 = s2; s2 = (int*)at; //goto loc_860EC } else if (s6 - a3 < 0) { //loc_860DC s6 = a3; at = (int)s3; } else { goto loc_86108; } //loc_860EC t0 = ((int*)&gpp->on)[0]; ((short*)at)[8] = a0; ((short*)at)[9] = a1; ((short*)at)[10] = a2; ((int*)at)[3] = t0; if (s7 != 0) { s7 = a3; } }//loc_86108 } loc_86108: gpp++; goto loc_85FD4; }//loc_86110 at = s4 - 4096; int* t00 = &scratchPad[0]; if (at >= 0) { s4 = at; } //loc_86120 t00[0] = s4; t00[1] = (int)s1; t00[7] = s5; t00[8] = (int)s2; t00[14] = s6; t00[15] = (int)s3; int* s66 = t00; s5 = (int)light; int s11 = SXY0; int s22 = SXY1; int s33 = SXY2; v0 = 3; int v1 = light->Light[3].pad; loc_86154: if (v0 != 0) { s4 = s66[1]; IR0 = s66[0]; t0 = ((int*)s4)[3]; int t3 = ((int*)s5)[2]; int s0 = t0 & 0xFF; t2 = t0 >> 20; t1 = (t0 >> 12) & 0xFF0; t0 >>= 4; t0 &= 0xFF0; IR1 = t0; IR2 = t1; IR3 = t2; int t5 = t3 >> 12; int t4 = t3 >> 4; docop2(0x198003D); v0--; if (v1 == 0) { t3 = ((short*)s4)[8]; t4 = ((short*)s4)[9]; t5 = ((short*)s4)[10]; t0 = t3; t1 = t4; t2 = t5; } else { //loc_861BC t3 <<= 4; t3 &= 0xFF0; t4 &= 0xFF0; t5 &= 0xFF0; RFC = t3; GFC = t4; BFC = t5; IR0 = 3584; t3 = ((short*)s4)[8]; docop2(0x980011); t4 = ((short*)s4)[9]; t5 = ((short*)s4)[10]; ((int*)s5)[0] = t0; ((short*)s5)[2] = t2; t1 = t0 >> 16; t0 <<= 16; t0 >>= 16; } //loc_86204 ((int*)s5)[2] = RGB2; ((int*)s66)[2] = IR1; ((int*)s66)[3] = IR2; ((int*)s66)[4] = IR3; MAC1 = s11; MAC2 = s22; MAC3 = s33; IR0 = 2048; t3 -= t0; t4 -= t1; t5 -= t2; docop2(0x1A8003E); t3 >>= 3; t4 >>= 3; t5 >>= 3; t0 += t3; t1 += t4; t2 += t5; ((short*)s66)[10] = t0; ((short*)s66)[11] = t1; ((short*)s66)[12] = t2; t0 &= 0xFFFF; t1 <<= 16; t0 |= t1; ((int*)s5)[0] = t0; ((int*)s5)[1] = t2; if (s0 != 0) { s11 = IR1; s22 = IR2; s33 = IR3; } //loc_86280 s66 += 7; s5 += 0xC; goto loc_86154; } //loc_8628C at = 0x1000000; if (v1 != 0) { IR1 = ((int*)s5)[0]; IR2 = ((int*)s5)[1]; IR3 = ((int*)s5)[2]; RFC = s11; GFC = s22; BFC = s33; IR0 = 1536; docop2(0x980011); s11 = IR1; s22 = IR2; s33 = IR3; }//loc_862C8 ((int*)s5)[0] = s11; ((int*)s5)[1] = s22; ((int*)s5)[2] = s33 | at; s11 <<= 1; s22 <<= 1; s33 <<= 1; RBK = s11; GBK = s22; BBK = s33; int s00 = (R11 & 0xFFFF) | ((R12 & 0xFFFF) << 16); s11 = (R13 & 0xFFFF) | ((R21 & 0xFFFF) << 16); s22 = (R22 & 0xFFFF) | ((R23 & 0xFFFF) << 16); s33 = (R31 & 0xFFFF) | ((R32 & 0xFFFF) << 16); s4 = R33; t0 = 0x808080; if (s7 != 0 && s7 < 0xFFF) { s7 >>= 5; t0 = s7 << 16; t1 = s7 << 8; t0 |= t1; t0 |= s7; } //loc_86330 R = (t0 & 0xFF); G = (t0 & 0xFF00) >> 8; B = (t0 & 0xFF0000) >> 16; CODE = (t0 & 0xFF000000) >> 24; struct MATRIX3D* s55 = &CamGTE; struct MATRIX3D* s666 = &LightPos; int* s77 = &scratchPad[0]; t0 = ((int*)s55)[0]; t1 = ((int*)s55)[1]; t2 = ((int*)s55)[2]; t3 = ((int*)s55)[3]; t4 = ((int*)s55)[4]; R11 = t0 & 0xFFFF; R12 = (t0 >> 16) & 0xFFFF; R13 = t1 & 0xFFFF; R21 = (t1 >> 16) & 0xFFFF; R22 = t2 & 0xFFFF; R23 = (t2 >> 16) & 0xFFFF; R31 = t3 & 0xFFFF; R32 = (t3 >> 16) & 0xFFFF; R33 = t4; VX0 = s77[5] & 0xFFFF; VY0 = (s77[5] >> 16) & 0xFFFF; VZ0 = s77[6] & 0xFFFF; VX1 = s77[12] & 0xFFFF; VY1 = (s77[12] >> 16) & 0xFFFF; docop2(0x486012); VZ1 = s77[13]; VX2 = s77[19] & 0xFFFF; VY2 = (s77[19] >> 16) & 0xFFFF; VZ2 = s77[20] & 0xFFFF; t1 = ((unsigned short*)s77)[18]; t0 = ((unsigned short*)s77)[4]; t1 <<= 16; t0 |= t1; t2 = ((unsigned short*)s77)[6]; t5 = IR1; t8 = IR2; t9 = IR3; docop2(0x48E012); t1 = ((unsigned short*)s77)[32]; t2 <<= 16; t1 |= t2; t3 = ((unsigned short*)s77)[34]; t2 = ((unsigned short*)s77)[20]; t3 <<= 16; t2 |= t3; t4 = ((unsigned short*)s77)[22]; t9 = IR1; t7 = IR2; int a0 = IR3; docop2(0x496012); t3 = ((unsigned short*)s77)[8]; t4 <<= 16; t3 |= t4; t4 = ((unsigned short*)s77)[36]; t5 &= 0xFFFF; t8 <<= 16; t5 |= t8; t6 &= 0xFFFF; t9 <<= 16; t6 |= t9; t7 &= 0xFFFF; a0 <<= 16; t7 |= a0; t8 = IR1; a0 = IR2; t9 = IR3; t8 &= 0xFFFF; a0 <<= 16; t8 |= a0; ((int*)s666)[0] = t5; ((int*)s666)[1] = t6; ((int*)s666)[2] = t7; ((int*)s666)[3] = t8; ((int*)s666)[4] = t9; LR1 = t0 & 0xFFFF; LR2 = (t0 >> 16) & 0xFFFF; LR3 = t1 & 0xFFFF; LG1 = (t1 >> 16) & 0xFFFF; LG2 = t2 & 0xFFFF; LG3 = (t2 >> 16) & 0xFFFF; LB1 = t3 & 0xFFFF; LB2 = (t3 >> 16) & 0xFFFF; LB3 = t4; R11 = s00 & 0xFFFF; R12 = (s00 >> 16) & 0xFFFF; R13 = s11 & 0xFFFF; R21 = (s11 >> 16) & 0xFFFF; R22 = s22 & 0xFFFF; R23 = (s22 >> 16) & 0xFFFF; R31 = s33 & 0xFFFF; R32 = (s33 >> 16) & 0xFFFF; R33 = s4; RFC = 0; GFC = 0; BFC = 0; } [Platform]: Android compile fixes. #include "LIGHT.H" #include "EFFECT2.H" #include "DRAW.H" #include "MATHS.H" #include "LOAD_LEV.H" #include "GTEREG.H" #include "MISC.H" #include "DRAWSPKS.H" void mNormaliseXYZ_L(int* x, int* y, int* z)//86500 (F) { IR1 = *x; IR2 = *y; IR3 = *z; int a3 = 0x1F; docop2(0xA00428); int v0 = MAC1; int v1 = MAC2; int at = MAC3; v0 += v1; v0 += at; LZCR = gte_leadingzerocount(v0); LZCS = v0; IR1 = *x; IR2 = *y; v1 = LZCR; at = -2; v1 &= at; a3 -= v1; a3 >>= 1; at = v1 - 24; if (at >= 0) { v0 <<= at; } else { //loc_8655C at = 24; at -= v1; v0 >>= at; } //loc_86568 v0 -= 64; v0 = ScalarTable[v0]; IR3 = *z; IR0 = v0; docop2(0x190003D); *x = MAC1; *y = MAC2; *z = MAC3; *x >>= a3; *y >>= a3; *z >>= a3; } int mSqrt_L(int a0)//8649C (F) { LZCR = gte_leadingzerocount(a0); LZCS = a0; int v0 = 0x1F; if (a0 != 0) { int v1 = LZCR; int at = -2; v1 &= at; v0 -= v1; v0 >>= 1; at = v1 - 24; if (at >= 0) { a0 <<= at; } else { at = 24; at -= v1; a0 >>= at; } //loc_864DC a0 -= 64; a0 = SqrtTable[a0]; a0 <<= v0; } //locret_864F8 return a0 >> 12; } void S_CalculateStaticMeshLight(long floor, long touch_bits, long mesh_bits, int anim_state)//8669C(<) { int t5 = 0; int t4 = 0; int t3 = 0; int t7; int t6; int t0; int a0; int a1; int a2; int v1; int at; int v0; int i; if (number_dynamics > 0) { t7 = floor; t6 = touch_bits; t0 = mesh_bits; //loc_866C4 for(i = 0; i < number_dynamics; i++) { IR1 = floor - dynamics[i].x; //loc_866E4 if (ABS(IR1) < 0x2001) { IR2 = touch_bits - dynamics[i].y; if (ABS(IR1) < 0x2001) { IR2 = mesh_bits - dynamics[i].z; if (ABS(IR2) < 0x2001) { docop2(0xA00428); a0 = MAC1; a1 = MAC2; a2 = MAC3; a0 += a1; a0 += a2; a0 = gte_leadingzerocount(a0); v0 = 0x1F; if (a0 != 0) { v1 = LZCR; at = -2; v1 &= at; v0 -= v1; v0 >>= 1; at = v1 - 0x18; if (at >= 0) { a0 <<= at; }//loc_86774 else { at = 0x18; at -= v1; a0 >>= at; } //loc_86780 a0 -= 0x40; a0 = SqrtTable[a0]; a0 <<= v0; } //loc_8679C v0 = a0 >> 12; v1 = dynamics[i].falloff >> 1; a0 = v0; v0 = a0 << 13; if (v1 >= a0) { v0 -= a0; v0 = v0 / v1; v1 = 0x1FFF; a0 = dynamics[i].r; v1 -= v0; at = a0 * v1; v0 = dynamics[i].g; a0 = v0 * v1; v0 = dynamics[i].b; v1 = v0 * v1; v0 = at >> 13; t3 += v0; v0 = a0 >> 13; t4 += v0; v0 = v1 >> 13; t5 += v0; } }//loc_86810 }//loc_86810 }//loc_86810 } }//loc_8681C v0 = t3 + t4; v0 += t5; a0 = anim_state; if (v0 != 0) { v0 = anim_state & 0x1F; v0 <<= 3; t3 += v0; v1 = anim_state & 0x3E0; v1 >>= 2; t4 += v1; v1 = anim_state & 0x7C00; v1 >>= 7; t5 += v1; if (t3 >= 0x100) { t3 = 0xFF; }//loc_86860 if (t4 >= 0x100) { t4 = 0xFF; }//loc_8686C if (t5 >= 0x100) { t5 = 0xFF; }//loc_86878 t4 <<= 8; t5 <<= 16; a0 = t3 | t4 | t5; } else { //loc_8688C v1 = a0 & 0x3E0; v0 = a0 & 0x7C00; a0 &= 0x1F; a0 <<= 3; v1 <<= 6; v0 <<= 9; a0 |= v1; a0 |= v0; } R = (a0 & 0xFF); G = (a0 & 0xFF00) >> 8; B = (a0 & 0xFF0000) >> 16; CODE = (a0 & 0xFF000000) >> 24; } void CalculateObjectLighting(struct ITEM_INFO* item/*a0*/, short* frmptr/*a1*/, struct STASHEDOBJ* sobject/*s0*/, short numnodestodraw/*s1*/) { if (item->shade < 0) { R11 = 4096; R12 = 0; R13 = 0; R21 = 0; R22 = 4096; R23 = 0; R31 = 0; R32 = 0; R33 = 4096; TRX = 0; TRY = 0; TRZ = 0; Matrix++; mRotYXZ(item->pos.y_rot, item->pos.x_rot, item->pos.z_rot); mTranslateXYZ((frmptr[0] + frmptr[1]) >> 1, (frmptr[2] + frmptr[4]) >> 1, (frmptr[3] + frmptr[5]) >> 1); mPopMatrix(); //S_CalculateLight(item->pos.x_pos + TRX, item->pos.y_pos + TRY, item->pos.z_pos + TRZ, item->room_number, &item->il); } else { //loc_8668C S_CalculateStaticMeshLight(item->pos.x_pos, item->pos.y_pos, item->pos.z_pos, 0x7FFF); } } void S_CalculateLight(long x, long y, long z, short room_num, struct ITEM_LIGHT* light) { struct room_info* r;//$t0 int scratchPad[256]; int t3; int t4; int t5; int t6; int v1; S_MemSet((char*)&scratchPad[0], 0, 1024); int* s1 = &scratchPad[21]; //at = 0x1000 s1[3] = 0; s1[4] = 0; ((short*)s1)[10] = 0x1000; int* s2 = &s1[8]; s2[3] = 0; s2[4] = 0; ((short*)s2)[10] = 0x1000; int* s3 = &s2[8]; s3[3] = 0; s3[4] = 0; ((short*)s3)[10] = 0x1000; int s4 = 0; int s5 = 0; int s6 = 0; int s7 = 4096; int t7 = x; int t8 = y; int t9 = z; //t0 = &room[0]; //s0 = gp r = &room[room_num]; struct LIGHTINFO* gp = r->light; int v0 = ((int*)&r->ambient)[0]; unsigned short fp = r->num_lights; int t2 = (v0 >> 12) & 0xFF0; int t1 = (v0 >> 4) & 0xFF0; int t0 = (v0 << 4) & 0xFF0; SXY0 = t0; SXY1 = t1; SXY2 = t2; loc_85D34: if (fp-- != 0) { int t3 = gp->Type; int t2 = ((int*)&gp->Inner)[0]; int t0 = t2 & 0xFF00; if (gp->Type == 0) { s4 |= 0x2000; int a0 = ((int*)&gp->nx)[0]; int a1 = ((int*)&gp->nz)[0]; int a2 = ((int*)&gp->Type)[0]; s1[4] = a0; s1[5] = a1; s1[3] = a2; gp++; goto loc_85D34; } else { //loc_85D70 t4 = gp->x; t5 = gp->y; t6 = gp->z; t4 -= t7; t5 -= t8; t6 -= t9; IR1 = t4; IR2 = t5; IR3 = t6; t0 >>= 1; docop2(0xA00428); t1 = (t2 & 0xFF) << 7; t2 >>= 16; int a3 = t3 & 1; int a0 = MAC1; int a1 = MAC2; int a2 = MAC3; a0 += a1; a0 += a2; int v0 = mSqrt_L(a0); a0 = t4; if (v0 < t0) { a1 = t5; a2 = t6; if (a3 != 0) { t4 = v0; mNormaliseXYZ_L(&a0, &a1, &a2); t5 = gp->Intensity; a3 = t5; if (t4 >= t1) { t4 -= t1; t5 = t0 - t1; t5 -= t4; a3 = (t5 * t2) >> 8; } //loc_85E0C int at = 4096; if (t3 - 3 == 0) { a3 = at - a3; if (a3 < s7) { gp++; s7 = a3; } goto loc_85D34; } goto loc_85ED0; } else { //loc_85E30 t4 = v0; mNormaliseXYZ_L(&a0, &a1, &a2); v0 = (R11 & 0xFFFF) | ((R12 & 0xFFFF) << 16); v1 = (R13 & 0xFFFF) | ((R21 & 0xFFFF) << 16); VX0 = ((int*)&gp->nx)[0] & 0xFFFF; VY0 = (((int*)&gp->nx)[0] >> 16) & 0xFFFF; VZ0 = ((int*)&gp->nz)[0] & 0xFFFF; a1 <<= 16; a0 &= 0xFFFF; a0 |= a1; R11 = a0 & 0xFFFF; R12 = (a0 >> 16) & 0xFFFF; R13 = a2 & 0xFFFF; R21 = (a2 >> 16) & 0xFFFF; t3 = t4 - t1; docop2(0x486012); t5 = t0 - t1; t5 -= t3; t1 = t5 * t2; t5 = ((int*)&gp->Length)[0]; t3 = ((unsigned short*)&gp->Intensity)[0]; t6 = t5 >> 16; t0 = IR1; R11 = v0 & 0xFFFF; R12 = (v0 >> 16) & 0xFFFF; R13 = v1 & 0xFFFF; R21 = (v1 >> 16) & 0xFFFF; t5 &= 0xFFFF; if (t0 >= t6) { if (t0 >= t5) { t0 = 4096; } //loc_85EA4 t1 >>= 8; a0 = (VX0 & 0xFFFF) | ((VY0 & 0xFFFF) << 16); if (t1 >= t3) { t1 = t3; } //loc_85EB8 a3 = t0 * t1; a2 = VZ0; a1 = a0 >> 16; a0 &= 0xFFFF; a3 >>= 12; loc_85ED0: int at = s5 - a3; if (s4 - a3 < 0) { s6 = s5; s5 = s4; s4 = a3; at = (int)s3; s3 = s2; s2 = s1; s1 = (int*)at; //j loc_85F2C } else if (s5 - a3 < 0) { //loc_85EFC s6 = s5; s5 = a3; at = (int)s3; s3 = s2; s2 = (int*)at; //j loc_85F2C } else if (s6 - a3 < 0) { //loc_85F1C s6 = a3; at = (int)s3; } else { goto loc_85F40; } loc_85F2C:///@TODO expand (implant) into ifs then let it all fall through. t0 = ((int*)&gp->Type)[0]; ((short*)at)[8] = a0; ((short*)at)[9] = a1; ((short*)at)[10] = a2; ((int*)at)[3] = t0; }//loc_85F40 } } loc_85F40: gp++; goto loc_85D34; } } //loc_85F48 int at = 4096; if (s4 != 0 || s7 - 4096 != 0) { IR0 = s7; IR1 = s4; IR2 = s5; IR3 = s6; t0 = (at - s7) + 4096; docop2(0x198003D); t1 = SXY0; t2 = SXY1; int t3 = SXY2; at = s4 < 4096 ? 1 : 0; s4 = IR1; s5 = IR2; s6 = IR3; IR1 = t1; IR2 = t2; IR3 = t3; docop2(0x198003D); t1 = IR1; t2 = IR2; t3 = IR3; SXY0 = t1; SXY1 = t2; SXY2 = t3; if (at == 0) { s4 = t0; } } //loc_85FCC fp = number_dynamics; struct DYNAMIC* gpp = &dynamics[0]; loc_85FD4: if (fp--) { t4 = gpp->x; t5 = gpp->y; t6 = gpp->z; t4 -= t7; t5 -= t8; t6 -= t9; IR1 = t4; IR2 = t5; IR3 = t6; int a0 = t4; if (t4 < 0) { a0 = -t4; } //loc_8600C docop2(0xA00428); int a1 = t5; if (t5 < 0) { a1 = -t5; } //loc_8601C int a2 = t6; if (t6 < 0) { a2 = -t6; } //loc_86028 if ((unsigned)a0 < 0x2000 && (unsigned)a1 < 0x2000 && (unsigned)a2 < 0x2000) { t0 = ((int*)&gpp->falloff)[0] >> 1; t1 = gpp->FalloffScale; a0 = MAC1; a1 = MAC2; a2 = MAC3; a0 += a1; a0 += a2; if (mSqrt_L(a0) < t0) { v0 = (v0 * t1) >> 8; a0 = t4; a1 = t5; a2 = t6; mNormaliseXYZ_L(&a0, &a1, &a2); int a3 = 4096 - v0; //at = s5 - a3 if (s4 - a3 < 0) { s6 = s5; s5 = s4; s4 = a3; at = (int)s3; s3 = s2; s2 = s1; s1 = (int*)at; //goto loc_860EC; }//loc_860BC else if (s5 - a3 < 0) { s6 = s5; s5 = a3; at = (int)s3; s3 = s2; s2 = (int*)at; //goto loc_860EC } else if (s6 - a3 < 0) { //loc_860DC s6 = a3; at = (int)s3; } else { goto loc_86108; } //loc_860EC t0 = ((int*)&gpp->on)[0]; ((short*)at)[8] = a0; ((short*)at)[9] = a1; ((short*)at)[10] = a2; ((int*)at)[3] = t0; if (s7 != 0) { s7 = a3; } }//loc_86108 } loc_86108: gpp++; goto loc_85FD4; }//loc_86110 at = s4 - 4096; int* t00 = &scratchPad[0]; if (at >= 0) { s4 = at; } //loc_86120 t00[0] = s4; t00[1] = (int)s1; t00[7] = s5; t00[8] = (int)s2; t00[14] = s6; t00[15] = (int)s3; int* s66 = t00; s5 = (int)light; int s11 = SXY0; int s22 = SXY1; int s33 = SXY2; v0 = 3; v1 = light->Light[3].pad; loc_86154: if (v0 != 0) { s4 = s66[1]; IR0 = s66[0]; t0 = ((int*)s4)[3]; int t3 = ((int*)s5)[2]; int s0 = t0 & 0xFF; t2 = t0 >> 20; t1 = (t0 >> 12) & 0xFF0; t0 >>= 4; t0 &= 0xFF0; IR1 = t0; IR2 = t1; IR3 = t2; int t5 = t3 >> 12; int t4 = t3 >> 4; docop2(0x198003D); v0--; if (v1 == 0) { t3 = ((short*)s4)[8]; t4 = ((short*)s4)[9]; t5 = ((short*)s4)[10]; t0 = t3; t1 = t4; t2 = t5; } else { //loc_861BC t3 <<= 4; t3 &= 0xFF0; t4 &= 0xFF0; t5 &= 0xFF0; RFC = t3; GFC = t4; BFC = t5; IR0 = 3584; t3 = ((short*)s4)[8]; docop2(0x980011); t4 = ((short*)s4)[9]; t5 = ((short*)s4)[10]; ((int*)s5)[0] = t0; ((short*)s5)[2] = t2; t1 = t0 >> 16; t0 <<= 16; t0 >>= 16; } //loc_86204 ((int*)s5)[2] = RGB2; ((int*)s66)[2] = IR1; ((int*)s66)[3] = IR2; ((int*)s66)[4] = IR3; MAC1 = s11; MAC2 = s22; MAC3 = s33; IR0 = 2048; t3 -= t0; t4 -= t1; t5 -= t2; docop2(0x1A8003E); t3 >>= 3; t4 >>= 3; t5 >>= 3; t0 += t3; t1 += t4; t2 += t5; ((short*)s66)[10] = t0; ((short*)s66)[11] = t1; ((short*)s66)[12] = t2; t0 &= 0xFFFF; t1 <<= 16; t0 |= t1; ((int*)s5)[0] = t0; ((int*)s5)[1] = t2; if (s0 != 0) { s11 = IR1; s22 = IR2; s33 = IR3; } //loc_86280 s66 += 7; s5 += 0xC; goto loc_86154; } //loc_8628C at = 0x1000000; if (v1 != 0) { IR1 = ((int*)s5)[0]; IR2 = ((int*)s5)[1]; IR3 = ((int*)s5)[2]; RFC = s11; GFC = s22; BFC = s33; IR0 = 1536; docop2(0x980011); s11 = IR1; s22 = IR2; s33 = IR3; }//loc_862C8 ((int*)s5)[0] = s11; ((int*)s5)[1] = s22; ((int*)s5)[2] = s33 | at; s11 <<= 1; s22 <<= 1; s33 <<= 1; RBK = s11; GBK = s22; BBK = s33; int s00 = (R11 & 0xFFFF) | ((R12 & 0xFFFF) << 16); s11 = (R13 & 0xFFFF) | ((R21 & 0xFFFF) << 16); s22 = (R22 & 0xFFFF) | ((R23 & 0xFFFF) << 16); s33 = (R31 & 0xFFFF) | ((R32 & 0xFFFF) << 16); s4 = R33; t0 = 0x808080; if (s7 != 0 && s7 < 0xFFF) { s7 >>= 5; t0 = s7 << 16; t1 = s7 << 8; t0 |= t1; t0 |= s7; } //loc_86330 R = (t0 & 0xFF); G = (t0 & 0xFF00) >> 8; B = (t0 & 0xFF0000) >> 16; CODE = (t0 & 0xFF000000) >> 24; struct MATRIX3D* s55 = &CamGTE; struct MATRIX3D* s666 = &LightPos; int* s77 = &scratchPad[0]; t0 = ((int*)s55)[0]; t1 = ((int*)s55)[1]; t2 = ((int*)s55)[2]; t3 = ((int*)s55)[3]; t4 = ((int*)s55)[4]; R11 = t0 & 0xFFFF; R12 = (t0 >> 16) & 0xFFFF; R13 = t1 & 0xFFFF; R21 = (t1 >> 16) & 0xFFFF; R22 = t2 & 0xFFFF; R23 = (t2 >> 16) & 0xFFFF; R31 = t3 & 0xFFFF; R32 = (t3 >> 16) & 0xFFFF; R33 = t4; VX0 = s77[5] & 0xFFFF; VY0 = (s77[5] >> 16) & 0xFFFF; VZ0 = s77[6] & 0xFFFF; VX1 = s77[12] & 0xFFFF; VY1 = (s77[12] >> 16) & 0xFFFF; docop2(0x486012); VZ1 = s77[13]; VX2 = s77[19] & 0xFFFF; VY2 = (s77[19] >> 16) & 0xFFFF; VZ2 = s77[20] & 0xFFFF; t1 = ((unsigned short*)s77)[18]; t0 = ((unsigned short*)s77)[4]; t1 <<= 16; t0 |= t1; t2 = ((unsigned short*)s77)[6]; t5 = IR1; t8 = IR2; t9 = IR3; docop2(0x48E012); t1 = ((unsigned short*)s77)[32]; t2 <<= 16; t1 |= t2; t3 = ((unsigned short*)s77)[34]; t2 = ((unsigned short*)s77)[20]; t3 <<= 16; t2 |= t3; t4 = ((unsigned short*)s77)[22]; t9 = IR1; t7 = IR2; int a0 = IR3; docop2(0x496012); t3 = ((unsigned short*)s77)[8]; t4 <<= 16; t3 |= t4; t4 = ((unsigned short*)s77)[36]; t5 &= 0xFFFF; t8 <<= 16; t5 |= t8; t6 &= 0xFFFF; t9 <<= 16; t6 |= t9; t7 &= 0xFFFF; a0 <<= 16; t7 |= a0; t8 = IR1; a0 = IR2; t9 = IR3; t8 &= 0xFFFF; a0 <<= 16; t8 |= a0; ((int*)s666)[0] = t5; ((int*)s666)[1] = t6; ((int*)s666)[2] = t7; ((int*)s666)[3] = t8; ((int*)s666)[4] = t9; LR1 = t0 & 0xFFFF; LR2 = (t0 >> 16) & 0xFFFF; LR3 = t1 & 0xFFFF; LG1 = (t1 >> 16) & 0xFFFF; LG2 = t2 & 0xFFFF; LG3 = (t2 >> 16) & 0xFFFF; LB1 = t3 & 0xFFFF; LB2 = (t3 >> 16) & 0xFFFF; LB3 = t4; R11 = s00 & 0xFFFF; R12 = (s00 >> 16) & 0xFFFF; R13 = s11 & 0xFFFF; R21 = (s11 >> 16) & 0xFFFF; R22 = s22 & 0xFFFF; R23 = (s22 >> 16) & 0xFFFF; R31 = s33 & 0xFFFF; R32 = (s33 >> 16) & 0xFFFF; R33 = s4; RFC = 0; GFC = 0; BFC = 0; }
// Begin CVS Header // $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/model/CProcessQueue.cpp,v $ // $Revision: 1.17 $ // $Name: $ // $Author: shoops $ // $Date: 2009/07/09 21:15:15 $ // End CVS Header // Copyright (C) 2008 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., EML Research, gGmbH, University of Heidelberg, // and The University of Manchester. // All rights reserved. #include <limits> #include "copasi.h" #include "CProcessQueue.h" #include "CMathModel.h" #include "function/CExpression.h" CProcessQueue::CKey::CKey() : mExecutionTime(0.0), mCascadingLevel(0), mEquality(false), mOrder(0), mEventId(std::numeric_limits<unsigned C_INT32>::max()) {} CProcessQueue::CKey::CKey(const CKey & src) : mExecutionTime(src.mExecutionTime), mCascadingLevel(src.mCascadingLevel), mEquality(src.mEquality), mOrder(src.mOrder), mEventId(src.mEventId) {} CProcessQueue::CKey::CKey(const C_FLOAT64 & executionTime, const bool & equality, const unsigned C_INT32 & order, const unsigned C_INT32 & eventId, const unsigned C_INT32 & cascadingLevel) : mExecutionTime(executionTime), mCascadingLevel(cascadingLevel), mEquality(equality), mOrder(order), mEventId(eventId) {} CProcessQueue::CKey::~CKey() {} bool CProcessQueue::CKey::operator < (const CProcessQueue::CKey & rhs) const { if (mExecutionTime != rhs.mExecutionTime) return mExecutionTime < rhs.mExecutionTime; if (mCascadingLevel != rhs.mCascadingLevel) return mCascadingLevel > rhs.mCascadingLevel; if (mEquality != rhs.mEquality) return mEquality; if (mOrder != rhs.mOrder) return mOrder < rhs.mOrder; return mEventId < rhs.mEventId; } CProcessQueue::CAction::CAction() : mpTarget(NULL), mValue(), mpExpression(NULL), mpEvent(NULL), mpProcessQueue(NULL) {} CProcessQueue::CAction::CAction(const CAction & src) : mpTarget(src.mpTarget), mValue(src.mValue), mpExpression(src.mpExpression), mpEvent(src.mpEvent), mpProcessQueue(src.mpProcessQueue) {} CProcessQueue::CAction::CAction(C_FLOAT64 * pTarget, const C_FLOAT64 & value, CMathEvent * pEvent) : mpTarget(pTarget), mValue(value), mpExpression(NULL), mpEvent(pEvent), mpProcessQueue(NULL) {} CProcessQueue::CAction::CAction(C_FLOAT64 * pTarget, CMathExpression * pExpression, CMathEvent * pEvent, CProcessQueue * pProcessQueue) : mpTarget(pTarget), mValue(), mpExpression(pExpression), mpEvent(pEvent), mpProcessQueue(pProcessQueue) {} CProcessQueue::CAction::~CAction() {} void CProcessQueue::CAction::process(const unsigned C_INT32 & eventId) { // If the expression pointer is not NULL we have a calculation. if (mpExpression != NULL) { // Calculate the execution time for delayed events. C_FLOAT64 ExecutionTime = mpEvent->getExecutionTime(mpProcessQueue->mTime); mpProcessQueue->addAssignment(ExecutionTime, mpProcessQueue->mEquality, mpEvent->getOrder(), eventId, mpTarget, mpExpression->calcValue(), mpEvent); } else { *mpTarget = mValue; } } CProcessQueue::CProcessQueue() : mCalculations(), mAssignments(), mExecutionLimit(10000), mExecutionCounter(0), mTime(0.0), mEquality(true), mCascadingLevel(0), mSimultaneousAssignments(false), mEventIdSet(), mRootsFound(0), mRootValues1(0), mRootValues2(0), mpRootValuesBefore(&mRootValues1), mpRootValuesAfter(&mRootValues2), mpResolveSimultaneousAssignments(NULL) {} CProcessQueue::CProcessQueue(const CProcessQueue & src): mCalculations(src.mCalculations), mAssignments(src.mAssignments), mExecutionLimit(src.mExecutionLimit), mExecutionCounter(src.mExecutionCounter), mTime(src.mTime), mEquality(src.mEquality), mCascadingLevel(src.mCascadingLevel), mSimultaneousAssignments(src.mSimultaneousAssignments), mEventIdSet(src.mEventIdSet), mRootsFound(src.mRootsFound), mRootValues1(src.mRootValues1), mRootValues2(src.mRootValues2), mpRootValuesBefore(&src.mRootValues1 == src.mpRootValuesBefore ? &mRootValues1 : &mRootValues2), mpRootValuesAfter(&src.mRootValues1 == src.mpRootValuesAfter ? &mRootValues1 : &mRootValues2), mpResolveSimultaneousAssignments(src.mpResolveSimultaneousAssignments) {} CProcessQueue::~CProcessQueue() {} bool CProcessQueue::addAssignment(const C_FLOAT64 & executionTime, const bool & equality, const unsigned C_INT32 & order, const unsigned C_INT32 & eventId, C_FLOAT64 * pTarget, const C_FLOAT64 & value, CMathEvent * pEvent) { // It is not possible to proceed backwards in time. if (executionTime < mTime) return false; unsigned C_INT32 CascadingLevel = mCascadingLevel; if (executionTime > mTime) CascadingLevel = 0; mAssignments.insert(std::make_pair(CKey(executionTime, equality, order, eventId, CascadingLevel), CAction(pTarget, value, pEvent))); return true; } bool CProcessQueue::addCalculation(const C_FLOAT64 & executionTime, const bool & equality, const unsigned C_INT32 & order, const unsigned C_INT32 & eventId, C_FLOAT64 * pTarget, CMathExpression * pExpression, CMathEvent * pEvent) { // It is not possible to proceed backwards in time. if (executionTime < mTime) return false; unsigned C_INT32 CascadingLevel = mCascadingLevel; if (executionTime > mTime) CascadingLevel = 0; mCalculations.insert(std::make_pair(CKey(executionTime, equality, order, eventId, CascadingLevel), CAction(pTarget, pExpression, pEvent, this))); return true; } void CProcessQueue::initialize(CMathModel * pMathModel) { mpMathModel = pMathModel; assert(mpMathModel != NULL); mTime = mpMathModel->getInitialTime(); mCalculations.clear(); mAssignments.clear(); mEventIdSet.clear(); mSimultaneousAssignments = false; unsigned C_INT32 NumRoots = mpMathModel->getNumRoots(); mRootsFound.resize(NumRoots); mRootsFound = 0; mRootValues1.resize(NumRoots); mRootValues2.resize(NumRoots); mpRootValuesBefore = &mRootValues1; mpRootValuesAfter = &mRootValues2; return; } bool CProcessQueue::process(const C_FLOAT64 & time, const bool & priorToOutput, resolveSimultaneousAssignments pResolveSimultaneousAssignments) { if (getProcessQueueExecutionTime() > time) return false; mTime = time; mEquality = priorToOutput; mpResolveSimultaneousAssignments = pResolveSimultaneousAssignments; mExecutionCounter = 0; mCascadingLevel = 0; bool success = true; bool stateChanged = false; range Calculations = getCalculations(); if (notEmpty(Calculations)) { // Execute and remove all current calculations. success = executeCalculations(Calculations); } range Assignments = getAssignments(); if (success && notEmpty(Assignments)) { mpMathModel->evaluateRoots(*mpRootValuesBefore, false); stateChanged = true; } // The algorithm below will work properly for user ordered events // as the queue enforces the proper ordering. while (success && notEmpty(Assignments) && mCascadingLevel != std::numeric_limits<unsigned C_INT32>::max()) { // We switch to the next cascading level so that events triggered by the // execution of assignments are properly scheduled. mCascadingLevel++; // Execute and remove all current assignments. success = executeAssignments(Assignments); // We need to compare the roots before the execution and after // to determine which roots need to be charged. if (rootsFound()) { // Since we are dealing with discrete changes we must only // process roots for equality. mpMathModel->processRoots(mTime, true, mRootsFound); } // Note, applying the events may have added new events to the queue. // The setting of the equality flag for these events may be either true // or false. // First we handle equalities. mEquality = true; // Retrieve the pending calculations. Calculations = getCalculations(); if (notEmpty(Calculations)) { // Execute and remove all current calculations. success = executeCalculations(Calculations); } // Retrieve the pending assignments. Assignments = getAssignments(); if (notEmpty(Assignments)) continue; // If we are here there are no more calculations and assignments for equality // for this level. mEquality = false; // Retrieve the pending calculations. Calculations = getCalculations(); if (notEmpty(Calculations)) { // Execute and remove all current calculations. success = executeCalculations(Calculations); } // Retrieve the pending assignments. Assignments = getAssignments(); while (!notEmpty(Assignments) && mCascadingLevel > 0) { // If we are here we have no more calculations and assignment for this level. mCascadingLevel--; // This will only return assignments when we have resolution algorithms for // them. Assignments = getAssignments(); } } if (mSimultaneousAssignments) { CCopasiMessage(CCopasiMessage::EXCEPTION, MCMathModel + 1); success = false; } return stateChanged; } CProcessQueue::range CProcessQueue::getCalculations() { range Calculations; CKey UpperBound(mTime, mEquality, std::numeric_limits<unsigned C_INT32>::max(), std::numeric_limits<unsigned C_INT32>::max(), mCascadingLevel); Calculations.first = mCalculations.begin(); if (Calculations.first != mCalculations.end() && Calculations.first->first < UpperBound) { Calculations.second = mCalculations.upper_bound(Calculations.first->first); // Check whether we have a second set of assignments with a different ID. if (Calculations.second != mCalculations.end() && Calculations.second->first < UpperBound) { mSimultaneousAssignments = true; // The resolution of simultaneous events is algorithm dependent. // The simulation routine should provide a call back function. if (mpResolveSimultaneousAssignments == NULL) { // TODO CRITICAL Create an error message } return (*mpResolveSimultaneousAssignments)(mCalculations, mTime, mEquality, mCascadingLevel); } } else { Calculations.first = Calculations.second = mCalculations.end(); } return Calculations; } CProcessQueue::range CProcessQueue::getAssignments() { range Assignments; CKey UpperBound(mTime, mEquality, std::numeric_limits<unsigned C_INT32>::max(), std::numeric_limits<unsigned C_INT32>::max(), mCascadingLevel); Assignments.first = mAssignments.begin(); if (Assignments.first != mAssignments.end() && Assignments.first->first < UpperBound) { Assignments.second = mAssignments.upper_bound(Assignments.first->first); // Check whether we have a second set of assignments with a different ID. if (Assignments.second != mAssignments.end() && Assignments.second->first < UpperBound) { mSimultaneousAssignments = true; // The resolution of simultaneous events is algorithm dependent. // The simulation routine should provide a call back function. if (mpResolveSimultaneousAssignments == NULL) { // TODO CRITICAL Create an error message } return (*mpResolveSimultaneousAssignments)(mAssignments, mTime, mEquality, mCascadingLevel); } } else { Assignments.first = Assignments.second = mAssignments.end(); } return Assignments; } bool CProcessQueue::executeCalculations(CProcessQueue::range & calculations) { bool success = true; iterator it = calculations.first; assert(it != mCalculations.end()); unsigned C_INT32 EventIdOld = it->first.getEventId(); unsigned C_INT32 EventIdNew = createEventId(); CMathEvent * pEvent = it->second.mpEvent; // Assure that all values are up to date. pEvent->applyValueRefreshes(); for (; it != calculations.second; ++it) { if (it->first.getEventId() != EventIdOld) { destroyEventId(EventIdOld); EventIdOld = it->first.getEventId(); EventIdNew = createEventId(); } it->second.process(EventIdNew); } destroyEventId(EventIdOld); mCalculations.erase(calculations.first, calculations.second); return success; } bool CProcessQueue::executeAssignments(CProcessQueue::range & assignments) { bool success = (mExecutionCounter < mExecutionLimit); iterator it = assignments.first; assert(it != mAssignments.end()); unsigned C_INT32 EventIdOld = it->first.getEventId(); unsigned C_INT32 EventIdNew = 0; CMathEvent * pEvent = it->second.mpEvent; EventIdNew = createEventId(); for (; it != assignments.second; ++it) it->second.process(EventIdNew); destroyEventId(EventIdOld); mAssignments.erase(assignments.first, assignments.second); // Update all dependent values. pEvent->applyDependentRefreshes(); mExecutionCounter++; return success; } bool CProcessQueue::rootsFound() { bool rootsFound = false; // Calculate the current root values mpMathModel->evaluateRoots(*mpRootValuesAfter, false); // Compare the root values before and after; C_INT * pRootFound = mRootsFound.array(); C_INT * pRootEnd = pRootFound + mRootsFound.size(); C_FLOAT64 * pValueBefore = mpRootValuesBefore->array(); C_FLOAT64 * pValueAfter = mpRootValuesAfter->array(); for (; pRootFound != pRootEnd; ++pRootFound, ++pValueBefore, ++pValueAfter) { if (*pValueBefore < 0.0 && *pValueAfter >= 0.0) { *pRootFound = 1; rootsFound = true; } else if (*pValueBefore > 0.0 && *pValueAfter <= 0.0) { *pRootFound = 1; rootsFound = true; } else { *pRootFound = 0; } } // Swap before and after. CVector< C_FLOAT64 > * pTmp = mpRootValuesBefore; mpRootValuesBefore = mpRootValuesAfter; mpRootValuesAfter = pTmp; return rootsFound; } // static bool CProcessQueue::notEmpty(const CProcessQueue::range & range) { return range.first != range.second; } const unsigned C_INT32 & CProcessQueue::createEventId() { unsigned C_INT32 EventId = 0; if (mEventIdSet.size() > 0) { EventId = * mEventIdSet.rbegin(); } return * mEventIdSet.insert(++EventId).first; } void CProcessQueue::destroyEventId(const unsigned C_INT32 & eventId) { mEventIdSet.erase(eventId); } const C_FLOAT64 & CProcessQueue::getProcessQueueExecutionTime() const { static C_FLOAT64 Infinity = std::numeric_limits< C_FLOAT64 >::infinity(); const C_FLOAT64 & CalculationTime = mCalculations.size() > 0 ? mCalculations.begin()->first.getExecutionTime() : Infinity; const C_FLOAT64 & AssignmentTime = mAssignments.size() > 0 ? mAssignments.begin()->first.getExecutionTime() : Infinity; return std::min(CalculationTime, AssignmentTime); } bool CProcessQueue::isEmpty() const { return (mAssignments.size() == 0) && (mCalculations.size() == 0); } Fixed problem with ignored checks for inequality in cascading events. // Begin CVS Header // $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/model/CProcessQueue.cpp,v $ // $Revision: 1.18 $ // $Name: $ // $Author: shoops $ // $Date: 2009/07/09 22:16:51 $ // End CVS Header // Copyright (C) 2008 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., EML Research, gGmbH, University of Heidelberg, // and The University of Manchester. // All rights reserved. #include <limits> #include "copasi.h" #include "CProcessQueue.h" #include "CMathModel.h" #include "function/CExpression.h" CProcessQueue::CKey::CKey() : mExecutionTime(0.0), mCascadingLevel(0), mEquality(false), mOrder(0), mEventId(std::numeric_limits<unsigned C_INT32>::max()) {} CProcessQueue::CKey::CKey(const CKey & src) : mExecutionTime(src.mExecutionTime), mCascadingLevel(src.mCascadingLevel), mEquality(src.mEquality), mOrder(src.mOrder), mEventId(src.mEventId) {} CProcessQueue::CKey::CKey(const C_FLOAT64 & executionTime, const bool & equality, const unsigned C_INT32 & order, const unsigned C_INT32 & eventId, const unsigned C_INT32 & cascadingLevel) : mExecutionTime(executionTime), mCascadingLevel(cascadingLevel), mEquality(equality), mOrder(order), mEventId(eventId) {} CProcessQueue::CKey::~CKey() {} bool CProcessQueue::CKey::operator < (const CProcessQueue::CKey & rhs) const { if (mExecutionTime != rhs.mExecutionTime) return mExecutionTime < rhs.mExecutionTime; if (mCascadingLevel != rhs.mCascadingLevel) return mCascadingLevel > rhs.mCascadingLevel; if (mEquality != rhs.mEquality) return mEquality; if (mOrder != rhs.mOrder) return mOrder < rhs.mOrder; return mEventId < rhs.mEventId; } CProcessQueue::CAction::CAction() : mpTarget(NULL), mValue(), mpExpression(NULL), mpEvent(NULL), mpProcessQueue(NULL) {} CProcessQueue::CAction::CAction(const CAction & src) : mpTarget(src.mpTarget), mValue(src.mValue), mpExpression(src.mpExpression), mpEvent(src.mpEvent), mpProcessQueue(src.mpProcessQueue) {} CProcessQueue::CAction::CAction(C_FLOAT64 * pTarget, const C_FLOAT64 & value, CMathEvent * pEvent) : mpTarget(pTarget), mValue(value), mpExpression(NULL), mpEvent(pEvent), mpProcessQueue(NULL) {} CProcessQueue::CAction::CAction(C_FLOAT64 * pTarget, CMathExpression * pExpression, CMathEvent * pEvent, CProcessQueue * pProcessQueue) : mpTarget(pTarget), mValue(), mpExpression(pExpression), mpEvent(pEvent), mpProcessQueue(pProcessQueue) {} CProcessQueue::CAction::~CAction() {} void CProcessQueue::CAction::process(const unsigned C_INT32 & eventId) { // If the expression pointer is not NULL we have a calculation. if (mpExpression != NULL) { // Calculate the execution time for delayed events. C_FLOAT64 ExecutionTime = mpEvent->getExecutionTime(mpProcessQueue->mTime); mpProcessQueue->addAssignment(ExecutionTime, mpProcessQueue->mEquality, mpEvent->getOrder(), eventId, mpTarget, mpExpression->calcValue(), mpEvent); } else { *mpTarget = mValue; } } CProcessQueue::CProcessQueue() : mCalculations(), mAssignments(), mExecutionLimit(10000), mExecutionCounter(0), mTime(0.0), mEquality(true), mCascadingLevel(0), mSimultaneousAssignments(false), mEventIdSet(), mRootsFound(0), mRootValues1(0), mRootValues2(0), mpRootValuesBefore(&mRootValues1), mpRootValuesAfter(&mRootValues2), mpResolveSimultaneousAssignments(NULL) {} CProcessQueue::CProcessQueue(const CProcessQueue & src): mCalculations(src.mCalculations), mAssignments(src.mAssignments), mExecutionLimit(src.mExecutionLimit), mExecutionCounter(src.mExecutionCounter), mTime(src.mTime), mEquality(src.mEquality), mCascadingLevel(src.mCascadingLevel), mSimultaneousAssignments(src.mSimultaneousAssignments), mEventIdSet(src.mEventIdSet), mRootsFound(src.mRootsFound), mRootValues1(src.mRootValues1), mRootValues2(src.mRootValues2), mpRootValuesBefore(&src.mRootValues1 == src.mpRootValuesBefore ? &mRootValues1 : &mRootValues2), mpRootValuesAfter(&src.mRootValues1 == src.mpRootValuesAfter ? &mRootValues1 : &mRootValues2), mpResolveSimultaneousAssignments(src.mpResolveSimultaneousAssignments) {} CProcessQueue::~CProcessQueue() {} bool CProcessQueue::addAssignment(const C_FLOAT64 & executionTime, const bool & equality, const unsigned C_INT32 & order, const unsigned C_INT32 & eventId, C_FLOAT64 * pTarget, const C_FLOAT64 & value, CMathEvent * pEvent) { // It is not possible to proceed backwards in time. if (executionTime < mTime) return false; unsigned C_INT32 CascadingLevel = mCascadingLevel; if (executionTime > mTime) CascadingLevel = 0; mAssignments.insert(std::make_pair(CKey(executionTime, equality, order, eventId, CascadingLevel), CAction(pTarget, value, pEvent))); return true; } bool CProcessQueue::addCalculation(const C_FLOAT64 & executionTime, const bool & equality, const unsigned C_INT32 & order, const unsigned C_INT32 & eventId, C_FLOAT64 * pTarget, CMathExpression * pExpression, CMathEvent * pEvent) { // It is not possible to proceed backwards in time. if (executionTime < mTime) return false; unsigned C_INT32 CascadingLevel = mCascadingLevel; if (executionTime > mTime) CascadingLevel = 0; mCalculations.insert(std::make_pair(CKey(executionTime, equality, order, eventId, CascadingLevel), CAction(pTarget, pExpression, pEvent, this))); return true; } void CProcessQueue::initialize(CMathModel * pMathModel) { mpMathModel = pMathModel; assert(mpMathModel != NULL); mTime = mpMathModel->getInitialTime(); mCalculations.clear(); mAssignments.clear(); mEventIdSet.clear(); mSimultaneousAssignments = false; unsigned C_INT32 NumRoots = mpMathModel->getNumRoots(); mRootsFound.resize(NumRoots); mRootsFound = 0; mRootValues1.resize(NumRoots); mRootValues2.resize(NumRoots); mpRootValuesBefore = &mRootValues1; mpRootValuesAfter = &mRootValues2; return; } bool CProcessQueue::process(const C_FLOAT64 & time, const bool & priorToOutput, resolveSimultaneousAssignments pResolveSimultaneousAssignments) { if (getProcessQueueExecutionTime() > time) return false; mTime = time; mEquality = priorToOutput; mpResolveSimultaneousAssignments = pResolveSimultaneousAssignments; mExecutionCounter = 0; mCascadingLevel = 0; bool success = true; bool stateChanged = false; range Calculations = getCalculations(); if (notEmpty(Calculations)) { // Execute and remove all current calculations. success = executeCalculations(Calculations); } range Assignments = getAssignments(); if (success && notEmpty(Assignments)) { mpMathModel->evaluateRoots(*mpRootValuesBefore, false); stateChanged = true; } // The algorithm below will work properly for user ordered events // as the queue enforces the proper ordering. while (success && notEmpty(Assignments) && mCascadingLevel != std::numeric_limits<unsigned C_INT32>::max()) { // We switch to the next cascading level so that events triggered by the // execution of assignments are properly scheduled. mCascadingLevel++; // Execute and remove all current assignments. success = executeAssignments(Assignments); // We need to compare the roots before the execution and after // to determine which roots need to be charged. if (rootsFound()) { // We have to deal with both types of found roots. mpMathModel->processRoots(mTime, true, mRootsFound); mpMathModel->processRoots(mTime, false, mRootsFound); } // Note, applying the events may have added new events to the queue. // The setting of the equality flag for these events may be either true // or false. // First we handle equalities. mEquality = true; // Retrieve the pending calculations. Calculations = getCalculations(); if (notEmpty(Calculations)) { // Execute and remove all current calculations. success = executeCalculations(Calculations); } // Retrieve the pending assignments. Assignments = getAssignments(); if (notEmpty(Assignments)) continue; // If we are here there are no more calculations and assignments for equality // for this level. mEquality = false; // Retrieve the pending calculations. Calculations = getCalculations(); if (notEmpty(Calculations)) { // Execute and remove all current calculations. success = executeCalculations(Calculations); } // Retrieve the pending assignments. Assignments = getAssignments(); while (!notEmpty(Assignments) && mCascadingLevel > 0) { // If we are here we have no more calculations and assignment for this level. mCascadingLevel--; // This will only return assignments when we have resolution algorithms for // them. Assignments = getAssignments(); } } if (mSimultaneousAssignments) { CCopasiMessage(CCopasiMessage::EXCEPTION, MCMathModel + 1); success = false; } return stateChanged; } CProcessQueue::range CProcessQueue::getCalculations() { range Calculations; CKey UpperBound(mTime, mEquality, std::numeric_limits<unsigned C_INT32>::max(), std::numeric_limits<unsigned C_INT32>::max(), mCascadingLevel); Calculations.first = mCalculations.begin(); if (Calculations.first != mCalculations.end() && Calculations.first->first < UpperBound) { Calculations.second = mCalculations.upper_bound(Calculations.first->first); // Check whether we have a second set of assignments with a different ID. if (Calculations.second != mCalculations.end() && Calculations.second->first < UpperBound) { mSimultaneousAssignments = true; // The resolution of simultaneous events is algorithm dependent. // The simulation routine should provide a call back function. if (mpResolveSimultaneousAssignments == NULL) { // TODO CRITICAL Create an error message } return (*mpResolveSimultaneousAssignments)(mCalculations, mTime, mEquality, mCascadingLevel); } } else { Calculations.first = Calculations.second = mCalculations.end(); } return Calculations; } CProcessQueue::range CProcessQueue::getAssignments() { range Assignments; CKey UpperBound(mTime, mEquality, std::numeric_limits<unsigned C_INT32>::max(), std::numeric_limits<unsigned C_INT32>::max(), mCascadingLevel); Assignments.first = mAssignments.begin(); if (Assignments.first != mAssignments.end() && Assignments.first->first < UpperBound) { Assignments.second = mAssignments.upper_bound(Assignments.first->first); // Check whether we have a second set of assignments with a different ID. if (Assignments.second != mAssignments.end() && Assignments.second->first < UpperBound) { mSimultaneousAssignments = true; // The resolution of simultaneous events is algorithm dependent. // The simulation routine should provide a call back function. if (mpResolveSimultaneousAssignments == NULL) { // TODO CRITICAL Create an error message } return (*mpResolveSimultaneousAssignments)(mAssignments, mTime, mEquality, mCascadingLevel); } } else { Assignments.first = Assignments.second = mAssignments.end(); } return Assignments; } bool CProcessQueue::executeCalculations(CProcessQueue::range & calculations) { bool success = true; iterator it = calculations.first; assert(it != mCalculations.end()); unsigned C_INT32 EventIdOld = it->first.getEventId(); unsigned C_INT32 EventIdNew = createEventId(); CMathEvent * pEvent = it->second.mpEvent; // Assure that all values are up to date. pEvent->applyValueRefreshes(); for (; it != calculations.second; ++it) { if (it->first.getEventId() != EventIdOld) { destroyEventId(EventIdOld); EventIdOld = it->first.getEventId(); EventIdNew = createEventId(); } it->second.process(EventIdNew); } destroyEventId(EventIdOld); mCalculations.erase(calculations.first, calculations.second); return success; } bool CProcessQueue::executeAssignments(CProcessQueue::range & assignments) { bool success = (mExecutionCounter < mExecutionLimit); iterator it = assignments.first; assert(it != mAssignments.end()); unsigned C_INT32 EventIdOld = it->first.getEventId(); unsigned C_INT32 EventIdNew = 0; CMathEvent * pEvent = it->second.mpEvent; EventIdNew = createEventId(); for (; it != assignments.second; ++it) it->second.process(EventIdNew); destroyEventId(EventIdOld); mAssignments.erase(assignments.first, assignments.second); // Update all dependent values. pEvent->applyDependentRefreshes(); mExecutionCounter++; return success; } bool CProcessQueue::rootsFound() { bool rootsFound = false; // Calculate the current root values mpMathModel->evaluateRoots(*mpRootValuesAfter, false); // Compare the root values before and after; C_INT * pRootFound = mRootsFound.array(); C_INT * pRootEnd = pRootFound + mRootsFound.size(); C_FLOAT64 * pValueBefore = mpRootValuesBefore->array(); C_FLOAT64 * pValueAfter = mpRootValuesAfter->array(); for (; pRootFound != pRootEnd; ++pRootFound, ++pValueBefore, ++pValueAfter) { if (*pValueBefore < 0.0 && *pValueAfter >= 0.0) { *pRootFound = 1; rootsFound = true; } else if (*pValueBefore > 0.0 && *pValueAfter <= 0.0) { *pRootFound = 1; rootsFound = true; } else { *pRootFound = 0; } } // Swap before and after. CVector< C_FLOAT64 > * pTmp = mpRootValuesBefore; mpRootValuesBefore = mpRootValuesAfter; mpRootValuesAfter = pTmp; return rootsFound; } // static bool CProcessQueue::notEmpty(const CProcessQueue::range & range) { return range.first != range.second; } const unsigned C_INT32 & CProcessQueue::createEventId() { unsigned C_INT32 EventId = 0; if (mEventIdSet.size() > 0) { EventId = * mEventIdSet.rbegin(); } return * mEventIdSet.insert(++EventId).first; } void CProcessQueue::destroyEventId(const unsigned C_INT32 & eventId) { mEventIdSet.erase(eventId); } const C_FLOAT64 & CProcessQueue::getProcessQueueExecutionTime() const { static C_FLOAT64 Infinity = std::numeric_limits< C_FLOAT64 >::infinity(); const C_FLOAT64 & CalculationTime = mCalculations.size() > 0 ? mCalculations.begin()->first.getExecutionTime() : Infinity; const C_FLOAT64 & AssignmentTime = mAssignments.size() > 0 ? mAssignments.begin()->first.getExecutionTime() : Infinity; return std::min(CalculationTime, AssignmentTime); } bool CProcessQueue::isEmpty() const { return (mAssignments.size() == 0) && (mCalculations.size() == 0); }
/* Copyright (C) 2005-2010, Thorvald Natvig <thorvald@natvig.com> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of the Mumble Developers nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "murmur_pch.h" #include "UnixMurmur.h" #include "Meta.h" QMutex *LimitTest::qm; QWaitCondition *LimitTest::qw; QWaitCondition *LimitTest::qstartw; LimitTest::LimitTest() : QThread() { } void LimitTest::run() { qm->lock(); qstartw->wakeAll(); qw->wait(qm); qm->unlock(); } void LimitTest::testLimits(QCoreApplication &a) { QAbstractEventDispatcher *ed = QAbstractEventDispatcher::instance(); if (QLatin1String(ed->metaObject()->className()) != QLatin1String("QEventDispatcherGlib")) qWarning("Not running with glib. While you may be able to open more descriptors, sockets above %d will not work", FD_SETSIZE); qWarning("Running descriptor test."); int count; QList<QFile *> ql; for (count=0;count < 524288; ++count) { QFile *qf = new QFile(a.applicationFilePath()); if (qf->open(QIODevice::ReadOnly)) ql.prepend(qf); else break; if ((count & 1023) == 0) qWarning("%d descriptors...", count); } foreach(QFile *qf, ql) delete qf; ql.clear(); qCritical("Managed to open %d descriptors", count); qm = new QMutex(); qw = new QWaitCondition(); qstartw = new QWaitCondition(); int fdcount = count / 8; if (sizeof(void *) < 8) if (fdcount > 1024) fdcount = 1024; QList<LimitTest *> qtl; for (count=0;count < fdcount; ++count) { LimitTest *t = new LimitTest(); t->tid = count; qtl << t; qm->lock(); t->start(); qstartw->wait(qm); qm->unlock(); if (! t->isRunning()) break; if ((count & 511) == 0) qWarning("%d threads...", count); } qm->lock(); qw->wakeAll(); qm->unlock(); foreach(LimitTest *qt, qtl) { if (! qt->wait(1000)) { qWarning("Thread %d failed to terminate...", qt->tid); qt->terminate(); } } qFatal("Managed to spawn %d threads", count); } extern QFile *qfLog; int UnixMurmur::iHupFd[2]; int UnixMurmur::iTermFd[2]; UnixMurmur::UnixMurmur() { bRoot = true; if (geteuid() != 0 && getuid() != 0) { bRoot = false; } if (::socketpair(AF_UNIX, SOCK_STREAM, 0, iHupFd)) qFatal("Couldn't create HUP socketpair"); if (::socketpair(AF_UNIX, SOCK_STREAM, 0, iTermFd)) qFatal("Couldn't create TERM socketpair"); qsnHup = new QSocketNotifier(iHupFd[1], QSocketNotifier::Read, this); qsnTerm = new QSocketNotifier(iTermFd[1], QSocketNotifier::Read, this); connect(qsnHup, SIGNAL(activated(int)), this, SLOT(handleSigHup())); connect(qsnTerm, SIGNAL(activated(int)), this, SLOT(handleSigTerm())); struct sigaction hup, term; hup.sa_handler = hupSignalHandler; sigemptyset(&hup.sa_mask); hup.sa_flags = SA_RESTART; if (sigaction(SIGHUP, &hup, NULL)) qFatal("Failed to install SIGHUP handler"); term.sa_handler = termSignalHandler; sigemptyset(&term.sa_mask); term.sa_flags = SA_RESTART; if (sigaction(SIGTERM, &term, NULL)) qFatal("Failed to install SIGTERM handler"); umask(S_IRWXO); } UnixMurmur::~UnixMurmur() { delete qsnHup; delete qsnTerm; qsnHup = NULL; qsnTerm = NULL; close(iHupFd[0]); close(iHupFd[1]); close(iTermFd[0]); close(iTermFd[1]); } void UnixMurmur::hupSignalHandler(int) { char a = 1; ::write(iHupFd[0], &a, sizeof(a)); } void UnixMurmur::termSignalHandler(int) { char a = 1; ::write(iTermFd[0], &a, sizeof(a)); } // Keep these two synchronized with matching actions in DBus.cpp void UnixMurmur::handleSigHup() { qsnHup->setEnabled(false); char tmp; ::read(iHupFd[1], &tmp, sizeof(tmp)); if (! qfLog || ! qfLog->isOpen()) { if (qfLog) { qWarning("Caught SIGHUP, but logfile not in use -- interpreting as hint to quit"); QCoreApplication::instance()->quit(); } else { qWarning("Caught SIGHUP, but logfile not in use"); } } else { qWarning("Caught SIGHUP, will reopen %s", qPrintable(Meta::mp.qsLogfile)); qfLog->close(); qfLog->setFileName(Meta::mp.qsLogfile); bool result = qfLog->open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text); if (! result) { delete qfLog; qfLog = NULL; } else { qfLog->setTextModeEnabled(true); qWarning("Log rotated successfully"); } } qsnHup->setEnabled(true); } void UnixMurmur::handleSigTerm() { qsnTerm->setEnabled(false); char tmp; ::read(iTermFd[1], &tmp, sizeof(tmp)); qCritical("Caught SIGTERM, exiting"); QCoreApplication::instance()->quit(); qsnTerm->setEnabled(true); } void UnixMurmur::setuid() { if (Meta::mp.uiUid != 0) { #ifdef Q_OS_DARWIN qCritical("WARNING: You are launching murmurd as root on Mac OS X or Darwin. Murmur does not need " "special privileges to set itself up on these systems, so this behavior is highly discouraged."); if (::setgid(Meta::mp.uiGid) != 0) qFatal("Failed to switch to gid %d", Meta::mp.uiGid); if (::setuid(Meta::mp.uiUid) != 0) qFatal("Failed to switch to uid %d", Meta::mp.uiUid); uid_t uid = getuid(), euid = geteuid(); gid_t gid = getgid(), egid = getegid(); if (uid == Meta::mp.uiUid && euid == Meta::mp.uiUid && gid == Meta::mp.uiGid && egid == Meta::mp.uiGid) { qCritical("Successfully switched to uid %d", Meta::mp.uiUid); } else qFatal("Couldn't switch uid/gid."); #else if (::initgroups(qPrintable(Meta::mp.qsName), Meta::mp.uiGid) != 0) qCritical("Can't initialize supplementary groups"); if (::setgid(Meta::mp.uiGid) != 0) qCritical("Failed to switch to gid %d", Meta::mp.uiGid); if (::setuid(Meta::mp.uiUid) != 0) { qFatal("Failed to become uid %d", Meta::mp.uiUid); } else { qCritical("Successfully switched to uid %d", Meta::mp.uiUid); initialcap(); } if (!Meta::mp.qsHome.isEmpty()) { // QDir::homePath is broken. It only looks at $HOME // instead of getpwuid() so we have to set our home // ourselves ::setenv("HOME", qPrintable(Meta::mp.qsHome), 1); } #endif } else if (bRoot) { qCritical("WARNING: You are running murmurd as root, without setting a uname in the ini file. This might be a security risk."); } } void UnixMurmur::initialcap() { #ifdef Q_OS_LINUX cap_value_t caps[] = {CAP_NET_ADMIN, CAP_SETUID, CAP_SETGID, CAP_CHOWN, CAP_SYS_RESOURCE, CAP_DAC_OVERRIDE }; if (! bRoot) return; int ncap = sizeof(caps)/sizeof(cap_value_t); if (geteuid() != 0) ncap--; cap_t c = cap_init(); cap_clear(c); cap_set_flag(c, CAP_EFFECTIVE, ncap, caps, CAP_SET); cap_set_flag(c, CAP_INHERITABLE, ncap, caps, CAP_SET); cap_set_flag(c, CAP_PERMITTED, ncap, caps, CAP_SET); if (cap_set_proc(c) != 0) { qCritical("Failed to set initial capabilities"); } else { prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0); } cap_free(c); #endif } void UnixMurmur::finalcap() { #ifdef Q_OS_LINUX cap_value_t caps[] = {CAP_NET_ADMIN, CAP_SYS_RESOURCE}; struct rlimit r; if (! bRoot) return; if (getrlimit(RLIMIT_RTPRIO, &r) != 0) { qCritical("Failed to get priority limits."); } else { qWarning("Resource limits were %ld %ld", r.rlim_cur, r.rlim_max); r.rlim_cur = r.rlim_max = 1; if (setrlimit(RLIMIT_RTPRIO, &r) != 0) { qCritical("Failed to set priority limits."); } } int ncap = sizeof(caps)/sizeof(cap_value_t); cap_t c = cap_init(); cap_clear(c); cap_set_flag(c, CAP_EFFECTIVE, ncap, caps, CAP_SET); cap_set_flag(c, CAP_PERMITTED, ncap, caps, CAP_SET); if (cap_set_proc(c) != 0) { qCritical("Failed to set final capabilities"); } else { qWarning("Successfully dropped capabilities"); } cap_free(c); #endif } Make log rotation more robust /* Copyright (C) 2005-2010, Thorvald Natvig <thorvald@natvig.com> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of the Mumble Developers nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "murmur_pch.h" #include "UnixMurmur.h" #include "Meta.h" QMutex *LimitTest::qm; QWaitCondition *LimitTest::qw; QWaitCondition *LimitTest::qstartw; LimitTest::LimitTest() : QThread() { } void LimitTest::run() { qm->lock(); qstartw->wakeAll(); qw->wait(qm); qm->unlock(); } void LimitTest::testLimits(QCoreApplication &a) { QAbstractEventDispatcher *ed = QAbstractEventDispatcher::instance(); if (QLatin1String(ed->metaObject()->className()) != QLatin1String("QEventDispatcherGlib")) qWarning("Not running with glib. While you may be able to open more descriptors, sockets above %d will not work", FD_SETSIZE); qWarning("Running descriptor test."); int count; QList<QFile *> ql; for (count=0;count < 524288; ++count) { QFile *qf = new QFile(a.applicationFilePath()); if (qf->open(QIODevice::ReadOnly)) ql.prepend(qf); else break; if ((count & 1023) == 0) qWarning("%d descriptors...", count); } foreach(QFile *qf, ql) delete qf; ql.clear(); qCritical("Managed to open %d descriptors", count); qm = new QMutex(); qw = new QWaitCondition(); qstartw = new QWaitCondition(); int fdcount = count / 8; if (sizeof(void *) < 8) if (fdcount > 1024) fdcount = 1024; QList<LimitTest *> qtl; for (count=0;count < fdcount; ++count) { LimitTest *t = new LimitTest(); t->tid = count; qtl << t; qm->lock(); t->start(); qstartw->wait(qm); qm->unlock(); if (! t->isRunning()) break; if ((count & 511) == 0) qWarning("%d threads...", count); } qm->lock(); qw->wakeAll(); qm->unlock(); foreach(LimitTest *qt, qtl) { if (! qt->wait(1000)) { qWarning("Thread %d failed to terminate...", qt->tid); qt->terminate(); } } qFatal("Managed to spawn %d threads", count); } extern QFile *qfLog; int UnixMurmur::iHupFd[2]; int UnixMurmur::iTermFd[2]; UnixMurmur::UnixMurmur() { bRoot = true; if (geteuid() != 0 && getuid() != 0) { bRoot = false; } if (::socketpair(AF_UNIX, SOCK_STREAM, 0, iHupFd)) qFatal("Couldn't create HUP socketpair"); if (::socketpair(AF_UNIX, SOCK_STREAM, 0, iTermFd)) qFatal("Couldn't create TERM socketpair"); qsnHup = new QSocketNotifier(iHupFd[1], QSocketNotifier::Read, this); qsnTerm = new QSocketNotifier(iTermFd[1], QSocketNotifier::Read, this); connect(qsnHup, SIGNAL(activated(int)), this, SLOT(handleSigHup())); connect(qsnTerm, SIGNAL(activated(int)), this, SLOT(handleSigTerm())); struct sigaction hup, term; hup.sa_handler = hupSignalHandler; sigemptyset(&hup.sa_mask); hup.sa_flags = SA_RESTART; if (sigaction(SIGHUP, &hup, NULL)) qFatal("Failed to install SIGHUP handler"); term.sa_handler = termSignalHandler; sigemptyset(&term.sa_mask); term.sa_flags = SA_RESTART; if (sigaction(SIGTERM, &term, NULL)) qFatal("Failed to install SIGTERM handler"); umask(S_IRWXO); } UnixMurmur::~UnixMurmur() { delete qsnHup; delete qsnTerm; qsnHup = NULL; qsnTerm = NULL; close(iHupFd[0]); close(iHupFd[1]); close(iTermFd[0]); close(iTermFd[1]); } void UnixMurmur::hupSignalHandler(int) { char a = 1; ssize_t len = ::write(iHupFd[0], &a, sizeof(a)); Q_UNUSED(len); } void UnixMurmur::termSignalHandler(int) { char a = 1; ssize_t len = ::write(iTermFd[0], &a, sizeof(a)); Q_UNUSED(len); } // Keep these two synchronized with matching actions in DBus.cpp void UnixMurmur::handleSigHup() { qsnHup->setEnabled(false); char tmp; ssize_t len = ::read(iHupFd[1], &tmp, sizeof(tmp)); Q_UNUSED(len); if (! qfLog) { qWarning("Caught SIGHUP, but logfile not in use"); } else if (! qfLog->isOpen()) { qWarning("Caught SIGHUP, but logfile not in use -- interpreting as hint to quit"); QCoreApplication::instance()->quit(); } else { qWarning("Caught SIGHUP, will reopen %s", qPrintable(Meta::mp.qsLogfile)); QFile *newlog = new QFile(Meta::mp.qsLogfile); bool result = newlog->open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text); if (! result) { delete newlog; qCritical("Failed to reopen logfile for writing, keeping old log"); } else { QFile *oldlog = qfLog; newlog->setTextModeEnabled(true); qfLog = newlog; oldlog->close(); delete oldlog; qWarning("Log rotated successfully"); } } qsnHup->setEnabled(true); } void UnixMurmur::handleSigTerm() { qsnTerm->setEnabled(false); char tmp; ssize_t len = ::read(iTermFd[1], &tmp, sizeof(tmp)); Q_UNUSED(len); qCritical("Caught SIGTERM, exiting"); QCoreApplication::instance()->quit(); qsnTerm->setEnabled(true); } void UnixMurmur::setuid() { if (Meta::mp.uiUid != 0) { #ifdef Q_OS_DARWIN qCritical("WARNING: You are launching murmurd as root on Mac OS X or Darwin. Murmur does not need " "special privileges to set itself up on these systems, so this behavior is highly discouraged."); if (::setgid(Meta::mp.uiGid) != 0) qFatal("Failed to switch to gid %d", Meta::mp.uiGid); if (::setuid(Meta::mp.uiUid) != 0) qFatal("Failed to switch to uid %d", Meta::mp.uiUid); uid_t uid = getuid(), euid = geteuid(); gid_t gid = getgid(), egid = getegid(); if (uid == Meta::mp.uiUid && euid == Meta::mp.uiUid && gid == Meta::mp.uiGid && egid == Meta::mp.uiGid) { qCritical("Successfully switched to uid %d", Meta::mp.uiUid); } else qFatal("Couldn't switch uid/gid."); #else if (::initgroups(qPrintable(Meta::mp.qsName), Meta::mp.uiGid) != 0) qCritical("Can't initialize supplementary groups"); if (::setgid(Meta::mp.uiGid) != 0) qCritical("Failed to switch to gid %d", Meta::mp.uiGid); if (::setuid(Meta::mp.uiUid) != 0) { qFatal("Failed to become uid %d", Meta::mp.uiUid); } else { qCritical("Successfully switched to uid %d", Meta::mp.uiUid); initialcap(); } if (!Meta::mp.qsHome.isEmpty()) { // QDir::homePath is broken. It only looks at $HOME // instead of getpwuid() so we have to set our home // ourselves ::setenv("HOME", qPrintable(Meta::mp.qsHome), 1); } #endif } else if (bRoot) { qCritical("WARNING: You are running murmurd as root, without setting a uname in the ini file. This might be a security risk."); } } void UnixMurmur::initialcap() { #ifdef Q_OS_LINUX cap_value_t caps[] = {CAP_NET_ADMIN, CAP_SETUID, CAP_SETGID, CAP_CHOWN, CAP_SYS_RESOURCE, CAP_DAC_OVERRIDE }; if (! bRoot) return; int ncap = sizeof(caps)/sizeof(cap_value_t); if (geteuid() != 0) ncap--; cap_t c = cap_init(); cap_clear(c); cap_set_flag(c, CAP_EFFECTIVE, ncap, caps, CAP_SET); cap_set_flag(c, CAP_INHERITABLE, ncap, caps, CAP_SET); cap_set_flag(c, CAP_PERMITTED, ncap, caps, CAP_SET); if (cap_set_proc(c) != 0) { qCritical("Failed to set initial capabilities"); } else { prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0); } cap_free(c); #endif } void UnixMurmur::finalcap() { #ifdef Q_OS_LINUX cap_value_t caps[] = {CAP_NET_ADMIN, CAP_SYS_RESOURCE}; struct rlimit r; if (! bRoot) return; if (getrlimit(RLIMIT_RTPRIO, &r) != 0) { qCritical("Failed to get priority limits."); } else { qWarning("Resource limits were %ld %ld", r.rlim_cur, r.rlim_max); r.rlim_cur = r.rlim_max = 1; if (setrlimit(RLIMIT_RTPRIO, &r) != 0) { qCritical("Failed to set priority limits."); } } int ncap = sizeof(caps)/sizeof(cap_value_t); cap_t c = cap_init(); cap_clear(c); cap_set_flag(c, CAP_EFFECTIVE, ncap, caps, CAP_SET); cap_set_flag(c, CAP_PERMITTED, ncap, caps, CAP_SET); if (cap_set_proc(c) != 0) { qCritical("Failed to set final capabilities"); } else { qWarning("Successfully dropped capabilities"); } cap_free(c); #endif }
//===- utils/TableGen/X86EVEX2VEXTablesEmitter.cpp - X86 backend-*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// /// /// This tablegen backend is responsible for emitting the X86 backend EVEX2VEX /// compression tables. /// //===----------------------------------------------------------------------===// #include "CodeGenTarget.h" #include "llvm/TableGen/Error.h" #include "llvm/TableGen/TableGenBackend.h" using namespace llvm; namespace { class X86EVEX2VEXTablesEmitter { RecordKeeper &Records; CodeGenTarget Target; // Hold all non-masked & non-broadcasted EVEX encoded instructions std::vector<const CodeGenInstruction *> EVEXInsts; // Hold all VEX encoded instructions. Divided into groups with same opcodes // to make the search more efficient std::map<uint64_t, std::vector<const CodeGenInstruction *>> VEXInsts; typedef std::pair<const CodeGenInstruction *, const CodeGenInstruction *> Entry; // Represent both compress tables std::vector<Entry> EVEX2VEX128; std::vector<Entry> EVEX2VEX256; public: X86EVEX2VEXTablesEmitter(RecordKeeper &R) : Records(R), Target(R) {} // run - Output X86 EVEX2VEX tables. void run(raw_ostream &OS); private: // Prints the given table as a C++ array of type // X86EvexToVexCompressTableEntry void printTable(const std::vector<Entry> &Table, raw_ostream &OS); }; void X86EVEX2VEXTablesEmitter::printTable(const std::vector<Entry> &Table, raw_ostream &OS) { StringRef Size = (Table == EVEX2VEX128) ? "128" : "256"; OS << "// X86 EVEX encoded instructions that have a VEX " << Size << " encoding\n" << "// (table format: <EVEX opcode, VEX-" << Size << " opcode>).\n" << "static const X86EvexToVexCompressTableEntry X86EvexToVex" << Size << "CompressTable[] = {\n" << " // EVEX scalar with corresponding VEX.\n"; // Print all entries added to the table for (auto Pair : Table) { OS << " { X86::" << Pair.first->TheDef->getName() << ", X86::" << Pair.second->TheDef->getName() << " },\n"; } OS << "};\n\n"; } // Return true if the 2 BitsInits are equal // Calculates the integer value residing BitsInit object static inline uint64_t getValueFromBitsInit(const BitsInit *B) { uint64_t Value = 0; for (unsigned i = 0, e = B->getNumBits(); i != e; ++i) { if (BitInit *Bit = dyn_cast<BitInit>(B->getBit(i))) Value |= uint64_t(Bit->getValue()) << i; else PrintFatalError("Invalid VectSize bit"); } return Value; } // Function object - Operator() returns true if the given VEX instruction // matches the EVEX instruction of this object. class IsMatch { const CodeGenInstruction *EVEXInst; public: IsMatch(const CodeGenInstruction *EVEXInst) : EVEXInst(EVEXInst) {} bool operator()(const CodeGenInstruction *VEXInst) { Record *RecE = EVEXInst->TheDef; Record *RecV = VEXInst->TheDef; bool EVEX_W = RecE->getValueAsBit("HasVEX_W"); bool VEX_W = RecV->getValueAsBit("HasVEX_W"); bool VEX_WIG = RecV->getValueAsBit("IgnoresVEX_W"); bool EVEX_WIG = RecE->getValueAsBit("IgnoresVEX_W"); bool EVEX_W1_VEX_W0 = RecE->getValueAsBit("EVEX_W1_VEX_W0"); if (RecV->getValueAsDef("OpEnc")->getName().str() != "EncVEX" || // VEX/EVEX fields RecV->getValueAsDef("OpPrefix") != RecE->getValueAsDef("OpPrefix") || RecV->getValueAsDef("OpMap") != RecE->getValueAsDef("OpMap") || RecV->getValueAsBit("hasVEX_4V") != RecE->getValueAsBit("hasVEX_4V") || RecV->getValueAsBit("hasEVEX_L2") != RecE->getValueAsBit("hasEVEX_L2") || RecV->getValueAsBit("hasVEX_L") != RecE->getValueAsBit("hasVEX_L") || // Match is allowed if either is VEX_WIG, or they match, or EVEX // is VEX_W1X and VEX is VEX_W0. (!(VEX_WIG || (!EVEX_WIG && EVEX_W == VEX_W) || (EVEX_W1_VEX_W0 && EVEX_W && !VEX_W))) || // Instruction's format RecV->getValueAsDef("Form") != RecE->getValueAsDef("Form") || RecV->getValueAsBit("isAsmParserOnly") != RecE->getValueAsBit("isAsmParserOnly")) return false; // This is needed for instructions with intrinsic version (_Int). // Where the only difference is the size of the operands. // For example: VUCOMISDZrm and Int_VUCOMISDrm // Also for instructions that their EVEX version was upgraded to work with // k-registers. For example VPCMPEQBrm (xmm output register) and // VPCMPEQBZ128rm (k register output register). for (unsigned i = 0, e = EVEXInst->Operands.size(); i < e; i++) { Record *OpRec1 = EVEXInst->Operands[i].Rec; Record *OpRec2 = VEXInst->Operands[i].Rec; if (OpRec1 == OpRec2) continue; if (isRegisterOperand(OpRec1) && isRegisterOperand(OpRec2)) { if (getRegOperandSize(OpRec1) != getRegOperandSize(OpRec2)) return false; } else if (isMemoryOperand(OpRec1) && isMemoryOperand(OpRec2)) { return false; } else if (isImmediateOperand(OpRec1) && isImmediateOperand(OpRec2)) { if (OpRec1->getValueAsDef("Type") != OpRec2->getValueAsDef("Type")) { return false; } } else return false; } return true; } private: static inline bool isRegisterOperand(const Record *Rec) { return Rec->isSubClassOf("RegisterClass") || Rec->isSubClassOf("RegisterOperand"); } static inline bool isMemoryOperand(const Record *Rec) { return Rec->isSubClassOf("Operand") && Rec->getValueAsString("OperandType") == "OPERAND_MEMORY"; } static inline bool isImmediateOperand(const Record *Rec) { return Rec->isSubClassOf("Operand") && Rec->getValueAsString("OperandType") == "OPERAND_IMMEDIATE"; } static inline unsigned int getRegOperandSize(const Record *RegRec) { if (RegRec->isSubClassOf("RegisterClass")) return RegRec->getValueAsInt("Alignment"); if (RegRec->isSubClassOf("RegisterOperand")) return RegRec->getValueAsDef("RegClass")->getValueAsInt("Alignment"); llvm_unreachable("Register operand's size not known!"); } }; void X86EVEX2VEXTablesEmitter::run(raw_ostream &OS) { emitSourceFileHeader("X86 EVEX2VEX tables", OS); ArrayRef<const CodeGenInstruction *> NumberedInstructions = Target.getInstructionsByEnumValue(); for (const CodeGenInstruction *Inst : NumberedInstructions) { // Filter non-X86 instructions. if (!Inst->TheDef->isSubClassOf("X86Inst")) continue; // Add VEX encoded instructions to one of VEXInsts vectors according to // it's opcode. if (Inst->TheDef->getValueAsDef("OpEnc")->getName() == "EncVEX") { uint64_t Opcode = getValueFromBitsInit(Inst->TheDef-> getValueAsBitsInit("Opcode")); VEXInsts[Opcode].push_back(Inst); } // Add relevant EVEX encoded instructions to EVEXInsts else if (Inst->TheDef->getValueAsDef("OpEnc")->getName() == "EncEVEX" && !Inst->TheDef->getValueAsBit("hasEVEX_K") && !Inst->TheDef->getValueAsBit("hasEVEX_B") && !Inst->TheDef->getValueAsBit("hasEVEX_L2") && !Inst->TheDef->getValueAsBit("notEVEX2VEXConvertible")) EVEXInsts.push_back(Inst); } for (const CodeGenInstruction *EVEXInst : EVEXInsts) { uint64_t Opcode = getValueFromBitsInit(EVEXInst->TheDef-> getValueAsBitsInit("Opcode")); // For each EVEX instruction look for a VEX match in the appropriate vector // (instructions with the same opcode) using function object IsMatch. // Allow EVEX2VEXOverride to explicitly specify a match. const CodeGenInstruction *VEXInst = nullptr; if (!EVEXInst->TheDef->isValueUnset("EVEX2VEXOverride")) { StringRef AltInstStr = EVEXInst->TheDef->getValueAsString("EVEX2VEXOverride"); Record *AltInstRec = Records.getDef(AltInstStr); assert(AltInstRec && "EVEX2VEXOverride instruction not found!"); VEXInst = &Target.getInstruction(AltInstRec); } else { auto Match = llvm::find_if(VEXInsts[Opcode], IsMatch(EVEXInst)); if (Match != VEXInsts[Opcode].end()) VEXInst = *Match; } if (!VEXInst) continue; // In case a match is found add new entry to the appropriate table if (EVEXInst->TheDef->getValueAsBit("hasVEX_L")) EVEX2VEX256.push_back(std::make_pair(EVEXInst, VEXInst)); // {0,1} else EVEX2VEX128.push_back(std::make_pair(EVEXInst, VEXInst)); // {0,0} } // Print both tables printTable(EVEX2VEX128, OS); printTable(EVEX2VEX256, OS); } } namespace llvm { void EmitX86EVEX2VEXTables(RecordKeeper &RK, raw_ostream &OS) { X86EVEX2VEXTablesEmitter(RK).run(OS); } } [X86] Remove check on isAsmParserOnly from EVEX2VEX tablegenerator. NFCI There are no instructions VEX or EVEX instructions that set this field. git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@357973 91177308-0d34-0410-b5e6-96231b3b80d8 //===- utils/TableGen/X86EVEX2VEXTablesEmitter.cpp - X86 backend-*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// /// /// This tablegen backend is responsible for emitting the X86 backend EVEX2VEX /// compression tables. /// //===----------------------------------------------------------------------===// #include "CodeGenTarget.h" #include "llvm/TableGen/Error.h" #include "llvm/TableGen/TableGenBackend.h" using namespace llvm; namespace { class X86EVEX2VEXTablesEmitter { RecordKeeper &Records; CodeGenTarget Target; // Hold all non-masked & non-broadcasted EVEX encoded instructions std::vector<const CodeGenInstruction *> EVEXInsts; // Hold all VEX encoded instructions. Divided into groups with same opcodes // to make the search more efficient std::map<uint64_t, std::vector<const CodeGenInstruction *>> VEXInsts; typedef std::pair<const CodeGenInstruction *, const CodeGenInstruction *> Entry; // Represent both compress tables std::vector<Entry> EVEX2VEX128; std::vector<Entry> EVEX2VEX256; public: X86EVEX2VEXTablesEmitter(RecordKeeper &R) : Records(R), Target(R) {} // run - Output X86 EVEX2VEX tables. void run(raw_ostream &OS); private: // Prints the given table as a C++ array of type // X86EvexToVexCompressTableEntry void printTable(const std::vector<Entry> &Table, raw_ostream &OS); }; void X86EVEX2VEXTablesEmitter::printTable(const std::vector<Entry> &Table, raw_ostream &OS) { StringRef Size = (Table == EVEX2VEX128) ? "128" : "256"; OS << "// X86 EVEX encoded instructions that have a VEX " << Size << " encoding\n" << "// (table format: <EVEX opcode, VEX-" << Size << " opcode>).\n" << "static const X86EvexToVexCompressTableEntry X86EvexToVex" << Size << "CompressTable[] = {\n" << " // EVEX scalar with corresponding VEX.\n"; // Print all entries added to the table for (auto Pair : Table) { OS << " { X86::" << Pair.first->TheDef->getName() << ", X86::" << Pair.second->TheDef->getName() << " },\n"; } OS << "};\n\n"; } // Return true if the 2 BitsInits are equal // Calculates the integer value residing BitsInit object static inline uint64_t getValueFromBitsInit(const BitsInit *B) { uint64_t Value = 0; for (unsigned i = 0, e = B->getNumBits(); i != e; ++i) { if (BitInit *Bit = dyn_cast<BitInit>(B->getBit(i))) Value |= uint64_t(Bit->getValue()) << i; else PrintFatalError("Invalid VectSize bit"); } return Value; } // Function object - Operator() returns true if the given VEX instruction // matches the EVEX instruction of this object. class IsMatch { const CodeGenInstruction *EVEXInst; public: IsMatch(const CodeGenInstruction *EVEXInst) : EVEXInst(EVEXInst) {} bool operator()(const CodeGenInstruction *VEXInst) { Record *RecE = EVEXInst->TheDef; Record *RecV = VEXInst->TheDef; bool EVEX_W = RecE->getValueAsBit("HasVEX_W"); bool VEX_W = RecV->getValueAsBit("HasVEX_W"); bool VEX_WIG = RecV->getValueAsBit("IgnoresVEX_W"); bool EVEX_WIG = RecE->getValueAsBit("IgnoresVEX_W"); bool EVEX_W1_VEX_W0 = RecE->getValueAsBit("EVEX_W1_VEX_W0"); if (RecV->getValueAsDef("OpEnc")->getName().str() != "EncVEX" || // VEX/EVEX fields RecV->getValueAsDef("OpPrefix") != RecE->getValueAsDef("OpPrefix") || RecV->getValueAsDef("OpMap") != RecE->getValueAsDef("OpMap") || RecV->getValueAsBit("hasVEX_4V") != RecE->getValueAsBit("hasVEX_4V") || RecV->getValueAsBit("hasEVEX_L2") != RecE->getValueAsBit("hasEVEX_L2") || RecV->getValueAsBit("hasVEX_L") != RecE->getValueAsBit("hasVEX_L") || // Match is allowed if either is VEX_WIG, or they match, or EVEX // is VEX_W1X and VEX is VEX_W0. (!(VEX_WIG || (!EVEX_WIG && EVEX_W == VEX_W) || (EVEX_W1_VEX_W0 && EVEX_W && !VEX_W))) || // Instruction's format RecV->getValueAsDef("Form") != RecE->getValueAsDef("Form")) return false; // This is needed for instructions with intrinsic version (_Int). // Where the only difference is the size of the operands. // For example: VUCOMISDZrm and Int_VUCOMISDrm // Also for instructions that their EVEX version was upgraded to work with // k-registers. For example VPCMPEQBrm (xmm output register) and // VPCMPEQBZ128rm (k register output register). for (unsigned i = 0, e = EVEXInst->Operands.size(); i < e; i++) { Record *OpRec1 = EVEXInst->Operands[i].Rec; Record *OpRec2 = VEXInst->Operands[i].Rec; if (OpRec1 == OpRec2) continue; if (isRegisterOperand(OpRec1) && isRegisterOperand(OpRec2)) { if (getRegOperandSize(OpRec1) != getRegOperandSize(OpRec2)) return false; } else if (isMemoryOperand(OpRec1) && isMemoryOperand(OpRec2)) { return false; } else if (isImmediateOperand(OpRec1) && isImmediateOperand(OpRec2)) { if (OpRec1->getValueAsDef("Type") != OpRec2->getValueAsDef("Type")) { return false; } } else return false; } return true; } private: static inline bool isRegisterOperand(const Record *Rec) { return Rec->isSubClassOf("RegisterClass") || Rec->isSubClassOf("RegisterOperand"); } static inline bool isMemoryOperand(const Record *Rec) { return Rec->isSubClassOf("Operand") && Rec->getValueAsString("OperandType") == "OPERAND_MEMORY"; } static inline bool isImmediateOperand(const Record *Rec) { return Rec->isSubClassOf("Operand") && Rec->getValueAsString("OperandType") == "OPERAND_IMMEDIATE"; } static inline unsigned int getRegOperandSize(const Record *RegRec) { if (RegRec->isSubClassOf("RegisterClass")) return RegRec->getValueAsInt("Alignment"); if (RegRec->isSubClassOf("RegisterOperand")) return RegRec->getValueAsDef("RegClass")->getValueAsInt("Alignment"); llvm_unreachable("Register operand's size not known!"); } }; void X86EVEX2VEXTablesEmitter::run(raw_ostream &OS) { emitSourceFileHeader("X86 EVEX2VEX tables", OS); ArrayRef<const CodeGenInstruction *> NumberedInstructions = Target.getInstructionsByEnumValue(); for (const CodeGenInstruction *Inst : NumberedInstructions) { // Filter non-X86 instructions. if (!Inst->TheDef->isSubClassOf("X86Inst")) continue; // Add VEX encoded instructions to one of VEXInsts vectors according to // it's opcode. if (Inst->TheDef->getValueAsDef("OpEnc")->getName() == "EncVEX") { uint64_t Opcode = getValueFromBitsInit(Inst->TheDef-> getValueAsBitsInit("Opcode")); VEXInsts[Opcode].push_back(Inst); } // Add relevant EVEX encoded instructions to EVEXInsts else if (Inst->TheDef->getValueAsDef("OpEnc")->getName() == "EncEVEX" && !Inst->TheDef->getValueAsBit("hasEVEX_K") && !Inst->TheDef->getValueAsBit("hasEVEX_B") && !Inst->TheDef->getValueAsBit("hasEVEX_L2") && !Inst->TheDef->getValueAsBit("notEVEX2VEXConvertible")) EVEXInsts.push_back(Inst); } for (const CodeGenInstruction *EVEXInst : EVEXInsts) { uint64_t Opcode = getValueFromBitsInit(EVEXInst->TheDef-> getValueAsBitsInit("Opcode")); // For each EVEX instruction look for a VEX match in the appropriate vector // (instructions with the same opcode) using function object IsMatch. // Allow EVEX2VEXOverride to explicitly specify a match. const CodeGenInstruction *VEXInst = nullptr; if (!EVEXInst->TheDef->isValueUnset("EVEX2VEXOverride")) { StringRef AltInstStr = EVEXInst->TheDef->getValueAsString("EVEX2VEXOverride"); Record *AltInstRec = Records.getDef(AltInstStr); assert(AltInstRec && "EVEX2VEXOverride instruction not found!"); VEXInst = &Target.getInstruction(AltInstRec); } else { auto Match = llvm::find_if(VEXInsts[Opcode], IsMatch(EVEXInst)); if (Match != VEXInsts[Opcode].end()) VEXInst = *Match; } if (!VEXInst) continue; // In case a match is found add new entry to the appropriate table if (EVEXInst->TheDef->getValueAsBit("hasVEX_L")) EVEX2VEX256.push_back(std::make_pair(EVEXInst, VEXInst)); // {0,1} else EVEX2VEX128.push_back(std::make_pair(EVEXInst, VEXInst)); // {0,0} } // Print both tables printTable(EVEX2VEX128, OS); printTable(EVEX2VEX256, OS); } } namespace llvm { void EmitX86EVEX2VEXTables(RecordKeeper &RK, raw_ostream &OS) { X86EVEX2VEXTablesEmitter(RK).run(OS); } }
#include "pcloudapp.h" #include "common.h" #include <QMenu> #include <QProcess> #include <QUrl> #include <QDir> #include <QDesktopServices> void PCloudApp::hideAllWindows(){ if (reglog) reglog->hide(); if (regwin) regwin->hide(); if (logwin) logwin->hide(); if (settingswin) settingswin->hide(); if (incomingshareswin) incomingshareswin->hide(); if (outgoingshareswin) outgoingshareswin->hide(); } void PCloudApp::setUser(binresult *userinfo){ emit logInSignal(find_res(userinfo, "auth")->str, find_res(userinfo, "email")->str); } void PCloudApp::showWindow(QMainWindow *win) { win->raise(); win->activateWindow(); win->showNormal(); win->setWindowState(Qt::WindowActive); this->setActiveWindow(win); } void PCloudApp::showRegLog(){ hideAllWindows(); if (!reglog) reglog=new RegLogWindow(this); showWindow(reglog); } void PCloudApp::showRegister(){ hideAllWindows(); if (!regwin) regwin=new RegisterWindow(this); showWindow(regwin); } void PCloudApp::showLogin(){ hideAllWindows(); if (!logwin) logwin=new LoginWindow(this); showWindow(logwin); } void PCloudApp::showSettings(){ hideAllWindows(); if (!settingswin) settingswin=new SettingsWindow(this); showWindow(settingswin); } void PCloudApp::openCloudDir(){ QDesktopServices::openUrl(QUrl::fromLocalFile(settings->get("path"))); } void PCloudApp::shareFolder(){ hideAllWindows(); if (!sharefolderwin) sharefolderwin=new ShareFolderWindow(this); showWindow(sharefolderwin); } void PCloudApp::outgoingShares(){ hideAllWindows(); if (!outgoingshareswin) outgoingshareswin=new SharesWindow(this, 0); showWindow(outgoingshareswin); } void PCloudApp::incomingShares() { hideAllWindows(); if (!incomingshareswin) incomingshareswin=new SharesWindow(this, 1); showWindow(incomingshareswin); } void PCloudApp::logOut(){ loggedin=false; username=""; tray->setContextMenu(notloggedmenu); tray->setToolTip("pCloud"); tray->setIcon(QIcon(OFFLINE_ICON)); settings->unset("auth"); unMount(); } void PCloudApp::upgradePlan() { QUrl url("https://my.pcloud.com/#page=plans&authtoken="+settings->get("auth")); QDesktopServices::openUrl(url); } void PCloudApp::doExit(){ unMount(); quit(); } void PCloudApp::trayClicked(QSystemTrayIcon::ActivationReason reason){ if (reason==QSystemTrayIcon::Trigger){ if (loggedin) openCloudDir(); else showLogin(); } } void PCloudApp::createMenus(){ notloggedmenu=new QMenu(); registerAction=new QAction("Register", this); connect(registerAction, SIGNAL(triggered()), this, SLOT(showRegister())); notloggedmenu->addAction(registerAction); loginAction=new QAction("Login", this); connect(loginAction, SIGNAL(triggered()), this, SLOT(showLogin())); notloggedmenu->addAction(loginAction); settingsAction=new QAction("Settings", this); connect(settingsAction, SIGNAL(triggered()), this, SLOT(showSettings())); notloggedmenu->addAction(settingsAction); notloggedmenu->addSeparator(); exitAction=new QAction("Exit", this); connect(exitAction, SIGNAL(triggered()), this, SLOT(doExit())); notloggedmenu->addAction(exitAction); openAction=new QAction("Open pCloud folder", this); connect(openAction, SIGNAL(triggered()), this, SLOT(openCloudDir())); shareFolderAction=new QAction("Share folder", this); connect(shareFolderAction, SIGNAL(triggered()), this, SLOT(shareFolder())); outgoingSharesAction=new QAction("My Shares", this); connect(outgoingSharesAction, SIGNAL(triggered()), this, SLOT(outgoingShares())); incomingSharesAction=new QAction("Shared with Me", this); connect(incomingSharesAction, SIGNAL(triggered()), this, SLOT(incomingShares())); upgradeAction=new QAction("Upgrade", this); connect(upgradeAction, SIGNAL(triggered()), this, SLOT(upgradePlan())); logoutAction=new QAction("Logout", this); connect(logoutAction, SIGNAL(triggered()), this, SLOT(logOut())); } PCloudApp::PCloudApp(int &argc, char **argv) : QApplication(argc, argv) { reglog=NULL; regwin=NULL; logwin=NULL; loggedmenu=NULL; settingswin=NULL; sharefolderwin=NULL; incomingshareswin=NULL; outgoingshareswin=NULL; mthread=NULL; loggedin=false; lastMessageType=0; createMenus(); settings=new PSettings(this); tray=new QSystemTrayIcon(this); tray->setIcon(QIcon(OFFLINE_ICON)); tray->setContextMenu(notloggedmenu); tray->setToolTip("pCloud"); connect(tray, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(trayClicked(QSystemTrayIcon::ActivationReason))); connect(tray, SIGNAL(messageClicked()), this, SLOT(trayMsgClicked())); connect(this, SIGNAL(logInSignal(QString, QString)), this, SLOT(logIn(QString, QString))); connect(this, SIGNAL(showLoginSignal()), this, SLOT(showLogin())); tray->show(); if (settings->isSet("auth") && settings->get("auth").length() > 0){ othread=new OnlineThread(this); othread->start(); } else{ othread=NULL; emit showLoginSignal(); } } PCloudApp::~PCloudApp(){ if (othread){ if (othread->isRunning()) othread->terminate(); othread->wait(); delete othread; } if (mthread){ if (mthread->isRunning()) mthread->terminate(); mthread->wait(); delete mthread; } delete settings; delete tray; if (loggedmenu) delete loggedmenu; delete notloggedmenu; delete registerAction; delete loginAction; delete exitAction; delete logoutAction; delete openAction; delete settingsAction; delete upgradeAction; delete shareFolderAction; if (regwin) delete regwin; if (reglog) delete reglog; if (logwin) delete logwin; if (settingswin) delete settingswin; if (sharefolderwin) delete sharefolderwin; if (incomingshareswin) delete incomingshareswin; if (outgoingshareswin) delete outgoingshareswin; } apisock *PCloudApp::getAPISock(){ if (settings->geti("usessl")) return api_connect_ssl(); else return api_connect(); } bool PCloudApp::isMounted(){ QDir dir(settings->get("path")+"/.pfs_settings"); return dir.exists(); } #ifdef Q_OS_WIN #define REGISTRY_KEY_PCLOUD "SOFTWARE\\PCloud\\pCloud" #define SZSERVICENAME L"pfs" static void storeKey(LPCSTR key, const char * val) { HRESULT hr; HKEY hKey; hr = RegCreateKeyExA(HKEY_LOCAL_MACHINE, REGISTRY_KEY_PCLOUD, 0, NULL, 0, KEY_ALL_ACCESS, NULL, &hKey, NULL); if (!hr) { hr = RegSetValueExA(hKey, key, 0, REG_SZ, (LPBYTE)val, strlen(val)+1); RegCloseKey(hKey); } } static void stopService() { SC_HANDLE schService; SERVICE_STATUS ssStatus; SC_HANDLE schSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); if (!schSCManager) return; schService = OpenService(schSCManager, SZSERVICENAME, SERVICE_ALL_ACCESS); if (schService) { ControlService(schService, SERVICE_CONTROL_STOP, &ssStatus); int retry = 5; while(QueryServiceStatus(schService, &ssStatus) && retry) { if (ssStatus.dwCurrentState == SERVICE_STOPPED) break; Sleep(1000); --retry; } CloseServiceHandle(schService); } CloseServiceHandle(schSCManager); } static bool restartService(QByteArray &err) { SC_HANDLE schService; SERVICE_STATUS ssStatus; SC_HANDLE schSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); if (!schSCManager) return false; schService = OpenService(schSCManager, SZSERVICENAME, SERVICE_ALL_ACCESS); if (schService) { ControlService(schService, SERVICE_CONTROL_STOP, &ssStatus); int retry = 5; while(QueryServiceStatus(schService, &ssStatus) && retry) { if (ssStatus.dwCurrentState == SERVICE_STOPPED) break; Sleep(1000); --retry; } if (!retry){ err = "Failed to stop PCloud fs."; } if (StartService(schService, 0, NULL)) { Sleep(1000); int retry = 5; while(QueryServiceStatus(schService, &ssStatus) && retry) { --retry; if (ssStatus.dwCurrentState == SERVICE_START_PENDING) Sleep(1000); else break; } if (!retry){ err = "Failed to start PCloud fs."; return false; } else{ err = ""; return true; } } CloseServiceHandle(schService); } CloseServiceHandle(schSCManager); return false; } #endif void PCloudApp::mount() { if (settings->isSet("auth")){ QByteArray auth=settings->get("auth").toUtf8(); apisock *conn=getAPISock(); binresult *res, *result; QByteArray err; if (!conn) return; res=send_command(conn, "userinfo", P_LSTR("auth", auth.constData(), auth.size()), P_BOOL("getauth", 1)); api_close(conn); result=find_res(res, "result"); if (!result){ free(res); return; } if (result->num!=0){ free(res); return; } userLogged(res, err); free(res); } } void PCloudApp::unMount(){ #ifdef Q_OS_WIN stopService(); #else QProcess process; QString path=settings->get("path"); process.start("umount", QStringList() << "-f" << path); if (process.waitForFinished() && process.exitCode()==0) return; process.start("fusermount", QStringList() << "-u" << path); if (process.waitForFinished() && process.exitCode()==0) return; process.start("fusermount", QStringList() << "-z" << "-u" << path); if (process.waitForFinished() && process.exitCode()==0) return; #endif } void PCloudApp::showError(QString err){ tray->showMessage("Error", err, QSystemTrayIcon::Warning); } void PCloudApp::showTrayMessage(QString title, QString msg) { tray->showMessage(title, msg, QSystemTrayIcon::Information); } void PCloudApp::logIn(QString auth, QString uname) { settings->set("auth", auth); #ifdef Q_OS_WIN if (!settings->isSet("path") || !settings->get("path").toUtf8()[0]){ QString path("a:"); path[0] = getFirstFreeDevice(); settings->set("path", path); } #endif loggedin=true; username=uname; tray->setToolTip(username); if (loggedmenu) delete loggedmenu; loggedmenu=new QMenu(); loggedmenu->addAction(username); loggedmenu->addAction(openAction); loggedmenu->addSeparator(); loggedmenu->addAction(shareFolderAction); loggedmenu->addAction(outgoingSharesAction); loggedmenu->addAction(incomingSharesAction); loggedmenu->addSeparator(); loggedmenu->addAction(settingsAction); loggedmenu->addSeparator(); loggedmenu->addAction(upgradeAction); loggedmenu->addAction(logoutAction); loggedmenu->addAction(exitAction); tray->setIcon(QIcon(ONLINE_ICON)); tray->setContextMenu(loggedmenu); if (!mthread){ mthread=new MonitoringThread(this); mthread->start(); } } void PCloudApp::trayMsgClicked() { if (lastMessageType&2) outgoingShares(); else if (lastMessageType) incomingShares(); } void PCloudApp::setOnlineStatus(bool online) { static bool lastStatus = isMounted(); if (online){ tray->setIcon(QIcon(ONLINE_ICON)); if (online != lastStatus) { lastMessageType = 0; tray->showMessage("PCloud connected", "", QSystemTrayIcon::Information); lastStatus = online; } } else{ tray->setIcon(QIcon(OFFLINE_ICON)); if (online != lastStatus){ lastMessageType = 0; tray->showMessage("PCloud disconnected", "", QSystemTrayIcon::Information); lastStatus = online; } } } bool PCloudApp::userLogged(binresult *userinfo, QByteArray &err){ if (isMounted()){ setUser(userinfo); return true; } else{ #ifdef Q_OS_WIN if (find_res(userinfo, "auth")){ if (!settings->isSet("path") || !settings->get("path").toUtf8()[0]){ QString path("a:"); path[0] = getFirstFreeDevice(); settings->set("path", path); } storeKey("path", settings->get("path").toUtf8()); storeKey("cachesize", settings->get("cachesize").toUtf8()); storeKey("ssl", settings->geti("usessl")?"SSL":""); storeKey("auth", find_res(userinfo, "auth")->str); QString auth(find_res(userinfo, "auth")->str); settings->set("auth", auth); if (restartService(err)){ setUser(userinfo); return true; } return false; } else { err = "User not logged in."; return false; } #else QProcess process; QStringList params; #ifdef Q_OS_MAC params.append("-o"); params.append("volname=pCloud"); // Adding -o local may or may not be a good idea params.append("-o"); params.append("local"); #endif params.append("--auth"); params.append(find_res(userinfo, "auth")->str); if (settings->geti("usessl")) params.append("--ssl"); params.append("--cache"); params.append(settings->get("cachesize")); params.append(settings->get("path")); #ifdef Q_OS_MAC process.start("/usr/local/bin/mount.pfs", params); #else process.start("mount.pfs", params); #endif if (!process.waitForFinished()){ err="Error mounting filesystem."; return false; } if (process.exitCode()==0){ setUser(userinfo); return true; } else { err=process.readAllStandardError(); return false; } #endif } } try running umount from /sbin #include "pcloudapp.h" #include "common.h" #include <QMenu> #include <QProcess> #include <QUrl> #include <QDir> #include <QDesktopServices> void PCloudApp::hideAllWindows(){ if (reglog) reglog->hide(); if (regwin) regwin->hide(); if (logwin) logwin->hide(); if (settingswin) settingswin->hide(); if (incomingshareswin) incomingshareswin->hide(); if (outgoingshareswin) outgoingshareswin->hide(); } void PCloudApp::setUser(binresult *userinfo){ emit logInSignal(find_res(userinfo, "auth")->str, find_res(userinfo, "email")->str); } void PCloudApp::showWindow(QMainWindow *win) { win->raise(); win->activateWindow(); win->showNormal(); win->setWindowState(Qt::WindowActive); this->setActiveWindow(win); } void PCloudApp::showRegLog(){ hideAllWindows(); if (!reglog) reglog=new RegLogWindow(this); showWindow(reglog); } void PCloudApp::showRegister(){ hideAllWindows(); if (!regwin) regwin=new RegisterWindow(this); showWindow(regwin); } void PCloudApp::showLogin(){ hideAllWindows(); if (!logwin) logwin=new LoginWindow(this); showWindow(logwin); } void PCloudApp::showSettings(){ hideAllWindows(); if (!settingswin) settingswin=new SettingsWindow(this); showWindow(settingswin); } void PCloudApp::openCloudDir(){ QDesktopServices::openUrl(QUrl::fromLocalFile(settings->get("path"))); } void PCloudApp::shareFolder(){ hideAllWindows(); if (!sharefolderwin) sharefolderwin=new ShareFolderWindow(this); showWindow(sharefolderwin); } void PCloudApp::outgoingShares(){ hideAllWindows(); if (!outgoingshareswin) outgoingshareswin=new SharesWindow(this, 0); showWindow(outgoingshareswin); } void PCloudApp::incomingShares() { hideAllWindows(); if (!incomingshareswin) incomingshareswin=new SharesWindow(this, 1); showWindow(incomingshareswin); } void PCloudApp::logOut(){ loggedin=false; username=""; tray->setContextMenu(notloggedmenu); tray->setToolTip("pCloud"); tray->setIcon(QIcon(OFFLINE_ICON)); settings->unset("auth"); unMount(); } void PCloudApp::upgradePlan() { QUrl url("https://my.pcloud.com/#page=plans&authtoken="+settings->get("auth")); QDesktopServices::openUrl(url); } void PCloudApp::doExit(){ unMount(); quit(); } void PCloudApp::trayClicked(QSystemTrayIcon::ActivationReason reason){ if (reason==QSystemTrayIcon::Trigger){ if (loggedin) openCloudDir(); else showLogin(); } } void PCloudApp::createMenus(){ notloggedmenu=new QMenu(); registerAction=new QAction("Register", this); connect(registerAction, SIGNAL(triggered()), this, SLOT(showRegister())); notloggedmenu->addAction(registerAction); loginAction=new QAction("Login", this); connect(loginAction, SIGNAL(triggered()), this, SLOT(showLogin())); notloggedmenu->addAction(loginAction); settingsAction=new QAction("Settings", this); connect(settingsAction, SIGNAL(triggered()), this, SLOT(showSettings())); notloggedmenu->addAction(settingsAction); notloggedmenu->addSeparator(); exitAction=new QAction("Exit", this); connect(exitAction, SIGNAL(triggered()), this, SLOT(doExit())); notloggedmenu->addAction(exitAction); openAction=new QAction("Open pCloud folder", this); connect(openAction, SIGNAL(triggered()), this, SLOT(openCloudDir())); shareFolderAction=new QAction("Share folder", this); connect(shareFolderAction, SIGNAL(triggered()), this, SLOT(shareFolder())); outgoingSharesAction=new QAction("My Shares", this); connect(outgoingSharesAction, SIGNAL(triggered()), this, SLOT(outgoingShares())); incomingSharesAction=new QAction("Shared with Me", this); connect(incomingSharesAction, SIGNAL(triggered()), this, SLOT(incomingShares())); upgradeAction=new QAction("Upgrade", this); connect(upgradeAction, SIGNAL(triggered()), this, SLOT(upgradePlan())); logoutAction=new QAction("Logout", this); connect(logoutAction, SIGNAL(triggered()), this, SLOT(logOut())); } PCloudApp::PCloudApp(int &argc, char **argv) : QApplication(argc, argv) { reglog=NULL; regwin=NULL; logwin=NULL; loggedmenu=NULL; settingswin=NULL; sharefolderwin=NULL; incomingshareswin=NULL; outgoingshareswin=NULL; mthread=NULL; loggedin=false; lastMessageType=0; createMenus(); settings=new PSettings(this); tray=new QSystemTrayIcon(this); tray->setIcon(QIcon(OFFLINE_ICON)); tray->setContextMenu(notloggedmenu); tray->setToolTip("pCloud"); connect(tray, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(trayClicked(QSystemTrayIcon::ActivationReason))); connect(tray, SIGNAL(messageClicked()), this, SLOT(trayMsgClicked())); connect(this, SIGNAL(logInSignal(QString, QString)), this, SLOT(logIn(QString, QString))); connect(this, SIGNAL(showLoginSignal()), this, SLOT(showLogin())); tray->show(); if (settings->isSet("auth") && settings->get("auth").length() > 0){ othread=new OnlineThread(this); othread->start(); } else{ othread=NULL; emit showLoginSignal(); } } PCloudApp::~PCloudApp(){ if (othread){ if (othread->isRunning()) othread->terminate(); othread->wait(); delete othread; } if (mthread){ if (mthread->isRunning()) mthread->terminate(); mthread->wait(); delete mthread; } delete settings; delete tray; if (loggedmenu) delete loggedmenu; delete notloggedmenu; delete registerAction; delete loginAction; delete exitAction; delete logoutAction; delete openAction; delete settingsAction; delete upgradeAction; delete shareFolderAction; if (regwin) delete regwin; if (reglog) delete reglog; if (logwin) delete logwin; if (settingswin) delete settingswin; if (sharefolderwin) delete sharefolderwin; if (incomingshareswin) delete incomingshareswin; if (outgoingshareswin) delete outgoingshareswin; } apisock *PCloudApp::getAPISock(){ if (settings->geti("usessl")) return api_connect_ssl(); else return api_connect(); } bool PCloudApp::isMounted(){ QDir dir(settings->get("path")+"/.pfs_settings"); return dir.exists(); } #ifdef Q_OS_WIN #define REGISTRY_KEY_PCLOUD "SOFTWARE\\PCloud\\pCloud" #define SZSERVICENAME L"pfs" static void storeKey(LPCSTR key, const char * val) { HRESULT hr; HKEY hKey; hr = RegCreateKeyExA(HKEY_LOCAL_MACHINE, REGISTRY_KEY_PCLOUD, 0, NULL, 0, KEY_ALL_ACCESS, NULL, &hKey, NULL); if (!hr) { hr = RegSetValueExA(hKey, key, 0, REG_SZ, (LPBYTE)val, strlen(val)+1); RegCloseKey(hKey); } } static void stopService() { SC_HANDLE schService; SERVICE_STATUS ssStatus; SC_HANDLE schSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); if (!schSCManager) return; schService = OpenService(schSCManager, SZSERVICENAME, SERVICE_ALL_ACCESS); if (schService) { ControlService(schService, SERVICE_CONTROL_STOP, &ssStatus); int retry = 5; while(QueryServiceStatus(schService, &ssStatus) && retry) { if (ssStatus.dwCurrentState == SERVICE_STOPPED) break; Sleep(1000); --retry; } CloseServiceHandle(schService); } CloseServiceHandle(schSCManager); } static bool restartService(QByteArray &err) { SC_HANDLE schService; SERVICE_STATUS ssStatus; SC_HANDLE schSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); if (!schSCManager) return false; schService = OpenService(schSCManager, SZSERVICENAME, SERVICE_ALL_ACCESS); if (schService) { ControlService(schService, SERVICE_CONTROL_STOP, &ssStatus); int retry = 5; while(QueryServiceStatus(schService, &ssStatus) && retry) { if (ssStatus.dwCurrentState == SERVICE_STOPPED) break; Sleep(1000); --retry; } if (!retry){ err = "Failed to stop PCloud fs."; } if (StartService(schService, 0, NULL)) { Sleep(1000); int retry = 5; while(QueryServiceStatus(schService, &ssStatus) && retry) { --retry; if (ssStatus.dwCurrentState == SERVICE_START_PENDING) Sleep(1000); else break; } if (!retry){ err = "Failed to start PCloud fs."; return false; } else{ err = ""; return true; } } CloseServiceHandle(schService); } CloseServiceHandle(schSCManager); return false; } #endif void PCloudApp::mount() { if (settings->isSet("auth")){ QByteArray auth=settings->get("auth").toUtf8(); apisock *conn=getAPISock(); binresult *res, *result; QByteArray err; if (!conn) return; res=send_command(conn, "userinfo", P_LSTR("auth", auth.constData(), auth.size()), P_BOOL("getauth", 1)); api_close(conn); result=find_res(res, "result"); if (!result){ free(res); return; } if (result->num!=0){ free(res); return; } userLogged(res, err); free(res); } } void PCloudApp::unMount(){ #ifdef Q_OS_WIN stopService(); #else QProcess process; QString path=settings->get("path"); process.start("umount", QStringList() << "-f" << path); if (process.waitForFinished() && process.exitCode()==0) return; process.start("/sbin/umount", QStringList() << "-f" << path); if (process.waitForFinished() && process.exitCode()==0) return; process.start("fusermount", QStringList() << "-u" << path); if (process.waitForFinished() && process.exitCode()==0) return; process.start("fusermount", QStringList() << "-z" << "-u" << path); if (process.waitForFinished() && process.exitCode()==0) return; #endif } void PCloudApp::showError(QString err){ tray->showMessage("Error", err, QSystemTrayIcon::Warning); } void PCloudApp::showTrayMessage(QString title, QString msg) { tray->showMessage(title, msg, QSystemTrayIcon::Information); } void PCloudApp::logIn(QString auth, QString uname) { settings->set("auth", auth); #ifdef Q_OS_WIN if (!settings->isSet("path") || !settings->get("path").toUtf8()[0]){ QString path("a:"); path[0] = getFirstFreeDevice(); settings->set("path", path); } #endif loggedin=true; username=uname; tray->setToolTip(username); if (loggedmenu) delete loggedmenu; loggedmenu=new QMenu(); loggedmenu->addAction(username); loggedmenu->addAction(openAction); loggedmenu->addSeparator(); loggedmenu->addAction(shareFolderAction); loggedmenu->addAction(outgoingSharesAction); loggedmenu->addAction(incomingSharesAction); loggedmenu->addSeparator(); loggedmenu->addAction(settingsAction); loggedmenu->addSeparator(); loggedmenu->addAction(upgradeAction); loggedmenu->addAction(logoutAction); loggedmenu->addAction(exitAction); tray->setIcon(QIcon(ONLINE_ICON)); tray->setContextMenu(loggedmenu); if (!mthread){ mthread=new MonitoringThread(this); mthread->start(); } } void PCloudApp::trayMsgClicked() { if (lastMessageType&2) outgoingShares(); else if (lastMessageType) incomingShares(); } void PCloudApp::setOnlineStatus(bool online) { static bool lastStatus = isMounted(); if (online){ tray->setIcon(QIcon(ONLINE_ICON)); if (online != lastStatus) { lastMessageType = 0; tray->showMessage("PCloud connected", "", QSystemTrayIcon::Information); lastStatus = online; } } else{ tray->setIcon(QIcon(OFFLINE_ICON)); if (online != lastStatus){ lastMessageType = 0; tray->showMessage("PCloud disconnected", "", QSystemTrayIcon::Information); lastStatus = online; } } } bool PCloudApp::userLogged(binresult *userinfo, QByteArray &err){ if (isMounted()){ setUser(userinfo); return true; } else{ #ifdef Q_OS_WIN if (find_res(userinfo, "auth")){ if (!settings->isSet("path") || !settings->get("path").toUtf8()[0]){ QString path("a:"); path[0] = getFirstFreeDevice(); settings->set("path", path); } storeKey("path", settings->get("path").toUtf8()); storeKey("cachesize", settings->get("cachesize").toUtf8()); storeKey("ssl", settings->geti("usessl")?"SSL":""); storeKey("auth", find_res(userinfo, "auth")->str); QString auth(find_res(userinfo, "auth")->str); settings->set("auth", auth); if (restartService(err)){ setUser(userinfo); return true; } return false; } else { err = "User not logged in."; return false; } #else QProcess process; QStringList params; #ifdef Q_OS_MAC params.append("-o"); params.append("volname=pCloud"); // Adding -o local may or may not be a good idea params.append("-o"); params.append("local"); #endif params.append("--auth"); params.append(find_res(userinfo, "auth")->str); if (settings->geti("usessl")) params.append("--ssl"); params.append("--cache"); params.append(settings->get("cachesize")); params.append(settings->get("path")); #ifdef Q_OS_MAC process.start("/usr/local/bin/mount.pfs", params); #else process.start("mount.pfs", params); #endif if (!process.waitForFinished()){ err="Error mounting filesystem."; return false; } if (process.exitCode()==0){ setUser(userinfo); return true; } else { err=process.readAllStandardError(); return false; } #endif } }
#include "MATHS.H" #include "LOAD_LEV.H" #include "SPECIFIC.H" #include <INLINE_C.H> #include "3D_GEN.H" #include "CAMERA.H" #include "DRAW.H" #include "GPU.H" #include "GTEREG.H" #include "DRAWSPKS.H" void mQuickW2VMatrix()//77AEC(<), 79B30(<) { MatrixSP = 0; Matrix = &MatrixStack[0]; ((int*)&MatrixStack)[0] = ((unsigned short*)phd_mxptr)[0] | ((unsigned short*)phd_mxptr)[2] << 16; ((int*)&MatrixStack)[1] = ((unsigned short*)phd_mxptr)[4] | ((unsigned short*)phd_mxptr)[8] << 16; ((int*)&MatrixStack)[2] = ((unsigned short*)phd_mxptr)[10] | ((unsigned short*)phd_mxptr)[12] << 16; ((int*)&MatrixStack)[3] = ((unsigned short*)phd_mxptr)[16] | ((unsigned short*)phd_mxptr)[18] << 16; R12 = ((short*)phd_mxptr)[2] << 16; R11 = ((short*)phd_mxptr)[0]; R21 = ((short*)phd_mxptr)[8] << 16; R13 = ((short*)phd_mxptr)[4]; R23 = ((short*)phd_mxptr)[12] << 16; R22 = ((short*)phd_mxptr)[10]; R32 = ((short*)phd_mxptr)[18] << 16; R31 = ((short*)phd_mxptr)[16]; ((short*)&MatrixStack)[8] = ((unsigned short*)phd_mxptr)[20]; ((short*)&MatrixStack)[10] = ((unsigned short*)phd_mxptr)[6]; ((short*)&MatrixStack)[12] = ((unsigned short*)phd_mxptr)[14]; ((short*)&MatrixStack)[14] = ((unsigned short*)phd_mxptr)[22]; R33 = ((unsigned short*)phd_mxptr)[20]; TRX = ((unsigned short*)phd_mxptr)[6]; TRY = ((unsigned short*)phd_mxptr)[14]; TRZ = ((unsigned short*)phd_mxptr)[22]; CamGTE.m00 = ((unsigned short*)&w2v_matrix)[0]; CamGTE.m01 = ((unsigned short*)&w2v_matrix)[2]; CamGTE.m02 = ((unsigned short*)&w2v_matrix)[4]; CamGTE.m10 = ((unsigned short*)&w2v_matrix)[8]; CamGTE.m11 = ((unsigned short*)&w2v_matrix)[10]; CamGTE.m12 = ((unsigned short*)&w2v_matrix)[12]; CamGTE.m20 = ((unsigned short*)&w2v_matrix)[16]; CamGTE.m21 = ((unsigned short*)&w2v_matrix)[18]; CamGTE.m22 = ((unsigned short*)&w2v_matrix)[20]; } void gte_sttr(struct PHD_VECTOR* vec)//To investigate, this should not be in this file. { vec->x = Matrix->tx >> 12; vec->y = Matrix->ty >> 12; vec->z = Matrix->tz >> 12; } long mGetAngle(long x, long z, long tx, long tz)//77678(<), 796BC(<) (F) { long dx = tx - x; long dz = tz - z; short table_index = 0; long result_angle = 0; long temp = 0; if ((dx | dz) != 0) { if (dx < 0) { table_index |= 0x10;//FIXME: += (4); dx = -dx; } //0x796E0 if (dz < 0) { table_index += 2; dz = -dz; } //796F0 if (dx < dz) { table_index += 1; temp = dx; dx = dz; dz = temp; } //7970C while (dz / 65536 != 0) { dx /= 2; dz /= 2; } //79724 result_angle = atanTab[dz * 2048 / dx]; result_angle += atanOctantTab[table_index]; if (result_angle < 0) { result_angle = -result_angle; }//79760 }//79760 return -result_angle & 0xFFFF; } long mSqrt(long value)//83B30(<), 85B74(<) (F) { long v0 = 0x1F; long v1 = gte_ldlzc(value); if (value != 0) { v1 &= 0xFFFFFFFE; v0 = v0 - v1 >> 1; long at = v1 - 0x18; if (v1 - 0x18 < 0) { //loc_85BA8 value >>= 0x18 - v1; } else { value <<= v1 - 0x18; } //loc_85BB4 value = SqrtTable[value - 0x40] << v0; }//locret_85BD0 return (value >> 12); } long phd_sqrt_asm(long value)//83B30(<), 85B74(<) (F) { long v0 = 0x1F; long v1 = gte_ldlzc(value); if (value != 0) { v1 &= 0xFFFFFFFE; v0 = v0 - v1 >> 1; long at = v1 - 0x18; if (v1 - 0x18 < 0) { //loc_85BA8 value >>= 0x18 - v1; } else { value <<= v1 - 0x18; } //loc_85BB4 value = SqrtTable[value - 0x40] << v0; }//locret_85BD0 return (value >> 12); } void ScaleCurrentMatrix(long bStoreInMatrix, long sx, long sy, long sz) { int t2, v0, v1; unsigned int t0, t1, at; t0 = R11; t1 = R13; t2 = R22; v0 = R31; v1 = R33; R12 = ((((t0 << 16) >> 16) * sx) >> 12) & 0xFFFF; R11 = ((((t0 >> 16) * sy) >> 12) << 16); R21 = ((((t1 << 16) >> 16) * sz) >> 12) & 0xFFFF; R13 = (((t1 >> 16) * sx) >> 12) << 16; R23 = ((((t2 << 16) >> 16) * sy) >> 12) & 0xFFFF; R22 = (((t2 >> 16) * sz) >> 12) << 16; R32 = ((((v0 << 16) >> 16) * sx) >> 12) & 0xFFFF; R31 = (((v0 >> 16) * sy) >> 12) << 16; R33 = ((((v1 << 16) >> 16) * sz) >> 12); if (bStoreInMatrix) { Matrix->m00 = R11; Matrix->m01 = R12; Matrix->m02 = R13; Matrix->m10 = R21; Matrix->m11 = R22; Matrix->m12 = R23; Matrix->m20 = R31; Matrix->m21 = R32; Matrix->m22 = R33; }//locret_77E68 } void mPushMatrix()//764D0(<), 78514(<) (F) { ++Matrix; Matrix->m00 = R11; Matrix->m01 = R12; Matrix->m02 = R13; Matrix->m10 = R21; Matrix->m11 = R22; Matrix->m12 = R23; Matrix->m20 = R31; Matrix->m21 = R32; Matrix->m22 = R33; Matrix->tx = TRX; Matrix->ty = TRY; Matrix->tz = TRZ; } void mPopMatrix()//76520(<), 78564(<) (F) { mLoadMatrix(--Matrix); } void mUnitMatrix() { UNIMPLEMENTED(); } void mPushUnitMatrix()//76534(<), 78578(<) { setrot(++Matrix, 0x1000, 0, 0x1000, 0, 0x1000); } void mTranslate()//76558(<) (!) { UNIMPLEMENTED(); } void mTranslateAbsXYZ(long x, long y, long z) { mTranslateXYZ(x - MatrixStack[0].tx, y - MatrixStack[0].ty, z - MatrixStack[0].tz); } void mTranslateXYZ(long x, long y, long z)//7658C(<), 785D0(<) (!) { int t0; int t1; int t2; int t3; int t4; int t5; t4 = y >> 15; if (y < 0) { y = -y; t4 = y >> 15; y &= 0x7FFF; t4 = -t4; y = -y; }//loc_765AC else { y &= 0x7FFF; } //loc_765B0 : t5 = z >> 15; if (z < 0) { z = -z; t5 = z >> 15; z &= 0x7FFF; t5 = -t5; z = -z; } else { //loc_765D0 z &= 0x7FFF; } //loc_765D4 t3 = x >> 15; if (x < 0) { x = -x; t3 = x >> 15; x &= 0x7FFF; t3 = -t3; x = -x; } else { x &= 0x7FFF; } IR1 = t3; IR2 = t4; IR3 = t5; docop2(0x41E012); t3 = MAC1; t4 = MAC2; t5 = MAC3; IR1 = x; IR2 = y; IR3 = z; docop2(0x498012); t0 = t3 << 3; if (t3 < 0) { t3 = -t3; t3 <<= 3; t0 = -t3; } //loc_7663C t1 = t4 << 3; if (t4 < 0) { t4 = -t4; t4 <<= 3; t1 = -t4; } //loc_76650 t2 = t5 << 3; if (t5 < 0) { t5 = -t5; t5 <<= 3; t2 = -t5; }//loc_76664 t3 = MAC1; t4 = MAC2; t5 = MAC3; t0 += t3; t1 += t4; t2 += t5; TRX = t0; TRY = t1; TRZ = t2; Matrix->tx = t0; Matrix->ty = t1; Matrix->tz = t2; } void mRotX(long rx)//7669C (F) { int t0; int t1; int t2; int t3; int t4; int t5; int t6; rx = (rx >> 2) & 0x3FFC; if (rx != 0) { //loc_766B4 t5 = (rcossin_tbl[rx >> 1] & 0xFFFF) | ((rcossin_tbl[rx >> 1 | 1] & 0xFFFF ) << 16); VX0 = (0xFFFF0000 & t5) & 0xFFFF; VY0 = ((0xFFFF0000 & t5) >> 16) & 0xFFFF; VZ0 = t5 & 0xFFFF; t0 = (R12 << 16 | R11) & 0xFFFF; t1 = (R21 << 16 | R13) & 0xFFFF0000; t3 = (R32 << 16 | R31) & 0xFFFF; docop2(0x486012); t6 = t5 >> 16; t5 <<= 16; t5 = -t5; VX1 = t5; VY1 = (t5 >> 16) & 0xFFFF; VZ1 = t6; t4 = MAC1; t2 = MAC2 & 0xFFFF; t5 = MAC3; docop2(0x48E012); t0 |= t4 << 16; t3 |= t5 << 16; t5 = MAC1 & 0xFFFF; t6 = MAC2; t4 = MAC3; t1 |= t5; t2 |= t6 << 16; SetRotation(t0, t1, t2, t3, t4); } } void mRotY(long ry)//76744 (F) { int t0; int t1; int t2; int t3; int t4; int t5; int t6; int t7; ry = (ry >> 2) & 0x3FFC; if (ry != 0) { t5 = (rcossin_tbl[ry >> 1] & 0xFFFF) | ((rcossin_tbl[ry >> 1 | 1] & 0xFFFF) << 16); t6 = t5 >> 16; t5 &= 0xFFFF; t2 = -t5; VX0 = t6; VY0 = (t5 >> 16) & 0xFFFF; VZ0 = t2; t0 = (R12 << 16 | R11) & 0xFFFF0000; t2 = (R23 << 16 | R22); t3 = (R32 << 16 | R31); docop2(0x486012); VX1 = t5; VY1 = (t5 >> 16) & 0xFFFF; VZ1 = t6; t4 = MAC1; t1 = MAC2; t5 = MAC3; docop2(0x48E012); t0 |= (t4 & 0xFFFF); t3 |= (t5 & 0xFFFF); t5 = MAC1; t6 = MAC2; t4 = MAC3; t1 = (t1 << 16) | (t5 & 0xFFFF); t2 |= t6 << 16; SetRotation(t0, t1, t2, t3, t4); } } void mRotYXZ(short y, short x, short z)//767E8 (F) { mRotY(y); mRotX(x); mRotZ(z); } void mRotZ(long rz)//76804 (F) { int t0; int t1; int t2; int t3; int t4; int t5; int t6; int t7; int a0; rz = (rz >> 2) & 0x3FFC; if (rz != 0) { //loc_7681C t0 = (rcossin_tbl[rz >> 1] & 0xFFFF) | ((rcossin_tbl[rz >> 1 | 1] & 0xFFFF) << 16); t1 = ((t0 >> 16) & 0xFFFF) | (t0 << 16); VX0 = (t1 & 0xFFFF); VY0 = ((t1 >> 16) & 0xFFFF); VZ0 = 0; t1 = (R21 << 16 | R13) & 0xFFFF; t2 = (R23 << 16 | R22) & 0xFFFF0000; t4 = R33; docop2(0x486012); t3 = t0 & 0xFFFF0000; t0 &= 0xFFFF; t0 = -t0; t0 &= 0xFFFF; t0 |= t3; VX1 = t0; VY1 = (t0 >> 16) & 0xFFFF; VZ1 = 0; t0 = MAC1 & 0xFFFF; t5 = MAC2; t3 = MAC3 & 0xFFFF; docop2(0x48E012); t5 <<= 16; t1 |= t5; t5 = MAC1; t6 = MAC2 & 0xFFFF; a0 = MAC3; t0 |= t5 << 16; t2 |= t6; t3 |= a0 << 16; SetRotation(t0, t1, t2, t3, t4); } } void mRotSuperPackedYXZ(short** a0, long a1)//768BC { unsigned short* a2; int v0; int at; a2 = (unsigned short*)a0[0]; if (a1 != 0) { //loc_768C4 do { v0 = *a2++; a1--; if (!(v0 & 0xC000)) { a2++; }//loc_768DC } while (a1 == 0); }//loc_768E8 v0 = *a2++; at = (v0 >> 14); at--; if (at != 0) { a0[0] = (short*)a2; if (at != 0) { mRotZ((v0 & 0xFFF) << 4); }//loc_76914 mRotY((v0 & 0xFFF) << 4); mRotX((v0 & 0xFFF) << 4); }//loc_76928 at = *a2++; a0[0] = (short*)a2; mRotY((((v0 << 16) | at) >> 4) & 0xFFC0); mRotX((((v0 << 16) | at) >> 14) & 0xFFC0); mRotZ((((v0 << 16) | at) & 0x3FF) << 6); } void mRotPackedYXZ(long yxz)//7693C (F) { UNIMPLEMENTED(); } void SetRotation(int t0, int t1, int t2, int t3, int t4)//7696C(<) (F) { R11 = t0 & 0xFFFF; R12 = t0 >> 16; R13 = t1 & 0xFFFF; R21 = t1 >> 16; R22 = t2 & 0xFFFF; R23 = t2 >> 16; R31 = t3 & 0xFFFF; R32 = t3 >> 16; R33 = t4; ((int*)&Matrix->m00)[0] = t0; ((int*)&Matrix->m02)[0] = t1; ((int*)&Matrix->m11)[0] = t2; ((int*)&Matrix->m20)[0] = t3; ((int*)&Matrix->m22)[0] = t4; } void setrot(struct MATRIX3D* m, long t0, long t1, long t2, long t3, long t4)//76970 TOCHECK { R11 = t0 >> 16; R12 = t0; R13 = t1 >> 16; R21 = t1; R22 = t2 >> 16; R23 = t2; R31 = t3 >> 16; R32 = t3; R33 = t4; ((int*)Matrix)[0] = t0; ((int*)Matrix)[1] = t1; ((int*)Matrix)[2] = t2; ((int*)Matrix)[3] = t3; ((int*)Matrix)[4] = t4; } void mLoadMatrix(struct MATRIX3D* m)//7699C(<), 789E0(<) TOCHECK { R11 = m->m00; R12 = m->m01; R13 = m->m02; R21 = m->m10; R22 = m->m11; R23 = m->m12; R31 = m->m20; R32 = m->m21; R33 = m->m22; TRX = m->tx; TRY = m->ty; TRZ = m->tz; return; } //Note: Original code is less optimal than this implementation. void mCopyMatrix(struct MATRIX3D* m)//769E4(<), 78A28(<) (F) TOCHECK { UNIMPLEMENTED(); } void ASM_GetBounds()//76A28 { UNIMPLEMENTED(); } void GetBounds()//76A28 { UNIMPLEMENTED(); } void mSetTrans(long x, long y, long z)//76AF4(<), 78B38(<) { TRX = x; TRY = y; TRZ = z; Matrix->tx = x; Matrix->ty = y; Matrix->tz = z; } void mClipBoundingBox(short* bounds)//76B14 { UNIMPLEMENTED(); } void InitInterpolation(long frac, long rate, struct MATRIX3D* m)//76CB4 { UNIMPLEMENTED(); } void iPushMatrix0()//76D3C(<), ?(<) (F) { UNIMPLEMENTED(); } void iPushMatrix(struct MATRIX3D* m)//81E60(<), ?(<) (F) { UNIMPLEMENTED(); } void iPopMatrix0() { UNIMPLEMENTED(); } void iPopMatrix(struct MATRIX3D* m, struct MATRIX3D* m2)//76D8C(<), ?(<) TOCHECK { UNIMPLEMENTED(); } void mPushMatrix0()//764D0 (F) { UNIMPLEMENTED(); } void mmPushMatrix(struct MATRIX3D* m)//81BBC(<) (F) { UNIMPLEMENTED(); } void SetRoomBounds(tr_room_portal* portal, int room_number, struct room_info* parent) { UNIMPLEMENTED(); } void GetRoomBoundsAsm(short room_number)//77E70(<), 79EB4(<) ///@TODO check if in right file { #if 0 GetRoomBoundsAsm: lui a1, 0x1F80 sw s0, 0xD8(a1) sw s1, 0xDC(a1) sw s2, 0xE0(a1) sw s3, 0xE4(a1) sw s4, 0xE8(a1) sw s5, 0xEC(a1) sw s6, 0xF0(a1) sw s7, 0xF4(a1) sw fp, 0xF8(a1) move s0, a1 lw s1, room - GP_ADDR(gp) move s2, zero li s3, 1 li s4, 0x1F8000FC move s5, zero lw fp, outside - GP_ADDR(gp) sb a0, 0(s0) sll a0, 4 sll at, a0, 2 add a0, at add a0, s1 lui t0, 0x1FF lui t1, 0xEF li t2, 2 sw t0, 0x40(a0) sw t1, 0x44(a0) sb t2, 0x37(a0) addiu t6, gp, CamPos - GP_ADDR cfc2 t1, r5 cfc2 t2, r6 cfc2 t3, r7 sw t1, 0xB0(s0) sw t2, 0xB4(s0) sw t3, 0xB8(s0) lw t1, 0(t6) lw t2, 4(t6) lw t3, 8(t6) sw t1, 0xBC(s0) sw t2, 0xC0(s0) sw t3, 0xC4(s0) loc_77F18: beq s2, s3, loc_78490 add t0, s0, s2 lbu s6, 0(t0) addi s2, 1 andi s2, 0x7F sll a0, s6, 4 sll at, a0, 2 add a0, at add a0, s1 lb v0, 0x37(a0) lw t1, 0x38(a0) addi v0, -2 lw t3, 0x3C(a0) lw t5, 0x40(a0) lw t7, 0x44(a0) srl t2, t1, 16 andi t1, 0xFFFF srl t4, t3, 16 andi t3, 0xFFFF srl t6, t5, 16 andi t5, 0xFFFF srl t8, t7, 16 andi t7, 0xFFFF slt at, t5, t1 beqz at, loc_77F84 slt at, t6, t2 move t1, t5 loc_77F84 : bnez at, loc_77F90 slt at, t7, t3 move t2, t6 loc_77F90 : beqz at, loc_77F9C slt at, t8, t4 move t3, t7 loc_77F9C : bnez at, loc_77FA8 sll t6, t2, 16 move t4, t8 loc_77FA8 : or t5, t1, t6 sll t6, t4, 16 or t6, t3 sw t5, 0x38(a0) sw t6, 0x3C(a0) andi at, v0, 1 bnez at, loc_77FD4 ori v0, 1 sh s6, 0(s4) addi s4, 2 addi s5, 1 loc_77FD4: lh s6, 0x4E(a0) sb v0, 0x37(a0) andi s6, 8 or fp, s6 lw s7, 4(a0) lw t0, 0x14(a0) beqz s7, loc_77F18 lw t1, 0x18(a0) lw t2, 0x1C(a0) bgez t0, loc_78018 sra t3, t0, 15 negu t0, t0 sra t3, t0, 15 andi t0, 0x7FFF negu t3, t3 j loc_7801C negu t0, t0 loc_78018 : andi t0, 0x7FFF loc_7801C : bgez t1, loc_7803C sra t4, t1, 15 negu t1, t1 sra t4, t1, 15 andi t1, 0x7FFF negu t4, t4 j loc_78040 negu t1, t1 loc_7803C : andi t1, 0x7FFF loc_78040 : bgez t2, loc_78060 sra t5, t2, 15 negu t2, t2 sra t5, t2, 15 andi t2, 0x7FFF negu t5, t5 j loc_78064 negu t2, t2 loc_78060 : andi t2, 0x7FFF loc_78064 : mtc2 t3, r9 mtc2 t4, r10 mtc2 t5, r11 nop nop cop2 0x41E012 lw t3, 0xB0(s0) lw t4, 0xB4(s0) lw t5, 0xB8(s0) ctc2 t3, r5 ctc2 t4, r6 ctc2 t5, r7 mfc2 t3, r25 mfc2 t4, r26 mtc2 t0, r9 mtc2 t1, r10 mtc2 t2, r11 mfc2 t5, r27 nop nop cop2 0x498012 bgez t3, loc_780C0 sll t0, t3, 3 negu t3, t3 sll t3, 3 negu t0, t3 loc_780C0 : bgez t4, loc_780D4 sll t1, t4, 3 negu t4, t4 sll t4, 3 negu t1, t4 loc_780D4 : bgez t5, loc_780E8 sll t2, t5, 3 negu t5, t5 sll t5, 3 negu t2, t5 loc_780E8 : mfc2 t3, r25 mfc2 t4, r26 mfc2 t5, r27 addu t0, t3 addu t1, t4 addu t2, t5 ctc2 t0, r5 ctc2 t1, r6 ctc2 t2, r7 lh v0, 0(s7) addi s7, 2 loc_78114: lh a1, 0(s7) addi s7, 2 lh t0, 0(s7) lw t1, 0x14(a0) beqz t0, loc_7814C lh t2, 6(s7) lw t3, 0xBC(s0) add t1, t2 sub t1, t3 beqz t1, loc_7847C xor t0, t1 bltz t0, loc_781A8 move a2, s7 j loc_7847C loc_7814C : lh t0, 2(s7) lw t1, 0x18(a0) beqz t0, loc_7817C lh t2, 8(s7) lw t3, 0xC0(s0) add t1, t2 sub t1, t3 beqz t1, loc_7847C xor t0, t1 bltz t0, loc_781A8 move a2, s7 j loc_7847C loc_7817C : lh t0, 4(s7) lw t1, 0x1C(a0) beqz t0, loc_7847C lh t2, 0xA(s7) lw t3, 0xC4(s0) add t1, t2 sub t1, t3 beqz t1, loc_7847C xor t0, t1 bgez t0, loc_7847C move a2, s7 loc_781A8 : sll a3, a1, 4 sll at, a3, 2 add a3, at add a3, s1 lw t0, 0x38(a3) lw t2, 0x40(a0) lw t4, 0x3C(a3) lw t6, 0x44(a0) srl t1, t0, 16 andi t0, 0xFFFF srl t3, t2, 16 andi t2, 0xFFFF srl t5, t4, 16 andi t4, 0xFFFF srl t7, t6, 16 andi t6, 0xFFFF slt at, t0, t2 beqz at, loc_78208 slt at, t1, t3 bnez at, loc_78208 slt at, t4, t6 beqz at, loc_78208 slt at, t5, t7 beqz at, loc_7847C loc_78208 : move t0, t3 move t1, t2 move t2, t7 move t3, t6 addi t4, s0, 0x80 move t5, zero move t6, zero li v1, 3 loc_78228: lhu t7, 6(a2) lhu t9, 8(a2) lhu t8, 0xA(a2) sll t9, 16 or t7, t9 mtc2 t7, r0 mtc2 t8, r1 addi a2, 6 nop nop cop2 0x480012 mfc2 t7, r9 mfc2 t8, r10 mfc2 t9, r11 cop2 0x180001 sw t7, 0(t4) sw t8, 4(t4) sw t9, 8(t4) bgtz t9, loc_78278 addi t4, 0xC j loc_782C8 addi t5, 1 loc_78278: slti at, t9, 0x5000 mfc2 t7, r14 bnez at, loc_7828C sra t8, t7, 16 addi t6, 1 loc_7828C : sll t7, 16 sra t7, 16 slt at, t7, t0 beqz at, loc_782A4 slt at, t7, t1 move t0, t7 loc_782A4 : bnez at, loc_782B0 slt at, t8, t2 move t1, t7 loc_782B0 : beqz at, loc_782BC slt at, t8, t3 move t2, t8 loc_782BC : bnez at, loc_782C8 nop move t3, t8 loc_782C8 : bnez v1, loc_78228 addi v1, -1 li at, 4 beq t5, at, loc_7847C addi t4, s0, 0x80 beq t6, at, loc_7847C li v1, 3 beqz t5, loc_78384 addi t5, t4, 0x24 loc_782EC: lw t6, 8(t4) lw t7, 8(t5) slti t8, t6, 1 slti t9, t7, 1 xor t8, t9 beqz t8, loc_78374 lw t6, 0(t4) lw t7, 0(t5) slt t8, t6, zero slt t9, t7, zero and t8, t9 beqz t8, loc_78328 slt t8, zero, t6 j loc_7833C move t0, zero loc_78328 : slt t9, zero, t7 and t8, t9 bnez t8, loc_7833C li t1, 0x1FF move t0, zero loc_7833C : lw t6, 4(t4) lw t7, 4(t5) slt t8, t6, zero slt t9, t7, zero and t8, t9 beqz t8, loc_78360 slt t8, zero, t6 j loc_78374 move t2, zero loc_78360 : slt t9, zero, t7 and t8, t9 bnez t8, loc_78374 li t3, 0xEF move t2, zero loc_78374 : move t5, t4 addi t4, 0xC bnez v1, loc_782EC addi v1, -1 loc_78384 : lw t4, 0x40(a0) lw t6, 0x44(a0) srl t5, t4, 16 andi t4, 0xFFFF srl t7, t6, 16 andi t6, 0xFFFF slt at, t0, t4 beqz at, loc_783AC slt at, t5, t1 move t0, t4 loc_783AC : beqz at, loc_783B8 slt at, t2, t6 move t1, t5 loc_783B8 : beqz at, loc_783C4 slt at, t7, t3 move t2, t6 loc_783C4 : beqz at, loc_783D0 sub at, t0, t1 move t3, t7 loc_783D0 : bgez at, loc_7847C sub at, t2, t3 bgez at, loc_7847C lb v1, 0x37(a3) add t4, s0, s3 andi at, v1, 2 bnez at, loc_7841C ori v1, 2 sb a1, 0(t4) addi s3, 1 andi s3, 0x7F sll t1, 16 or t0, t1 sll t3, 16 or t2, t3 sw t0, 0x40(a3) sw t2, 0x44(a3) j loc_7847C sb v1, 0x37(a3) loc_7841C: lw t4, 0x40(a3) lw t6, 0x44(a3) srl t5, t4, 16 andi t4, 0xFFFF srl t7, t6, 16 andi t6, 0xFFFF slt at, t0, t4 beqz at, loc_78444 slt at, t5, t1 move t4, t0 loc_78444 : beqz at, loc_78450 slt at, t2, t6 move t5, t1 loc_78450 : beqz at, loc_7845C slt at, t7, t3 move t6, t2 loc_7845C : beqz at, loc_78468 sll t5, 16 move t7, t3 loc_78468 : or t4, t5 sll t7, 16 or t6, t7 sw t4, 0x40(a3) sw t6, 0x44(a3) loc_7847C : addi v0, -1 bgtz v0, loc_78114 addi s7, 0x1E j loc_77F18 nop loc_78490 : addiu t0, gp, draw_rooms - GP_ADDR li s4, 0x1F8000FC addiu v0, s5, -1 move s5, zero loc_784A4 : lh a1, 0(s4) addi s4, 2 sh a1, 0(t0) addiu t0, 2 addiu s5, 1 bgtz v0, loc_784A4 addi v0, -1 sw s5, number_draw_rooms - GP_ADDR(gp) sw fp, outside - GP_ADDR(gp) lui a0, 0x1F80 lw s0, 0xD8(a0) lw s1, 0xDC(a0) lw s2, 0xE0(a0) lw s3, 0xE4(a0) lw s4, 0xE8(a0) lw s5, 0xEC(a0) lw s6, 0xF0(a0) lw s7, 0xF4(a0) jr ra lw fp, 0xF8(a0) #endif UNIMPLEMENTED(); } void phd_GetVectorAngles(long dx, long dy, long dz, short* angles)//77928 { int t0, t1, t2; t0 = dx; t1 = dy; t2 = dz; angles[0] = phd_atan_asm(dz, dx); goto loc_7795C; loc_77950: t0 >>= 2; t1 >>= 2; t2 >>= 2; loc_7795C: if (((t0 << 16) >> 16) != t0) { goto loc_77950; } if (((t1 << 16) >> 16) != t1) { goto loc_77950; } if (((t2 << 16) >> 16) != t2) { goto loc_77950; } IR1 = t0; IR2 = t2; docop2(0xA00428); int v0 = phd_atan_asm(mSqrt(MAC1 + MAC2), t1); if (t1 > 0 && (v0 << 16) > 0 || t1 < 0 && (v0 << 16) < 0) { v0 = -v0; } angles[1] = v0; } void phd_LookAt(long xsrc, long ysrc, long zsrc, long xtar, long ytar, long ztar, long roll) { short temp; CamPos.x = xsrc; CamPos.y = ysrc; CamPos.z = zsrc; viewer.x_pos = xsrc; viewer.y_pos = ysrc; viewer.z_pos = zsrc; viewer.z_rot = roll; phd_GetVectorAngles(xtar - xsrc, ytar - ysrc, ztar - zsrc, &viewer.x_rot); temp = viewer.y_rot; viewer.y_rot = viewer.x_rot; viewer.x_rot = temp; phd_GenerateW2V(&viewer); } void phd_GenerateW2V(struct PHD_3DPOS* view) { int t0, t1, t2, t3, t4, t5, t6, v0, v1, a0, a1, a2, a3, at; a2 = view->x_rot; v1 = view->y_rot; t0 = SIN(a2); t2 = SIN(v1); a1 = view->z_rot; t4 = (t0 * t2) >> 12; t3 = COS(v1); t1 = SIN(a1); t5 = t4 * t1; phd_mxptr = &matrix_stack[0]; v1 = t0 * t3; v0 = COS(a2); t0 = -t0; matrix_stack[9] = t0; w2v_matrix[9] = t0; t6 = v0 * t1; a1 = COS(a1); v1 >>= 12; t6 >>= 12; matrix_stack[1] = t6; w2v_matrix[1] = t6; t6 = (v1 * t1) >> 12; a3 = (t2 * a1) >> 12; t6 -= a3; matrix_stack[2] = t6; w2v_matrix[2] = t6; t6 = t4 * a1; a3 = view->x_pos; t4 = view->y_pos; a0 = view->z_pos; matrix_stack[3] = a3; w2v_matrix[3] = a3; matrix_stack[7] = t4; w2v_matrix[7] = t4; a3 = t3 * t1; matrix_stack[11] = a0; w2v_matrix[11] = a0; t4 = (v0 * a1) >> 14; t0 = (v0 * a1) >> 12; w2v_matrix[5] = t0; a2 = (v0 * t2) >> 12; t0 -= t4; matrix_stack[8] = a2; w2v_matrix[8] = a2; matrix_stack[5] = t0; a2 = (v0 * t3) >> 12; t6 >>= 12; matrix_stack[10] = a2; w2v_matrix[10] = a2; t0 = v1 * a1; a3 >>= 12; t6 -= a3; a2 = t2 * t1; w2v_matrix[4] = t6; at = t6 >> 2; t6 -= at; matrix_stack[4] = t6; t0 >>= 12; v0 = a2 >> 12; t0 += v0; w2v_matrix[6] = t0; at = t0 >> 2; t0 -= at; matrix_stack[6] = t0; v0 = t5 >> 12; v1 = (t3 * a1) >> 12; v0 += v1; matrix_stack[0] = v0; w2v_matrix[0] = v0; } long phd_atan_asm(long x, long y)// (F) { int a2, a3, v0; if (x == 0 && y == 0) { return 0; } a2 = 0; if (x < 0) { a2 = 4; x = -x; } //loc_77A64 if (y < 0) { a2 += 2; y = -y; } v0 = x; if (x < y) { a2 += 1; x = y; y = v0; } else { //loc_77A90 goto loc_77A98; } loc_77A90: y >>= 1; x >>= 1; loc_77A98: v0 = (y << 16) >> 16; if (v0 != y) { goto loc_77A90; }//loc_77A90 v0 = y << 11; a3 = (v0 / x); v0 = atanOctantTab[a2]; x = atanTab[a3]; v0 = x + v0; if (v0 < 0) { v0 = -v0; } return v0; } void mRotBoundingBoxNoPersp(short* bounds, short* tbounds) { UNIMPLEMENTED(); } Update MATHS.C Correct mRotX mRotY mRotZ SetRotation #include "MATHS.H" #include "LOAD_LEV.H" #include "SPECIFIC.H" #include <INLINE_C.H> #include "3D_GEN.H" #include "CAMERA.H" #include "DRAW.H" #include "GPU.H" #include "GTEREG.H" #include "DRAWSPKS.H" void mQuickW2VMatrix()//77AEC(<), 79B30(<) { MatrixSP = 0; Matrix = &MatrixStack[0]; ((int*)&MatrixStack)[0] = ((unsigned short*)phd_mxptr)[0] | ((unsigned short*)phd_mxptr)[2] << 16; ((int*)&MatrixStack)[1] = ((unsigned short*)phd_mxptr)[4] | ((unsigned short*)phd_mxptr)[8] << 16; ((int*)&MatrixStack)[2] = ((unsigned short*)phd_mxptr)[10] | ((unsigned short*)phd_mxptr)[12] << 16; ((int*)&MatrixStack)[3] = ((unsigned short*)phd_mxptr)[16] | ((unsigned short*)phd_mxptr)[18] << 16; R12 = ((short*)phd_mxptr)[2] << 16; R11 = ((short*)phd_mxptr)[0]; R21 = ((short*)phd_mxptr)[8] << 16; R13 = ((short*)phd_mxptr)[4]; R23 = ((short*)phd_mxptr)[12] << 16; R22 = ((short*)phd_mxptr)[10]; R32 = ((short*)phd_mxptr)[18] << 16; R31 = ((short*)phd_mxptr)[16]; ((short*)&MatrixStack)[8] = ((unsigned short*)phd_mxptr)[20]; ((short*)&MatrixStack)[10] = ((unsigned short*)phd_mxptr)[6]; ((short*)&MatrixStack)[12] = ((unsigned short*)phd_mxptr)[14]; ((short*)&MatrixStack)[14] = ((unsigned short*)phd_mxptr)[22]; R33 = ((unsigned short*)phd_mxptr)[20]; TRX = ((unsigned short*)phd_mxptr)[6]; TRY = ((unsigned short*)phd_mxptr)[14]; TRZ = ((unsigned short*)phd_mxptr)[22]; CamGTE.m00 = ((unsigned short*)&w2v_matrix)[0]; CamGTE.m01 = ((unsigned short*)&w2v_matrix)[2]; CamGTE.m02 = ((unsigned short*)&w2v_matrix)[4]; CamGTE.m10 = ((unsigned short*)&w2v_matrix)[8]; CamGTE.m11 = ((unsigned short*)&w2v_matrix)[10]; CamGTE.m12 = ((unsigned short*)&w2v_matrix)[12]; CamGTE.m20 = ((unsigned short*)&w2v_matrix)[16]; CamGTE.m21 = ((unsigned short*)&w2v_matrix)[18]; CamGTE.m22 = ((unsigned short*)&w2v_matrix)[20]; } void gte_sttr(struct PHD_VECTOR* vec)//To investigate, this should not be in this file. { vec->x = Matrix->tx >> 12; vec->y = Matrix->ty >> 12; vec->z = Matrix->tz >> 12; } long mGetAngle(long x, long z, long tx, long tz)//77678(<), 796BC(<) (F) { long dx = tx - x; long dz = tz - z; short table_index = 0; long result_angle = 0; long temp = 0; if ((dx | dz) != 0) { if (dx < 0) { table_index |= 0x10;//FIXME: += (4); dx = -dx; } //0x796E0 if (dz < 0) { table_index += 2; dz = -dz; } //796F0 if (dx < dz) { table_index += 1; temp = dx; dx = dz; dz = temp; } //7970C while (dz / 65536 != 0) { dx /= 2; dz /= 2; } //79724 result_angle = atanTab[dz * 2048 / dx]; result_angle += atanOctantTab[table_index]; if (result_angle < 0) { result_angle = -result_angle; }//79760 }//79760 return -result_angle & 0xFFFF; } long mSqrt(long value)//83B30(<), 85B74(<) (F) { long v0 = 0x1F; long v1 = gte_ldlzc(value); if (value != 0) { v1 &= 0xFFFFFFFE; v0 = v0 - v1 >> 1; long at = v1 - 0x18; if (v1 - 0x18 < 0) { //loc_85BA8 value >>= 0x18 - v1; } else { value <<= v1 - 0x18; } //loc_85BB4 value = SqrtTable[value - 0x40] << v0; }//locret_85BD0 return (value >> 12); } long phd_sqrt_asm(long value)//83B30(<), 85B74(<) (F) { long v0 = 0x1F; long v1 = gte_ldlzc(value); if (value != 0) { v1 &= 0xFFFFFFFE; v0 = v0 - v1 >> 1; long at = v1 - 0x18; if (v1 - 0x18 < 0) { //loc_85BA8 value >>= 0x18 - v1; } else { value <<= v1 - 0x18; } //loc_85BB4 value = SqrtTable[value - 0x40] << v0; }//locret_85BD0 return (value >> 12); } void ScaleCurrentMatrix(long bStoreInMatrix, long sx, long sy, long sz) { int t2, v0, v1; unsigned int t0, t1, at; t0 = R11; t1 = R13; t2 = R22; v0 = R31; v1 = R33; R12 = ((((t0 << 16) >> 16) * sx) >> 12) & 0xFFFF; R11 = ((((t0 >> 16) * sy) >> 12) << 16); R21 = ((((t1 << 16) >> 16) * sz) >> 12) & 0xFFFF; R13 = (((t1 >> 16) * sx) >> 12) << 16; R23 = ((((t2 << 16) >> 16) * sy) >> 12) & 0xFFFF; R22 = (((t2 >> 16) * sz) >> 12) << 16; R32 = ((((v0 << 16) >> 16) * sx) >> 12) & 0xFFFF; R31 = (((v0 >> 16) * sy) >> 12) << 16; R33 = ((((v1 << 16) >> 16) * sz) >> 12); if (bStoreInMatrix) { Matrix->m00 = R11; Matrix->m01 = R12; Matrix->m02 = R13; Matrix->m10 = R21; Matrix->m11 = R22; Matrix->m12 = R23; Matrix->m20 = R31; Matrix->m21 = R32; Matrix->m22 = R33; }//locret_77E68 } void mPushMatrix()//764D0(<), 78514(<) (F) { ++Matrix; Matrix->m00 = R11; Matrix->m01 = R12; Matrix->m02 = R13; Matrix->m10 = R21; Matrix->m11 = R22; Matrix->m12 = R23; Matrix->m20 = R31; Matrix->m21 = R32; Matrix->m22 = R33; Matrix->tx = TRX; Matrix->ty = TRY; Matrix->tz = TRZ; } void mPopMatrix()//76520(<), 78564(<) (F) { mLoadMatrix(--Matrix); } void mUnitMatrix() { UNIMPLEMENTED(); } void mPushUnitMatrix()//76534(<), 78578(<) { setrot(++Matrix, 0x1000, 0, 0x1000, 0, 0x1000); } void mTranslate()//76558(<) (!) { UNIMPLEMENTED(); } void mTranslateAbsXYZ(long x, long y, long z) { mTranslateXYZ(x - MatrixStack[0].tx, y - MatrixStack[0].ty, z - MatrixStack[0].tz); } void mTranslateXYZ(long x, long y, long z)//7658C(<), 785D0(<) (!) { int t0; int t1; int t2; int t3; int t4; int t5; t4 = y >> 15; if (y < 0) { y = -y; t4 = y >> 15; y &= 0x7FFF; t4 = -t4; y = -y; }//loc_765AC else { y &= 0x7FFF; } //loc_765B0 : t5 = z >> 15; if (z < 0) { z = -z; t5 = z >> 15; z &= 0x7FFF; t5 = -t5; z = -z; } else { //loc_765D0 z &= 0x7FFF; } //loc_765D4 t3 = x >> 15; if (x < 0) { x = -x; t3 = x >> 15; x &= 0x7FFF; t3 = -t3; x = -x; } else { x &= 0x7FFF; } IR1 = t3; IR2 = t4; IR3 = t5; docop2(0x41E012); t3 = MAC1; t4 = MAC2; t5 = MAC3; IR1 = x; IR2 = y; IR3 = z; docop2(0x498012); t0 = t3 << 3; if (t3 < 0) { t3 = -t3; t3 <<= 3; t0 = -t3; } //loc_7663C t1 = t4 << 3; if (t4 < 0) { t4 = -t4; t4 <<= 3; t1 = -t4; } //loc_76650 t2 = t5 << 3; if (t5 < 0) { t5 = -t5; t5 <<= 3; t2 = -t5; }//loc_76664 t3 = MAC1; t4 = MAC2; t5 = MAC3; t0 += t3; t1 += t4; t2 += t5; TRX = t0; TRY = t1; TRZ = t2; Matrix->tx = t0; Matrix->ty = t1; Matrix->tz = t2; } void mRotX(long rx)//7669C (F) { int t0; int t1; int t2; int t3; int t4; int t5; int t6; rx = (rx >> 2) & 0x3FFC; if (rx != 0) { //loc_766B4 t5 = (rcossin_tbl[rx >> 1] & 0xFFFF) | ((rcossin_tbl[rx >> 1 | 1] & 0xFFFF ) << 16); VX0 = (0xFFFF0000 & t5) & 0xFFFF; VY0 = ((0xFFFF0000 & t5) >> 16) & 0xFFFF; VZ0 = t5 & 0xFFFF; t0 = ((R12 << 16) | (R11 & 0xFFFF)) & 0xFFFF; t1 = ((R21 << 16) | (R13 & 0xFFFF)) & 0xFFFF0000; t3 = ((R32 << 16) | (R31 & 0xFFFF)) & 0xFFFF; docop2(0x486012); t6 = t5 >> 16; t5 <<= 16; t5 = -t5; VX1 = t5; VY1 = (t5 >> 16) & 0xFFFF; VZ1 = t6; t4 = MAC1; t2 = MAC2 & 0xFFFF; t5 = MAC3; docop2(0x48E012); t0 |= t4 << 16; t3 |= t5 << 16; t5 = MAC1 & 0xFFFF; t6 = MAC2; t4 = MAC3; t1 |= t5; t2 |= t6 << 16; SetRotation(t0, t1, t2, t3, t4); } } void mRotY(long ry)//76744 (F) { int t0; int t1; int t2; int t3; int t4; int t5; int t6; int t7; ry = (ry >> 2) & 0x3FFC; if (ry != 0) { t5 = (rcossin_tbl[ry >> 1] & 0xFFFF) | ((rcossin_tbl[ry >> 1 | 1] & 0xFFFF) << 16); t6 = t5 >> 16; t5 &= 0xFFFF; t2 = -t5; VX0 = t6; VY0 = (t5 >> 16) & 0xFFFF; VZ0 = t2; t0 = ((R12 << 16) | (R11 & 0xFFFF)) & 0xFFFF0000; t2 = ((R23 << 16) | (R22 & 0xFFFF)) & 0xFFFF; t3 = ((R32 << 16) | (R31 & 0xFFFF)) & 0xFFFF0000; docop2(0x486012); VX1 = t5; VY1 = (t5 >> 16) & 0xFFFF; VZ1 = t6; t4 = MAC1 & 0xFFFF; t1 = MAC2; t5 = MAC3 & 0xFFFF; docop2(0x48E012); t0 |= t4; t3 |= t5; t5 = MAC1 & 0xFFFF; t6 = MAC2; t4 = MAC3; t1 = (t1 << 16) | (t5); t2 |= t6 << 16; SetRotation(t0, t1, t2, t3, t4); } } void mRotYXZ(short y, short x, short z)//767E8 (F) { mRotY(y); mRotX(x); mRotZ(z); } void mRotZ(long rz)//76804 (F) { int t0; int t1; int t2; int t3; int t4; int t5; int t6; int t7; int a0; rz = (rz >> 2) & 0x3FFC; if (rz != 0) { //loc_7681C t0 = (rcossin_tbl[rz >> 1] & 0xFFFF) | ((rcossin_tbl[rz >> 1 | 1] & 0xFFFF) << 16); t1 = ((t0 >> 16) & 0xFFFF) | (t0 << 16); VX0 = (t1 & 0xFFFF); VY0 = ((t1 >> 16) & 0xFFFF); VZ0 = 0; t1 = ((R21 << 16) | (R13 & 0xFFFF)) & 0xFFFF; t2 = ((R23 << 16) | (R22 & 0xFFFF)) & 0xFFFF0000; t4 = R33; docop2(0x486012); t3 = t0 & 0xFFFF0000; t0 &= 0xFFFF; t0 = -t0; t0 &= 0xFFFF; t0 |= t3; VX1 = t0; VY1 = (t0 >> 16) & 0xFFFF; VZ1 = 0; t0 = MAC1 & 0xFFFF; t5 = MAC2; t3 = MAC3 & 0xFFFF; docop2(0x48E012); t5 <<= 16; t1 |= t5; t5 = MAC1; t6 = MAC2 & 0xFFFF; a0 = MAC3; t0 |= t5 << 16; t2 |= t6; t3 |= a0 << 16; SetRotation(t0, t1, t2, t3, t4); } } void mRotSuperPackedYXZ(short** a0, long a1)//768BC { unsigned short* a2; int v0; int at; a2 = (unsigned short*)a0[0]; if (a1 != 0) { //loc_768C4 do { v0 = *a2++; a1--; if (!(v0 & 0xC000)) { a2++; }//loc_768DC } while (a1 == 0); }//loc_768E8 v0 = *a2++; at = (v0 >> 14); at--; if (at != 0) { a0[0] = (short*)a2; if (at != 0) { mRotZ((v0 & 0xFFF) << 4); }//loc_76914 mRotY((v0 & 0xFFF) << 4); mRotX((v0 & 0xFFF) << 4); }//loc_76928 at = *a2++; a0[0] = (short*)a2; mRotY((((v0 << 16) | at) >> 4) & 0xFFC0); mRotX((((v0 << 16) | at) >> 14) & 0xFFC0); mRotZ((((v0 << 16) | at) & 0x3FF) << 6); } void mRotPackedYXZ(long yxz)//7693C (F) { UNIMPLEMENTED(); } void SetRotation(int t0, int t1, int t2, int t3, int t4)//7696C(<) (F) { R11 = (t0 & 0xFFFF); R12 = (t0 >> 16) & 0xFFFF; R13 = (t1 & 0xFFFF); R21 = (t1 >> 16) & 0xFFFF; R22 = (t2 & 0xFFFF); R23 = (t2 >> 16) & 0xFFFF; R31 = (t3 & 0xFFFF); R32 = (t3 >> 16) & 0xFFFF; R33 = t4; ((int*)&Matrix->m00)[0] = t0; ((int*)&Matrix->m02)[0] = t1; ((int*)&Matrix->m11)[0] = t2; ((int*)&Matrix->m20)[0] = t3; ((int*)&Matrix->m22)[0] = t4; } void setrot(struct MATRIX3D* m, long t0, long t1, long t2, long t3, long t4)//76970 TOCHECK { R11 = t0 >> 16; R12 = t0; R13 = t1 >> 16; R21 = t1; R22 = t2 >> 16; R23 = t2; R31 = t3 >> 16; R32 = t3; R33 = t4; ((int*)Matrix)[0] = t0; ((int*)Matrix)[1] = t1; ((int*)Matrix)[2] = t2; ((int*)Matrix)[3] = t3; ((int*)Matrix)[4] = t4; } void mLoadMatrix(struct MATRIX3D* m)//7699C(<), 789E0(<) TOCHECK { R11 = m->m00; R12 = m->m01; R13 = m->m02; R21 = m->m10; R22 = m->m11; R23 = m->m12; R31 = m->m20; R32 = m->m21; R33 = m->m22; TRX = m->tx; TRY = m->ty; TRZ = m->tz; return; } //Note: Original code is less optimal than this implementation. void mCopyMatrix(struct MATRIX3D* m)//769E4(<), 78A28(<) (F) TOCHECK { UNIMPLEMENTED(); } void ASM_GetBounds()//76A28 { UNIMPLEMENTED(); } void GetBounds()//76A28 { UNIMPLEMENTED(); } void mSetTrans(long x, long y, long z)//76AF4(<), 78B38(<) { TRX = x; TRY = y; TRZ = z; Matrix->tx = x; Matrix->ty = y; Matrix->tz = z; } void mClipBoundingBox(short* bounds)//76B14 { UNIMPLEMENTED(); } void InitInterpolation(long frac, long rate, struct MATRIX3D* m)//76CB4 { UNIMPLEMENTED(); } void iPushMatrix0()//76D3C(<), ?(<) (F) { UNIMPLEMENTED(); } void iPushMatrix(struct MATRIX3D* m)//81E60(<), ?(<) (F) { UNIMPLEMENTED(); } void iPopMatrix0() { UNIMPLEMENTED(); } void iPopMatrix(struct MATRIX3D* m, struct MATRIX3D* m2)//76D8C(<), ?(<) TOCHECK { UNIMPLEMENTED(); } void mPushMatrix0()//764D0 (F) { UNIMPLEMENTED(); } void mmPushMatrix(struct MATRIX3D* m)//81BBC(<) (F) { UNIMPLEMENTED(); } void SetRoomBounds(tr_room_portal* portal, int room_number, struct room_info* parent) { UNIMPLEMENTED(); } void GetRoomBoundsAsm(short room_number)//77E70(<), 79EB4(<) ///@TODO check if in right file { #if 0 GetRoomBoundsAsm: lui a1, 0x1F80 sw s0, 0xD8(a1) sw s1, 0xDC(a1) sw s2, 0xE0(a1) sw s3, 0xE4(a1) sw s4, 0xE8(a1) sw s5, 0xEC(a1) sw s6, 0xF0(a1) sw s7, 0xF4(a1) sw fp, 0xF8(a1) move s0, a1 lw s1, room - GP_ADDR(gp) move s2, zero li s3, 1 li s4, 0x1F8000FC move s5, zero lw fp, outside - GP_ADDR(gp) sb a0, 0(s0) sll a0, 4 sll at, a0, 2 add a0, at add a0, s1 lui t0, 0x1FF lui t1, 0xEF li t2, 2 sw t0, 0x40(a0) sw t1, 0x44(a0) sb t2, 0x37(a0) addiu t6, gp, CamPos - GP_ADDR cfc2 t1, r5 cfc2 t2, r6 cfc2 t3, r7 sw t1, 0xB0(s0) sw t2, 0xB4(s0) sw t3, 0xB8(s0) lw t1, 0(t6) lw t2, 4(t6) lw t3, 8(t6) sw t1, 0xBC(s0) sw t2, 0xC0(s0) sw t3, 0xC4(s0) loc_77F18: beq s2, s3, loc_78490 add t0, s0, s2 lbu s6, 0(t0) addi s2, 1 andi s2, 0x7F sll a0, s6, 4 sll at, a0, 2 add a0, at add a0, s1 lb v0, 0x37(a0) lw t1, 0x38(a0) addi v0, -2 lw t3, 0x3C(a0) lw t5, 0x40(a0) lw t7, 0x44(a0) srl t2, t1, 16 andi t1, 0xFFFF srl t4, t3, 16 andi t3, 0xFFFF srl t6, t5, 16 andi t5, 0xFFFF srl t8, t7, 16 andi t7, 0xFFFF slt at, t5, t1 beqz at, loc_77F84 slt at, t6, t2 move t1, t5 loc_77F84 : bnez at, loc_77F90 slt at, t7, t3 move t2, t6 loc_77F90 : beqz at, loc_77F9C slt at, t8, t4 move t3, t7 loc_77F9C : bnez at, loc_77FA8 sll t6, t2, 16 move t4, t8 loc_77FA8 : or t5, t1, t6 sll t6, t4, 16 or t6, t3 sw t5, 0x38(a0) sw t6, 0x3C(a0) andi at, v0, 1 bnez at, loc_77FD4 ori v0, 1 sh s6, 0(s4) addi s4, 2 addi s5, 1 loc_77FD4: lh s6, 0x4E(a0) sb v0, 0x37(a0) andi s6, 8 or fp, s6 lw s7, 4(a0) lw t0, 0x14(a0) beqz s7, loc_77F18 lw t1, 0x18(a0) lw t2, 0x1C(a0) bgez t0, loc_78018 sra t3, t0, 15 negu t0, t0 sra t3, t0, 15 andi t0, 0x7FFF negu t3, t3 j loc_7801C negu t0, t0 loc_78018 : andi t0, 0x7FFF loc_7801C : bgez t1, loc_7803C sra t4, t1, 15 negu t1, t1 sra t4, t1, 15 andi t1, 0x7FFF negu t4, t4 j loc_78040 negu t1, t1 loc_7803C : andi t1, 0x7FFF loc_78040 : bgez t2, loc_78060 sra t5, t2, 15 negu t2, t2 sra t5, t2, 15 andi t2, 0x7FFF negu t5, t5 j loc_78064 negu t2, t2 loc_78060 : andi t2, 0x7FFF loc_78064 : mtc2 t3, r9 mtc2 t4, r10 mtc2 t5, r11 nop nop cop2 0x41E012 lw t3, 0xB0(s0) lw t4, 0xB4(s0) lw t5, 0xB8(s0) ctc2 t3, r5 ctc2 t4, r6 ctc2 t5, r7 mfc2 t3, r25 mfc2 t4, r26 mtc2 t0, r9 mtc2 t1, r10 mtc2 t2, r11 mfc2 t5, r27 nop nop cop2 0x498012 bgez t3, loc_780C0 sll t0, t3, 3 negu t3, t3 sll t3, 3 negu t0, t3 loc_780C0 : bgez t4, loc_780D4 sll t1, t4, 3 negu t4, t4 sll t4, 3 negu t1, t4 loc_780D4 : bgez t5, loc_780E8 sll t2, t5, 3 negu t5, t5 sll t5, 3 negu t2, t5 loc_780E8 : mfc2 t3, r25 mfc2 t4, r26 mfc2 t5, r27 addu t0, t3 addu t1, t4 addu t2, t5 ctc2 t0, r5 ctc2 t1, r6 ctc2 t2, r7 lh v0, 0(s7) addi s7, 2 loc_78114: lh a1, 0(s7) addi s7, 2 lh t0, 0(s7) lw t1, 0x14(a0) beqz t0, loc_7814C lh t2, 6(s7) lw t3, 0xBC(s0) add t1, t2 sub t1, t3 beqz t1, loc_7847C xor t0, t1 bltz t0, loc_781A8 move a2, s7 j loc_7847C loc_7814C : lh t0, 2(s7) lw t1, 0x18(a0) beqz t0, loc_7817C lh t2, 8(s7) lw t3, 0xC0(s0) add t1, t2 sub t1, t3 beqz t1, loc_7847C xor t0, t1 bltz t0, loc_781A8 move a2, s7 j loc_7847C loc_7817C : lh t0, 4(s7) lw t1, 0x1C(a0) beqz t0, loc_7847C lh t2, 0xA(s7) lw t3, 0xC4(s0) add t1, t2 sub t1, t3 beqz t1, loc_7847C xor t0, t1 bgez t0, loc_7847C move a2, s7 loc_781A8 : sll a3, a1, 4 sll at, a3, 2 add a3, at add a3, s1 lw t0, 0x38(a3) lw t2, 0x40(a0) lw t4, 0x3C(a3) lw t6, 0x44(a0) srl t1, t0, 16 andi t0, 0xFFFF srl t3, t2, 16 andi t2, 0xFFFF srl t5, t4, 16 andi t4, 0xFFFF srl t7, t6, 16 andi t6, 0xFFFF slt at, t0, t2 beqz at, loc_78208 slt at, t1, t3 bnez at, loc_78208 slt at, t4, t6 beqz at, loc_78208 slt at, t5, t7 beqz at, loc_7847C loc_78208 : move t0, t3 move t1, t2 move t2, t7 move t3, t6 addi t4, s0, 0x80 move t5, zero move t6, zero li v1, 3 loc_78228: lhu t7, 6(a2) lhu t9, 8(a2) lhu t8, 0xA(a2) sll t9, 16 or t7, t9 mtc2 t7, r0 mtc2 t8, r1 addi a2, 6 nop nop cop2 0x480012 mfc2 t7, r9 mfc2 t8, r10 mfc2 t9, r11 cop2 0x180001 sw t7, 0(t4) sw t8, 4(t4) sw t9, 8(t4) bgtz t9, loc_78278 addi t4, 0xC j loc_782C8 addi t5, 1 loc_78278: slti at, t9, 0x5000 mfc2 t7, r14 bnez at, loc_7828C sra t8, t7, 16 addi t6, 1 loc_7828C : sll t7, 16 sra t7, 16 slt at, t7, t0 beqz at, loc_782A4 slt at, t7, t1 move t0, t7 loc_782A4 : bnez at, loc_782B0 slt at, t8, t2 move t1, t7 loc_782B0 : beqz at, loc_782BC slt at, t8, t3 move t2, t8 loc_782BC : bnez at, loc_782C8 nop move t3, t8 loc_782C8 : bnez v1, loc_78228 addi v1, -1 li at, 4 beq t5, at, loc_7847C addi t4, s0, 0x80 beq t6, at, loc_7847C li v1, 3 beqz t5, loc_78384 addi t5, t4, 0x24 loc_782EC: lw t6, 8(t4) lw t7, 8(t5) slti t8, t6, 1 slti t9, t7, 1 xor t8, t9 beqz t8, loc_78374 lw t6, 0(t4) lw t7, 0(t5) slt t8, t6, zero slt t9, t7, zero and t8, t9 beqz t8, loc_78328 slt t8, zero, t6 j loc_7833C move t0, zero loc_78328 : slt t9, zero, t7 and t8, t9 bnez t8, loc_7833C li t1, 0x1FF move t0, zero loc_7833C : lw t6, 4(t4) lw t7, 4(t5) slt t8, t6, zero slt t9, t7, zero and t8, t9 beqz t8, loc_78360 slt t8, zero, t6 j loc_78374 move t2, zero loc_78360 : slt t9, zero, t7 and t8, t9 bnez t8, loc_78374 li t3, 0xEF move t2, zero loc_78374 : move t5, t4 addi t4, 0xC bnez v1, loc_782EC addi v1, -1 loc_78384 : lw t4, 0x40(a0) lw t6, 0x44(a0) srl t5, t4, 16 andi t4, 0xFFFF srl t7, t6, 16 andi t6, 0xFFFF slt at, t0, t4 beqz at, loc_783AC slt at, t5, t1 move t0, t4 loc_783AC : beqz at, loc_783B8 slt at, t2, t6 move t1, t5 loc_783B8 : beqz at, loc_783C4 slt at, t7, t3 move t2, t6 loc_783C4 : beqz at, loc_783D0 sub at, t0, t1 move t3, t7 loc_783D0 : bgez at, loc_7847C sub at, t2, t3 bgez at, loc_7847C lb v1, 0x37(a3) add t4, s0, s3 andi at, v1, 2 bnez at, loc_7841C ori v1, 2 sb a1, 0(t4) addi s3, 1 andi s3, 0x7F sll t1, 16 or t0, t1 sll t3, 16 or t2, t3 sw t0, 0x40(a3) sw t2, 0x44(a3) j loc_7847C sb v1, 0x37(a3) loc_7841C: lw t4, 0x40(a3) lw t6, 0x44(a3) srl t5, t4, 16 andi t4, 0xFFFF srl t7, t6, 16 andi t6, 0xFFFF slt at, t0, t4 beqz at, loc_78444 slt at, t5, t1 move t4, t0 loc_78444 : beqz at, loc_78450 slt at, t2, t6 move t5, t1 loc_78450 : beqz at, loc_7845C slt at, t7, t3 move t6, t2 loc_7845C : beqz at, loc_78468 sll t5, 16 move t7, t3 loc_78468 : or t4, t5 sll t7, 16 or t6, t7 sw t4, 0x40(a3) sw t6, 0x44(a3) loc_7847C : addi v0, -1 bgtz v0, loc_78114 addi s7, 0x1E j loc_77F18 nop loc_78490 : addiu t0, gp, draw_rooms - GP_ADDR li s4, 0x1F8000FC addiu v0, s5, -1 move s5, zero loc_784A4 : lh a1, 0(s4) addi s4, 2 sh a1, 0(t0) addiu t0, 2 addiu s5, 1 bgtz v0, loc_784A4 addi v0, -1 sw s5, number_draw_rooms - GP_ADDR(gp) sw fp, outside - GP_ADDR(gp) lui a0, 0x1F80 lw s0, 0xD8(a0) lw s1, 0xDC(a0) lw s2, 0xE0(a0) lw s3, 0xE4(a0) lw s4, 0xE8(a0) lw s5, 0xEC(a0) lw s6, 0xF0(a0) lw s7, 0xF4(a0) jr ra lw fp, 0xF8(a0) #endif UNIMPLEMENTED(); } void phd_GetVectorAngles(long dx, long dy, long dz, short* angles)//77928 { int t0, t1, t2; t0 = dx; t1 = dy; t2 = dz; angles[0] = phd_atan_asm(dz, dx); goto loc_7795C; loc_77950: t0 >>= 2; t1 >>= 2; t2 >>= 2; loc_7795C: if (((t0 << 16) >> 16) != t0) { goto loc_77950; } if (((t1 << 16) >> 16) != t1) { goto loc_77950; } if (((t2 << 16) >> 16) != t2) { goto loc_77950; } IR1 = t0; IR2 = t2; docop2(0xA00428); int v0 = phd_atan_asm(mSqrt(MAC1 + MAC2), t1); if (t1 > 0 && (v0 << 16) > 0 || t1 < 0 && (v0 << 16) < 0) { v0 = -v0; } angles[1] = v0; } void phd_LookAt(long xsrc, long ysrc, long zsrc, long xtar, long ytar, long ztar, long roll) { short temp; CamPos.x = xsrc; CamPos.y = ysrc; CamPos.z = zsrc; viewer.x_pos = xsrc; viewer.y_pos = ysrc; viewer.z_pos = zsrc; viewer.z_rot = roll; phd_GetVectorAngles(xtar - xsrc, ytar - ysrc, ztar - zsrc, &viewer.x_rot); temp = viewer.y_rot; viewer.y_rot = viewer.x_rot; viewer.x_rot = temp; phd_GenerateW2V(&viewer); } void phd_GenerateW2V(struct PHD_3DPOS* view) { int t0, t1, t2, t3, t4, t5, t6, v0, v1, a0, a1, a2, a3, at; a2 = view->x_rot; v1 = view->y_rot; t0 = SIN(a2); t2 = SIN(v1); a1 = view->z_rot; t4 = (t0 * t2) >> 12; t3 = COS(v1); t1 = SIN(a1); t5 = t4 * t1; phd_mxptr = &matrix_stack[0]; v1 = t0 * t3; v0 = COS(a2); t0 = -t0; matrix_stack[9] = t0; w2v_matrix[9] = t0; t6 = v0 * t1; a1 = COS(a1); v1 >>= 12; t6 >>= 12; matrix_stack[1] = t6; w2v_matrix[1] = t6; t6 = (v1 * t1) >> 12; a3 = (t2 * a1) >> 12; t6 -= a3; matrix_stack[2] = t6; w2v_matrix[2] = t6; t6 = t4 * a1; a3 = view->x_pos; t4 = view->y_pos; a0 = view->z_pos; matrix_stack[3] = a3; w2v_matrix[3] = a3; matrix_stack[7] = t4; w2v_matrix[7] = t4; a3 = t3 * t1; matrix_stack[11] = a0; w2v_matrix[11] = a0; t4 = (v0 * a1) >> 14; t0 = (v0 * a1) >> 12; w2v_matrix[5] = t0; a2 = (v0 * t2) >> 12; t0 -= t4; matrix_stack[8] = a2; w2v_matrix[8] = a2; matrix_stack[5] = t0; a2 = (v0 * t3) >> 12; t6 >>= 12; matrix_stack[10] = a2; w2v_matrix[10] = a2; t0 = v1 * a1; a3 >>= 12; t6 -= a3; a2 = t2 * t1; w2v_matrix[4] = t6; at = t6 >> 2; t6 -= at; matrix_stack[4] = t6; t0 >>= 12; v0 = a2 >> 12; t0 += v0; w2v_matrix[6] = t0; at = t0 >> 2; t0 -= at; matrix_stack[6] = t0; v0 = t5 >> 12; v1 = (t3 * a1) >> 12; v0 += v1; matrix_stack[0] = v0; w2v_matrix[0] = v0; } long phd_atan_asm(long x, long y)// (F) { int a2, a3, v0; if (x == 0 && y == 0) { return 0; } a2 = 0; if (x < 0) { a2 = 4; x = -x; } //loc_77A64 if (y < 0) { a2 += 2; y = -y; } v0 = x; if (x < y) { a2 += 1; x = y; y = v0; } else { //loc_77A90 goto loc_77A98; } loc_77A90: y >>= 1; x >>= 1; loc_77A98: v0 = (y << 16) >> 16; if (v0 != y) { goto loc_77A90; }//loc_77A90 v0 = y << 11; a3 = (v0 / x); v0 = atanOctantTab[a2]; x = atanTab[a3]; v0 = x + v0; if (v0 < 0) { v0 = -v0; } return v0; } void mRotBoundingBoxNoPersp(short* bounds, short* tbounds) { UNIMPLEMENTED(); }
/** * File name: CNewton.cpp * * Programmer: Yongqun He * Contact email: yohe@vt.edu * Purpose: This is the .cpp file for the class CNewton. * It is an important approach to solve the steady state solution problem * */ #include "copasi.h" #include "CNewton.h" #include "tnt/lu.h" //default constructor CNewton::CNewton() { mModel = NULL; mNewtonLimit = DefaultNewtonLimit; mSs_nfunction=0; mSs_solution = 0; mSs_x = NULL; mSs_xnew = NULL; // mSs_dxdt = NULL; mSs_h = NULL; mSs_ipvt = NULL; // initialize(); } // constructor CNewton::CNewton(C_INT32 anInt) { mModel = NULL; mNewtonLimit = anInt; mSs_nfunction = 0; mSs_solution = 0; //initialize(); } // copy constructor CNewton::CNewton(const CNewton& source) { mModel = source.mModel; mNewtonLimit = source.mNewtonLimit; mSs_nfunction = source.mSs_nfunction; mSs_solution = source.mSs_solution; mSs_x = source.mSs_x; mSs_xnew = source.mSs_xnew; mSs_dxdt =source.mSs_dxdt; mSs_h = source.mSs_h; mSs_jacob = source.mSs_jacob; mSs_ipvt = source.mSs_ipvt; } // initialize pointers void CNewton::initialize() { cleanup(); unsigned C_INT32 dim = mModel->getIndMetab(); mSs_xnew = new C_FLOAT64[dim]; // mSs_xnew = new C_FLOAT64[dim]; mSs_dxdt.newsize(dim); mSs_h = new C_FLOAT64[dim]; mSs_ipvt = new C_INT32[dim]; mSs_jacob.setModel(*mModel); } //Y.H. //set up mSs_x and mSs_x's default values //they should come from steady state class, though void CNewton::init_Ss_x(void) { mSs_x = mModel->getInitialNumbers(); } //Object assignment overloading CNewton& CNewton::operator=(const CNewton& source) { if(this != &source) { mModel = source.mModel; mNewtonLimit = source.mNewtonLimit; mSs_nfunction = source.mSs_nfunction; mSs_solution = source.mSs_solution; mSs_x = source.mSs_x; mSs_xnew = source.mSs_xnew; mSs_dxdt =source.mSs_dxdt; mSs_h = source.mSs_h; mSs_jacob = source.mSs_jacob; mSs_ipvt = source.mSs_ipvt; } return *this; } //destructor CNewton::~CNewton() { cout << "~CNewton " << endl; } //set mModel void CNewton::setModel(CModel * aModel) { mModel = aModel; initialize(); } //get mModel CModel * CNewton::getModel() const { return mModel; } // set mSSRes void CNewton::setSSRes(C_FLOAT64 aDouble) { mSSRes = aDouble; } //get mSSRes C_FLOAT64 CNewton::getSSRes() const { return mSSRes; } // get mSs_xnew C_FLOAT64 * CNewton::getSs_xnew() const { return mSs_xnew; } // get mSs_dxdt const TNT::Vector < C_FLOAT64 > & CNewton::getSs_dxdt() const { return mSs_dxdt; } // set mDerivFactor void CNewton::setDerivFactor(C_FLOAT64 aDouble) { mDerivFactor = aDouble; } // get mDerivFactor C_FLOAT64 CNewton::getDerivFactor() const { return mDerivFactor; } void CNewton::setNewtonLimit(C_INT32 limit) {mNewtonLimit = limit;} C_INT32 CNewton::getNewtonLimit() const {return mNewtonLimit;} // set mSs_nfunction void CNewton::setSs_nfunction(C_INT32 aInt) { mSs_nfunction = aInt; } // get mDerivFactor C_INT32 CNewton::getSs_nfunction() const { return mSs_nfunction; } // finds out if current state is a valid steady state C_INT32 CNewton::isSteadyState( void ) { unsigned C_INT32 i, dim = mModel->getIndMetab(); double maxrate; mSs_solution = SS_NOT_FOUND; for( i=0; i<dim; i++ ) if( mSs_x[i] < 0.0 ) return SS_NOT_FOUND; //FEval( 0, 0, mSs_x, ss_dxdt ); mModel->lSODAEval(dim, 0, mSs_xnew, &mSs_dxdt[0] ); mSs_nfunction++; // maxrate = SS_XNorn( ss_dxdt ); maxrate = xNorm(dim, &mSs_dxdt[0] - 1, 1); if( maxrate < mSSRes ) mSs_solution = SS_FOUND; return mSs_solution; } //similar to SS_Newton() in gepasi except a few modification // void CNewton::process(void) { int i,j,k; C_FLOAT64 maxrate, nmaxrate; C_INT32 info; mSs_solution = SS_NOT_FOUND; //by Yongqun He //get the dimensions of the matrix int dim = mModel->getIndMetab(); // try // { // mModel->lSODAEval(0, 0, mSs_x, mSs_dxdt ); //changed by Yongqun He mModel->lSODAEval(dim, 0, mSs_x, &mSs_dxdt[0] ); mSs_nfunction++; maxrate =xNorm(dim, &mSs_dxdt[0] - 1, 1); if( maxrate < mSSRes ) mSs_solution = SS_FOUND; if( mSs_solution == SS_FOUND ) { for( i=0; i<dim; i++ ) if( mSs_x[i] < 0.0 ) { mSs_solution = SS_NOT_FOUND; break; } } // } // finally // { //} if( mSs_solution==SS_FOUND ) return; for( k=0; k<mNewtonLimit; k++ ) { // try //{ //JEval( mSs_x, mSs_jacob ); mSs_jacob.jacobEval(mSs_x, mDerivFactor, mSSRes); /* :TODO: We have to check whether LU is really needed? */ TNT::Matrix < C_FLOAT64 > LU = mSs_jacob.getJacob(); TNT::Vector < unsigned C_INT32 > rowLU(dim); // LU decomposition of Jacobian info = TNT::LU_factor(LU, rowLU); // dgefa( mSs_jacob, dim, mSs_ipvt, &info); if( info!=0 ) { // jacobian is singular mSs_solution = SS_SINGULAR_JACOBIAN; return; } // solve mSs_jacob . x = mSs_h for x (result in mSs_dxdt) TNT::LU_solve(LU, rowLU, mSs_dxdt); // dgesl( mSs_jacob, mModel->getIndMetab(), mSs_ipvt, mSs_dxdt, 0 ); // } //finally //{ //} nmaxrate = maxrate * 1.001; // copy values of increment to mSs_h for(i=0;i<dim;i++) mSs_h[i] = mSs_dxdt[i]; for( i=0; (i<32) && (nmaxrate>maxrate) ; i++ ) { for( j=0; j<dim; j++ ) { mSs_xnew[j] = mSs_x[j] - mSs_h[j]; mSs_h[j] /= 2; } // this is done inside lSODAEval // mModel->setConcentrations(mSs_xnew); // update the dependent metabolites // try //{ //FEval( 0, 0, mSs_xnew, mSs_dxdt ); mModel->lSODAEval(dim, 0, mSs_xnew, &mSs_dxdt[0] ); mSs_nfunction++; nmaxrate = xNorm(dim, &mSs_dxdt[0] - 1, 1); //} //finally //{ //} } if( i==32 ) { if( maxrate < mSSRes ) { mSs_solution = SS_FOUND; // check if solution is valid for( i=0; i<mModel->getIntMetab(); i++ ) if( mSs_x[i] < 0.0 ) { mSs_solution = SS_NOT_FOUND; break; } return; } else { mSs_solution = SS_DAMPING_LIMIT; return; } } for(i=0;i<dim;i++) mSs_x[i] = mSs_xnew[i]; maxrate = nmaxrate; } if( maxrate < mSSRes ) { mSs_solution = SS_FOUND; // check if solution is valid for( i=0; i<dim; i++ ) if( mSs_x[i] < 0.0 ) { mSs_solution = SS_NOT_FOUND; break; } return; } else { mSs_solution = SS_ITERATION_LIMIT; return; } } // Clean up internal pointer variables void CNewton::cleanup(void) { if (mSs_x) delete [] mSs_x; mSs_x = NULL; if (mSs_xnew) delete [] mSs_xnew; mSs_xnew = NULL; // if (mSs_dxdt) delete [] mSs_dxdt; // mSs_dxdt = NULL; if (mSs_h) delete [] mSs_h; mSs_h = NULL; if (mSs_ipvt) delete [] mSs_ipvt; mSs_ipvt = NULL; } #ifdef XXXX // evaluates the Jacobian matrix void CNewton::JEval( double *y, double **ydot ) { register int i, j; double store, temp, *f1, *f2; double K1, K2, K3; // constants for differentiation by finite differences K1 = 1 + mDerivFactor; K2 = 1 - mDerivFactor; K3 = 2 * mDerivFactor; // arrays to store function values f1 = new double[mModel->getIntMetab()+1]; f2 = new double[mModel->getIntMetab()+1]; // iterate over all metabolites for( i=1; i<mModel->getIndMetab()+1; i++ ) { // if y[i] is zero, the derivative will be calculated at a small // positive value (no point in considering negative values!). // let's stick with mSSRes*(1.0+mDerivFactor) store = y[i]; if( store < mSSRes ) temp = mSSRes*K1; else temp = store; y[i] = temp*K1; //FEval( 0, 0, y, f1 ); mModel->lSODAEval(0, 0, y, f1); mSs_nfunction++; y[i] = temp*K2; //FEval( 0, 0, y, f2 ); mModel->lSODAEval(0, 0, y, f2); mSs_nfunction++; for( j=1; j<mModel->getIndMetab()+1; j++ ) ydot[j][i] = (f1[j]-f2[j])/(temp*K3); y[i] = store; } delete [] f1; delete [] f2; //Yongqun He: no plan to count the JEval() yet. Maybe later. //ss_njacob++; } #endif // XXXX change the isSteadyState() function /** * File name: CNewton.cpp * * Programmer: Yongqun He * Contact email: yohe@vt.edu * Purpose: This is the .cpp file for the class CNewton. * It is an important approach to solve the steady state solution problem * */ #include "copasi.h" #include "CNewton.h" #include "tnt/lu.h" //default constructor CNewton::CNewton() { mModel = NULL; mNewtonLimit = DefaultNewtonLimit; mSs_nfunction=0; mSs_solution = 0; mSs_x = NULL; mSs_xnew = NULL; // mSs_dxdt = NULL; mSs_h = NULL; mSs_ipvt = NULL; // initialize(); } // constructor CNewton::CNewton(C_INT32 anInt) { mModel = NULL; mNewtonLimit = anInt; mSs_nfunction = 0; mSs_solution = 0; //initialize(); } // copy constructor CNewton::CNewton(const CNewton& source) { mModel = source.mModel; mNewtonLimit = source.mNewtonLimit; mSs_nfunction = source.mSs_nfunction; mSs_solution = source.mSs_solution; mSs_x = source.mSs_x; mSs_xnew = source.mSs_xnew; mSs_dxdt =source.mSs_dxdt; mSs_h = source.mSs_h; mSs_jacob = source.mSs_jacob; mSs_ipvt = source.mSs_ipvt; } // initialize pointers void CNewton::initialize() { cleanup(); unsigned C_INT32 dim = mModel->getIndMetab(); mSs_xnew = new C_FLOAT64[dim]; // mSs_xnew = new C_FLOAT64[dim]; mSs_dxdt.newsize(dim); mSs_h = new C_FLOAT64[dim]; mSs_ipvt = new C_INT32[dim]; mSs_jacob.setModel(*mModel); } //Y.H. //set up mSs_x and mSs_x's default values //they should come from steady state class, though void CNewton::init_Ss_x(void) { mSs_x = mModel->getInitialNumbers(); } //Object assignment overloading CNewton& CNewton::operator=(const CNewton& source) { if(this != &source) { mModel = source.mModel; mNewtonLimit = source.mNewtonLimit; mSs_nfunction = source.mSs_nfunction; mSs_solution = source.mSs_solution; mSs_x = source.mSs_x; mSs_xnew = source.mSs_xnew; mSs_dxdt =source.mSs_dxdt; mSs_h = source.mSs_h; mSs_jacob = source.mSs_jacob; mSs_ipvt = source.mSs_ipvt; } return *this; } //destructor CNewton::~CNewton() { cout << "~CNewton " << endl; } //set mModel void CNewton::setModel(CModel * aModel) { mModel = aModel; initialize(); } //get mModel CModel * CNewton::getModel() const { return mModel; } // set mSSRes void CNewton::setSSRes(C_FLOAT64 aDouble) { mSSRes = aDouble; } //get mSSRes C_FLOAT64 CNewton::getSSRes() const { return mSSRes; } // get mSs_xnew C_FLOAT64 * CNewton::getSs_xnew() const { return mSs_xnew; } // get mSs_dxdt const TNT::Vector < C_FLOAT64 > & CNewton::getSs_dxdt() const { return mSs_dxdt; } // set mDerivFactor void CNewton::setDerivFactor(C_FLOAT64 aDouble) { mDerivFactor = aDouble; } // get mDerivFactor C_FLOAT64 CNewton::getDerivFactor() const { return mDerivFactor; } void CNewton::setNewtonLimit(C_INT32 limit) {mNewtonLimit = limit;} C_INT32 CNewton::getNewtonLimit() const {return mNewtonLimit;} // set mSs_nfunction void CNewton::setSs_nfunction(C_INT32 aInt) { mSs_nfunction = aInt; } // get mDerivFactor C_INT32 CNewton::getSs_nfunction() const { return mSs_nfunction; } // finds out if current state is a valid steady state C_INT32 CNewton::isSteadyState( void ) { return mSs_solution; } /* // finds out if current state is a valid steady state C_INT32 CNewton::isSteadyState( void ) { unsigned C_INT32 i, dim = mModel->getIndMetab(); double maxrate; mSs_solution = SS_NOT_FOUND; for( i=0; i<dim; i++ ) if( mSs_x[i] < 0.0 ) return SS_NOT_FOUND; //FEval( 0, 0, mSs_x, ss_dxdt ); mModel->lSODAEval(dim, 0, mSs_xnew, &mSs_dxdt[0] ); mSs_nfunction++; // maxrate = SS_XNorn( ss_dxdt ); maxrate = xNorm(dim, &mSs_dxdt[0] - 1, 1); if( maxrate < mSSRes ) mSs_solution = SS_FOUND; return mSs_solution; } */ //similar to SS_Newton() in gepasi except a few modification // void CNewton::process(void) { int i,j,k; C_FLOAT64 maxrate, nmaxrate; C_INT32 info; mSs_solution = SS_NOT_FOUND; //by Yongqun He //get the dimensions of the matrix int dim = mModel->getIndMetab(); // try // { // mModel->lSODAEval(0, 0, mSs_x, mSs_dxdt ); //changed by Yongqun He mModel->lSODAEval(dim, 0, mSs_x, &mSs_dxdt[0] ); mSs_nfunction++; maxrate =xNorm(dim, &mSs_dxdt[0] - 1, 1); if( maxrate < mSSRes ) mSs_solution = SS_FOUND; if( mSs_solution == SS_FOUND ) { for( i=0; i<dim; i++ ) if( mSs_x[i] < 0.0 ) { mSs_solution = SS_NOT_FOUND; break; } } // } // finally // { //} if( mSs_solution==SS_FOUND ) return; for( k=0; k<mNewtonLimit; k++ ) { // try //{ //JEval( mSs_x, mSs_jacob ); mSs_jacob.jacobEval(mSs_x, mDerivFactor, mSSRes); /* :TODO: We have to check whether LU is really needed? */ TNT::Matrix < C_FLOAT64 > LU = mSs_jacob.getJacob(); TNT::Vector < unsigned C_INT32 > rowLU(dim); // LU decomposition of Jacobian info = TNT::LU_factor(LU, rowLU); // dgefa( mSs_jacob, dim, mSs_ipvt, &info); if( info!=0 ) { // jacobian is singular mSs_solution = SS_SINGULAR_JACOBIAN; return; } // solve mSs_jacob . x = mSs_h for x (result in mSs_dxdt) TNT::LU_solve(LU, rowLU, mSs_dxdt); // dgesl( mSs_jacob, mModel->getIndMetab(), mSs_ipvt, mSs_dxdt, 0 ); // } //finally //{ //} nmaxrate = maxrate * 1.001; // copy values of increment to mSs_h for(i=0;i<dim;i++) mSs_h[i] = mSs_dxdt[i]; for( i=0; (i<32) && (nmaxrate>maxrate) ; i++ ) { for( j=0; j<dim; j++ ) { mSs_xnew[j] = mSs_x[j] - mSs_h[j]; mSs_h[j] /= 2; } // this is done inside lSODAEval // mModel->setConcentrations(mSs_xnew); // update the dependent metabolites // try //{ //FEval( 0, 0, mSs_xnew, mSs_dxdt ); mModel->lSODAEval(dim, 0, mSs_xnew, &mSs_dxdt[0] ); mSs_nfunction++; nmaxrate = xNorm(dim, &mSs_dxdt[0] - 1, 1); //} //finally //{ //} } if( i==32 ) { if( maxrate < mSSRes ) { mSs_solution = SS_FOUND; // check if solution is valid for( i=0; i<mModel->getIntMetab(); i++ ) if( mSs_x[i] < 0.0 ) { mSs_solution = SS_NOT_FOUND; break; } return; } else { mSs_solution = SS_DAMPING_LIMIT; return; } } for(i=0;i<dim;i++) mSs_x[i] = mSs_xnew[i]; maxrate = nmaxrate; } if( maxrate < mSSRes ) { mSs_solution = SS_FOUND; // check if solution is valid for( i=0; i<dim; i++ ) if( mSs_x[i] < 0.0 ) { mSs_solution = SS_NOT_FOUND; break; } return; } else { mSs_solution = SS_ITERATION_LIMIT; return; } } // Clean up internal pointer variables void CNewton::cleanup(void) { if (mSs_x) delete [] mSs_x; mSs_x = NULL; if (mSs_xnew) delete [] mSs_xnew; mSs_xnew = NULL; // if (mSs_dxdt) delete [] mSs_dxdt; // mSs_dxdt = NULL; if (mSs_h) delete [] mSs_h; mSs_h = NULL; if (mSs_ipvt) delete [] mSs_ipvt; mSs_ipvt = NULL; } #ifdef XXXX // evaluates the Jacobian matrix void CNewton::JEval( double *y, double **ydot ) { register int i, j; double store, temp, *f1, *f2; double K1, K2, K3; // constants for differentiation by finite differences K1 = 1 + mDerivFactor; K2 = 1 - mDerivFactor; K3 = 2 * mDerivFactor; // arrays to store function values f1 = new double[mModel->getIntMetab()+1]; f2 = new double[mModel->getIntMetab()+1]; // iterate over all metabolites for( i=1; i<mModel->getIndMetab()+1; i++ ) { // if y[i] is zero, the derivative will be calculated at a small // positive value (no point in considering negative values!). // let's stick with mSSRes*(1.0+mDerivFactor) store = y[i]; if( store < mSSRes ) temp = mSSRes*K1; else temp = store; y[i] = temp*K1; //FEval( 0, 0, y, f1 ); mModel->lSODAEval(0, 0, y, f1); mSs_nfunction++; y[i] = temp*K2; //FEval( 0, 0, y, f2 ); mModel->lSODAEval(0, 0, y, f2); mSs_nfunction++; for( j=1; j<mModel->getIndMetab()+1; j++ ) ydot[j][i] = (f1[j]-f2[j])/(temp*K3); y[i] = store; } delete [] f1; delete [] f2; //Yongqun He: no plan to count the JEval() yet. Maybe later. //ss_njacob++; } #endif // XXXX
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "config.h" #include "bindings/core/v8/PrivateScriptRunner.h" #include "bindings/core/v8/DOMWrapperWorld.h" #include "bindings/core/v8/V8Binding.h" #include "bindings/core/v8/V8PerContextData.h" #include "bindings/core/v8/V8ScriptRunner.h" #include "core/PrivateScriptSources.h" #ifndef NDEBUG #include "core/PrivateScriptSourcesForTesting.h" #endif namespace WebCore { static v8::Handle<v8::Value> compilePrivateScript(v8::Isolate* isolate, String className) { size_t index; #ifndef NDEBUG for (index = 0; index < WTF_ARRAY_LENGTH(kPrivateScriptSourcesForTesting); index++) { if (className == kPrivateScriptSourcesForTesting[index].name) break; } if (index != WTF_ARRAY_LENGTH(kPrivateScriptSourcesForTesting)) { String source(reinterpret_cast<const char*>(kPrivateScriptSourcesForTesting[index].source), kPrivateScriptSourcesForTesting[index].size); return V8ScriptRunner::compileAndRunInternalScript(v8String(isolate, source), isolate); } #endif // |kPrivateScriptSources| is defined in V8PrivateScriptSources.h, which is auto-generated // by make_private_script.py. for (index = 0; index < WTF_ARRAY_LENGTH(kPrivateScriptSources); index++) { if (className == kPrivateScriptSources[index].name) break; } RELEASE_ASSERT(index != WTF_ARRAY_LENGTH(kPrivateScriptSources)); String source(reinterpret_cast<const char*>(kPrivateScriptSources[index].source), kPrivateScriptSources[index].size); return V8ScriptRunner::compileAndRunInternalScript(v8String(isolate, source), isolate); } static v8::Handle<v8::Object> classObjectOfPrivateScript(ScriptState* scriptState, String className) { ASSERT(scriptState->perContextData()); ASSERT(scriptState->executionContext()); v8::Isolate* isolate = scriptState->isolate(); v8::Handle<v8::Value> compiledClass = scriptState->perContextData()->compiledPrivateScript(className); if (compiledClass.IsEmpty()) { v8::Handle<v8::Value> installedClasses = scriptState->perContextData()->compiledPrivateScript("PrivateScriptRunner"); if (installedClasses.IsEmpty()) { installedClasses = compilePrivateScript(isolate, "PrivateScriptRunner"); scriptState->perContextData()->setCompiledPrivateScript("PrivateScriptRunner", installedClasses); } RELEASE_ASSERT(!installedClasses.IsEmpty()); RELEASE_ASSERT(installedClasses->IsObject()); compilePrivateScript(isolate, className); compiledClass = v8::Handle<v8::Object>::Cast(installedClasses)->Get(v8String(isolate, className)); RELEASE_ASSERT(!compiledClass.IsEmpty()); RELEASE_ASSERT(compiledClass->IsObject()); scriptState->perContextData()->setCompiledPrivateScript(className, compiledClass); } return v8::Handle<v8::Object>::Cast(compiledClass); } // FIXME: Replace this method with a V8 API for getOwnPropertyDescriptor, once V8 is rolled. static v8::Handle<v8::Object> getOwnPropertyDescriptor(ScriptState* scriptState, v8::Handle<v8::Object> classObject, String name) { ASSERT(!scriptState->contextIsEmpty()); v8::Handle<v8::Value> object = scriptState->context()->Global()->Get(v8String(scriptState->isolate(), "Object")); RELEASE_ASSERT(!object.IsEmpty()); RELEASE_ASSERT(object->IsObject()); v8::Handle<v8::Value> getOwnPropertyDescriptorFunction = v8::Handle<v8::Object>::Cast(object)->Get(v8String(scriptState->isolate(), "getOwnPropertyDescriptor")); RELEASE_ASSERT(!getOwnPropertyDescriptorFunction.IsEmpty()); RELEASE_ASSERT(getOwnPropertyDescriptorFunction->IsFunction()); v8::Handle<v8::Value> argv[] = { classObject, v8String(scriptState->isolate(), name) }; v8::Handle<v8::Value> descriptor = V8ScriptRunner::callInternalFunction(v8::Handle<v8::Function>::Cast(getOwnPropertyDescriptorFunction), object, WTF_ARRAY_LENGTH(argv), argv, scriptState->isolate()); RELEASE_ASSERT(!descriptor.IsEmpty()); RELEASE_ASSERT(descriptor->IsObject()); return v8::Handle<v8::Object>::Cast(descriptor); } static void initializeHolderIfNeeded(ScriptState* scriptState, v8::Handle<v8::Object> classObject, v8::Handle<v8::Value> holder) { RELEASE_ASSERT(!holder.IsEmpty()); RELEASE_ASSERT(holder->IsObject()); v8::Handle<v8::Object> holderObject = v8::Handle<v8::Object>::Cast(holder); v8::Isolate* isolate = scriptState->isolate(); v8::Handle<v8::Value> isInitialized = V8HiddenValue::getHiddenValue(isolate, holderObject, V8HiddenValue::privateScriptObjectIsInitialized(isolate)); if (isInitialized.IsEmpty()) { v8::Handle<v8::Value> initializeFunction = classObject->Get(v8String(isolate, "constructor")); if (!initializeFunction.IsEmpty()) { RELEASE_ASSERT(initializeFunction->IsFunction()); V8ScriptRunner::callFunction(v8::Handle<v8::Function>::Cast(initializeFunction), scriptState->executionContext(), holder, 0, 0, isolate); isInitialized = v8Boolean(true, isolate); V8HiddenValue::setHiddenValue(isolate, holderObject, V8HiddenValue::privateScriptObjectIsInitialized(isolate), isInitialized); } } } v8::Handle<v8::Value> PrivateScriptRunner::installClass(LocalFrame* frame, String className) { if (!frame) return v8::Handle<v8::Value>(); v8::Handle<v8::Context> context = toV8Context(frame, DOMWrapperWorld::privateScriptIsolatedWorld()); if (context.IsEmpty()) return v8::Handle<v8::Value>(); ScriptState* scriptState = ScriptState::from(context); if (!scriptState->executionContext()) return v8::Handle<v8::Value>(); ScriptState::Scope scope(scriptState); return classObjectOfPrivateScript(scriptState, className); } v8::Handle<v8::Value> PrivateScriptRunner::runDOMAttributeGetter(ScriptState* scriptState, String className, String attributeName, v8::Handle<v8::Value> holder) { v8::Handle<v8::Object> classObject = classObjectOfPrivateScript(scriptState, className); v8::Handle<v8::Object> descriptor = getOwnPropertyDescriptor(scriptState, classObject, attributeName); v8::Handle<v8::Value> getter = descriptor->Get(v8String(scriptState->isolate(), "get")); RELEASE_ASSERT(!getter.IsEmpty()); RELEASE_ASSERT(getter->IsFunction()); initializeHolderIfNeeded(scriptState, classObject, holder); return V8ScriptRunner::callFunction(v8::Handle<v8::Function>::Cast(getter), scriptState->executionContext(), holder, 0, 0, scriptState->isolate()); } void PrivateScriptRunner::runDOMAttributeSetter(ScriptState* scriptState, String className, String attributeName, v8::Handle<v8::Value> holder, v8::Handle<v8::Value> v8Value) { v8::Handle<v8::Object> classObject = classObjectOfPrivateScript(scriptState, className); v8::Handle<v8::Object> descriptor = getOwnPropertyDescriptor(scriptState, classObject, attributeName); v8::Handle<v8::Value> setter = descriptor->Get(v8String(scriptState->isolate(), "set")); RELEASE_ASSERT(!setter.IsEmpty()); RELEASE_ASSERT(setter->IsFunction()); initializeHolderIfNeeded(scriptState, classObject, holder); v8::Handle<v8::Value> argv[] = { v8Value }; V8ScriptRunner::callFunction(v8::Handle<v8::Function>::Cast(setter), scriptState->executionContext(), holder, WTF_ARRAY_LENGTH(argv), argv, scriptState->isolate()); } v8::Handle<v8::Value> PrivateScriptRunner::runDOMMethod(ScriptState* scriptState, String className, String methodName, v8::Handle<v8::Value> holder, int argc, v8::Handle<v8::Value> argv[]) { v8::Handle<v8::Object> classObject = classObjectOfPrivateScript(scriptState, className); v8::Handle<v8::Value> method = classObject->Get(v8String(scriptState->isolate(), methodName)); RELEASE_ASSERT(!method.IsEmpty()); RELEASE_ASSERT(method->IsFunction()); initializeHolderIfNeeded(scriptState, classObject, holder); return V8ScriptRunner::callFunction(v8::Handle<v8::Function>::Cast(method), scriptState->executionContext(), holder, argc, argv, scriptState->isolate()); } } // namespace WebCore '.constructor' in private scripts should not be called multiple times This is just a subtle bug fix. |isInitialized| should be set when initializeHolderIfNeeded runs at the first time. BUG=341031 Review URL: https://codereview.chromium.org/380253003 git-svn-id: bf5cd6ccde378db821296732a091cfbcf5285fbd@177894 bbb929c8-8fbe-4397-9dbb-9b2b20218538 // Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "config.h" #include "bindings/core/v8/PrivateScriptRunner.h" #include "bindings/core/v8/DOMWrapperWorld.h" #include "bindings/core/v8/V8Binding.h" #include "bindings/core/v8/V8PerContextData.h" #include "bindings/core/v8/V8ScriptRunner.h" #include "core/PrivateScriptSources.h" #ifndef NDEBUG #include "core/PrivateScriptSourcesForTesting.h" #endif namespace WebCore { static v8::Handle<v8::Value> compilePrivateScript(v8::Isolate* isolate, String className) { size_t index; #ifndef NDEBUG for (index = 0; index < WTF_ARRAY_LENGTH(kPrivateScriptSourcesForTesting); index++) { if (className == kPrivateScriptSourcesForTesting[index].name) break; } if (index != WTF_ARRAY_LENGTH(kPrivateScriptSourcesForTesting)) { String source(reinterpret_cast<const char*>(kPrivateScriptSourcesForTesting[index].source), kPrivateScriptSourcesForTesting[index].size); return V8ScriptRunner::compileAndRunInternalScript(v8String(isolate, source), isolate); } #endif // |kPrivateScriptSources| is defined in V8PrivateScriptSources.h, which is auto-generated // by make_private_script.py. for (index = 0; index < WTF_ARRAY_LENGTH(kPrivateScriptSources); index++) { if (className == kPrivateScriptSources[index].name) break; } RELEASE_ASSERT(index != WTF_ARRAY_LENGTH(kPrivateScriptSources)); String source(reinterpret_cast<const char*>(kPrivateScriptSources[index].source), kPrivateScriptSources[index].size); return V8ScriptRunner::compileAndRunInternalScript(v8String(isolate, source), isolate); } static v8::Handle<v8::Object> classObjectOfPrivateScript(ScriptState* scriptState, String className) { ASSERT(scriptState->perContextData()); ASSERT(scriptState->executionContext()); v8::Isolate* isolate = scriptState->isolate(); v8::Handle<v8::Value> compiledClass = scriptState->perContextData()->compiledPrivateScript(className); if (compiledClass.IsEmpty()) { v8::Handle<v8::Value> installedClasses = scriptState->perContextData()->compiledPrivateScript("PrivateScriptRunner"); if (installedClasses.IsEmpty()) { installedClasses = compilePrivateScript(isolate, "PrivateScriptRunner"); scriptState->perContextData()->setCompiledPrivateScript("PrivateScriptRunner", installedClasses); } RELEASE_ASSERT(!installedClasses.IsEmpty()); RELEASE_ASSERT(installedClasses->IsObject()); compilePrivateScript(isolate, className); compiledClass = v8::Handle<v8::Object>::Cast(installedClasses)->Get(v8String(isolate, className)); RELEASE_ASSERT(!compiledClass.IsEmpty()); RELEASE_ASSERT(compiledClass->IsObject()); scriptState->perContextData()->setCompiledPrivateScript(className, compiledClass); } return v8::Handle<v8::Object>::Cast(compiledClass); } // FIXME: Replace this method with a V8 API for getOwnPropertyDescriptor, once V8 is rolled. static v8::Handle<v8::Object> getOwnPropertyDescriptor(ScriptState* scriptState, v8::Handle<v8::Object> classObject, String name) { ASSERT(!scriptState->contextIsEmpty()); v8::Handle<v8::Value> object = scriptState->context()->Global()->Get(v8String(scriptState->isolate(), "Object")); RELEASE_ASSERT(!object.IsEmpty()); RELEASE_ASSERT(object->IsObject()); v8::Handle<v8::Value> getOwnPropertyDescriptorFunction = v8::Handle<v8::Object>::Cast(object)->Get(v8String(scriptState->isolate(), "getOwnPropertyDescriptor")); RELEASE_ASSERT(!getOwnPropertyDescriptorFunction.IsEmpty()); RELEASE_ASSERT(getOwnPropertyDescriptorFunction->IsFunction()); v8::Handle<v8::Value> argv[] = { classObject, v8String(scriptState->isolate(), name) }; v8::Handle<v8::Value> descriptor = V8ScriptRunner::callInternalFunction(v8::Handle<v8::Function>::Cast(getOwnPropertyDescriptorFunction), object, WTF_ARRAY_LENGTH(argv), argv, scriptState->isolate()); RELEASE_ASSERT(!descriptor.IsEmpty()); RELEASE_ASSERT(descriptor->IsObject()); return v8::Handle<v8::Object>::Cast(descriptor); } static void initializeHolderIfNeeded(ScriptState* scriptState, v8::Handle<v8::Object> classObject, v8::Handle<v8::Value> holder) { RELEASE_ASSERT(!holder.IsEmpty()); RELEASE_ASSERT(holder->IsObject()); v8::Handle<v8::Object> holderObject = v8::Handle<v8::Object>::Cast(holder); v8::Isolate* isolate = scriptState->isolate(); v8::Handle<v8::Value> isInitialized = V8HiddenValue::getHiddenValue(isolate, holderObject, V8HiddenValue::privateScriptObjectIsInitialized(isolate)); if (isInitialized.IsEmpty()) { v8::Handle<v8::Value> initializeFunction = classObject->Get(v8String(isolate, "constructor")); if (!initializeFunction.IsEmpty() && initializeFunction->IsFunction()) { V8ScriptRunner::callFunction(v8::Handle<v8::Function>::Cast(initializeFunction), scriptState->executionContext(), holder, 0, 0, isolate); } isInitialized = v8Boolean(true, isolate); V8HiddenValue::setHiddenValue(isolate, holderObject, V8HiddenValue::privateScriptObjectIsInitialized(isolate), isInitialized); } } v8::Handle<v8::Value> PrivateScriptRunner::installClass(LocalFrame* frame, String className) { if (!frame) return v8::Handle<v8::Value>(); v8::Handle<v8::Context> context = toV8Context(frame, DOMWrapperWorld::privateScriptIsolatedWorld()); if (context.IsEmpty()) return v8::Handle<v8::Value>(); ScriptState* scriptState = ScriptState::from(context); if (!scriptState->executionContext()) return v8::Handle<v8::Value>(); ScriptState::Scope scope(scriptState); return classObjectOfPrivateScript(scriptState, className); } v8::Handle<v8::Value> PrivateScriptRunner::runDOMAttributeGetter(ScriptState* scriptState, String className, String attributeName, v8::Handle<v8::Value> holder) { v8::Handle<v8::Object> classObject = classObjectOfPrivateScript(scriptState, className); v8::Handle<v8::Object> descriptor = getOwnPropertyDescriptor(scriptState, classObject, attributeName); v8::Handle<v8::Value> getter = descriptor->Get(v8String(scriptState->isolate(), "get")); RELEASE_ASSERT(!getter.IsEmpty()); RELEASE_ASSERT(getter->IsFunction()); initializeHolderIfNeeded(scriptState, classObject, holder); return V8ScriptRunner::callFunction(v8::Handle<v8::Function>::Cast(getter), scriptState->executionContext(), holder, 0, 0, scriptState->isolate()); } void PrivateScriptRunner::runDOMAttributeSetter(ScriptState* scriptState, String className, String attributeName, v8::Handle<v8::Value> holder, v8::Handle<v8::Value> v8Value) { v8::Handle<v8::Object> classObject = classObjectOfPrivateScript(scriptState, className); v8::Handle<v8::Object> descriptor = getOwnPropertyDescriptor(scriptState, classObject, attributeName); v8::Handle<v8::Value> setter = descriptor->Get(v8String(scriptState->isolate(), "set")); RELEASE_ASSERT(!setter.IsEmpty()); RELEASE_ASSERT(setter->IsFunction()); initializeHolderIfNeeded(scriptState, classObject, holder); v8::Handle<v8::Value> argv[] = { v8Value }; V8ScriptRunner::callFunction(v8::Handle<v8::Function>::Cast(setter), scriptState->executionContext(), holder, WTF_ARRAY_LENGTH(argv), argv, scriptState->isolate()); } v8::Handle<v8::Value> PrivateScriptRunner::runDOMMethod(ScriptState* scriptState, String className, String methodName, v8::Handle<v8::Value> holder, int argc, v8::Handle<v8::Value> argv[]) { v8::Handle<v8::Object> classObject = classObjectOfPrivateScript(scriptState, className); v8::Handle<v8::Value> method = classObject->Get(v8String(scriptState->isolate(), methodName)); RELEASE_ASSERT(!method.IsEmpty()); RELEASE_ASSERT(method->IsFunction()); initializeHolderIfNeeded(scriptState, classObject, holder); return V8ScriptRunner::callFunction(v8::Handle<v8::Function>::Cast(method), scriptState->executionContext(), holder, argc, argv, scriptState->isolate()); } } // namespace WebCore
#include "MATHS.H" #include "LOAD_LEV.H" #include "SPECIFIC.H" #include <INLINE_C.H> #include "3D_GEN.H" #include "CAMERA.H" #include "DRAW.H" #include "GPU.H" #include "GTEREG.H" #include "DRAWSPKS.H" void mQuickW2VMatrix()//77AEC(<), 79B30(<) { MatrixSP = 0; Matrix = &MatrixStack[0]; ((int*)&MatrixStack)[0] = ((unsigned short*)phd_mxptr)[0] | ((unsigned short*)phd_mxptr)[2] << 16; ((int*)&MatrixStack)[1] = ((unsigned short*)phd_mxptr)[4] | ((unsigned short*)phd_mxptr)[8] << 16; ((int*)&MatrixStack)[2] = ((unsigned short*)phd_mxptr)[10] | ((unsigned short*)phd_mxptr)[12] << 16; ((int*)&MatrixStack)[3] = ((unsigned short*)phd_mxptr)[16] | ((unsigned short*)phd_mxptr)[18] << 16; R12 = ((short*)phd_mxptr)[2] << 16; R11 = ((short*)phd_mxptr)[0]; R21 = ((short*)phd_mxptr)[8] << 16; R13 = ((short*)phd_mxptr)[4]; R23 = ((short*)phd_mxptr)[12] << 16; R22 = ((short*)phd_mxptr)[10]; R32 = ((short*)phd_mxptr)[18] << 16; R31 = ((short*)phd_mxptr)[16]; ((short*)&MatrixStack)[8] = ((unsigned short*)phd_mxptr)[20]; ((short*)&MatrixStack)[10] = ((unsigned short*)phd_mxptr)[6]; ((short*)&MatrixStack)[12] = ((unsigned short*)phd_mxptr)[14]; ((short*)&MatrixStack)[14] = ((unsigned short*)phd_mxptr)[22]; R33 = ((unsigned short*)phd_mxptr)[20]; TRX = ((unsigned short*)phd_mxptr)[6]; TRY = ((unsigned short*)phd_mxptr)[14]; TRZ = ((unsigned short*)phd_mxptr)[22]; CamGTE.m00 = ((unsigned short*)&w2v_matrix)[0]; CamGTE.m01 = ((unsigned short*)&w2v_matrix)[2]; CamGTE.m02 = ((unsigned short*)&w2v_matrix)[4]; CamGTE.m10 = ((unsigned short*)&w2v_matrix)[8]; CamGTE.m11 = ((unsigned short*)&w2v_matrix)[10]; CamGTE.m12 = ((unsigned short*)&w2v_matrix)[12]; CamGTE.m20 = ((unsigned short*)&w2v_matrix)[16]; CamGTE.m21 = ((unsigned short*)&w2v_matrix)[18]; CamGTE.m22 = ((unsigned short*)&w2v_matrix)[20]; } void gte_sttr(struct PHD_VECTOR* vec)//To investigate, this should not be in this file. { vec->x = Matrix->tx >> 12; vec->y = Matrix->ty >> 12; vec->z = Matrix->tz >> 12; } long mGetAngle(long x, long z, long tx, long tz)//77678(<), 796BC(<) (F) { long dx = tx - x; long dz = tz - z; short table_index = 0; long result_angle = 0; long temp = 0; if ((dx | dz) != 0) { if (dx < 0) { table_index |= 0x10;//FIXME: += (4); dx = -dx; } //0x796E0 if (dz < 0) { table_index += 2; dz = -dz; } //796F0 if (dx < dz) { table_index += 1; temp = dx; dx = dz; dz = temp; } //7970C while (dz / 65536 != 0) { dx /= 2; dz /= 2; } //79724 result_angle = atanTab[dz * 2048 / dx]; result_angle += atanOctantTab[table_index]; if (result_angle < 0) { result_angle = -result_angle; }//79760 }//79760 return -result_angle & 0xFFFF; } long mSqrt(long value)//83B30(<), 85B74(<) (F) { long v0 = 0x1F; long v1 = gte_ldlzc(value); if (value != 0) { v1 &= 0xFFFFFFFE; v0 = v0 - v1 >> 1; long at = v1 - 0x18; if (v1 - 0x18 < 0) { //loc_85BA8 value >>= 0x18 - v1; } else { value <<= v1 - 0x18; } //loc_85BB4 value = SqrtTable[value - 0x40] << v0; }//locret_85BD0 return (value >> 12); } long phd_sqrt_asm(long value)//83B30(<), 85B74(<) (F) { long v0 = 0x1F; long v1 = gte_ldlzc(value); if (value != 0) { v1 &= 0xFFFFFFFE; v0 = v0 - v1 >> 1; long at = v1 - 0x18; if (v1 - 0x18 < 0) { //loc_85BA8 value >>= 0x18 - v1; } else { value <<= v1 - 0x18; } //loc_85BB4 value = SqrtTable[value - 0x40] << v0; }//locret_85BD0 return (value >> 12); } void ScaleCurrentMatrix(long bStoreInMatrix, long sx, long sy, long sz) { int t2, v0, v1; unsigned int t0, t1, at; t0 = R11; t1 = R13; t2 = R22; v0 = R31; v1 = R33; R12 = ((((t0 << 16) >> 16) * sx) >> 12) & 0xFFFF; R11 = ((((t0 >> 16) * sy) >> 12) << 16); R21 = ((((t1 << 16) >> 16) * sz) >> 12) & 0xFFFF; R13 = (((t1 >> 16) * sx) >> 12) << 16; R23 = ((((t2 << 16) >> 16) * sy) >> 12) & 0xFFFF; R22 = (((t2 >> 16) * sz) >> 12) << 16; R32 = ((((v0 << 16) >> 16) * sx) >> 12) & 0xFFFF; R31 = (((v0 >> 16) * sy) >> 12) << 16; R33 = ((((v1 << 16) >> 16) * sz) >> 12); if (bStoreInMatrix) { Matrix->m00 = R11; Matrix->m01 = R12; Matrix->m02 = R13; Matrix->m10 = R21; Matrix->m11 = R22; Matrix->m12 = R23; Matrix->m20 = R31; Matrix->m21 = R32; Matrix->m22 = R33; }//locret_77E68 } void mPushMatrix()//764D0(<), 78514(<) (F) { ++Matrix; Matrix->m00 = R11; Matrix->m01 = R12; Matrix->m02 = R13; Matrix->m10 = R21; Matrix->m11 = R22; Matrix->m12 = R23; Matrix->m20 = R31; Matrix->m21 = R32; Matrix->m22 = R33; Matrix->tx = TRX; Matrix->ty = TRY; Matrix->tz = TRZ; } void mPopMatrix()//76520(<), 78564(<) (F) { mLoadMatrix(--Matrix); } void mUnitMatrix() { UNIMPLEMENTED(); } void mPushUnitMatrix()//76534(<), 78578(<) { setrot(++Matrix, 0x1000, 0, 0x1000, 0, 0x1000); } void mTranslate()//76558(<) (!) { UNIMPLEMENTED(); } void mTranslateAbsXYZ(long x, long y, long z) { mTranslateXYZ(x - MatrixStack[0].tx, y - MatrixStack[0].ty, z - MatrixStack[0].tz); } void mTranslateXYZ(long x, long y, long z)//7658C(<), 785D0(<) (!) { int t0; int t1; int t2; int t3; int t4; int t5; t4 = y >> 15; if (y < 0) { y = -y; t4 = y >> 15; y &= 0x7FFF; t4 = -t4; y = -y; }//loc_765AC else { y &= 0x7FFF; } //loc_765B0 : t5 = z >> 15; if (z < 0) { z = -z; t5 = z >> 15; z &= 0x7FFF; t5 = -t5; z = -z; } else { //loc_765D0 z &= 0x7FFF; } //loc_765D4 t3 = x >> 15; if (x < 0) { x = -x; t3 = x >> 15; x &= 0x7FFF; t3 = -t3; x = -x; } else { x &= 0x7FFF; } IR1 = t3; IR2 = t4; IR3 = t5; docop2(0x41E012); t3 = MAC1; t4 = MAC2; t5 = MAC3; IR1 = x; IR2 = y; IR3 = z; docop2(0x498012); t0 = t3 << 3; if (t3 < 0) { t3 = -t3; t3 <<= 3; t0 = -t3; } //loc_7663C t1 = t4 << 3; if (t4 < 0) { t4 = -t4; t4 <<= 3; t1 = -t4; } //loc_76650 t2 = t5 << 3; if (t5 < 0) { t5 = -t5; t5 <<= 3; t2 = -t5; }//loc_76664 t3 = MAC1; t4 = MAC2; t5 = MAC3; t0 += t3; t1 += t4; t2 += t5; TRX = t0; TRY = t1; TRZ = t2; Matrix->tx = t0; Matrix->ty = t1; Matrix->tz = t2; } void mRotX(long rx)//7669C (F) { int t0; int t1; int t2; int t3; int t4; int t5; int t6; rx = (rx >> 2) & 0x3FFC; if (rx != 0) { //loc_766B4 t5 = (rcossin_tbl[rx >> 1] & 0xFFFF) | ((rcossin_tbl[rx >> 1 | 1] & 0xFFFF ) << 16); VX0 = (0xFFFF0000 & t5) & 0xFFFF; VY0 = ((0xFFFF0000 & t5) >> 16) & 0xFFFF; VZ0 = t5 & 0xFFFF; t0 = (R12 << 16 | R11) & 0xFFFF; t1 = (R21 << 16 | R13) & 0xFFFF0000; t3 = (R32 << 16 | R31) & 0xFFFF; docop2(0x486012); t6 = t5 >> 16; t5 <<= 16; t5 = -t5; VX1 = t5; VY1 = (t5 >> 16) & 0xFFFF; VZ1 = t6; t4 = MAC1; t2 = MAC2 & 0xFFFF; t5 = MAC3; docop2(0x48E012); t0 |= t4 << 16; t3 |= t5 << 16; t5 = MAC1 & 0xFFFF; t6 = MAC2; t4 = MAC3; t1 |= t5; t2 |= t6 << 16; SetRotation(t0, t1, t2, t3, t4); } } void mRotY(long ry)//76744 (F) { int t0; int t1; int t2; int t3; int t4; int t5; int t6; int t7; ry = (ry >> 2) & 0x3FFC; if (ry != 0) { t5 = rcossin_tbl[ry]; t6 = t5 >> 16; t5 &= 0xFFFF; t2 = -t5; VX0 = t6; VZ0 = t2; t0 = (R12 << 16 | R11) & 0xFFFF0000; t2 = (R23 << 16 | R22) & 0xFFFF; t3 = (R32 << 16 | R31) & 0xFFFF0000; docop2(0x486012); VX1 = t5; VZ1 = t6; t4 = MAC1; t1 = MAC2; t5 = MAC3; docop2(0x48E012); t0 |= (t4 & 0xFFFF); t3 |= (t5 & 0xFFFF); t1 = (t1 << 16) | (t5 & 0xFFFF); t5 = MAC1; t6 = MAC2; t4 = MAC3; t2 |= t6 << 16; SetRotation(t0, t1, t2, t3, t4); } } void mRotYXZ(short y, short x, short z)//767E8 (F) { //mRotY(y); mRotX(x); mRotZ(z); } void mRotZ(long rz)//76804 (F) { int t0; int t1; int t2; int t3; int t4; int t5; int t6; int t7; rz = (rz >> 2) & 0x3FFC; if (rz != 0) { t0 = rcossin_tbl[rz]; } #if 0 loc_7681C : la t0, rcossin_tbl add t0, a0 lw t0, 0(t0) lui t7, 0xFFFF srl t1, t0, 16 sll t2, t0, 16 or t1, t2 mtc2 t1, r0 mtc2 zero, r1 cfc2 t1, r1 cfc2 t2, r2 cfc2 t4, r4 cop2 0x486012 and t3, t0, t7 andi t0, 0xFFFF neg t0, t0 andi t0, 0xFFFF or t0, t3 mtc2 t0, r2 mtc2 zero, r3 andi t1, 0xFFFF mfc2 t0, r25 mfc2 t5, r26 mfc2 t3, r27 cop2 0x48E012 and t2, t7 andi t0, 0xFFFF sll t5, 16 or t1, t5 andi t3, 0xFFFF mfc2 t5, r25 mfc2 t6, r26 mfc2 a0, r27 sll t5, 16 or t0, t5 andi t6, 0xFFFF or t2, t6 sll a0, 16 j SetRotation or t3, a0 #endif } void mRotSuperPackedYXZ(short** a0, long a1)//768BC { unsigned short* a2; int v0; int at; a2 = (unsigned short*)a0[0]; if (a1 != 0) { //loc_768C4 do { v0 = *a2++; a1--; if (!(v0 & 0xC000)) { a2++; }//loc_768DC } while (a1 == 0); }//loc_768E8 v0 = *a2++; at = (v0 >> 14); at--; if (at != 0) { a0[0] = (short*)a2; if (at != 0) { mRotZ((v0 & 0xFFF) << 4); }//loc_76914 mRotY((v0 & 0xFFF) << 4); mRotX((v0 & 0xFFF) << 4); }//loc_76928 at = *a2++; a0[0] = (short*)a2; mRotY((((v0 << 16) | at) >> 4) & 0xFFC0); mRotX((((v0 << 16) | at) >> 14) & 0xFFC0); mRotZ((((v0 << 16) | at) & 0x3FF) << 6); } void mRotPackedYXZ(long yxz)//7693C (F) { UNIMPLEMENTED(); } void SetRotation(int t0, int t1, int t2, int t3, int t4)//7696C(<) (F) { R11 = t0 & 0xFFFF; R12 = t0 >> 16; R13 = t1 & 0xFFFF; R21 = t1 >> 16; R22 = t2 & 0xFFFF; R23 = t2 >> 16; R31 = t3 & 0xFFFF; R32 = t3 >> 16; R33 = t4; ((int*)&Matrix->m00)[0] = t0; ((int*)&Matrix->m02)[0] = t1; ((int*)&Matrix->m11)[0] = t2; ((int*)&Matrix->m20)[0] = t3; ((int*)&Matrix->m22)[0] = t4; } void setrot(struct MATRIX3D* m, long t0, long t1, long t2, long t3, long t4)//76970 TOCHECK { R11 = t0 >> 16; R12 = t0; R13 = t1 >> 16; R21 = t1; R22 = t2 >> 16; R23 = t2; R31 = t3 >> 16; R32 = t3; R33 = t4; ((int*)Matrix)[0] = t0; ((int*)Matrix)[1] = t1; ((int*)Matrix)[2] = t2; ((int*)Matrix)[3] = t3; ((int*)Matrix)[4] = t4; } void mLoadMatrix(struct MATRIX3D* m)//7699C(<), 789E0(<) TOCHECK { R11 = m->m00; R12 = m->m01; R13 = m->m02; R21 = m->m10; R22 = m->m11; R23 = m->m12; R31 = m->m20; R32 = m->m21; R33 = m->m22; TRX = m->tx; TRY = m->ty; TRZ = m->tz; return; } //Note: Original code is less optimal than this implementation. void mCopyMatrix(struct MATRIX3D* m)//769E4(<), 78A28(<) (F) TOCHECK { UNIMPLEMENTED(); } void ASM_GetBounds()//76A28 { UNIMPLEMENTED(); } void GetBounds()//76A28 { UNIMPLEMENTED(); } void mSetTrans(long x, long y, long z)//76AF4(<), 78B38(<) { TRX = x; TRY = y; TRZ = z; Matrix->tx = x; Matrix->ty = y; Matrix->tz = z; } void mClipBoundingBox(short* bounds)//76B14 { UNIMPLEMENTED(); } void InitInterpolation(long frac, long rate, struct MATRIX3D* m)//76CB4 { UNIMPLEMENTED(); } void iPushMatrix0()//76D3C(<), ?(<) (F) { UNIMPLEMENTED(); } void iPushMatrix(struct MATRIX3D* m)//81E60(<), ?(<) (F) { UNIMPLEMENTED(); } void iPopMatrix0() { UNIMPLEMENTED(); } void iPopMatrix(struct MATRIX3D* m, struct MATRIX3D* m2)//76D8C(<), ?(<) TOCHECK { UNIMPLEMENTED(); } void mPushMatrix0()//764D0 (F) { UNIMPLEMENTED(); } void mmPushMatrix(struct MATRIX3D* m)//81BBC(<) (F) { UNIMPLEMENTED(); } void SetRoomBounds(tr_room_portal* portal, int room_number, struct room_info* parent) { UNIMPLEMENTED(); } void GetRoomBoundsAsm(short room_number)//77E70(<), 79EB4(<) ///@TODO check if in right file { #if 0 GetRoomBoundsAsm: lui a1, 0x1F80 sw s0, 0xD8(a1) sw s1, 0xDC(a1) sw s2, 0xE0(a1) sw s3, 0xE4(a1) sw s4, 0xE8(a1) sw s5, 0xEC(a1) sw s6, 0xF0(a1) sw s7, 0xF4(a1) sw fp, 0xF8(a1) move s0, a1 lw s1, room - GP_ADDR(gp) move s2, zero li s3, 1 li s4, 0x1F8000FC move s5, zero lw fp, outside - GP_ADDR(gp) sb a0, 0(s0) sll a0, 4 sll at, a0, 2 add a0, at add a0, s1 lui t0, 0x1FF lui t1, 0xEF li t2, 2 sw t0, 0x40(a0) sw t1, 0x44(a0) sb t2, 0x37(a0) addiu t6, gp, CamPos - GP_ADDR cfc2 t1, r5 cfc2 t2, r6 cfc2 t3, r7 sw t1, 0xB0(s0) sw t2, 0xB4(s0) sw t3, 0xB8(s0) lw t1, 0(t6) lw t2, 4(t6) lw t3, 8(t6) sw t1, 0xBC(s0) sw t2, 0xC0(s0) sw t3, 0xC4(s0) loc_77F18: beq s2, s3, loc_78490 add t0, s0, s2 lbu s6, 0(t0) addi s2, 1 andi s2, 0x7F sll a0, s6, 4 sll at, a0, 2 add a0, at add a0, s1 lb v0, 0x37(a0) lw t1, 0x38(a0) addi v0, -2 lw t3, 0x3C(a0) lw t5, 0x40(a0) lw t7, 0x44(a0) srl t2, t1, 16 andi t1, 0xFFFF srl t4, t3, 16 andi t3, 0xFFFF srl t6, t5, 16 andi t5, 0xFFFF srl t8, t7, 16 andi t7, 0xFFFF slt at, t5, t1 beqz at, loc_77F84 slt at, t6, t2 move t1, t5 loc_77F84 : bnez at, loc_77F90 slt at, t7, t3 move t2, t6 loc_77F90 : beqz at, loc_77F9C slt at, t8, t4 move t3, t7 loc_77F9C : bnez at, loc_77FA8 sll t6, t2, 16 move t4, t8 loc_77FA8 : or t5, t1, t6 sll t6, t4, 16 or t6, t3 sw t5, 0x38(a0) sw t6, 0x3C(a0) andi at, v0, 1 bnez at, loc_77FD4 ori v0, 1 sh s6, 0(s4) addi s4, 2 addi s5, 1 loc_77FD4: lh s6, 0x4E(a0) sb v0, 0x37(a0) andi s6, 8 or fp, s6 lw s7, 4(a0) lw t0, 0x14(a0) beqz s7, loc_77F18 lw t1, 0x18(a0) lw t2, 0x1C(a0) bgez t0, loc_78018 sra t3, t0, 15 negu t0, t0 sra t3, t0, 15 andi t0, 0x7FFF negu t3, t3 j loc_7801C negu t0, t0 loc_78018 : andi t0, 0x7FFF loc_7801C : bgez t1, loc_7803C sra t4, t1, 15 negu t1, t1 sra t4, t1, 15 andi t1, 0x7FFF negu t4, t4 j loc_78040 negu t1, t1 loc_7803C : andi t1, 0x7FFF loc_78040 : bgez t2, loc_78060 sra t5, t2, 15 negu t2, t2 sra t5, t2, 15 andi t2, 0x7FFF negu t5, t5 j loc_78064 negu t2, t2 loc_78060 : andi t2, 0x7FFF loc_78064 : mtc2 t3, r9 mtc2 t4, r10 mtc2 t5, r11 nop nop cop2 0x41E012 lw t3, 0xB0(s0) lw t4, 0xB4(s0) lw t5, 0xB8(s0) ctc2 t3, r5 ctc2 t4, r6 ctc2 t5, r7 mfc2 t3, r25 mfc2 t4, r26 mtc2 t0, r9 mtc2 t1, r10 mtc2 t2, r11 mfc2 t5, r27 nop nop cop2 0x498012 bgez t3, loc_780C0 sll t0, t3, 3 negu t3, t3 sll t3, 3 negu t0, t3 loc_780C0 : bgez t4, loc_780D4 sll t1, t4, 3 negu t4, t4 sll t4, 3 negu t1, t4 loc_780D4 : bgez t5, loc_780E8 sll t2, t5, 3 negu t5, t5 sll t5, 3 negu t2, t5 loc_780E8 : mfc2 t3, r25 mfc2 t4, r26 mfc2 t5, r27 addu t0, t3 addu t1, t4 addu t2, t5 ctc2 t0, r5 ctc2 t1, r6 ctc2 t2, r7 lh v0, 0(s7) addi s7, 2 loc_78114: lh a1, 0(s7) addi s7, 2 lh t0, 0(s7) lw t1, 0x14(a0) beqz t0, loc_7814C lh t2, 6(s7) lw t3, 0xBC(s0) add t1, t2 sub t1, t3 beqz t1, loc_7847C xor t0, t1 bltz t0, loc_781A8 move a2, s7 j loc_7847C loc_7814C : lh t0, 2(s7) lw t1, 0x18(a0) beqz t0, loc_7817C lh t2, 8(s7) lw t3, 0xC0(s0) add t1, t2 sub t1, t3 beqz t1, loc_7847C xor t0, t1 bltz t0, loc_781A8 move a2, s7 j loc_7847C loc_7817C : lh t0, 4(s7) lw t1, 0x1C(a0) beqz t0, loc_7847C lh t2, 0xA(s7) lw t3, 0xC4(s0) add t1, t2 sub t1, t3 beqz t1, loc_7847C xor t0, t1 bgez t0, loc_7847C move a2, s7 loc_781A8 : sll a3, a1, 4 sll at, a3, 2 add a3, at add a3, s1 lw t0, 0x38(a3) lw t2, 0x40(a0) lw t4, 0x3C(a3) lw t6, 0x44(a0) srl t1, t0, 16 andi t0, 0xFFFF srl t3, t2, 16 andi t2, 0xFFFF srl t5, t4, 16 andi t4, 0xFFFF srl t7, t6, 16 andi t6, 0xFFFF slt at, t0, t2 beqz at, loc_78208 slt at, t1, t3 bnez at, loc_78208 slt at, t4, t6 beqz at, loc_78208 slt at, t5, t7 beqz at, loc_7847C loc_78208 : move t0, t3 move t1, t2 move t2, t7 move t3, t6 addi t4, s0, 0x80 move t5, zero move t6, zero li v1, 3 loc_78228: lhu t7, 6(a2) lhu t9, 8(a2) lhu t8, 0xA(a2) sll t9, 16 or t7, t9 mtc2 t7, r0 mtc2 t8, r1 addi a2, 6 nop nop cop2 0x480012 mfc2 t7, r9 mfc2 t8, r10 mfc2 t9, r11 cop2 0x180001 sw t7, 0(t4) sw t8, 4(t4) sw t9, 8(t4) bgtz t9, loc_78278 addi t4, 0xC j loc_782C8 addi t5, 1 loc_78278: slti at, t9, 0x5000 mfc2 t7, r14 bnez at, loc_7828C sra t8, t7, 16 addi t6, 1 loc_7828C : sll t7, 16 sra t7, 16 slt at, t7, t0 beqz at, loc_782A4 slt at, t7, t1 move t0, t7 loc_782A4 : bnez at, loc_782B0 slt at, t8, t2 move t1, t7 loc_782B0 : beqz at, loc_782BC slt at, t8, t3 move t2, t8 loc_782BC : bnez at, loc_782C8 nop move t3, t8 loc_782C8 : bnez v1, loc_78228 addi v1, -1 li at, 4 beq t5, at, loc_7847C addi t4, s0, 0x80 beq t6, at, loc_7847C li v1, 3 beqz t5, loc_78384 addi t5, t4, 0x24 loc_782EC: lw t6, 8(t4) lw t7, 8(t5) slti t8, t6, 1 slti t9, t7, 1 xor t8, t9 beqz t8, loc_78374 lw t6, 0(t4) lw t7, 0(t5) slt t8, t6, zero slt t9, t7, zero and t8, t9 beqz t8, loc_78328 slt t8, zero, t6 j loc_7833C move t0, zero loc_78328 : slt t9, zero, t7 and t8, t9 bnez t8, loc_7833C li t1, 0x1FF move t0, zero loc_7833C : lw t6, 4(t4) lw t7, 4(t5) slt t8, t6, zero slt t9, t7, zero and t8, t9 beqz t8, loc_78360 slt t8, zero, t6 j loc_78374 move t2, zero loc_78360 : slt t9, zero, t7 and t8, t9 bnez t8, loc_78374 li t3, 0xEF move t2, zero loc_78374 : move t5, t4 addi t4, 0xC bnez v1, loc_782EC addi v1, -1 loc_78384 : lw t4, 0x40(a0) lw t6, 0x44(a0) srl t5, t4, 16 andi t4, 0xFFFF srl t7, t6, 16 andi t6, 0xFFFF slt at, t0, t4 beqz at, loc_783AC slt at, t5, t1 move t0, t4 loc_783AC : beqz at, loc_783B8 slt at, t2, t6 move t1, t5 loc_783B8 : beqz at, loc_783C4 slt at, t7, t3 move t2, t6 loc_783C4 : beqz at, loc_783D0 sub at, t0, t1 move t3, t7 loc_783D0 : bgez at, loc_7847C sub at, t2, t3 bgez at, loc_7847C lb v1, 0x37(a3) add t4, s0, s3 andi at, v1, 2 bnez at, loc_7841C ori v1, 2 sb a1, 0(t4) addi s3, 1 andi s3, 0x7F sll t1, 16 or t0, t1 sll t3, 16 or t2, t3 sw t0, 0x40(a3) sw t2, 0x44(a3) j loc_7847C sb v1, 0x37(a3) loc_7841C: lw t4, 0x40(a3) lw t6, 0x44(a3) srl t5, t4, 16 andi t4, 0xFFFF srl t7, t6, 16 andi t6, 0xFFFF slt at, t0, t4 beqz at, loc_78444 slt at, t5, t1 move t4, t0 loc_78444 : beqz at, loc_78450 slt at, t2, t6 move t5, t1 loc_78450 : beqz at, loc_7845C slt at, t7, t3 move t6, t2 loc_7845C : beqz at, loc_78468 sll t5, 16 move t7, t3 loc_78468 : or t4, t5 sll t7, 16 or t6, t7 sw t4, 0x40(a3) sw t6, 0x44(a3) loc_7847C : addi v0, -1 bgtz v0, loc_78114 addi s7, 0x1E j loc_77F18 nop loc_78490 : addiu t0, gp, draw_rooms - GP_ADDR li s4, 0x1F8000FC addiu v0, s5, -1 move s5, zero loc_784A4 : lh a1, 0(s4) addi s4, 2 sh a1, 0(t0) addiu t0, 2 addiu s5, 1 bgtz v0, loc_784A4 addi v0, -1 sw s5, number_draw_rooms - GP_ADDR(gp) sw fp, outside - GP_ADDR(gp) lui a0, 0x1F80 lw s0, 0xD8(a0) lw s1, 0xDC(a0) lw s2, 0xE0(a0) lw s3, 0xE4(a0) lw s4, 0xE8(a0) lw s5, 0xEC(a0) lw s6, 0xF0(a0) lw s7, 0xF4(a0) jr ra lw fp, 0xF8(a0) #endif UNIMPLEMENTED(); } void phd_GetVectorAngles(long dx, long dy, long dz, short* angles)//77928 { int t0, t1, t2; t0 = dx; t1 = dy; t2 = dz; angles[0] = phd_atan_asm(dz, dx); goto loc_7795C; loc_77950: t0 >>= 2; t1 >>= 2; t2 >>= 2; loc_7795C: if (((t0 << 16) >> 16) != t0) { goto loc_77950; } if (((t1 << 16) >> 16) != t1) { goto loc_77950; } if (((t2 << 16) >> 16) != t2) { goto loc_77950; } IR1 = t0; IR2 = t2; docop2(0xA00428); int v0 = phd_atan_asm(mSqrt(MAC1 + MAC2), t1); if (t1 > 0 && (v0 << 16) > 0 || t1 < 0 && (v0 << 16) < 0) { v0 = -v0; } angles[1] = v0; } void phd_LookAt(long xsrc, long ysrc, long zsrc, long xtar, long ytar, long ztar, long roll) { short temp; CamPos.x = xsrc; CamPos.y = ysrc; CamPos.z = zsrc; viewer.x_pos = xsrc; viewer.y_pos = ysrc; viewer.z_pos = zsrc; viewer.z_rot = roll; phd_GetVectorAngles(xtar - xsrc, ytar - ysrc, ztar - zsrc, &viewer.x_rot); temp = viewer.y_rot; viewer.y_rot = viewer.x_rot; viewer.x_rot = temp; phd_GenerateW2V(&viewer); } void phd_GenerateW2V(struct PHD_3DPOS* view) { int t0, t1, t2, t3, t4, t5, t6, v0, v1, a0, a1, a2, a3, at; a2 = view->x_rot; v1 = view->y_rot; t0 = SIN(a2); t2 = SIN(v1); a1 = view->z_rot; t4 = (t0 * t2) >> 12; t3 = COS(v1); t1 = SIN(a1); t5 = t4 * t1; phd_mxptr = &matrix_stack[0]; v1 = t0 * t3; v0 = COS(a2); t0 = -t0; matrix_stack[9] = t0; w2v_matrix[9] = t0; t6 = v0 * t1; a1 = COS(a1); v1 >>= 12; t6 >>= 12; matrix_stack[1] = t6; w2v_matrix[1] = t6; t6 = (v1 * t1) >> 12; a3 = (t2 * a1) >> 12; t6 -= a3; matrix_stack[2] = t6; w2v_matrix[2] = t6; t6 = t4 * a1; a3 = view->x_pos; t4 = view->y_pos; a0 = view->z_pos; matrix_stack[3] = a3; w2v_matrix[3] = a3; matrix_stack[7] = t4; w2v_matrix[7] = t4; a3 = t3 * t1; matrix_stack[11] = a0; w2v_matrix[11] = a0; t4 = (v0 * a1) >> 14; t0 = (v0 * a1) >> 12; w2v_matrix[5] = t0; a2 = (v0 * t2) >> 12; t0 -= t4; matrix_stack[8] = a2; w2v_matrix[8] = a2; matrix_stack[5] = t0; a2 = (v0 * t3) >> 12; t6 >>= 12; matrix_stack[10] = a2; w2v_matrix[10] = a2; t0 = v1 * a1; a3 >>= 12; t6 -= a3; a2 = t2 * t1; w2v_matrix[4] = t6; at = t6 >> 2; t6 -= at; matrix_stack[4] = t6; t0 >>= 12; v0 = a2 >> 12; t0 += v0; w2v_matrix[6] = t0; at = t0 >> 2; t0 -= at; matrix_stack[6] = t0; v0 = t5 >> 12; v1 = (t3 * a1) >> 12; v0 += v1; matrix_stack[0] = v0; w2v_matrix[0] = v0; } long phd_atan_asm(long x, long y)// (F) { int a2, a3, v0; if (x == 0 && y == 0) { return 0; } a2 = 0; if (x < 0) { a2 = 4; x = -x; } //loc_77A64 if (y < 0) { a2 += 2; y = -y; } v0 = x; if (x < y) { a2 += 1; x = y; y = v0; } else { //loc_77A90 goto loc_77A98; } loc_77A90: y >>= 1; x >>= 1; loc_77A98: v0 = (y << 16) >> 16; if (v0 != y) { goto loc_77A90; }//loc_77A90 v0 = y << 11; a3 = (v0 / x); v0 = atanOctantTab[a2]; x = atanTab[a3]; v0 = x + v0; if (v0 < 0) { v0 = -v0; } return v0; } void mRotBoundingBoxNoPersp(short* bounds, short* tbounds) { UNIMPLEMENTED(); } Update MATHS.C Add mRotZ #include "MATHS.H" #include "LOAD_LEV.H" #include "SPECIFIC.H" #include <INLINE_C.H> #include "3D_GEN.H" #include "CAMERA.H" #include "DRAW.H" #include "GPU.H" #include "GTEREG.H" #include "DRAWSPKS.H" void mQuickW2VMatrix()//77AEC(<), 79B30(<) { MatrixSP = 0; Matrix = &MatrixStack[0]; ((int*)&MatrixStack)[0] = ((unsigned short*)phd_mxptr)[0] | ((unsigned short*)phd_mxptr)[2] << 16; ((int*)&MatrixStack)[1] = ((unsigned short*)phd_mxptr)[4] | ((unsigned short*)phd_mxptr)[8] << 16; ((int*)&MatrixStack)[2] = ((unsigned short*)phd_mxptr)[10] | ((unsigned short*)phd_mxptr)[12] << 16; ((int*)&MatrixStack)[3] = ((unsigned short*)phd_mxptr)[16] | ((unsigned short*)phd_mxptr)[18] << 16; R12 = ((short*)phd_mxptr)[2] << 16; R11 = ((short*)phd_mxptr)[0]; R21 = ((short*)phd_mxptr)[8] << 16; R13 = ((short*)phd_mxptr)[4]; R23 = ((short*)phd_mxptr)[12] << 16; R22 = ((short*)phd_mxptr)[10]; R32 = ((short*)phd_mxptr)[18] << 16; R31 = ((short*)phd_mxptr)[16]; ((short*)&MatrixStack)[8] = ((unsigned short*)phd_mxptr)[20]; ((short*)&MatrixStack)[10] = ((unsigned short*)phd_mxptr)[6]; ((short*)&MatrixStack)[12] = ((unsigned short*)phd_mxptr)[14]; ((short*)&MatrixStack)[14] = ((unsigned short*)phd_mxptr)[22]; R33 = ((unsigned short*)phd_mxptr)[20]; TRX = ((unsigned short*)phd_mxptr)[6]; TRY = ((unsigned short*)phd_mxptr)[14]; TRZ = ((unsigned short*)phd_mxptr)[22]; CamGTE.m00 = ((unsigned short*)&w2v_matrix)[0]; CamGTE.m01 = ((unsigned short*)&w2v_matrix)[2]; CamGTE.m02 = ((unsigned short*)&w2v_matrix)[4]; CamGTE.m10 = ((unsigned short*)&w2v_matrix)[8]; CamGTE.m11 = ((unsigned short*)&w2v_matrix)[10]; CamGTE.m12 = ((unsigned short*)&w2v_matrix)[12]; CamGTE.m20 = ((unsigned short*)&w2v_matrix)[16]; CamGTE.m21 = ((unsigned short*)&w2v_matrix)[18]; CamGTE.m22 = ((unsigned short*)&w2v_matrix)[20]; } void gte_sttr(struct PHD_VECTOR* vec)//To investigate, this should not be in this file. { vec->x = Matrix->tx >> 12; vec->y = Matrix->ty >> 12; vec->z = Matrix->tz >> 12; } long mGetAngle(long x, long z, long tx, long tz)//77678(<), 796BC(<) (F) { long dx = tx - x; long dz = tz - z; short table_index = 0; long result_angle = 0; long temp = 0; if ((dx | dz) != 0) { if (dx < 0) { table_index |= 0x10;//FIXME: += (4); dx = -dx; } //0x796E0 if (dz < 0) { table_index += 2; dz = -dz; } //796F0 if (dx < dz) { table_index += 1; temp = dx; dx = dz; dz = temp; } //7970C while (dz / 65536 != 0) { dx /= 2; dz /= 2; } //79724 result_angle = atanTab[dz * 2048 / dx]; result_angle += atanOctantTab[table_index]; if (result_angle < 0) { result_angle = -result_angle; }//79760 }//79760 return -result_angle & 0xFFFF; } long mSqrt(long value)//83B30(<), 85B74(<) (F) { long v0 = 0x1F; long v1 = gte_ldlzc(value); if (value != 0) { v1 &= 0xFFFFFFFE; v0 = v0 - v1 >> 1; long at = v1 - 0x18; if (v1 - 0x18 < 0) { //loc_85BA8 value >>= 0x18 - v1; } else { value <<= v1 - 0x18; } //loc_85BB4 value = SqrtTable[value - 0x40] << v0; }//locret_85BD0 return (value >> 12); } long phd_sqrt_asm(long value)//83B30(<), 85B74(<) (F) { long v0 = 0x1F; long v1 = gte_ldlzc(value); if (value != 0) { v1 &= 0xFFFFFFFE; v0 = v0 - v1 >> 1; long at = v1 - 0x18; if (v1 - 0x18 < 0) { //loc_85BA8 value >>= 0x18 - v1; } else { value <<= v1 - 0x18; } //loc_85BB4 value = SqrtTable[value - 0x40] << v0; }//locret_85BD0 return (value >> 12); } void ScaleCurrentMatrix(long bStoreInMatrix, long sx, long sy, long sz) { int t2, v0, v1; unsigned int t0, t1, at; t0 = R11; t1 = R13; t2 = R22; v0 = R31; v1 = R33; R12 = ((((t0 << 16) >> 16) * sx) >> 12) & 0xFFFF; R11 = ((((t0 >> 16) * sy) >> 12) << 16); R21 = ((((t1 << 16) >> 16) * sz) >> 12) & 0xFFFF; R13 = (((t1 >> 16) * sx) >> 12) << 16; R23 = ((((t2 << 16) >> 16) * sy) >> 12) & 0xFFFF; R22 = (((t2 >> 16) * sz) >> 12) << 16; R32 = ((((v0 << 16) >> 16) * sx) >> 12) & 0xFFFF; R31 = (((v0 >> 16) * sy) >> 12) << 16; R33 = ((((v1 << 16) >> 16) * sz) >> 12); if (bStoreInMatrix) { Matrix->m00 = R11; Matrix->m01 = R12; Matrix->m02 = R13; Matrix->m10 = R21; Matrix->m11 = R22; Matrix->m12 = R23; Matrix->m20 = R31; Matrix->m21 = R32; Matrix->m22 = R33; }//locret_77E68 } void mPushMatrix()//764D0(<), 78514(<) (F) { ++Matrix; Matrix->m00 = R11; Matrix->m01 = R12; Matrix->m02 = R13; Matrix->m10 = R21; Matrix->m11 = R22; Matrix->m12 = R23; Matrix->m20 = R31; Matrix->m21 = R32; Matrix->m22 = R33; Matrix->tx = TRX; Matrix->ty = TRY; Matrix->tz = TRZ; } void mPopMatrix()//76520(<), 78564(<) (F) { mLoadMatrix(--Matrix); } void mUnitMatrix() { UNIMPLEMENTED(); } void mPushUnitMatrix()//76534(<), 78578(<) { setrot(++Matrix, 0x1000, 0, 0x1000, 0, 0x1000); } void mTranslate()//76558(<) (!) { UNIMPLEMENTED(); } void mTranslateAbsXYZ(long x, long y, long z) { mTranslateXYZ(x - MatrixStack[0].tx, y - MatrixStack[0].ty, z - MatrixStack[0].tz); } void mTranslateXYZ(long x, long y, long z)//7658C(<), 785D0(<) (!) { int t0; int t1; int t2; int t3; int t4; int t5; t4 = y >> 15; if (y < 0) { y = -y; t4 = y >> 15; y &= 0x7FFF; t4 = -t4; y = -y; }//loc_765AC else { y &= 0x7FFF; } //loc_765B0 : t5 = z >> 15; if (z < 0) { z = -z; t5 = z >> 15; z &= 0x7FFF; t5 = -t5; z = -z; } else { //loc_765D0 z &= 0x7FFF; } //loc_765D4 t3 = x >> 15; if (x < 0) { x = -x; t3 = x >> 15; x &= 0x7FFF; t3 = -t3; x = -x; } else { x &= 0x7FFF; } IR1 = t3; IR2 = t4; IR3 = t5; docop2(0x41E012); t3 = MAC1; t4 = MAC2; t5 = MAC3; IR1 = x; IR2 = y; IR3 = z; docop2(0x498012); t0 = t3 << 3; if (t3 < 0) { t3 = -t3; t3 <<= 3; t0 = -t3; } //loc_7663C t1 = t4 << 3; if (t4 < 0) { t4 = -t4; t4 <<= 3; t1 = -t4; } //loc_76650 t2 = t5 << 3; if (t5 < 0) { t5 = -t5; t5 <<= 3; t2 = -t5; }//loc_76664 t3 = MAC1; t4 = MAC2; t5 = MAC3; t0 += t3; t1 += t4; t2 += t5; TRX = t0; TRY = t1; TRZ = t2; Matrix->tx = t0; Matrix->ty = t1; Matrix->tz = t2; } void mRotX(long rx)//7669C (F) { int t0; int t1; int t2; int t3; int t4; int t5; int t6; rx = (rx >> 2) & 0x3FFC; if (rx != 0) { //loc_766B4 t5 = (rcossin_tbl[rx >> 1] & 0xFFFF) | ((rcossin_tbl[rx >> 1 | 1] & 0xFFFF ) << 16); VX0 = (0xFFFF0000 & t5) & 0xFFFF; VY0 = ((0xFFFF0000 & t5) >> 16) & 0xFFFF; VZ0 = t5 & 0xFFFF; t0 = (R12 << 16 | R11) & 0xFFFF; t1 = (R21 << 16 | R13) & 0xFFFF0000; t3 = (R32 << 16 | R31) & 0xFFFF; docop2(0x486012); t6 = t5 >> 16; t5 <<= 16; t5 = -t5; VX1 = t5; VY1 = (t5 >> 16) & 0xFFFF; VZ1 = t6; t4 = MAC1; t2 = MAC2 & 0xFFFF; t5 = MAC3; docop2(0x48E012); t0 |= t4 << 16; t3 |= t5 << 16; t5 = MAC1 & 0xFFFF; t6 = MAC2; t4 = MAC3; t1 |= t5; t2 |= t6 << 16; SetRotation(t0, t1, t2, t3, t4); } } void mRotY(long ry)//76744 (F) { int t0; int t1; int t2; int t3; int t4; int t5; int t6; int t7; ry = (ry >> 2) & 0x3FFC; if (ry != 0) { t5 = rcossin_tbl[ry]; t6 = t5 >> 16; t5 &= 0xFFFF; t2 = -t5; VX0 = t6; VZ0 = t2; t0 = (R12 << 16 | R11) & 0xFFFF0000; t2 = (R23 << 16 | R22) & 0xFFFF; t3 = (R32 << 16 | R31) & 0xFFFF0000; docop2(0x486012); VX1 = t5; VZ1 = t6; t4 = MAC1; t1 = MAC2; t5 = MAC3; docop2(0x48E012); t0 |= (t4 & 0xFFFF); t3 |= (t5 & 0xFFFF); t1 = (t1 << 16) | (t5 & 0xFFFF); t5 = MAC1; t6 = MAC2; t4 = MAC3; t2 |= t6 << 16; SetRotation(t0, t1, t2, t3, t4); } } void mRotYXZ(short y, short x, short z)//767E8 (F) { //mRotY(y); //mRotX(x); mRotZ(z); } void mRotZ(long rz)//76804 (F) { int t0; int t1; int t2; int t3; int t4; int t5; int t6; int t7; int a0; rz = (rz >> 2) & 0x3FFC; if (rz != 0) { //loc_7681C t0 = (rcossin_tbl[rz >> 1] & 0xFFFF) | ((rcossin_tbl[rz >> 1 | 1] & 0xFFFF) << 16); t1 = ((t0 >> 16) & 0xFFFF) | (t0 << 16); VX0 = (t1 & 0xFFFF); VY0 = ((t1 >> 16) & 0xFFFF); VZ0 = 0; t1 = (R21 << 16 | R13) & 0xFFFF; t2 = (R23 << 16 | R22) & 0xFFFF0000; t4 = R33; docop2(0x486012); t3 = t0 & 0xFFFF0000; t0 &= 0xFFFF; t0 = -t0; t0 &= 0xFFFF; t0 |= t3; VX1 = t0; VY1 = (t0 >> 16) & 0xFFFF; VZ1 = 0; t0 = MAC1 & 0xFFFF; t5 = MAC2; t3 = MAC3 & 0xFFFF; docop2(0x48E012); t5 <<= 16; t1 |= t5; t5 = MAC1; t6 = MAC2 & 0xFFFF; a0 = MAC3; t0 |= t5 << 16; t2 |= t6; t3 |= a0 << 16; SetRotation(t0, t1, t2, t3, t4); } } void mRotSuperPackedYXZ(short** a0, long a1)//768BC { unsigned short* a2; int v0; int at; a2 = (unsigned short*)a0[0]; if (a1 != 0) { //loc_768C4 do { v0 = *a2++; a1--; if (!(v0 & 0xC000)) { a2++; }//loc_768DC } while (a1 == 0); }//loc_768E8 v0 = *a2++; at = (v0 >> 14); at--; if (at != 0) { a0[0] = (short*)a2; if (at != 0) { mRotZ((v0 & 0xFFF) << 4); }//loc_76914 mRotY((v0 & 0xFFF) << 4); mRotX((v0 & 0xFFF) << 4); }//loc_76928 at = *a2++; a0[0] = (short*)a2; mRotY((((v0 << 16) | at) >> 4) & 0xFFC0); mRotX((((v0 << 16) | at) >> 14) & 0xFFC0); mRotZ((((v0 << 16) | at) & 0x3FF) << 6); } void mRotPackedYXZ(long yxz)//7693C (F) { UNIMPLEMENTED(); } void SetRotation(int t0, int t1, int t2, int t3, int t4)//7696C(<) (F) { R11 = t0 & 0xFFFF; R12 = t0 >> 16; R13 = t1 & 0xFFFF; R21 = t1 >> 16; R22 = t2 & 0xFFFF; R23 = t2 >> 16; R31 = t3 & 0xFFFF; R32 = t3 >> 16; R33 = t4; ((int*)&Matrix->m00)[0] = t0; ((int*)&Matrix->m02)[0] = t1; ((int*)&Matrix->m11)[0] = t2; ((int*)&Matrix->m20)[0] = t3; ((int*)&Matrix->m22)[0] = t4; } void setrot(struct MATRIX3D* m, long t0, long t1, long t2, long t3, long t4)//76970 TOCHECK { R11 = t0 >> 16; R12 = t0; R13 = t1 >> 16; R21 = t1; R22 = t2 >> 16; R23 = t2; R31 = t3 >> 16; R32 = t3; R33 = t4; ((int*)Matrix)[0] = t0; ((int*)Matrix)[1] = t1; ((int*)Matrix)[2] = t2; ((int*)Matrix)[3] = t3; ((int*)Matrix)[4] = t4; } void mLoadMatrix(struct MATRIX3D* m)//7699C(<), 789E0(<) TOCHECK { R11 = m->m00; R12 = m->m01; R13 = m->m02; R21 = m->m10; R22 = m->m11; R23 = m->m12; R31 = m->m20; R32 = m->m21; R33 = m->m22; TRX = m->tx; TRY = m->ty; TRZ = m->tz; return; } //Note: Original code is less optimal than this implementation. void mCopyMatrix(struct MATRIX3D* m)//769E4(<), 78A28(<) (F) TOCHECK { UNIMPLEMENTED(); } void ASM_GetBounds()//76A28 { UNIMPLEMENTED(); } void GetBounds()//76A28 { UNIMPLEMENTED(); } void mSetTrans(long x, long y, long z)//76AF4(<), 78B38(<) { TRX = x; TRY = y; TRZ = z; Matrix->tx = x; Matrix->ty = y; Matrix->tz = z; } void mClipBoundingBox(short* bounds)//76B14 { UNIMPLEMENTED(); } void InitInterpolation(long frac, long rate, struct MATRIX3D* m)//76CB4 { UNIMPLEMENTED(); } void iPushMatrix0()//76D3C(<), ?(<) (F) { UNIMPLEMENTED(); } void iPushMatrix(struct MATRIX3D* m)//81E60(<), ?(<) (F) { UNIMPLEMENTED(); } void iPopMatrix0() { UNIMPLEMENTED(); } void iPopMatrix(struct MATRIX3D* m, struct MATRIX3D* m2)//76D8C(<), ?(<) TOCHECK { UNIMPLEMENTED(); } void mPushMatrix0()//764D0 (F) { UNIMPLEMENTED(); } void mmPushMatrix(struct MATRIX3D* m)//81BBC(<) (F) { UNIMPLEMENTED(); } void SetRoomBounds(tr_room_portal* portal, int room_number, struct room_info* parent) { UNIMPLEMENTED(); } void GetRoomBoundsAsm(short room_number)//77E70(<), 79EB4(<) ///@TODO check if in right file { #if 0 GetRoomBoundsAsm: lui a1, 0x1F80 sw s0, 0xD8(a1) sw s1, 0xDC(a1) sw s2, 0xE0(a1) sw s3, 0xE4(a1) sw s4, 0xE8(a1) sw s5, 0xEC(a1) sw s6, 0xF0(a1) sw s7, 0xF4(a1) sw fp, 0xF8(a1) move s0, a1 lw s1, room - GP_ADDR(gp) move s2, zero li s3, 1 li s4, 0x1F8000FC move s5, zero lw fp, outside - GP_ADDR(gp) sb a0, 0(s0) sll a0, 4 sll at, a0, 2 add a0, at add a0, s1 lui t0, 0x1FF lui t1, 0xEF li t2, 2 sw t0, 0x40(a0) sw t1, 0x44(a0) sb t2, 0x37(a0) addiu t6, gp, CamPos - GP_ADDR cfc2 t1, r5 cfc2 t2, r6 cfc2 t3, r7 sw t1, 0xB0(s0) sw t2, 0xB4(s0) sw t3, 0xB8(s0) lw t1, 0(t6) lw t2, 4(t6) lw t3, 8(t6) sw t1, 0xBC(s0) sw t2, 0xC0(s0) sw t3, 0xC4(s0) loc_77F18: beq s2, s3, loc_78490 add t0, s0, s2 lbu s6, 0(t0) addi s2, 1 andi s2, 0x7F sll a0, s6, 4 sll at, a0, 2 add a0, at add a0, s1 lb v0, 0x37(a0) lw t1, 0x38(a0) addi v0, -2 lw t3, 0x3C(a0) lw t5, 0x40(a0) lw t7, 0x44(a0) srl t2, t1, 16 andi t1, 0xFFFF srl t4, t3, 16 andi t3, 0xFFFF srl t6, t5, 16 andi t5, 0xFFFF srl t8, t7, 16 andi t7, 0xFFFF slt at, t5, t1 beqz at, loc_77F84 slt at, t6, t2 move t1, t5 loc_77F84 : bnez at, loc_77F90 slt at, t7, t3 move t2, t6 loc_77F90 : beqz at, loc_77F9C slt at, t8, t4 move t3, t7 loc_77F9C : bnez at, loc_77FA8 sll t6, t2, 16 move t4, t8 loc_77FA8 : or t5, t1, t6 sll t6, t4, 16 or t6, t3 sw t5, 0x38(a0) sw t6, 0x3C(a0) andi at, v0, 1 bnez at, loc_77FD4 ori v0, 1 sh s6, 0(s4) addi s4, 2 addi s5, 1 loc_77FD4: lh s6, 0x4E(a0) sb v0, 0x37(a0) andi s6, 8 or fp, s6 lw s7, 4(a0) lw t0, 0x14(a0) beqz s7, loc_77F18 lw t1, 0x18(a0) lw t2, 0x1C(a0) bgez t0, loc_78018 sra t3, t0, 15 negu t0, t0 sra t3, t0, 15 andi t0, 0x7FFF negu t3, t3 j loc_7801C negu t0, t0 loc_78018 : andi t0, 0x7FFF loc_7801C : bgez t1, loc_7803C sra t4, t1, 15 negu t1, t1 sra t4, t1, 15 andi t1, 0x7FFF negu t4, t4 j loc_78040 negu t1, t1 loc_7803C : andi t1, 0x7FFF loc_78040 : bgez t2, loc_78060 sra t5, t2, 15 negu t2, t2 sra t5, t2, 15 andi t2, 0x7FFF negu t5, t5 j loc_78064 negu t2, t2 loc_78060 : andi t2, 0x7FFF loc_78064 : mtc2 t3, r9 mtc2 t4, r10 mtc2 t5, r11 nop nop cop2 0x41E012 lw t3, 0xB0(s0) lw t4, 0xB4(s0) lw t5, 0xB8(s0) ctc2 t3, r5 ctc2 t4, r6 ctc2 t5, r7 mfc2 t3, r25 mfc2 t4, r26 mtc2 t0, r9 mtc2 t1, r10 mtc2 t2, r11 mfc2 t5, r27 nop nop cop2 0x498012 bgez t3, loc_780C0 sll t0, t3, 3 negu t3, t3 sll t3, 3 negu t0, t3 loc_780C0 : bgez t4, loc_780D4 sll t1, t4, 3 negu t4, t4 sll t4, 3 negu t1, t4 loc_780D4 : bgez t5, loc_780E8 sll t2, t5, 3 negu t5, t5 sll t5, 3 negu t2, t5 loc_780E8 : mfc2 t3, r25 mfc2 t4, r26 mfc2 t5, r27 addu t0, t3 addu t1, t4 addu t2, t5 ctc2 t0, r5 ctc2 t1, r6 ctc2 t2, r7 lh v0, 0(s7) addi s7, 2 loc_78114: lh a1, 0(s7) addi s7, 2 lh t0, 0(s7) lw t1, 0x14(a0) beqz t0, loc_7814C lh t2, 6(s7) lw t3, 0xBC(s0) add t1, t2 sub t1, t3 beqz t1, loc_7847C xor t0, t1 bltz t0, loc_781A8 move a2, s7 j loc_7847C loc_7814C : lh t0, 2(s7) lw t1, 0x18(a0) beqz t0, loc_7817C lh t2, 8(s7) lw t3, 0xC0(s0) add t1, t2 sub t1, t3 beqz t1, loc_7847C xor t0, t1 bltz t0, loc_781A8 move a2, s7 j loc_7847C loc_7817C : lh t0, 4(s7) lw t1, 0x1C(a0) beqz t0, loc_7847C lh t2, 0xA(s7) lw t3, 0xC4(s0) add t1, t2 sub t1, t3 beqz t1, loc_7847C xor t0, t1 bgez t0, loc_7847C move a2, s7 loc_781A8 : sll a3, a1, 4 sll at, a3, 2 add a3, at add a3, s1 lw t0, 0x38(a3) lw t2, 0x40(a0) lw t4, 0x3C(a3) lw t6, 0x44(a0) srl t1, t0, 16 andi t0, 0xFFFF srl t3, t2, 16 andi t2, 0xFFFF srl t5, t4, 16 andi t4, 0xFFFF srl t7, t6, 16 andi t6, 0xFFFF slt at, t0, t2 beqz at, loc_78208 slt at, t1, t3 bnez at, loc_78208 slt at, t4, t6 beqz at, loc_78208 slt at, t5, t7 beqz at, loc_7847C loc_78208 : move t0, t3 move t1, t2 move t2, t7 move t3, t6 addi t4, s0, 0x80 move t5, zero move t6, zero li v1, 3 loc_78228: lhu t7, 6(a2) lhu t9, 8(a2) lhu t8, 0xA(a2) sll t9, 16 or t7, t9 mtc2 t7, r0 mtc2 t8, r1 addi a2, 6 nop nop cop2 0x480012 mfc2 t7, r9 mfc2 t8, r10 mfc2 t9, r11 cop2 0x180001 sw t7, 0(t4) sw t8, 4(t4) sw t9, 8(t4) bgtz t9, loc_78278 addi t4, 0xC j loc_782C8 addi t5, 1 loc_78278: slti at, t9, 0x5000 mfc2 t7, r14 bnez at, loc_7828C sra t8, t7, 16 addi t6, 1 loc_7828C : sll t7, 16 sra t7, 16 slt at, t7, t0 beqz at, loc_782A4 slt at, t7, t1 move t0, t7 loc_782A4 : bnez at, loc_782B0 slt at, t8, t2 move t1, t7 loc_782B0 : beqz at, loc_782BC slt at, t8, t3 move t2, t8 loc_782BC : bnez at, loc_782C8 nop move t3, t8 loc_782C8 : bnez v1, loc_78228 addi v1, -1 li at, 4 beq t5, at, loc_7847C addi t4, s0, 0x80 beq t6, at, loc_7847C li v1, 3 beqz t5, loc_78384 addi t5, t4, 0x24 loc_782EC: lw t6, 8(t4) lw t7, 8(t5) slti t8, t6, 1 slti t9, t7, 1 xor t8, t9 beqz t8, loc_78374 lw t6, 0(t4) lw t7, 0(t5) slt t8, t6, zero slt t9, t7, zero and t8, t9 beqz t8, loc_78328 slt t8, zero, t6 j loc_7833C move t0, zero loc_78328 : slt t9, zero, t7 and t8, t9 bnez t8, loc_7833C li t1, 0x1FF move t0, zero loc_7833C : lw t6, 4(t4) lw t7, 4(t5) slt t8, t6, zero slt t9, t7, zero and t8, t9 beqz t8, loc_78360 slt t8, zero, t6 j loc_78374 move t2, zero loc_78360 : slt t9, zero, t7 and t8, t9 bnez t8, loc_78374 li t3, 0xEF move t2, zero loc_78374 : move t5, t4 addi t4, 0xC bnez v1, loc_782EC addi v1, -1 loc_78384 : lw t4, 0x40(a0) lw t6, 0x44(a0) srl t5, t4, 16 andi t4, 0xFFFF srl t7, t6, 16 andi t6, 0xFFFF slt at, t0, t4 beqz at, loc_783AC slt at, t5, t1 move t0, t4 loc_783AC : beqz at, loc_783B8 slt at, t2, t6 move t1, t5 loc_783B8 : beqz at, loc_783C4 slt at, t7, t3 move t2, t6 loc_783C4 : beqz at, loc_783D0 sub at, t0, t1 move t3, t7 loc_783D0 : bgez at, loc_7847C sub at, t2, t3 bgez at, loc_7847C lb v1, 0x37(a3) add t4, s0, s3 andi at, v1, 2 bnez at, loc_7841C ori v1, 2 sb a1, 0(t4) addi s3, 1 andi s3, 0x7F sll t1, 16 or t0, t1 sll t3, 16 or t2, t3 sw t0, 0x40(a3) sw t2, 0x44(a3) j loc_7847C sb v1, 0x37(a3) loc_7841C: lw t4, 0x40(a3) lw t6, 0x44(a3) srl t5, t4, 16 andi t4, 0xFFFF srl t7, t6, 16 andi t6, 0xFFFF slt at, t0, t4 beqz at, loc_78444 slt at, t5, t1 move t4, t0 loc_78444 : beqz at, loc_78450 slt at, t2, t6 move t5, t1 loc_78450 : beqz at, loc_7845C slt at, t7, t3 move t6, t2 loc_7845C : beqz at, loc_78468 sll t5, 16 move t7, t3 loc_78468 : or t4, t5 sll t7, 16 or t6, t7 sw t4, 0x40(a3) sw t6, 0x44(a3) loc_7847C : addi v0, -1 bgtz v0, loc_78114 addi s7, 0x1E j loc_77F18 nop loc_78490 : addiu t0, gp, draw_rooms - GP_ADDR li s4, 0x1F8000FC addiu v0, s5, -1 move s5, zero loc_784A4 : lh a1, 0(s4) addi s4, 2 sh a1, 0(t0) addiu t0, 2 addiu s5, 1 bgtz v0, loc_784A4 addi v0, -1 sw s5, number_draw_rooms - GP_ADDR(gp) sw fp, outside - GP_ADDR(gp) lui a0, 0x1F80 lw s0, 0xD8(a0) lw s1, 0xDC(a0) lw s2, 0xE0(a0) lw s3, 0xE4(a0) lw s4, 0xE8(a0) lw s5, 0xEC(a0) lw s6, 0xF0(a0) lw s7, 0xF4(a0) jr ra lw fp, 0xF8(a0) #endif UNIMPLEMENTED(); } void phd_GetVectorAngles(long dx, long dy, long dz, short* angles)//77928 { int t0, t1, t2; t0 = dx; t1 = dy; t2 = dz; angles[0] = phd_atan_asm(dz, dx); goto loc_7795C; loc_77950: t0 >>= 2; t1 >>= 2; t2 >>= 2; loc_7795C: if (((t0 << 16) >> 16) != t0) { goto loc_77950; } if (((t1 << 16) >> 16) != t1) { goto loc_77950; } if (((t2 << 16) >> 16) != t2) { goto loc_77950; } IR1 = t0; IR2 = t2; docop2(0xA00428); int v0 = phd_atan_asm(mSqrt(MAC1 + MAC2), t1); if (t1 > 0 && (v0 << 16) > 0 || t1 < 0 && (v0 << 16) < 0) { v0 = -v0; } angles[1] = v0; } void phd_LookAt(long xsrc, long ysrc, long zsrc, long xtar, long ytar, long ztar, long roll) { short temp; CamPos.x = xsrc; CamPos.y = ysrc; CamPos.z = zsrc; viewer.x_pos = xsrc; viewer.y_pos = ysrc; viewer.z_pos = zsrc; viewer.z_rot = roll; phd_GetVectorAngles(xtar - xsrc, ytar - ysrc, ztar - zsrc, &viewer.x_rot); temp = viewer.y_rot; viewer.y_rot = viewer.x_rot; viewer.x_rot = temp; phd_GenerateW2V(&viewer); } void phd_GenerateW2V(struct PHD_3DPOS* view) { int t0, t1, t2, t3, t4, t5, t6, v0, v1, a0, a1, a2, a3, at; a2 = view->x_rot; v1 = view->y_rot; t0 = SIN(a2); t2 = SIN(v1); a1 = view->z_rot; t4 = (t0 * t2) >> 12; t3 = COS(v1); t1 = SIN(a1); t5 = t4 * t1; phd_mxptr = &matrix_stack[0]; v1 = t0 * t3; v0 = COS(a2); t0 = -t0; matrix_stack[9] = t0; w2v_matrix[9] = t0; t6 = v0 * t1; a1 = COS(a1); v1 >>= 12; t6 >>= 12; matrix_stack[1] = t6; w2v_matrix[1] = t6; t6 = (v1 * t1) >> 12; a3 = (t2 * a1) >> 12; t6 -= a3; matrix_stack[2] = t6; w2v_matrix[2] = t6; t6 = t4 * a1; a3 = view->x_pos; t4 = view->y_pos; a0 = view->z_pos; matrix_stack[3] = a3; w2v_matrix[3] = a3; matrix_stack[7] = t4; w2v_matrix[7] = t4; a3 = t3 * t1; matrix_stack[11] = a0; w2v_matrix[11] = a0; t4 = (v0 * a1) >> 14; t0 = (v0 * a1) >> 12; w2v_matrix[5] = t0; a2 = (v0 * t2) >> 12; t0 -= t4; matrix_stack[8] = a2; w2v_matrix[8] = a2; matrix_stack[5] = t0; a2 = (v0 * t3) >> 12; t6 >>= 12; matrix_stack[10] = a2; w2v_matrix[10] = a2; t0 = v1 * a1; a3 >>= 12; t6 -= a3; a2 = t2 * t1; w2v_matrix[4] = t6; at = t6 >> 2; t6 -= at; matrix_stack[4] = t6; t0 >>= 12; v0 = a2 >> 12; t0 += v0; w2v_matrix[6] = t0; at = t0 >> 2; t0 -= at; matrix_stack[6] = t0; v0 = t5 >> 12; v1 = (t3 * a1) >> 12; v0 += v1; matrix_stack[0] = v0; w2v_matrix[0] = v0; } long phd_atan_asm(long x, long y)// (F) { int a2, a3, v0; if (x == 0 && y == 0) { return 0; } a2 = 0; if (x < 0) { a2 = 4; x = -x; } //loc_77A64 if (y < 0) { a2 += 2; y = -y; } v0 = x; if (x < y) { a2 += 1; x = y; y = v0; } else { //loc_77A90 goto loc_77A98; } loc_77A90: y >>= 1; x >>= 1; loc_77A98: v0 = (y << 16) >> 16; if (v0 != y) { goto loc_77A90; }//loc_77A90 v0 = y << 11; a3 = (v0 / x); v0 = atanOctantTab[a2]; x = atanTab[a3]; v0 = x + v0; if (v0 < 0) { v0 = -v0; } return v0; } void mRotBoundingBoxNoPersp(short* bounds, short* tbounds) { UNIMPLEMENTED(); }
/* Begin CVS Header $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/utilities/CDirEntry.cpp,v $ $Revision: 1.4 $ $Name: $ $Author: shoops $ $Date: 2005/05/13 17:27:50 $ End CVS Header */ #include <sys/types.h> #include <sys/stat.h> #ifdef WIN32 # include <io.h> # include <direct.h> # define stat _stat # define S_IFREG _S_IFREG # define S_IFDIR _S_IFDIR # define access _access # define mkdir _mkdir # define rmdir _rmdir #else # include <dirent.h> # include <unistd.h> #endif // WIN32 #include "copasi.h" #include "CDirEntry.h" bool CDirEntry::isFile(const std::string & path) { struct stat st; if (stat(path.c_str(), & st) == -1) return false; #ifdef WIN32 return ((st.st_mode & S_IFREG) == S_IFREG); #else return S_ISREG(st.st_mode); #endif } bool CDirEntry::isDir(const std::string & path) { struct stat st; if (stat(path.c_str(), & st) == -1) return false; #ifdef WIN32 return ((st.st_mode & S_IFDIR) == S_IFDIR); #else return S_ISDIR(st.st_mode); #endif } bool CDirEntry::exist(const std::string & path) { struct stat st; if (stat(path.c_str(), & st) == -1) return false; #ifdef WIN32 return ((st.st_mode & S_IFREG) == S_IFREG || (st.st_mode & S_IFDIR) == S_IFDIR); #else return (S_ISREG(st.st_mode) || S_ISDIR(st.st_mode)); #endif } bool CDirEntry::isReadable(const std::string & path) {return (access(path.c_str(), 0x4) == 0);} bool CDirEntry::isWritable(const std::string & path) {return (access(path.c_str(), 0x2) == 0);} bool CDirEntry::createDir(const std::string & dir, const std::string & parent) { std::string Separator; #ifdef WIN32 Separator = "\\"; #else Separator = "/"; #endif std::string Dir; if (parent != "") Dir = parent + Separator; Dir += dir; // Check whether the directory already exists and is writable. if (isDir(Dir) && isWritable(Dir)) return true; // Check whether the parent directory exists and is writable. if (!isDir(parent) || !isWritable(parent)) return false; #ifdef WIN32 return (mkdir(Dir.c_str()) == 0); #else return (mkdir(Dir.c_str(), 0) == 0); #endif } bool CDirEntry::remove(const std::string & path) { if (isDir(path)) return (rmdir(path.c_str()) == 0); else if (isFile(path)) return (::remove(path.c_str()) == 0); return false; } bool CDirEntry::removeFiles(const std::string & pattern, const std::string & path) { bool success = true; // :TODO: #ifdef WIN32 // Append to the "path" mask for all files in directory std::string FilePattern = path + "\\" + pattern; // Open directory stream and try read info about first entry struct _finddata_t Entry; C_INT32 hList = _findfirst(FilePattern.c_str(), &Entry); if (hList == -1) return success; if (Entry.attrib | _A_NORMAL) { if (::remove((path + "\\" + Entry.name).c_str()) != 0) success = false; } else { if (rmdir((path + "\\" + Entry.name).c_str()) != 0) success = false; } while (_findnext(hList, &Entry) == 0) if (Entry.attrib | _A_NORMAL) { if (::remove((path + "\\" + Entry.name).c_str()) != 0) success = false; } else { if (rmdir((path + "\\" + Entry.name).c_str()) != 0) success = false; } _findclose(hList); #else DIR * pDir = opendir(path.c_str()); if (!pDir) return false; struct dirent * pEntry; while ((pEntry = readdir(pDir)) != NULL) { // Match pattern. if (isDir(pEntry->d_name)) { if (rmdir((path + "/" + pEntry->d_name).c_str()) != 0) success = false; } else { if (::remove((path + "/" + pEntry->d_name).c_str()) != 0) success = false; } pEntry = readdir(pDir); } closedir(pDir); #endif // WIN32 return success; } Simplified removeFiles for WIN32 platform. /* Begin CVS Header $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/utilities/CDirEntry.cpp,v $ $Revision: 1.5 $ $Name: $ $Author: shoops $ $Date: 2005/05/13 18:21:34 $ End CVS Header */ #include <sys/types.h> #include <sys/stat.h> #ifdef WIN32 # include <io.h> # include <direct.h> # define stat _stat # define S_IFREG _S_IFREG # define S_IFDIR _S_IFDIR # define access _access # define mkdir _mkdir # define rmdir _rmdir #else # include <dirent.h> # include <unistd.h> #endif // WIN32 #include "copasi.h" #include "CDirEntry.h" bool CDirEntry::isFile(const std::string & path) { struct stat st; if (stat(path.c_str(), & st) == -1) return false; #ifdef WIN32 return ((st.st_mode & S_IFREG) == S_IFREG); #else return S_ISREG(st.st_mode); #endif } bool CDirEntry::isDir(const std::string & path) { struct stat st; if (stat(path.c_str(), & st) == -1) return false; #ifdef WIN32 return ((st.st_mode & S_IFDIR) == S_IFDIR); #else return S_ISDIR(st.st_mode); #endif } bool CDirEntry::exist(const std::string & path) { struct stat st; if (stat(path.c_str(), & st) == -1) return false; #ifdef WIN32 return ((st.st_mode & S_IFREG) == S_IFREG || (st.st_mode & S_IFDIR) == S_IFDIR); #else return (S_ISREG(st.st_mode) || S_ISDIR(st.st_mode)); #endif } bool CDirEntry::isReadable(const std::string & path) {return (access(path.c_str(), 0x4) == 0);} bool CDirEntry::isWritable(const std::string & path) {return (access(path.c_str(), 0x2) == 0);} bool CDirEntry::createDir(const std::string & dir, const std::string & parent) { std::string Separator; #ifdef WIN32 Separator = "\\"; #else Separator = "/"; #endif std::string Dir; if (parent != "") Dir = parent + Separator; Dir += dir; // Check whether the directory already exists and is writable. if (isDir(Dir) && isWritable(Dir)) return true; // Check whether the parent directory exists and is writable. if (!isDir(parent) || !isWritable(parent)) return false; #ifdef WIN32 return (mkdir(Dir.c_str()) == 0); #else return (mkdir(Dir.c_str(), 0) == 0); #endif } bool CDirEntry::remove(const std::string & path) { if (isDir(path)) return (rmdir(path.c_str()) == 0); else if (isFile(path)) return (::remove(path.c_str()) == 0); return false; } bool CDirEntry::removeFiles(const std::string & pattern, const std::string & path) { bool success = true; // :TODO: #ifdef WIN32 // Append to the "path" mask for all files in directory std::string FilePattern = path + "\\" + pattern; // Open directory stream and try read info about first entry struct _finddata_t Entry; C_INT32 hList = _findfirst(FilePattern.c_str(), &Entry); if (hList == -1) return success; do { if (Entry.attrib | _A_NORMAL) { if (::remove((path + "\\" + Entry.name).c_str()) != 0) success = false; } else { if (rmdir((path + "\\" + Entry.name).c_str()) != 0) success = false; } } while (_findnext(hList, &Entry) == 0); _findclose(hList); #else DIR * pDir = opendir(path.c_str()); if (!pDir) return false; struct dirent * pEntry; while ((pEntry = readdir(pDir)) != NULL) { // Match pattern. if (isDir(pEntry->d_name)) { if (rmdir((path + "/" + pEntry->d_name).c_str()) != 0) success = false; } else { if (::remove((path + "/" + pEntry->d_name).c_str()) != 0) success = false; } pEntry = readdir(pDir); } closedir(pDir); #endif // WIN32 return success; }
// Formatting library for C++ - module tests // // Copyright (c) 2012 - present, Victor Zverovich // All rights reserved. // // For the license information refer to format.h. // // Copyright (c) 2021 - present, Daniela Engert // All Rights Reserved // {fmt} module. #ifdef _MSC_FULL_VER // hide some implementation bugs in msvc // that are not essential to users of the module. # define FMT_HIDE_MODULE_BUGS #endif #define FMT_MODULE_TEST #include <bit> #include <chrono> #include <exception> #include <iterator> #include <locale> #include <memory> #include <ostream> #include <string> #include <string_view> #include <system_error> #if (__has_include(<fcntl.h>) || defined(__APPLE__) || \ defined(__linux__)) && \ (!defined(WINAPI_FAMILY) || (WINAPI_FAMILY == WINAPI_FAMILY_DESKTOP_APP)) # include <fcntl.h> # define FMT_USE_FCNTL 1 #else # define FMT_USE_FCNTL 0 #endif #define FMT_NOEXCEPT noexcept #if defined(_WIN32) && !defined(__MINGW32__) # define FMT_POSIX(call) _##call #else # define FMT_POSIX(call) call #endif #define FMT_OS_H_ // don't pull in os.h directly or indirectly import fmt; // check for macros leaking from BMI static bool macro_leaked = #if defined(FMT_CORE_H_) || defined(FMT_FORMAT_H_) true; #else false; #endif // Include sources to pick up functions and classes from the module rather than // from the non-modular library which is baked into the 'test-main' library. // This averts linker problems: // - strong ownership model: missing linker symbols // - weak ownership model: duplicate linker symbols #include "gtest-extra.cc" #include "util.cc" // an implicitly exported namespace must be visible [module.interface]/2.2 TEST(module_test, namespace) { using namespace fmt; using namespace fmt::literals; ASSERT_TRUE(true); } namespace detail { bool oops_detail_namespace_is_visible; } namespace fmt { bool namespace_detail_invisible() { #if defined(FMT_HIDE_MODULE_BUGS) && defined(_MSC_FULL_VER) && \ _MSC_FULL_VER <= 192930129 // bug in msvc up to 16.11-pre1: // the namespace is visible even when it is neither // implicitly nor explicitly exported return true; #else using namespace detail; // this fails to compile if fmt::detail is visible return !oops_detail_namespace_is_visible; #endif } } // namespace fmt // the non-exported namespace 'detail' must be invisible [module.interface]/2 TEST(module_test, detail_namespace) { EXPECT_TRUE(fmt::namespace_detail_invisible()); } // macros must not be imported from a *named* module [cpp.import]/5.1 TEST(module_test, macros) { #if defined(FMT_HIDE_MODULE_BUGS) && defined(_MSC_FULL_VER) && \ _MSC_FULL_VER <= 192930129 // bug in msvc up to 16.11-pre1: // include-guard macros leak from BMI // and even worse: they cannot be #undef-ined macro_leaked = false; #endif EXPECT_FALSE(macro_leaked); } // The following is less about functional testing (that's done elsewhere) // but rather visibility of all client-facing overloads, reachability of // non-exported entities, name lookup and overload resolution within // template instantitions. // Excercise all exported entities of the API at least once. // Instantiate as many code paths as possible. TEST(module_test, to_string) { EXPECT_EQ("42", fmt::to_string(42)); EXPECT_EQ("42", fmt::to_string(42.0)); EXPECT_EQ(L"42", fmt::to_wstring(42)); EXPECT_EQ(L"42", fmt::to_wstring(42.0)); } TEST(module_test, format) { EXPECT_EQ("42", fmt::format("{:}", 42)); EXPECT_EQ("-42", fmt::format("{0}", -42.0)); EXPECT_EQ(L"42", fmt::format(L"{:}", 42)); EXPECT_EQ(L"-42", fmt::format(L"{0}", -42.0)); } TEST(module_test, format_to) { std::string s; fmt::format_to(std::back_inserter(s), "{}", 42); EXPECT_EQ("42", s); char buffer[4] = {0}; fmt::format_to(buffer, "{}", 42); EXPECT_EQ("42", std::string_view(buffer)); fmt::memory_buffer mb; fmt::format_to(mb, "{}", 42); EXPECT_EQ("42", std::string_view(buffer)); std::wstring w; fmt::format_to(std::back_inserter(w), L"{}", 42); EXPECT_EQ(L"42", w); wchar_t wbuffer[4] = {0}; fmt::format_to(wbuffer, L"{}", 42); EXPECT_EQ(L"42", std::wstring_view(wbuffer)); fmt::wmemory_buffer wb; fmt::format_to(wb, L"{}", 42); EXPECT_EQ(L"42", std::wstring_view(wbuffer)); } TEST(module_test, formatted_size) { EXPECT_EQ(2u, fmt::formatted_size("{}", 42)); EXPECT_EQ(2u, fmt::formatted_size(L"{}", 42)); } TEST(module_test, format_to_n) { std::string s; auto result = fmt::format_to_n(std::back_inserter(s), 1, "{}", 42); EXPECT_EQ(2u, result.size); char buffer[4] = {0}; fmt::format_to_n(buffer, 3, "{}", 12345); std::wstring w; auto wresult = fmt::format_to_n(std::back_inserter(w), 1, L"{}", 42); EXPECT_EQ(2u, wresult.size); wchar_t wbuffer[4] = {0}; fmt::format_to_n(wbuffer, 3, L"{}", 12345); } TEST(module_test, format_args) { auto no_args = fmt::format_args(); EXPECT_FALSE(no_args.get(1)); fmt::basic_format_args args = fmt::make_format_args(42); EXPECT_TRUE(args.max_size() > 0); auto arg0 = args.get(0); EXPECT_TRUE(arg0); decltype(arg0) arg_none; EXPECT_FALSE(arg_none); EXPECT_TRUE(arg0.type() != arg_none.type()); } TEST(module_test, wformat_args) { auto no_args = fmt::wformat_args(); EXPECT_FALSE(no_args.get(1)); fmt::basic_format_args args = fmt::make_wformat_args(42); EXPECT_TRUE(args.get(0)); } TEST(module_test, checked_format_args) { fmt::basic_format_args args = fmt::make_args_checked<int>("{}", 42); EXPECT_TRUE(args.get(0)); fmt::basic_format_args wargs = fmt::make_args_checked<int>(L"{}", 42); EXPECT_TRUE(wargs.get(0)); } TEST(module_test, dynamic_format_args) { fmt::dynamic_format_arg_store<fmt::format_context> dyn_store; dyn_store.push_back(fmt::arg("a42", 42)); fmt::basic_format_args args = dyn_store; EXPECT_FALSE(args.get(3)); EXPECT_TRUE(args.get(fmt::string_view("a42"))); fmt::dynamic_format_arg_store<fmt::wformat_context> wdyn_store; wdyn_store.push_back(fmt::arg(L"a42", 42)); fmt::basic_format_args wargs = wdyn_store; EXPECT_FALSE(wargs.get(3)); EXPECT_TRUE(wargs.get(fmt::wstring_view(L"a42"))); } TEST(module_test, vformat) { EXPECT_EQ("42", fmt::vformat("{}", fmt::make_format_args(42))); EXPECT_EQ(L"42", fmt::vformat(fmt::to_string_view(L"{}"), fmt::make_wformat_args(42))); } TEST(module_test, vformat_to) { auto store = fmt::make_format_args(42); std::string s; fmt::vformat_to(std::back_inserter(s), "{}", store); EXPECT_EQ("42", s); char buffer[4] = {0}; fmt::vformat_to(buffer, "{:}", store); EXPECT_EQ("42", std::string_view(buffer)); auto wstore = fmt::make_wformat_args(42); std::wstring w; fmt::vformat_to(std::back_inserter(w), L"{}", wstore); EXPECT_EQ(L"42", w); wchar_t wbuffer[4] = {0}; fmt::vformat_to(wbuffer, L"{:}", wstore); EXPECT_EQ(L"42", std::wstring_view(wbuffer)); } TEST(module_test, vformat_to_n) { auto store = fmt::make_format_args(12345); std::string s; auto result = fmt::vformat_to_n(std::back_inserter(s), 1, "{}", store); char buffer[4] = {0}; fmt::vformat_to_n(buffer, 3, "{:}", store); auto wstore = fmt::make_wformat_args(12345); std::wstring w; auto wresult = fmt::vformat_to_n(std::back_inserter(w), 1, fmt::to_string_view(L"{}"), wstore); wchar_t wbuffer[4] = {0}; fmt::vformat_to_n(wbuffer, 3, fmt::to_string_view(L"{:}"), wstore); } std::string as_string(std::wstring_view text) { return {reinterpret_cast<const char*>(text.data()), text.size() * sizeof(text[0])}; } TEST(module_test, print) { EXPECT_WRITE(stdout, fmt::print("{}µ", 42), "42µ"); EXPECT_WRITE(stderr, fmt::print(stderr, "{}µ", 4.2), "4.2µ"); if (false) { EXPECT_WRITE(stdout, fmt::print(L"{}µ", 42), as_string(L"42µ")); EXPECT_WRITE(stderr, fmt::print(stderr, L"{}µ", 4.2), as_string(L"4.2µ")); } } TEST(module_test, vprint) { EXPECT_WRITE(stdout, fmt::vprint("{:}µ", fmt::make_format_args(42)), "42µ"); EXPECT_WRITE(stderr, fmt::vprint(stderr, "{}", fmt::make_format_args(4.2)), "4.2"); if (false) { EXPECT_WRITE(stdout, fmt::vprint(L"{:}µ", fmt::make_wformat_args(42)), as_string(L"42µ")); EXPECT_WRITE(stderr, fmt::vprint(stderr, L"{}", fmt::make_wformat_args(42)), as_string(L"42")); } } TEST(module_test, named_args) { EXPECT_EQ("42", fmt::format("{answer}", fmt::arg("answer", 42))); EXPECT_EQ(L"42", fmt::format(L"{answer}", fmt::arg(L"answer", 42))); } TEST(module_test, literals) { using namespace fmt::literals; EXPECT_EQ("42", fmt::format("{answer}", "answer"_a = 42)); EXPECT_EQ("42", "{}"_format(42)); EXPECT_EQ(L"42", fmt::format(L"{answer}", L"answer"_a = 42)); EXPECT_EQ(L"42", L"{}"_format(42)); } TEST(module_test, locale) { auto store = fmt::make_format_args(4.2); const auto classic = std::locale::classic(); EXPECT_EQ("4.2", fmt::format(classic, "{:L}", 4.2)); EXPECT_EQ("4.2", fmt::vformat(classic, "{:L}", store)); std::string s; fmt::vformat_to(std::back_inserter(s), classic, "{:L}", store); EXPECT_EQ("4.2", s); EXPECT_EQ("4.2", fmt::format("{:L}", 4.2)); auto wstore = fmt::make_wformat_args(4.2); EXPECT_EQ(L"4.2", fmt::format(classic, L"{:L}", 4.2)); EXPECT_EQ(L"4.2", fmt::vformat(classic, L"{:L}", wstore)); std::wstring w; fmt::vformat_to(std::back_inserter(w), classic, L"{:L}", wstore); EXPECT_EQ(L"4.2", w); EXPECT_EQ(L"4.2", fmt::format(L"{:L}", 4.2)); } TEST(module_test, string_view) { fmt::string_view nsv("fmt"); EXPECT_EQ("fmt", nsv); EXPECT_TRUE(fmt::string_view("fmt") == nsv); fmt::wstring_view wsv(L"fmt"); EXPECT_EQ(L"fmt", wsv); EXPECT_TRUE(fmt::wstring_view(L"fmt") == wsv); } TEST(module_test, memory_buffer) { fmt::basic_memory_buffer<char, fmt::inline_buffer_size> buffer; fmt::format_to(buffer, "{}", "42"); EXPECT_EQ("42", to_string(buffer)); fmt::memory_buffer nbuffer(std::move(buffer)); EXPECT_EQ("42", to_string(nbuffer)); buffer = std::move(nbuffer); EXPECT_EQ("42", to_string(buffer)); nbuffer.clear(); EXPECT_EQ(0u, to_string(nbuffer).size()); fmt::wmemory_buffer wbuffer; EXPECT_EQ(0u, to_string(wbuffer).size()); } TEST(module_test, is_char) { EXPECT_TRUE(fmt::is_char<char>()); EXPECT_TRUE(fmt::is_char<wchar_t>()); EXPECT_TRUE(fmt::is_char<char8_t>()); EXPECT_TRUE(fmt::is_char<char16_t>()); EXPECT_TRUE(fmt::is_char<char32_t>()); EXPECT_FALSE(fmt::is_char<signed char>()); } TEST(module_test, ptr) { uintptr_t answer = 42; auto p = std::bit_cast<int*>(answer); EXPECT_EQ("0x2a", fmt::to_string(fmt::ptr(p))); std::unique_ptr<int> up(p); EXPECT_EQ("0x2a", fmt::to_string(fmt::ptr(up))); up.release(); auto sp = std::make_shared<int>(0); p = sp.get(); EXPECT_EQ(fmt::to_string(fmt::ptr(p)), fmt::to_string(fmt::ptr(sp))); } TEST(module_test, errors) { auto store = fmt::make_format_args(42); EXPECT_THROW(throw fmt::format_error("oops"), std::exception); EXPECT_THROW(throw fmt::vsystem_error(0, "{}", store), std::system_error); EXPECT_THROW(throw fmt::system_error(0, "{}", 42), std::system_error); fmt::memory_buffer buffer; fmt::format_system_error(buffer, 0, "oops"); auto oops = to_string(buffer); EXPECT_TRUE(oops.size() > 0); EXPECT_WRITE(stderr, fmt::report_system_error(0, "oops"), oops + '\n'); #ifdef _WIN32 EXPECT_THROW(throw fmt::vwindows_error(0, "{}", store), std::system_error); EXPECT_THROW(throw fmt::windows_error(0, "{}", 42), std::system_error); output_redirect redirect(stderr); fmt::report_windows_error(0, "oops"); EXPECT_TRUE(redirect.restore_and_read().size() > 0); #endif } TEST(module_test, error_code) { EXPECT_EQ("generic:42", fmt::format("{0}", std::error_code(42, std::generic_category()))); EXPECT_EQ("system:42", fmt::format("{0}", std::error_code(42, fmt::system_category()))); EXPECT_EQ(L"generic:42", fmt::format(L"{0}", std::error_code(42, std::generic_category()))); } TEST(module_test, format_int) { fmt::format_int sanswer(42); EXPECT_EQ("42", fmt::string_view(sanswer.data(), sanswer.size())); fmt::format_int uanswer(42u); EXPECT_EQ("42", fmt::string_view(uanswer.data(), uanswer.size())); } struct test_formatter : fmt::formatter<char> { bool check() { return true; } }; struct test_dynamic_formatter : fmt::dynamic_formatter<> { bool check() { return true; } }; TEST(module_test, formatter) { EXPECT_TRUE(test_formatter{}.check()); EXPECT_TRUE(test_dynamic_formatter{}.check()); } TEST(module_test, join) { int arr[3] = {1, 2, 3}; std::vector<double> vec{1.0, 2.0, 3.0}; std::initializer_list<int> il{1, 2, 3}; auto sep = fmt::to_string_view(", "); EXPECT_EQ("1, 2, 3", to_string(fmt::join(arr + 0, arr + 3, sep))); EXPECT_EQ("1, 2, 3", to_string(fmt::join(arr, sep))); EXPECT_EQ("1, 2, 3", to_string(fmt::join(vec.begin(), vec.end(), sep))); EXPECT_EQ("1, 2, 3", to_string(fmt::join(vec, sep))); EXPECT_EQ("1, 2, 3", to_string(fmt::join(il, sep))); auto wsep = fmt::to_string_view(L", "); EXPECT_EQ(L"1, 2, 3", fmt::format(L"{}", fmt::join(arr + 0, arr + 3, wsep))); EXPECT_EQ(L"1, 2, 3", fmt::format(L"{}", fmt::join(arr, wsep))); EXPECT_EQ(L"1, 2, 3", fmt::format(L"{}", fmt::join(il, wsep))); } TEST(module_test, time) { auto time_now = std::time(nullptr); EXPECT_TRUE(fmt::localtime(time_now).tm_year > 120); EXPECT_TRUE(fmt::gmtime(time_now).tm_year > 120); auto chrono_now = std::chrono::system_clock::now(); EXPECT_TRUE(fmt::localtime(chrono_now).tm_year > 120); EXPECT_TRUE(fmt::gmtime(chrono_now).tm_year > 120); } TEST(module_test, time_point) { auto now = std::chrono::system_clock::now(); std::string_view past("2021-05-20 10:30:15"); EXPECT_TRUE(past < fmt::format("{:%Y-%m-%d %H:%M:%S}", now)); std::wstring_view wpast(L"2021-05-20 10:30:15"); EXPECT_TRUE(wpast < fmt::format(L"{:%Y-%m-%d %H:%M:%S}", now)); } TEST(module_test, time_duration) { using us = std::chrono::duration<double, std::micro>; EXPECT_EQ("42s", fmt::format("{}", std::chrono::seconds{42})); EXPECT_EQ("4.2µs", fmt::format("{:3.1}", us{4.234})); EXPECT_EQ("4.2µs", fmt::format(std::locale::classic(), "{:L}", us{4.2})); EXPECT_EQ(L"42s", fmt::format(L"{}", std::chrono::seconds{42})); EXPECT_EQ(L"4.2µs", fmt::format(L"{:3.1}", us{4.234})); EXPECT_EQ(L"4.2µs", fmt::format(std::locale::classic(), L"{:L}", us{4.2})); } TEST(module_test, weekday) { EXPECT_EQ("Monday", std::format(std::locale::classic(), "{:%A}", fmt::weekday(1))); } TEST(module_test, to_string_view) { using fmt::to_string_view; fmt::string_view nsv{to_string_view("42")}; EXPECT_EQ("42", nsv); fmt::wstring_view wsv{to_string_view(L"42")}; EXPECT_EQ(L"42", wsv); } TEST(module_test, printf) { EXPECT_WRITE(stdout, fmt::printf("%f", 42.123456), "42.123456"); EXPECT_WRITE(stdout, fmt::printf("%d", 42), "42"); if (false) { EXPECT_WRITE(stdout, fmt::printf(L"%f", 42.123456), as_string(L"42.123456")); EXPECT_WRITE(stdout, fmt::printf(L"%d", 42), as_string(L"42")); } } TEST(module_test, fprintf) { EXPECT_WRITE(stderr, fmt::fprintf(stderr, "%d", 42), "42"); std::ostringstream os; fmt::fprintf(os, "%s", "bla"); EXPECT_EQ("bla", os.str()); EXPECT_WRITE(stderr, fmt::fprintf(stderr, L"%d", 42), as_string(L"42")); std::wostringstream ws; fmt::fprintf(ws, L"%s", L"bla"); EXPECT_EQ(L"bla", ws.str()); } TEST(module_test, sprintf) { EXPECT_EQ("42", fmt::sprintf("%d", 42)); EXPECT_EQ(L"42", fmt::sprintf(L"%d", 42)); } TEST(module_test, vprintf) { EXPECT_WRITE(stdout, fmt::vprintf("%d", fmt::make_printf_args(42)), "42"); if (false) { EXPECT_WRITE(stdout, fmt::vprintf(L"%d", fmt::make_wprintf_args(42)), as_string(L"42")); } } TEST(module_test, vfprintf) { auto args = fmt::make_printf_args(42); EXPECT_WRITE(stderr, fmt::vfprintf(stderr, "%d", args), "42"); std::ostringstream os; fmt::vfprintf(os, "%d", args); EXPECT_EQ("42", os.str()); auto wargs = fmt::make_wprintf_args(42); if (false) { EXPECT_WRITE(stderr, fmt::vfprintf(stderr, L"%d", wargs), as_string(L"42")); } std::wostringstream ws; fmt::vfprintf(ws, L"%d", wargs); EXPECT_EQ(L"42", ws.str()); } TEST(module_test, vsprintf) { EXPECT_EQ("42", fmt::vsprintf("%d", fmt::make_printf_args(42))); EXPECT_EQ(L"42", fmt::vsprintf(L"%d", fmt::make_wprintf_args(42))); } TEST(module_test, color) { auto fg_check = fg(fmt::rgb(255, 200, 30)); auto bg_check = bg(fmt::color::dark_slate_gray) | fmt::emphasis::italic; auto emphasis_check = fmt::emphasis::underline | fmt::emphasis::bold; EXPECT_EQ("\x1B[30m42\x1B[0m", fmt::format(fg(fmt::terminal_color::black), "{}", 42)); EXPECT_EQ(L"\x1B[30m42\x1B[0m", fmt::format(fg(fmt::terminal_color::black), L"{}", 42)); } TEST(module_test, cstring_view) { auto s = "fmt"; EXPECT_EQ(s, fmt::cstring_view(s).c_str()); auto w = L"fmt"; EXPECT_EQ(w, fmt::wcstring_view(w).c_str()); } TEST(module_test, buffered_file) { EXPECT_TRUE(fmt::buffered_file{}.get() == nullptr); } TEST(module_test, output_file) { fmt::ostream out = fmt::output_file("module-test", fmt::buffer_size = 1); out.close(); } struct custom_context { using char_type = char; using parse_context_type = fmt::format_parse_context; }; TEST(module_test, custom_context) { fmt::basic_format_arg<custom_context> custom_arg; EXPECT_TRUE(!custom_arg); } struct disabled_formatter {}; TEST(module_test, has_formatter) { EXPECT_FALSE( (fmt::has_formatter<disabled_formatter, fmt::format_context>::value)); } TEST(module_test, is_formattable) { EXPECT_FALSE(fmt::is_formattable<disabled_formatter>::value); } TEST(module_test, compile_format_string) { using namespace fmt::literals; EXPECT_EQ("42", fmt::format("{0:x}"_cf, 0x42)); EXPECT_EQ(L"42", fmt::format(L"{:}"_cf, 42)); EXPECT_EQ("4.2", fmt::format("{arg:3.1f}"_cf, "arg"_a = 4.2)); EXPECT_EQ(L" 42", fmt::format(L"{arg:>3}"_cf, L"arg"_a = L"42")); } Upgrade `module-test` to msvc 16.11.5 and 17.0-pre5 (#2558) // Formatting library for C++ - module tests // // Copyright (c) 2012 - present, Victor Zverovich // All rights reserved. // // For the license information refer to format.h. // // Copyright (c) 2021 - present, Daniela Engert // All Rights Reserved // {fmt} module. #ifdef _MSC_FULL_VER // hide some implementation bugs in msvc // that are not essential to users of the module. # define FMT_HIDE_MODULE_BUGS #endif #define FMT_MODULE_TEST #include <bit> #include <chrono> #include <exception> #include <iterator> #include <locale> #include <memory> #include <ostream> #include <string> #include <string_view> #include <system_error> #if (__has_include(<fcntl.h>) || defined(__APPLE__) || \ defined(__linux__)) && \ (!defined(WINAPI_FAMILY) || (WINAPI_FAMILY == WINAPI_FAMILY_DESKTOP_APP)) # include <fcntl.h> # define FMT_USE_FCNTL 1 #else # define FMT_USE_FCNTL 0 #endif #define FMT_NOEXCEPT noexcept #if defined(_WIN32) && !defined(__MINGW32__) # define FMT_POSIX(call) _##call #else # define FMT_POSIX(call) call #endif #define FMT_OS_H_ // don't pull in os.h directly or indirectly import fmt; // check for macros leaking from BMI static bool macro_leaked = #if defined(FMT_CORE_H_) || defined(FMT_FORMAT_H_) true; #else false; #endif // Include sources to pick up functions and classes from the module rather than // from the non-modular library which is baked into the 'test-main' library. // This averts linker problems: // - strong ownership model: missing linker symbols // - weak ownership model: duplicate linker symbols #include "gtest-extra.cc" #include "util.cc" // an implicitly exported namespace must be visible [module.interface]/2.2 TEST(module_test, namespace) { using namespace fmt; using namespace fmt::literals; ASSERT_TRUE(true); } namespace detail { bool oops_detail_namespace_is_visible; } namespace fmt { bool namespace_detail_invisible() { #if defined(FMT_HIDE_MODULE_BUGS) && defined(_MSC_FULL_VER) && \ ((_MSC_VER == 1929 && _MSC_FULL_VER <= 192930136) || \ (_MSC_VER == 1930 && _MSC_FULL_VER <= 193030704)) // bug in msvc up to 16.11.5 / 17.0-pre5: // the namespace is visible even when it is neither // implicitly nor explicitly exported return true; #else using namespace detail; // this fails to compile if fmt::detail is visible return !oops_detail_namespace_is_visible; #endif } } // namespace fmt // the non-exported namespace 'detail' must be invisible [module.interface]/2 TEST(module_test, detail_namespace) { EXPECT_TRUE(fmt::namespace_detail_invisible()); } // macros must not be imported from a *named* module [cpp.import]/5.1 TEST(module_test, macros) { #if defined(FMT_HIDE_MODULE_BUGS) && defined(_MSC_FULL_VER) && \ _MSC_FULL_VER <= 192930130 // bug in msvc up to 16.11-pre2: // include-guard macros leak from BMI // and even worse: they cannot be #undef-ined macro_leaked = false; #endif EXPECT_FALSE(macro_leaked); } // The following is less about functional testing (that's done elsewhere) // but rather visibility of all client-facing overloads, reachability of // non-exported entities, name lookup and overload resolution within // template instantitions. // Excercise all exported entities of the API at least once. // Instantiate as many code paths as possible. TEST(module_test, to_string) { EXPECT_EQ("42", fmt::to_string(42)); EXPECT_EQ("42", fmt::to_string(42.0)); EXPECT_EQ(L"42", fmt::to_wstring(42)); EXPECT_EQ(L"42", fmt::to_wstring(42.0)); } TEST(module_test, format) { EXPECT_EQ("42", fmt::format("{:}", 42)); EXPECT_EQ("-42", fmt::format("{0}", -42.0)); EXPECT_EQ(L"42", fmt::format(L"{:}", 42)); EXPECT_EQ(L"-42", fmt::format(L"{0}", -42.0)); } TEST(module_test, format_to) { std::string s; fmt::format_to(std::back_inserter(s), "{}", 42); EXPECT_EQ("42", s); char buffer[4] = {0}; fmt::format_to(buffer, "{}", 42); EXPECT_EQ("42", std::string_view(buffer)); fmt::memory_buffer mb; fmt::format_to(mb, "{}", 42); EXPECT_EQ("42", std::string_view(buffer)); std::wstring w; fmt::format_to(std::back_inserter(w), L"{}", 42); EXPECT_EQ(L"42", w); wchar_t wbuffer[4] = {0}; fmt::format_to(wbuffer, L"{}", 42); EXPECT_EQ(L"42", std::wstring_view(wbuffer)); fmt::wmemory_buffer wb; fmt::format_to(wb, L"{}", 42); EXPECT_EQ(L"42", std::wstring_view(wbuffer)); } TEST(module_test, formatted_size) { EXPECT_EQ(2u, fmt::formatted_size("{}", 42)); EXPECT_EQ(2u, fmt::formatted_size(L"{}", 42)); } TEST(module_test, format_to_n) { std::string s; auto result = fmt::format_to_n(std::back_inserter(s), 1, "{}", 42); EXPECT_EQ(2u, result.size); char buffer[4] = {0}; fmt::format_to_n(buffer, 3, "{}", 12345); std::wstring w; auto wresult = fmt::format_to_n(std::back_inserter(w), 1, L"{}", 42); EXPECT_EQ(2u, wresult.size); wchar_t wbuffer[4] = {0}; fmt::format_to_n(wbuffer, 3, L"{}", 12345); } TEST(module_test, format_args) { auto no_args = fmt::format_args(); EXPECT_FALSE(no_args.get(1)); fmt::basic_format_args args = fmt::make_format_args(42); EXPECT_TRUE(args.max_size() > 0); auto arg0 = args.get(0); EXPECT_TRUE(arg0); decltype(arg0) arg_none; EXPECT_FALSE(arg_none); EXPECT_TRUE(arg0.type() != arg_none.type()); } TEST(module_test, wformat_args) { auto no_args = fmt::wformat_args(); EXPECT_FALSE(no_args.get(1)); fmt::basic_format_args args = fmt::make_wformat_args(42); EXPECT_TRUE(args.get(0)); } TEST(module_test, checked_format_args) { fmt::basic_format_args args = fmt::make_args_checked<int>("{}", 42); EXPECT_TRUE(args.get(0)); fmt::basic_format_args wargs = fmt::make_args_checked<int>(L"{}", 42); EXPECT_TRUE(wargs.get(0)); } TEST(module_test, dynamic_format_args) { fmt::dynamic_format_arg_store<fmt::format_context> dyn_store; dyn_store.push_back(fmt::arg("a42", 42)); fmt::basic_format_args args = dyn_store; EXPECT_FALSE(args.get(3)); EXPECT_TRUE(args.get(fmt::string_view("a42"))); fmt::dynamic_format_arg_store<fmt::wformat_context> wdyn_store; wdyn_store.push_back(fmt::arg(L"a42", 42)); fmt::basic_format_args wargs = wdyn_store; EXPECT_FALSE(wargs.get(3)); EXPECT_TRUE(wargs.get(fmt::wstring_view(L"a42"))); } TEST(module_test, vformat) { EXPECT_EQ("42", fmt::vformat("{}", fmt::make_format_args(42))); EXPECT_EQ(L"42", fmt::vformat(fmt::to_string_view(L"{}"), fmt::make_wformat_args(42))); } TEST(module_test, vformat_to) { auto store = fmt::make_format_args(42); std::string s; fmt::vformat_to(std::back_inserter(s), "{}", store); EXPECT_EQ("42", s); char buffer[4] = {0}; fmt::vformat_to(buffer, "{:}", store); EXPECT_EQ("42", std::string_view(buffer)); auto wstore = fmt::make_wformat_args(42); std::wstring w; fmt::vformat_to(std::back_inserter(w), L"{}", wstore); EXPECT_EQ(L"42", w); wchar_t wbuffer[4] = {0}; fmt::vformat_to(wbuffer, L"{:}", wstore); EXPECT_EQ(L"42", std::wstring_view(wbuffer)); } TEST(module_test, vformat_to_n) { auto store = fmt::make_format_args(12345); std::string s; auto result = fmt::vformat_to_n(std::back_inserter(s), 1, "{}", store); char buffer[4] = {0}; fmt::vformat_to_n(buffer, 3, "{:}", store); auto wstore = fmt::make_wformat_args(12345); std::wstring w; auto wresult = fmt::vformat_to_n(std::back_inserter(w), 1, fmt::to_string_view(L"{}"), wstore); wchar_t wbuffer[4] = {0}; fmt::vformat_to_n(wbuffer, 3, fmt::to_string_view(L"{:}"), wstore); } std::string as_string(std::wstring_view text) { return {reinterpret_cast<const char*>(text.data()), text.size() * sizeof(text[0])}; } TEST(module_test, print) { EXPECT_WRITE(stdout, fmt::print("{}µ", 42), "42µ"); EXPECT_WRITE(stderr, fmt::print(stderr, "{}µ", 4.2), "4.2µ"); if (false) { EXPECT_WRITE(stdout, fmt::print(L"{}µ", 42), as_string(L"42µ")); EXPECT_WRITE(stderr, fmt::print(stderr, L"{}µ", 4.2), as_string(L"4.2µ")); } } TEST(module_test, vprint) { EXPECT_WRITE(stdout, fmt::vprint("{:}µ", fmt::make_format_args(42)), "42µ"); EXPECT_WRITE(stderr, fmt::vprint(stderr, "{}", fmt::make_format_args(4.2)), "4.2"); if (false) { EXPECT_WRITE(stdout, fmt::vprint(L"{:}µ", fmt::make_wformat_args(42)), as_string(L"42µ")); EXPECT_WRITE(stderr, fmt::vprint(stderr, L"{}", fmt::make_wformat_args(42)), as_string(L"42")); } } TEST(module_test, named_args) { EXPECT_EQ("42", fmt::format("{answer}", fmt::arg("answer", 42))); EXPECT_EQ(L"42", fmt::format(L"{answer}", fmt::arg(L"answer", 42))); } TEST(module_test, literals) { using namespace fmt::literals; EXPECT_EQ("42", fmt::format("{answer}", "answer"_a = 42)); EXPECT_EQ("42", "{}"_format(42)); EXPECT_EQ(L"42", fmt::format(L"{answer}", L"answer"_a = 42)); EXPECT_EQ(L"42", L"{}"_format(42)); } TEST(module_test, locale) { auto store = fmt::make_format_args(4.2); const auto classic = std::locale::classic(); EXPECT_EQ("4.2", fmt::format(classic, "{:L}", 4.2)); EXPECT_EQ("4.2", fmt::vformat(classic, "{:L}", store)); std::string s; fmt::vformat_to(std::back_inserter(s), classic, "{:L}", store); EXPECT_EQ("4.2", s); EXPECT_EQ("4.2", fmt::format("{:L}", 4.2)); auto wstore = fmt::make_wformat_args(4.2); EXPECT_EQ(L"4.2", fmt::format(classic, L"{:L}", 4.2)); EXPECT_EQ(L"4.2", fmt::vformat(classic, L"{:L}", wstore)); std::wstring w; fmt::vformat_to(std::back_inserter(w), classic, L"{:L}", wstore); EXPECT_EQ(L"4.2", w); EXPECT_EQ(L"4.2", fmt::format(L"{:L}", 4.2)); } TEST(module_test, string_view) { fmt::string_view nsv("fmt"); EXPECT_EQ("fmt", nsv); EXPECT_TRUE(fmt::string_view("fmt") == nsv); fmt::wstring_view wsv(L"fmt"); EXPECT_EQ(L"fmt", wsv); EXPECT_TRUE(fmt::wstring_view(L"fmt") == wsv); } TEST(module_test, memory_buffer) { fmt::basic_memory_buffer<char, fmt::inline_buffer_size> buffer; fmt::format_to(buffer, "{}", "42"); EXPECT_EQ("42", to_string(buffer)); fmt::memory_buffer nbuffer(std::move(buffer)); EXPECT_EQ("42", to_string(nbuffer)); buffer = std::move(nbuffer); EXPECT_EQ("42", to_string(buffer)); nbuffer.clear(); EXPECT_EQ(0u, to_string(nbuffer).size()); fmt::wmemory_buffer wbuffer; EXPECT_EQ(0u, to_string(wbuffer).size()); } TEST(module_test, is_char) { EXPECT_TRUE(fmt::is_char<char>()); EXPECT_TRUE(fmt::is_char<wchar_t>()); EXPECT_TRUE(fmt::is_char<char8_t>()); EXPECT_TRUE(fmt::is_char<char16_t>()); EXPECT_TRUE(fmt::is_char<char32_t>()); EXPECT_FALSE(fmt::is_char<signed char>()); } TEST(module_test, ptr) { uintptr_t answer = 42; auto p = std::bit_cast<int*>(answer); EXPECT_EQ("0x2a", fmt::to_string(fmt::ptr(p))); std::unique_ptr<int> up(p); EXPECT_EQ("0x2a", fmt::to_string(fmt::ptr(up))); up.release(); auto sp = std::make_shared<int>(0); p = sp.get(); EXPECT_EQ(fmt::to_string(fmt::ptr(p)), fmt::to_string(fmt::ptr(sp))); } TEST(module_test, errors) { auto store = fmt::make_format_args(42); EXPECT_THROW(throw fmt::format_error("oops"), std::exception); EXPECT_THROW(throw fmt::vsystem_error(0, "{}", store), std::system_error); EXPECT_THROW(throw fmt::system_error(0, "{}", 42), std::system_error); fmt::memory_buffer buffer; fmt::format_system_error(buffer, 0, "oops"); auto oops = to_string(buffer); EXPECT_TRUE(oops.size() > 0); EXPECT_WRITE(stderr, fmt::report_system_error(0, "oops"), oops + '\n'); #ifdef _WIN32 EXPECT_THROW(throw fmt::vwindows_error(0, "{}", store), std::system_error); EXPECT_THROW(throw fmt::windows_error(0, "{}", 42), std::system_error); output_redirect redirect(stderr); fmt::report_windows_error(0, "oops"); EXPECT_TRUE(redirect.restore_and_read().size() > 0); #endif } TEST(module_test, error_code) { EXPECT_EQ("generic:42", fmt::format("{0}", std::error_code(42, std::generic_category()))); EXPECT_EQ("system:42", fmt::format("{0}", std::error_code(42, fmt::system_category()))); EXPECT_EQ(L"generic:42", fmt::format(L"{0}", std::error_code(42, std::generic_category()))); } TEST(module_test, format_int) { fmt::format_int sanswer(42); EXPECT_EQ("42", fmt::string_view(sanswer.data(), sanswer.size())); fmt::format_int uanswer(42u); EXPECT_EQ("42", fmt::string_view(uanswer.data(), uanswer.size())); } struct test_formatter : fmt::formatter<char> { bool check() { return true; } }; struct test_dynamic_formatter : fmt::dynamic_formatter<> { bool check() { return true; } }; TEST(module_test, formatter) { EXPECT_TRUE(test_formatter{}.check()); EXPECT_TRUE(test_dynamic_formatter{}.check()); } TEST(module_test, join) { int arr[3] = {1, 2, 3}; std::vector<double> vec{1.0, 2.0, 3.0}; std::initializer_list<int> il{1, 2, 3}; auto sep = fmt::to_string_view(", "); EXPECT_EQ("1, 2, 3", to_string(fmt::join(arr + 0, arr + 3, sep))); EXPECT_EQ("1, 2, 3", to_string(fmt::join(arr, sep))); EXPECT_EQ("1, 2, 3", to_string(fmt::join(vec.begin(), vec.end(), sep))); EXPECT_EQ("1, 2, 3", to_string(fmt::join(vec, sep))); EXPECT_EQ("1, 2, 3", to_string(fmt::join(il, sep))); auto wsep = fmt::to_string_view(L", "); EXPECT_EQ(L"1, 2, 3", fmt::format(L"{}", fmt::join(arr + 0, arr + 3, wsep))); EXPECT_EQ(L"1, 2, 3", fmt::format(L"{}", fmt::join(arr, wsep))); EXPECT_EQ(L"1, 2, 3", fmt::format(L"{}", fmt::join(il, wsep))); } TEST(module_test, time) { auto time_now = std::time(nullptr); EXPECT_TRUE(fmt::localtime(time_now).tm_year > 120); EXPECT_TRUE(fmt::gmtime(time_now).tm_year > 120); auto chrono_now = std::chrono::system_clock::now(); EXPECT_TRUE(fmt::localtime(chrono_now).tm_year > 120); EXPECT_TRUE(fmt::gmtime(chrono_now).tm_year > 120); } TEST(module_test, time_point) { auto now = std::chrono::system_clock::now(); std::string_view past("2021-05-20 10:30:15"); EXPECT_TRUE(past < fmt::format("{:%Y-%m-%d %H:%M:%S}", now)); std::wstring_view wpast(L"2021-05-20 10:30:15"); EXPECT_TRUE(wpast < fmt::format(L"{:%Y-%m-%d %H:%M:%S}", now)); } TEST(module_test, time_duration) { using us = std::chrono::duration<double, std::micro>; EXPECT_EQ("42s", fmt::format("{}", std::chrono::seconds{42})); EXPECT_EQ("4.2µs", fmt::format("{:3.1}", us{4.234})); EXPECT_EQ("4.2µs", fmt::format(std::locale::classic(), "{:L}", us{4.2})); EXPECT_EQ(L"42s", fmt::format(L"{}", std::chrono::seconds{42})); EXPECT_EQ(L"4.2µs", fmt::format(L"{:3.1}", us{4.234})); EXPECT_EQ(L"4.2µs", fmt::format(std::locale::classic(), L"{:L}", us{4.2})); } TEST(module_test, weekday) { EXPECT_EQ("Mon", fmt::format(std::locale::classic(), "{}", fmt::weekday(1))); } TEST(module_test, to_string_view) { using fmt::to_string_view; fmt::string_view nsv{to_string_view("42")}; EXPECT_EQ("42", nsv); fmt::wstring_view wsv{to_string_view(L"42")}; EXPECT_EQ(L"42", wsv); } TEST(module_test, printf) { EXPECT_WRITE(stdout, fmt::printf("%f", 42.123456), "42.123456"); EXPECT_WRITE(stdout, fmt::printf("%d", 42), "42"); if (false) { EXPECT_WRITE(stdout, fmt::printf(L"%f", 42.123456), as_string(L"42.123456")); EXPECT_WRITE(stdout, fmt::printf(L"%d", 42), as_string(L"42")); } } TEST(module_test, fprintf) { EXPECT_WRITE(stderr, fmt::fprintf(stderr, "%d", 42), "42"); std::ostringstream os; fmt::fprintf(os, "%s", "bla"); EXPECT_EQ("bla", os.str()); EXPECT_WRITE(stderr, fmt::fprintf(stderr, L"%d", 42), as_string(L"42")); std::wostringstream ws; fmt::fprintf(ws, L"%s", L"bla"); EXPECT_EQ(L"bla", ws.str()); } TEST(module_test, sprintf) { EXPECT_EQ("42", fmt::sprintf("%d", 42)); EXPECT_EQ(L"42", fmt::sprintf(L"%d", 42)); } TEST(module_test, vprintf) { EXPECT_WRITE(stdout, fmt::vprintf("%d", fmt::make_printf_args(42)), "42"); if (false) { EXPECT_WRITE(stdout, fmt::vprintf(L"%d", fmt::make_wprintf_args(42)), as_string(L"42")); } } TEST(module_test, vfprintf) { auto args = fmt::make_printf_args(42); EXPECT_WRITE(stderr, fmt::vfprintf(stderr, "%d", args), "42"); std::ostringstream os; fmt::vfprintf(os, "%d", args); EXPECT_EQ("42", os.str()); auto wargs = fmt::make_wprintf_args(42); if (false) { EXPECT_WRITE(stderr, fmt::vfprintf(stderr, L"%d", wargs), as_string(L"42")); } std::wostringstream ws; fmt::vfprintf(ws, L"%d", wargs); EXPECT_EQ(L"42", ws.str()); } TEST(module_test, vsprintf) { EXPECT_EQ("42", fmt::vsprintf("%d", fmt::make_printf_args(42))); EXPECT_EQ(L"42", fmt::vsprintf(L"%d", fmt::make_wprintf_args(42))); } TEST(module_test, color) { auto fg_check = fg(fmt::rgb(255, 200, 30)); auto bg_check = bg(fmt::color::dark_slate_gray) | fmt::emphasis::italic; auto emphasis_check = fmt::emphasis::underline | fmt::emphasis::bold; EXPECT_EQ("\x1B[30m42\x1B[0m", fmt::format(fg(fmt::terminal_color::black), "{}", 42)); EXPECT_EQ(L"\x1B[30m42\x1B[0m", fmt::format(fg(fmt::terminal_color::black), L"{}", 42)); } TEST(module_test, cstring_view) { auto s = "fmt"; EXPECT_EQ(s, fmt::cstring_view(s).c_str()); auto w = L"fmt"; EXPECT_EQ(w, fmt::wcstring_view(w).c_str()); } TEST(module_test, buffered_file) { EXPECT_TRUE(fmt::buffered_file{}.get() == nullptr); } TEST(module_test, output_file) { fmt::ostream out = fmt::output_file("module-test", fmt::buffer_size = 1); out.close(); } struct custom_context { using char_type = char; using parse_context_type = fmt::format_parse_context; }; TEST(module_test, custom_context) { fmt::basic_format_arg<custom_context> custom_arg; EXPECT_TRUE(!custom_arg); } struct disabled_formatter {}; TEST(module_test, has_formatter) { EXPECT_FALSE( (fmt::has_formatter<disabled_formatter, fmt::format_context>::value)); } TEST(module_test, is_formattable) { EXPECT_FALSE(fmt::is_formattable<disabled_formatter>::value); } TEST(module_test, compile_format_string) { using namespace fmt::literals; EXPECT_EQ("42", fmt::format("{0:x}"_cf, 0x42)); EXPECT_EQ(L"42", fmt::format(L"{:}"_cf, 42)); EXPECT_EQ("4.2", fmt::format("{arg:3.1f}"_cf, "arg"_a = 4.2)); EXPECT_EQ(L" 42", fmt::format(L"{arg:>3}"_cf, L"arg"_a = L"42")); }
// Copyright (c) 2010-2021, Lawrence Livermore National Security, LLC. Produced // at the Lawrence Livermore National Laboratory. All Rights reserved. See files // LICENSE and NOTICE for details. LLNL-CODE-806117. // // This file is part of the MFEM library. For more information and source code // availability visit https://mfem.org. // // MFEM is free software; you can redistribute it and/or modify it under the // terms of the BSD-3 license. We welcome feedback and contributions, see file // CONTRIBUTING.md for details. #include "constraints.hpp" #include "../fem/pfespace.hpp" #include <set> namespace mfem { Eliminator::Eliminator(const SparseMatrix& B, const Array<int>& lagrange_tdofs_, const Array<int>& primary_tdofs_, const Array<int>& secondary_tdofs_) : lagrange_tdofs(lagrange_tdofs_), primary_tdofs(primary_tdofs_), secondary_tdofs(secondary_tdofs_) { MFEM_VERIFY(lagrange_tdofs.Size() == secondary_tdofs.Size(), "Dof sizes don't match!"); Bp.SetSize(lagrange_tdofs.Size(), primary_tdofs.Size()); B.GetSubMatrix(lagrange_tdofs, primary_tdofs, Bp); Bs.SetSize(lagrange_tdofs.Size(), secondary_tdofs.Size()); B.GetSubMatrix(lagrange_tdofs, secondary_tdofs, Bs); BsT.Transpose(Bs); ipiv.SetSize(Bs.Height()); Bsinverse.data = Bs.GetData(); Bsinverse.ipiv = ipiv.GetData(); Bsinverse.Factor(Bs.Height()); ipivT.SetSize(Bs.Height()); BsTinverse.data = BsT.GetData(); BsTinverse.ipiv = ipivT.GetData(); BsTinverse.Factor(Bs.Height()); } void Eliminator::Eliminate(const Vector& in, Vector& out) const { Bp.Mult(in, out); Bsinverse.Solve(Bs.Height(), 1, out); out *= -1.0; } void Eliminator::EliminateTranspose(const Vector& in, Vector& out) const { Vector work(in); BsTinverse.Solve(Bs.Height(), 1, work); Bp.MultTranspose(work, out); out *= -1.0; } void Eliminator::LagrangeSecondary(const Vector& in, Vector& out) const { out = in; Bsinverse.Solve(Bs.Height(), 1, out); } void Eliminator::LagrangeSecondaryTranspose(const Vector& in, Vector& out) const { out = in; BsTinverse.Solve(Bs.Height(), 1, out); } void Eliminator::ExplicitAssembly(DenseMatrix& mat) const { mat.SetSize(Bp.Height(), Bp.Width()); mat = Bp; Bsinverse.Solve(Bs.Height(), Bp.Width(), mat.GetData()); mat *= -1.0; } EliminationProjection::EliminationProjection(const Operator& A, Array<Eliminator*>& eliminators_) : Operator(A.Height()), Aop(A), eliminators(eliminators_) { } void EliminationProjection::Mult(const Vector& in, Vector& out) const { MFEM_ASSERT(in.Size() == width, "Wrong vector size!"); MFEM_ASSERT(out.Size() == height, "Wrong vector size!"); out = in; for (int k = 0; k < eliminators.Size(); ++k) { Eliminator* elim = eliminators[k]; Vector subvec_in; Vector subvec_out(elim->SecondaryDofs().Size()); in.GetSubVector(elim->PrimaryDofs(), subvec_in); elim->Eliminate(subvec_in, subvec_out); out.SetSubVector(elim->SecondaryDofs(), subvec_out); } } void EliminationProjection::MultTranspose(const Vector& in, Vector& out) const { MFEM_ASSERT(in.Size() == height, "Wrong vector size!"); MFEM_ASSERT(out.Size() == width, "Wrong vector size!"); out = in; for (int k = 0; k < eliminators.Size(); ++k) { Eliminator* elim = eliminators[k]; Vector subvec_in; Vector subvec_out(elim->PrimaryDofs().Size()); in.GetSubVector(elim->SecondaryDofs(), subvec_in); elim->EliminateTranspose(subvec_in, subvec_out); out.AddElementVector(elim->PrimaryDofs(), subvec_out); out.SetSubVector(elim->SecondaryDofs(), 0.0); } } SparseMatrix * EliminationProjection::AssembleExact() const { SparseMatrix * out = new SparseMatrix(height, width); for (int i = 0; i < height; ++i) { out->Add(i, i, 1.0); } for (int k = 0; k < eliminators.Size(); ++k) { Eliminator* elim = eliminators[k]; DenseMatrix mat; elim->ExplicitAssembly(mat); for (int iz = 0; iz < elim->SecondaryDofs().Size(); ++iz) { int i = elim->SecondaryDofs()[iz]; for (int jz = 0; jz < elim->PrimaryDofs().Size(); ++jz) { int j = elim->PrimaryDofs()[jz]; out->Add(i, j, mat(iz, jz)); } out->Set(i, i, 0.0); } } out->Finalize(); return out; } void EliminationProjection::BuildGTilde(const Vector& r, Vector& rtilde) const { MFEM_ASSERT(rtilde.Size() == Aop.Height(), "Sizes don't match!"); rtilde = 0.0; for (int k = 0; k < eliminators.Size(); ++k) { Eliminator* elim = eliminators[k]; Vector subr; r.GetSubVector(elim->LagrangeDofs(), subr); Vector bsinvr(subr.Size()); elim->LagrangeSecondary(subr, bsinvr); rtilde.AddElementVector(elim->SecondaryDofs(), bsinvr); } } void EliminationProjection::RecoverMultiplier( const Vector& disprhs, const Vector& disp, Vector& lagrangem) const { lagrangem = 0.0; MFEM_ASSERT(disp.Size() == Aop.Height(), "Sizes don't match!"); Vector fullrhs(Aop.Height()); Aop.Mult(disp, fullrhs); fullrhs -= disprhs; fullrhs *= -1.0; for (int k = 0; k < eliminators.Size(); ++k) { Eliminator* elim = eliminators[k]; Vector localsec; fullrhs.GetSubVector(elim->SecondaryDofs(), localsec); Vector locallagrange(localsec.Size()); elim->LagrangeSecondaryTranspose(localsec, locallagrange); lagrangem.AddElementVector(elim->LagrangeDofs(), locallagrange); } } #ifdef MFEM_USE_MPI EliminationSolver::~EliminationSolver() { delete h_explicit_operator; for (auto elim : eliminators) { delete elim; } delete projector; delete prec; } void EliminationSolver::BuildExplicitOperator() { SparseMatrix * explicit_projector = projector->AssembleExact(); HypreParMatrix * h_explicit_projector = new HypreParMatrix(hA.GetComm(), hA.GetGlobalNumRows(), hA.GetRowStarts(), explicit_projector); h_explicit_projector->CopyRowStarts(); h_explicit_projector->CopyColStarts(); h_explicit_operator = RAP(&hA, h_explicit_projector); /// next line because of square projector h_explicit_operator->EliminateZeroRows(); h_explicit_operator->CopyRowStarts(); h_explicit_operator->CopyColStarts(); delete explicit_projector; delete h_explicit_projector; } EliminationSolver::EliminationSolver(HypreParMatrix& A, SparseMatrix& B, Array<int>& primary_dofs, Array<int>& secondary_dofs) : ConstrainedSolver(A.GetComm(), A, B), hA(A), prec(nullptr) { MFEM_VERIFY(secondary_dofs.Size() == B.Height(), "Wrong number of dofs for elimination!"); Array<int> lagrange_dofs(secondary_dofs.Size()); for (int i = 0; i < lagrange_dofs.Size(); ++i) { lagrange_dofs[i] = i; } eliminators.Append(new Eliminator(B, lagrange_dofs, primary_dofs, secondary_dofs)); projector = new EliminationProjection(hA, eliminators); } EliminationSolver::EliminationSolver(HypreParMatrix& A, SparseMatrix& B, Array<int>& constraint_rowstarts) : ConstrainedSolver(A.GetComm(), A, B), hA(A), prec(nullptr) { if (!B.Empty()) { int * I = B.GetI(); int * J = B.GetJ(); double * data = B.GetData(); for (int k = 0; k < constraint_rowstarts.Size() - 1; ++k) { int constraint_size = constraint_rowstarts[k + 1] - constraint_rowstarts[k]; Array<int> lagrange_dofs(constraint_size); Array<int> primary_dofs; Array<int> secondary_dofs(constraint_size); secondary_dofs = -1; // loop through rows, identify one secondary dof for each row for (int i = constraint_rowstarts[k]; i < constraint_rowstarts[k + 1]; ++i) { lagrange_dofs[i - constraint_rowstarts[k]] = i; for (int jptr = I[i]; jptr < I[i + 1]; ++jptr) { int j = J[jptr]; double val = data[jptr]; if (std::abs(val) > 1.e-12 && secondary_dofs.Find(j) == -1) { secondary_dofs[i - constraint_rowstarts[k]] = j; break; } } } // loop through rows again, assigning non-secondary dofs as primary for (int i = constraint_rowstarts[k]; i < constraint_rowstarts[k + 1]; ++i) { MFEM_ASSERT(secondary_dofs[i - constraint_rowstarts[k]] >= 0, "Secondary dofs don't match rows!"); for (int jptr = I[i]; jptr < I[i + 1]; ++jptr) { int j = J[jptr]; if (secondary_dofs.Find(j) == -1) { primary_dofs.Append(j); } } } primary_dofs.Sort(); primary_dofs.Unique(); eliminators.Append(new Eliminator(B, lagrange_dofs, primary_dofs, secondary_dofs)); } } projector = new EliminationProjection(hA, eliminators); } void EliminationSolver::PrimalMult(const Vector& rhs, Vector& sol) const { if (!prec) { prec = BuildPreconditioner(); } IterativeSolver * krylov = BuildKrylov(); krylov->SetOperator(*h_explicit_operator); krylov->SetPreconditioner(*prec); krylov->SetMaxIter(max_iter); krylov->SetRelTol(rel_tol); krylov->SetAbsTol(abs_tol); krylov->SetPrintLevel(print_level); Vector rtilde(rhs.Size()); if (constraint_rhs.Size() > 0) { projector->BuildGTilde(constraint_rhs, rtilde); } else { rtilde = 0.0; } Vector temprhs(rhs); hA.Mult(-1.0, rtilde, 1.0, temprhs); Vector reducedrhs(rhs.Size()); projector->MultTranspose(temprhs, reducedrhs); Vector reducedsol(rhs.Size()); reducedsol = 0.0; krylov->Mult(reducedrhs, reducedsol); final_iter = krylov->GetNumIterations(); final_norm = krylov->GetFinalNorm(); converged = krylov->GetConverged(); delete krylov; projector->Mult(reducedsol, sol); projector->RecoverMultiplier(temprhs, sol, multiplier_sol); sol += rtilde; } void PenaltyConstrainedSolver::Initialize(HypreParMatrix& A, HypreParMatrix& B) { HypreParMatrix * hBT = B.Transpose(); HypreParMatrix * hBTB = ParMult(hBT, &B, true); // this matrix doesn't get cleanly deleted? // (hypre comm pkg) penalized_mat = Add(1.0, A, penalty, *hBTB); delete hBTB; delete hBT; } PenaltyConstrainedSolver::PenaltyConstrainedSolver( HypreParMatrix& A, SparseMatrix& B, double penalty_) : ConstrainedSolver(A.GetComm(), A, B), penalty(penalty_), constraintB(B), prec(nullptr) { HYPRE_Int hB_row_starts[2] = {0, B.Height()}; HYPRE_Int hB_col_starts[2] = {0, B.Width()}; HypreParMatrix hB(A.GetComm(), B.Height(), B.Width(), hB_row_starts, hB_col_starts, &B); Initialize(A, hB); } PenaltyConstrainedSolver::PenaltyConstrainedSolver( HypreParMatrix& A, HypreParMatrix& B, double penalty_) : ConstrainedSolver(A.GetComm(), A, B), penalty(penalty_), constraintB(B), prec(nullptr) { Initialize(A, B); } PenaltyConstrainedSolver::~PenaltyConstrainedSolver() { delete penalized_mat; delete prec; } void PenaltyConstrainedSolver::PrimalMult(const Vector& b, Vector& x) const { if (!prec) { prec = BuildPreconditioner(); } IterativeSolver * krylov = BuildKrylov(); // form penalized right-hand side Vector penalized_rhs(b); if (constraint_rhs.Size() > 0) { Vector temp(x.Size()); constraintB.MultTranspose(constraint_rhs, temp); temp *= penalty; penalized_rhs += temp; } // actually solve krylov->SetOperator(*penalized_mat); krylov->SetRelTol(rel_tol); krylov->SetAbsTol(abs_tol); krylov->SetMaxIter(max_iter); krylov->SetPrintLevel(print_level); krylov->SetPreconditioner(*prec); krylov->Mult(penalized_rhs, x); final_iter = krylov->GetNumIterations(); final_norm = krylov->GetFinalNorm(); converged = krylov->GetConverged(); delete krylov; constraintB.Mult(x, multiplier_sol); if (constraint_rhs.Size() > 0) { multiplier_sol -= constraint_rhs; } multiplier_sol *= penalty; } #endif /// because IdentityOperator isn't a Solver class IdentitySolver : public Solver { public: IdentitySolver(int size) : Solver(size) { } void Mult(const Vector& x, Vector& y) const { y = x; } void SetOperator(const Operator& op) { } }; void SchurConstrainedSolver::Initialize() { offsets[0] = 0; offsets[1] = A.Height(); offsets[2] = A.Height() + B.Height(); block_op = new BlockOperator(offsets); block_op->SetBlock(0, 0, &A); block_op->SetBlock(1, 0, &B); tr_B = new TransposeOperator(&B); block_op->SetBlock(0, 1, tr_B); block_pc = new BlockDiagonalPreconditioner(block_op->RowOffsets()), rel_tol = 1.e-6; } #ifdef MFEM_USE_MPI SchurConstrainedSolver::SchurConstrainedSolver(MPI_Comm comm, Operator& A_, Operator& B_, Solver& primal_pc_) : ConstrainedSolver(comm, A_, B_), offsets(3), primal_pc(&primal_pc_), dual_pc(nullptr) { Initialize(); primal_pc->SetOperator(block_op->GetBlock(0, 0)); dual_pc = new IdentitySolver(block_op->RowOffsets()[2] - block_op->RowOffsets()[1]); block_pc->SetDiagonalBlock(0, primal_pc); block_pc->SetDiagonalBlock(1, dual_pc); } #endif SchurConstrainedSolver::SchurConstrainedSolver(Operator& A_, Operator& B_, Solver& primal_pc_) : ConstrainedSolver(A_, B_), offsets(3), primal_pc(&primal_pc_), dual_pc(nullptr) { Initialize(); primal_pc->SetOperator(block_op->GetBlock(0, 0)); dual_pc = new IdentitySolver(block_op->RowOffsets()[2] - block_op->RowOffsets()[1]); block_pc->SetDiagonalBlock(0, primal_pc); block_pc->SetDiagonalBlock(1, dual_pc); } #ifdef MFEM_USE_MPI // protected constructor SchurConstrainedSolver::SchurConstrainedSolver(MPI_Comm comm, Operator& A_, Operator& B_) : ConstrainedSolver(comm, A_, B_), offsets(3), primal_pc(nullptr), dual_pc(nullptr) { Initialize(); } #endif // protected constructor SchurConstrainedSolver::SchurConstrainedSolver(Operator& A_, Operator& B_) : ConstrainedSolver(A_, B_), offsets(3), primal_pc(nullptr), dual_pc(nullptr) { Initialize(); } SchurConstrainedSolver::~SchurConstrainedSolver() { delete block_op; delete tr_B; delete block_pc; delete dual_pc; } void SchurConstrainedSolver::Mult(const Vector& x, Vector& y) const { GMRESSolver * gmres; #ifdef MFEM_USE_MPI if (GetComm() != MPI_COMM_NULL) { gmres = new GMRESSolver(GetComm()); } else #endif { gmres = new GMRESSolver; } gmres->SetOperator(*block_op); gmres->SetRelTol(rel_tol); gmres->SetAbsTol(abs_tol); gmres->SetMaxIter(max_iter); gmres->SetPrintLevel(print_level); gmres->SetPreconditioner( const_cast<BlockDiagonalPreconditioner&>(*block_pc)); gmres->Mult(x, y); final_iter = gmres->GetNumIterations(); delete gmres; } #ifdef MFEM_USE_MPI SchurConstrainedHypreSolver::SchurConstrainedHypreSolver(MPI_Comm comm, HypreParMatrix& hA_, HypreParMatrix& hB_, int dimension, bool reorder) : SchurConstrainedSolver(comm, hA_, hB_), hA(hA_), hB(hB_) { auto h_primal_pc = new HypreBoomerAMG(hA); h_primal_pc->SetPrintLevel(0); if (dimension > 0) { h_primal_pc->SetSystemsOptions(dimension, reorder); } primal_pc = h_primal_pc; HypreParMatrix * scaledB = new HypreParMatrix(hB); Vector diagA; hA.GetDiag(diagA); HypreParMatrix * scaledBT = scaledB->Transpose(); scaledBT->InvScaleRows(diagA); schur_mat = ParMult(scaledB, scaledBT); schur_mat->CopyRowStarts(); schur_mat->CopyColStarts(); auto h_dual_pc = new HypreBoomerAMG(*schur_mat); h_dual_pc->SetPrintLevel(0); dual_pc = h_dual_pc; delete scaledB; delete scaledBT; block_pc->SetDiagonalBlock(0, primal_pc); block_pc->SetDiagonalBlock(1, dual_pc); } SchurConstrainedHypreSolver::~SchurConstrainedHypreSolver() { delete schur_mat; delete primal_pc; } #endif void ConstrainedSolver::Initialize() { height = A.Height() + B.Height(); width = A.Width() + B.Height(); workb.SetSize(A.Height()); workx.SetSize(A.Height()); constraint_rhs.SetSize(B.Height()); constraint_rhs = 0.0; multiplier_sol.SetSize(B.Height()); } #ifdef MFEM_USE_MPI ConstrainedSolver::ConstrainedSolver(MPI_Comm comm, Operator& A_, Operator& B_) : IterativeSolver(comm), A(A_), B(B_) { Initialize(); } #endif ConstrainedSolver::ConstrainedSolver(Operator& A_, Operator& B_) : A(A_), B(B_) { Initialize(); } void ConstrainedSolver::SetConstraintRHS(const Vector& r) { MFEM_VERIFY(r.Size() == multiplier_sol.Size(), "Vector is wrong size!"); constraint_rhs = r; } void ConstrainedSolver::PrimalMult(const Vector& f, Vector &x) const { Vector pworkb(A.Height() + B.Height()); Vector pworkx(A.Height() + B.Height()); pworkb = 0.0; pworkx = 0.0; for (int i = 0; i < f.Size(); ++i) { pworkb(i) = f(i); pworkx(i) = x(i); } for (int i = 0; i < B.Height(); ++i) { pworkb(f.Size() + i) = constraint_rhs(i); } Mult(pworkb, pworkx); for (int i = 0; i < f.Size(); ++i) { x(i) = pworkx(i); } for (int i = 0; i < B.Height(); ++i) { multiplier_sol(i) = pworkx(f.Size() + i); } } void ConstrainedSolver::Mult(const Vector& f_and_r, Vector& x_and_lambda) const { workb.MakeRef(const_cast<Vector&>(f_and_r), 0); workx.MakeRef(x_and_lambda, 0); Vector ref_constraint_rhs(f_and_r.GetData() + A.Height(), B.Height()); constraint_rhs = ref_constraint_rhs; PrimalMult(workb, workx); Vector ref_constraint_sol(x_and_lambda.GetData() + A.Height(), B.Height()); GetMultiplierSolution(ref_constraint_sol); } /* Helper routine to reduce code duplication - given a node (which MFEM sometimes calls a "dof"), this returns what normal people call a dof but which MFEM sometimes calls a "vdof" - note that MFEM's naming conventions regarding this are not entirely consistent. In parallel, this always returns the "truedof" in parallel numbering. */ int CanonicalNodeNumber(FiniteElementSpace& fespace, int node, bool parallel, int d=0) { #ifdef MFEM_USE_MPI if (parallel) { try { ParFiniteElementSpace& pfespace = dynamic_cast<ParFiniteElementSpace&>(fespace); const int vdof = pfespace.DofToVDof(node, d); return pfespace.GetLocalTDofNumber(vdof); } catch (std::bad_cast&) { MFEM_ABORT("Asked for parallel form of serial object!"); return -1; } } else #endif { return fespace.DofToVDof(node, d); } } SparseMatrix * BuildNormalConstraints(FiniteElementSpace& fespace, Array<int>& constrained_att, Array<int>& constraint_rowstarts, bool parallel) { int dim = fespace.GetVDim(); // dof_constraint maps a dof (column of the constraint matrix) to // a block-constraint // the indexing is by tdof, but a single tdof uniquely identifies a node // so we only store one tdof independent of dimension std::map<int, int> dof_bconstraint; // constraints[j] is a map from attribute to row number, // the j itself is the index of a block-constraint std::vector<std::map<int, int> > constraints; int n_bconstraints = 0; int n_rows = 0; for (int att : constrained_att) { // identify tdofs on constrained boundary std::set<int> constrained_tdofs; for (int i = 0; i < fespace.GetNBE(); ++i) { if (fespace.GetBdrAttribute(i) == att) { Array<int> nodes; // get nodes on boundary (MFEM sometimes calls these dofs, what // we call dofs it calls vdofs) fespace.GetBdrElementDofs(i, nodes); for (auto k : nodes) { // get the (local) dof number corresponding to // the x-coordinate dof for node k int tdof = CanonicalNodeNumber(fespace, k, parallel); if (tdof >= 0) { constrained_tdofs.insert(tdof); } } } } // fill in the maps identifying which constraints (rows) correspond to // which tdofs for (auto k : constrained_tdofs) { auto it = dof_bconstraint.find(k); if (it == dof_bconstraint.end()) { // build new block constraint dof_bconstraint[k] = n_bconstraints++; constraints.emplace_back(); constraints.back()[att] = n_rows++; } else { // add tdof to existing block constraint constraints[it->second][att] = n_rows++; } } } // reorder so block-constraints eliminated together are grouped together in // adjacent rows { std::map<int, int> reorder_rows; int new_row = 0; constraint_rowstarts.DeleteAll(); constraint_rowstarts.Append(0); for (auto& it : dof_bconstraint) { int bconstraint_index = it.second; bool nconstraint = false; for (auto& att_it : constraints[bconstraint_index]) { auto rrit = reorder_rows.find(att_it.second); if (rrit == reorder_rows.end()) { nconstraint = true; reorder_rows[att_it.second] = new_row++; } } if (nconstraint) { constraint_rowstarts.Append(new_row); } } MFEM_VERIFY(new_row == n_rows, "Remapping failed!"); for (auto& constraint_map : constraints) { for (auto& it : constraint_map) { it.second = reorder_rows[it.second]; } } } SparseMatrix * out = new SparseMatrix(n_rows, fespace.GetTrueVSize()); // fill in constraint matrix with normal vector information Vector nor(dim); // how many times we have seen a node (key is truek) std::map<int, int> node_visits; for (int i = 0; i < fespace.GetNBE(); ++i) { int att = fespace.GetBdrAttribute(i); if (constrained_att.FindSorted(att) != -1) { ElementTransformation * Tr = fespace.GetBdrElementTransformation(i); const FiniteElement * fe = fespace.GetBE(i); const IntegrationRule& nodes = fe->GetNodes(); Array<int> dofs; fespace.GetBdrElementDofs(i, dofs); MFEM_VERIFY(dofs.Size() == nodes.Size(), "Something wrong in finite element space!"); for (int j = 0; j < dofs.Size(); ++j) { Tr->SetIntPoint(&nodes[j]); // the normal returned in the next line is scaled by h, which is // probably what we want in most applications CalcOrtho(Tr->Jacobian(), nor); int k = dofs[j]; int truek = CanonicalNodeNumber(fespace, k, parallel); if (truek >= 0) { auto nv_it = node_visits.find(truek); if (nv_it == node_visits.end()) { node_visits[truek] = 1; } else { node_visits[truek]++; } int visits = node_visits[truek]; int bconstraint = dof_bconstraint[truek]; int row = constraints[bconstraint][att]; for (int d = 0; d < dim; ++d) { int inner_truek = CanonicalNodeNumber(fespace, k, parallel, d); if (visits == 1) { out->Add(row, inner_truek, nor[d]); } else { out->SetColPtr(row); const double pv = out->SearchRow(inner_truek); const double scaling = ((double) (visits - 1)) / ((double) visits); // incremental average, based on how many times // this node has been visited out->Set(row, inner_truek, scaling * pv + (1.0 / visits) * nor[d]); } } } } } } out->Finalize(); return out; } #ifdef MFEM_USE_MPI SparseMatrix * ParBuildNormalConstraints(ParFiniteElementSpace& fespace, Array<int>& constrained_att, Array<int>& constraint_rowstarts) { return BuildNormalConstraints(fespace, constrained_att, constraint_rowstarts, true); } #endif } PenaltyConstrainedSolver: bug fix in one constructor when used in parallel // Copyright (c) 2010-2021, Lawrence Livermore National Security, LLC. Produced // at the Lawrence Livermore National Laboratory. All Rights reserved. See files // LICENSE and NOTICE for details. LLNL-CODE-806117. // // This file is part of the MFEM library. For more information and source code // availability visit https://mfem.org. // // MFEM is free software; you can redistribute it and/or modify it under the // terms of the BSD-3 license. We welcome feedback and contributions, see file // CONTRIBUTING.md for details. #include "constraints.hpp" #include "../fem/pfespace.hpp" #include <set> namespace mfem { Eliminator::Eliminator(const SparseMatrix& B, const Array<int>& lagrange_tdofs_, const Array<int>& primary_tdofs_, const Array<int>& secondary_tdofs_) : lagrange_tdofs(lagrange_tdofs_), primary_tdofs(primary_tdofs_), secondary_tdofs(secondary_tdofs_) { MFEM_VERIFY(lagrange_tdofs.Size() == secondary_tdofs.Size(), "Dof sizes don't match!"); Bp.SetSize(lagrange_tdofs.Size(), primary_tdofs.Size()); B.GetSubMatrix(lagrange_tdofs, primary_tdofs, Bp); Bs.SetSize(lagrange_tdofs.Size(), secondary_tdofs.Size()); B.GetSubMatrix(lagrange_tdofs, secondary_tdofs, Bs); BsT.Transpose(Bs); ipiv.SetSize(Bs.Height()); Bsinverse.data = Bs.GetData(); Bsinverse.ipiv = ipiv.GetData(); Bsinverse.Factor(Bs.Height()); ipivT.SetSize(Bs.Height()); BsTinverse.data = BsT.GetData(); BsTinverse.ipiv = ipivT.GetData(); BsTinverse.Factor(Bs.Height()); } void Eliminator::Eliminate(const Vector& in, Vector& out) const { Bp.Mult(in, out); Bsinverse.Solve(Bs.Height(), 1, out); out *= -1.0; } void Eliminator::EliminateTranspose(const Vector& in, Vector& out) const { Vector work(in); BsTinverse.Solve(Bs.Height(), 1, work); Bp.MultTranspose(work, out); out *= -1.0; } void Eliminator::LagrangeSecondary(const Vector& in, Vector& out) const { out = in; Bsinverse.Solve(Bs.Height(), 1, out); } void Eliminator::LagrangeSecondaryTranspose(const Vector& in, Vector& out) const { out = in; BsTinverse.Solve(Bs.Height(), 1, out); } void Eliminator::ExplicitAssembly(DenseMatrix& mat) const { mat.SetSize(Bp.Height(), Bp.Width()); mat = Bp; Bsinverse.Solve(Bs.Height(), Bp.Width(), mat.GetData()); mat *= -1.0; } EliminationProjection::EliminationProjection(const Operator& A, Array<Eliminator*>& eliminators_) : Operator(A.Height()), Aop(A), eliminators(eliminators_) { } void EliminationProjection::Mult(const Vector& in, Vector& out) const { MFEM_ASSERT(in.Size() == width, "Wrong vector size!"); MFEM_ASSERT(out.Size() == height, "Wrong vector size!"); out = in; for (int k = 0; k < eliminators.Size(); ++k) { Eliminator* elim = eliminators[k]; Vector subvec_in; Vector subvec_out(elim->SecondaryDofs().Size()); in.GetSubVector(elim->PrimaryDofs(), subvec_in); elim->Eliminate(subvec_in, subvec_out); out.SetSubVector(elim->SecondaryDofs(), subvec_out); } } void EliminationProjection::MultTranspose(const Vector& in, Vector& out) const { MFEM_ASSERT(in.Size() == height, "Wrong vector size!"); MFEM_ASSERT(out.Size() == width, "Wrong vector size!"); out = in; for (int k = 0; k < eliminators.Size(); ++k) { Eliminator* elim = eliminators[k]; Vector subvec_in; Vector subvec_out(elim->PrimaryDofs().Size()); in.GetSubVector(elim->SecondaryDofs(), subvec_in); elim->EliminateTranspose(subvec_in, subvec_out); out.AddElementVector(elim->PrimaryDofs(), subvec_out); out.SetSubVector(elim->SecondaryDofs(), 0.0); } } SparseMatrix * EliminationProjection::AssembleExact() const { SparseMatrix * out = new SparseMatrix(height, width); for (int i = 0; i < height; ++i) { out->Add(i, i, 1.0); } for (int k = 0; k < eliminators.Size(); ++k) { Eliminator* elim = eliminators[k]; DenseMatrix mat; elim->ExplicitAssembly(mat); for (int iz = 0; iz < elim->SecondaryDofs().Size(); ++iz) { int i = elim->SecondaryDofs()[iz]; for (int jz = 0; jz < elim->PrimaryDofs().Size(); ++jz) { int j = elim->PrimaryDofs()[jz]; out->Add(i, j, mat(iz, jz)); } out->Set(i, i, 0.0); } } out->Finalize(); return out; } void EliminationProjection::BuildGTilde(const Vector& r, Vector& rtilde) const { MFEM_ASSERT(rtilde.Size() == Aop.Height(), "Sizes don't match!"); rtilde = 0.0; for (int k = 0; k < eliminators.Size(); ++k) { Eliminator* elim = eliminators[k]; Vector subr; r.GetSubVector(elim->LagrangeDofs(), subr); Vector bsinvr(subr.Size()); elim->LagrangeSecondary(subr, bsinvr); rtilde.AddElementVector(elim->SecondaryDofs(), bsinvr); } } void EliminationProjection::RecoverMultiplier( const Vector& disprhs, const Vector& disp, Vector& lagrangem) const { lagrangem = 0.0; MFEM_ASSERT(disp.Size() == Aop.Height(), "Sizes don't match!"); Vector fullrhs(Aop.Height()); Aop.Mult(disp, fullrhs); fullrhs -= disprhs; fullrhs *= -1.0; for (int k = 0; k < eliminators.Size(); ++k) { Eliminator* elim = eliminators[k]; Vector localsec; fullrhs.GetSubVector(elim->SecondaryDofs(), localsec); Vector locallagrange(localsec.Size()); elim->LagrangeSecondaryTranspose(localsec, locallagrange); lagrangem.AddElementVector(elim->LagrangeDofs(), locallagrange); } } #ifdef MFEM_USE_MPI EliminationSolver::~EliminationSolver() { delete h_explicit_operator; for (auto elim : eliminators) { delete elim; } delete projector; delete prec; } void EliminationSolver::BuildExplicitOperator() { SparseMatrix * explicit_projector = projector->AssembleExact(); HypreParMatrix * h_explicit_projector = new HypreParMatrix(hA.GetComm(), hA.GetGlobalNumRows(), hA.GetRowStarts(), explicit_projector); h_explicit_projector->CopyRowStarts(); h_explicit_projector->CopyColStarts(); h_explicit_operator = RAP(&hA, h_explicit_projector); /// next line because of square projector h_explicit_operator->EliminateZeroRows(); h_explicit_operator->CopyRowStarts(); h_explicit_operator->CopyColStarts(); delete explicit_projector; delete h_explicit_projector; } EliminationSolver::EliminationSolver(HypreParMatrix& A, SparseMatrix& B, Array<int>& primary_dofs, Array<int>& secondary_dofs) : ConstrainedSolver(A.GetComm(), A, B), hA(A), prec(nullptr) { MFEM_VERIFY(secondary_dofs.Size() == B.Height(), "Wrong number of dofs for elimination!"); Array<int> lagrange_dofs(secondary_dofs.Size()); for (int i = 0; i < lagrange_dofs.Size(); ++i) { lagrange_dofs[i] = i; } eliminators.Append(new Eliminator(B, lagrange_dofs, primary_dofs, secondary_dofs)); projector = new EliminationProjection(hA, eliminators); } EliminationSolver::EliminationSolver(HypreParMatrix& A, SparseMatrix& B, Array<int>& constraint_rowstarts) : ConstrainedSolver(A.GetComm(), A, B), hA(A), prec(nullptr) { if (!B.Empty()) { int * I = B.GetI(); int * J = B.GetJ(); double * data = B.GetData(); for (int k = 0; k < constraint_rowstarts.Size() - 1; ++k) { int constraint_size = constraint_rowstarts[k + 1] - constraint_rowstarts[k]; Array<int> lagrange_dofs(constraint_size); Array<int> primary_dofs; Array<int> secondary_dofs(constraint_size); secondary_dofs = -1; // loop through rows, identify one secondary dof for each row for (int i = constraint_rowstarts[k]; i < constraint_rowstarts[k + 1]; ++i) { lagrange_dofs[i - constraint_rowstarts[k]] = i; for (int jptr = I[i]; jptr < I[i + 1]; ++jptr) { int j = J[jptr]; double val = data[jptr]; if (std::abs(val) > 1.e-12 && secondary_dofs.Find(j) == -1) { secondary_dofs[i - constraint_rowstarts[k]] = j; break; } } } // loop through rows again, assigning non-secondary dofs as primary for (int i = constraint_rowstarts[k]; i < constraint_rowstarts[k + 1]; ++i) { MFEM_ASSERT(secondary_dofs[i - constraint_rowstarts[k]] >= 0, "Secondary dofs don't match rows!"); for (int jptr = I[i]; jptr < I[i + 1]; ++jptr) { int j = J[jptr]; if (secondary_dofs.Find(j) == -1) { primary_dofs.Append(j); } } } primary_dofs.Sort(); primary_dofs.Unique(); eliminators.Append(new Eliminator(B, lagrange_dofs, primary_dofs, secondary_dofs)); } } projector = new EliminationProjection(hA, eliminators); } void EliminationSolver::PrimalMult(const Vector& rhs, Vector& sol) const { if (!prec) { prec = BuildPreconditioner(); } IterativeSolver * krylov = BuildKrylov(); krylov->SetOperator(*h_explicit_operator); krylov->SetPreconditioner(*prec); krylov->SetMaxIter(max_iter); krylov->SetRelTol(rel_tol); krylov->SetAbsTol(abs_tol); krylov->SetPrintLevel(print_level); Vector rtilde(rhs.Size()); if (constraint_rhs.Size() > 0) { projector->BuildGTilde(constraint_rhs, rtilde); } else { rtilde = 0.0; } Vector temprhs(rhs); hA.Mult(-1.0, rtilde, 1.0, temprhs); Vector reducedrhs(rhs.Size()); projector->MultTranspose(temprhs, reducedrhs); Vector reducedsol(rhs.Size()); reducedsol = 0.0; krylov->Mult(reducedrhs, reducedsol); final_iter = krylov->GetNumIterations(); final_norm = krylov->GetFinalNorm(); converged = krylov->GetConverged(); delete krylov; projector->Mult(reducedsol, sol); projector->RecoverMultiplier(temprhs, sol, multiplier_sol); sol += rtilde; } void PenaltyConstrainedSolver::Initialize(HypreParMatrix& A, HypreParMatrix& B) { HypreParMatrix * hBT = B.Transpose(); HypreParMatrix * hBTB = ParMult(hBT, &B, true); // this matrix doesn't get cleanly deleted? // (hypre comm pkg) (*hBTB) *= penalty; penalized_mat = ParAdd(&A, hBTB); delete hBTB; delete hBT; } PenaltyConstrainedSolver::PenaltyConstrainedSolver( HypreParMatrix& A, SparseMatrix& B, double penalty_) : ConstrainedSolver(A.GetComm(), A, B), penalty(penalty_), constraintB(B), prec(nullptr) { int rank, size; MPI_Comm_rank(A.GetComm(), &rank); MPI_Comm_size(A.GetComm(), &size); int constraint_running_total = 0; int local_constraints = B.Height(); MPI_Scan(&local_constraints, &constraint_running_total, 1, MPI_INT, MPI_SUM, A.GetComm()); int global_constraints = 0; if (rank == size - 1) { global_constraints = constraint_running_total; } MPI_Bcast(&global_constraints, 1, MPI_INT, size - 1, A.GetComm()); HYPRE_Int glob_num_rows = global_constraints; HYPRE_Int glob_num_cols = A.N(); HYPRE_Int row_starts[2] = {constraint_running_total - local_constraints, constraint_running_total }; HYPRE_Int col_starts[2] = {A.ColPart()[0], A.ColPart()[1]}; HypreParMatrix hB(A.GetComm(), glob_num_rows, glob_num_cols, row_starts, col_starts, &B); hB.CopyRowStarts(); hB.CopyColStarts(); Initialize(A, hB); } PenaltyConstrainedSolver::PenaltyConstrainedSolver( HypreParMatrix& A, HypreParMatrix& B, double penalty_) : ConstrainedSolver(A.GetComm(), A, B), penalty(penalty_), constraintB(B), prec(nullptr) { Initialize(A, B); } PenaltyConstrainedSolver::~PenaltyConstrainedSolver() { delete penalized_mat; delete prec; } void PenaltyConstrainedSolver::PrimalMult(const Vector& b, Vector& x) const { if (!prec) { prec = BuildPreconditioner(); } IterativeSolver * krylov = BuildKrylov(); // form penalized right-hand side Vector penalized_rhs(b); if (constraint_rhs.Size() > 0) { Vector temp(x.Size()); constraintB.MultTranspose(constraint_rhs, temp); temp *= penalty; penalized_rhs += temp; } // actually solve krylov->SetOperator(*penalized_mat); krylov->SetRelTol(rel_tol); krylov->SetAbsTol(abs_tol); krylov->SetMaxIter(max_iter); krylov->SetPrintLevel(print_level); krylov->SetPreconditioner(*prec); krylov->Mult(penalized_rhs, x); final_iter = krylov->GetNumIterations(); final_norm = krylov->GetFinalNorm(); converged = krylov->GetConverged(); delete krylov; constraintB.Mult(x, multiplier_sol); if (constraint_rhs.Size() > 0) { multiplier_sol -= constraint_rhs; } multiplier_sol *= penalty; } #endif /// because IdentityOperator isn't a Solver class IdentitySolver : public Solver { public: IdentitySolver(int size) : Solver(size) { } void Mult(const Vector& x, Vector& y) const { y = x; } void SetOperator(const Operator& op) { } }; void SchurConstrainedSolver::Initialize() { offsets[0] = 0; offsets[1] = A.Height(); offsets[2] = A.Height() + B.Height(); block_op = new BlockOperator(offsets); block_op->SetBlock(0, 0, &A); block_op->SetBlock(1, 0, &B); tr_B = new TransposeOperator(&B); block_op->SetBlock(0, 1, tr_B); block_pc = new BlockDiagonalPreconditioner(block_op->RowOffsets()), rel_tol = 1.e-6; } #ifdef MFEM_USE_MPI SchurConstrainedSolver::SchurConstrainedSolver(MPI_Comm comm, Operator& A_, Operator& B_, Solver& primal_pc_) : ConstrainedSolver(comm, A_, B_), offsets(3), primal_pc(&primal_pc_), dual_pc(nullptr) { Initialize(); primal_pc->SetOperator(block_op->GetBlock(0, 0)); dual_pc = new IdentitySolver(block_op->RowOffsets()[2] - block_op->RowOffsets()[1]); block_pc->SetDiagonalBlock(0, primal_pc); block_pc->SetDiagonalBlock(1, dual_pc); } #endif SchurConstrainedSolver::SchurConstrainedSolver(Operator& A_, Operator& B_, Solver& primal_pc_) : ConstrainedSolver(A_, B_), offsets(3), primal_pc(&primal_pc_), dual_pc(nullptr) { Initialize(); primal_pc->SetOperator(block_op->GetBlock(0, 0)); dual_pc = new IdentitySolver(block_op->RowOffsets()[2] - block_op->RowOffsets()[1]); block_pc->SetDiagonalBlock(0, primal_pc); block_pc->SetDiagonalBlock(1, dual_pc); } #ifdef MFEM_USE_MPI // protected constructor SchurConstrainedSolver::SchurConstrainedSolver(MPI_Comm comm, Operator& A_, Operator& B_) : ConstrainedSolver(comm, A_, B_), offsets(3), primal_pc(nullptr), dual_pc(nullptr) { Initialize(); } #endif // protected constructor SchurConstrainedSolver::SchurConstrainedSolver(Operator& A_, Operator& B_) : ConstrainedSolver(A_, B_), offsets(3), primal_pc(nullptr), dual_pc(nullptr) { Initialize(); } SchurConstrainedSolver::~SchurConstrainedSolver() { delete block_op; delete tr_B; delete block_pc; delete dual_pc; } void SchurConstrainedSolver::Mult(const Vector& x, Vector& y) const { GMRESSolver * gmres; #ifdef MFEM_USE_MPI if (GetComm() != MPI_COMM_NULL) { gmres = new GMRESSolver(GetComm()); } else #endif { gmres = new GMRESSolver; } gmres->SetOperator(*block_op); gmres->SetRelTol(rel_tol); gmres->SetAbsTol(abs_tol); gmres->SetMaxIter(max_iter); gmres->SetPrintLevel(print_level); gmres->SetPreconditioner( const_cast<BlockDiagonalPreconditioner&>(*block_pc)); gmres->Mult(x, y); final_iter = gmres->GetNumIterations(); delete gmres; } #ifdef MFEM_USE_MPI SchurConstrainedHypreSolver::SchurConstrainedHypreSolver(MPI_Comm comm, HypreParMatrix& hA_, HypreParMatrix& hB_, int dimension, bool reorder) : SchurConstrainedSolver(comm, hA_, hB_), hA(hA_), hB(hB_) { auto h_primal_pc = new HypreBoomerAMG(hA); h_primal_pc->SetPrintLevel(0); if (dimension > 0) { h_primal_pc->SetSystemsOptions(dimension, reorder); } primal_pc = h_primal_pc; HypreParMatrix * scaledB = new HypreParMatrix(hB); Vector diagA; hA.GetDiag(diagA); HypreParMatrix * scaledBT = scaledB->Transpose(); scaledBT->InvScaleRows(diagA); schur_mat = ParMult(scaledB, scaledBT); schur_mat->CopyRowStarts(); schur_mat->CopyColStarts(); auto h_dual_pc = new HypreBoomerAMG(*schur_mat); h_dual_pc->SetPrintLevel(0); dual_pc = h_dual_pc; delete scaledB; delete scaledBT; block_pc->SetDiagonalBlock(0, primal_pc); block_pc->SetDiagonalBlock(1, dual_pc); } SchurConstrainedHypreSolver::~SchurConstrainedHypreSolver() { delete schur_mat; delete primal_pc; } #endif void ConstrainedSolver::Initialize() { height = A.Height() + B.Height(); width = A.Width() + B.Height(); workb.SetSize(A.Height()); workx.SetSize(A.Height()); constraint_rhs.SetSize(B.Height()); constraint_rhs = 0.0; multiplier_sol.SetSize(B.Height()); } #ifdef MFEM_USE_MPI ConstrainedSolver::ConstrainedSolver(MPI_Comm comm, Operator& A_, Operator& B_) : IterativeSolver(comm), A(A_), B(B_) { Initialize(); } #endif ConstrainedSolver::ConstrainedSolver(Operator& A_, Operator& B_) : A(A_), B(B_) { Initialize(); } void ConstrainedSolver::SetConstraintRHS(const Vector& r) { MFEM_VERIFY(r.Size() == multiplier_sol.Size(), "Vector is wrong size!"); constraint_rhs = r; } void ConstrainedSolver::PrimalMult(const Vector& f, Vector &x) const { Vector pworkb(A.Height() + B.Height()); Vector pworkx(A.Height() + B.Height()); pworkb = 0.0; pworkx = 0.0; for (int i = 0; i < f.Size(); ++i) { pworkb(i) = f(i); pworkx(i) = x(i); } for (int i = 0; i < B.Height(); ++i) { pworkb(f.Size() + i) = constraint_rhs(i); } Mult(pworkb, pworkx); for (int i = 0; i < f.Size(); ++i) { x(i) = pworkx(i); } for (int i = 0; i < B.Height(); ++i) { multiplier_sol(i) = pworkx(f.Size() + i); } } void ConstrainedSolver::Mult(const Vector& f_and_r, Vector& x_and_lambda) const { workb.MakeRef(const_cast<Vector&>(f_and_r), 0); workx.MakeRef(x_and_lambda, 0); Vector ref_constraint_rhs(f_and_r.GetData() + A.Height(), B.Height()); constraint_rhs = ref_constraint_rhs; PrimalMult(workb, workx); Vector ref_constraint_sol(x_and_lambda.GetData() + A.Height(), B.Height()); GetMultiplierSolution(ref_constraint_sol); } /* Helper routine to reduce code duplication - given a node (which MFEM sometimes calls a "dof"), this returns what normal people call a dof but which MFEM sometimes calls a "vdof" - note that MFEM's naming conventions regarding this are not entirely consistent. In parallel, this always returns the "truedof" in parallel numbering. */ int CanonicalNodeNumber(FiniteElementSpace& fespace, int node, bool parallel, int d=0) { #ifdef MFEM_USE_MPI if (parallel) { try { ParFiniteElementSpace& pfespace = dynamic_cast<ParFiniteElementSpace&>(fespace); const int vdof = pfespace.DofToVDof(node, d); return pfespace.GetLocalTDofNumber(vdof); } catch (std::bad_cast&) { MFEM_ABORT("Asked for parallel form of serial object!"); return -1; } } else #endif { return fespace.DofToVDof(node, d); } } SparseMatrix * BuildNormalConstraints(FiniteElementSpace& fespace, Array<int>& constrained_att, Array<int>& constraint_rowstarts, bool parallel) { int dim = fespace.GetVDim(); // dof_constraint maps a dof (column of the constraint matrix) to // a block-constraint // the indexing is by tdof, but a single tdof uniquely identifies a node // so we only store one tdof independent of dimension std::map<int, int> dof_bconstraint; // constraints[j] is a map from attribute to row number, // the j itself is the index of a block-constraint std::vector<std::map<int, int> > constraints; int n_bconstraints = 0; int n_rows = 0; for (int att : constrained_att) { // identify tdofs on constrained boundary std::set<int> constrained_tdofs; for (int i = 0; i < fespace.GetNBE(); ++i) { if (fespace.GetBdrAttribute(i) == att) { Array<int> nodes; // get nodes on boundary (MFEM sometimes calls these dofs, what // we call dofs it calls vdofs) fespace.GetBdrElementDofs(i, nodes); for (auto k : nodes) { // get the (local) dof number corresponding to // the x-coordinate dof for node k int tdof = CanonicalNodeNumber(fespace, k, parallel); if (tdof >= 0) { constrained_tdofs.insert(tdof); } } } } // fill in the maps identifying which constraints (rows) correspond to // which tdofs for (auto k : constrained_tdofs) { auto it = dof_bconstraint.find(k); if (it == dof_bconstraint.end()) { // build new block constraint dof_bconstraint[k] = n_bconstraints++; constraints.emplace_back(); constraints.back()[att] = n_rows++; } else { // add tdof to existing block constraint constraints[it->second][att] = n_rows++; } } } // reorder so block-constraints eliminated together are grouped together in // adjacent rows { std::map<int, int> reorder_rows; int new_row = 0; constraint_rowstarts.DeleteAll(); constraint_rowstarts.Append(0); for (auto& it : dof_bconstraint) { int bconstraint_index = it.second; bool nconstraint = false; for (auto& att_it : constraints[bconstraint_index]) { auto rrit = reorder_rows.find(att_it.second); if (rrit == reorder_rows.end()) { nconstraint = true; reorder_rows[att_it.second] = new_row++; } } if (nconstraint) { constraint_rowstarts.Append(new_row); } } MFEM_VERIFY(new_row == n_rows, "Remapping failed!"); for (auto& constraint_map : constraints) { for (auto& it : constraint_map) { it.second = reorder_rows[it.second]; } } } SparseMatrix * out = new SparseMatrix(n_rows, fespace.GetTrueVSize()); // fill in constraint matrix with normal vector information Vector nor(dim); // how many times we have seen a node (key is truek) std::map<int, int> node_visits; for (int i = 0; i < fespace.GetNBE(); ++i) { int att = fespace.GetBdrAttribute(i); if (constrained_att.FindSorted(att) != -1) { ElementTransformation * Tr = fespace.GetBdrElementTransformation(i); const FiniteElement * fe = fespace.GetBE(i); const IntegrationRule& nodes = fe->GetNodes(); Array<int> dofs; fespace.GetBdrElementDofs(i, dofs); MFEM_VERIFY(dofs.Size() == nodes.Size(), "Something wrong in finite element space!"); for (int j = 0; j < dofs.Size(); ++j) { Tr->SetIntPoint(&nodes[j]); // the normal returned in the next line is scaled by h, which is // probably what we want in most applications CalcOrtho(Tr->Jacobian(), nor); int k = dofs[j]; int truek = CanonicalNodeNumber(fespace, k, parallel); if (truek >= 0) { auto nv_it = node_visits.find(truek); if (nv_it == node_visits.end()) { node_visits[truek] = 1; } else { node_visits[truek]++; } int visits = node_visits[truek]; int bconstraint = dof_bconstraint[truek]; int row = constraints[bconstraint][att]; for (int d = 0; d < dim; ++d) { int inner_truek = CanonicalNodeNumber(fespace, k, parallel, d); if (visits == 1) { out->Add(row, inner_truek, nor[d]); } else { out->SetColPtr(row); const double pv = out->SearchRow(inner_truek); const double scaling = ((double) (visits - 1)) / ((double) visits); // incremental average, based on how many times // this node has been visited out->Set(row, inner_truek, scaling * pv + (1.0 / visits) * nor[d]); } } } } } } out->Finalize(); return out; } #ifdef MFEM_USE_MPI SparseMatrix * ParBuildNormalConstraints(ParFiniteElementSpace& fespace, Array<int>& constrained_att, Array<int>& constraint_rowstarts) { return BuildNormalConstraints(fespace, constrained_att, constraint_rowstarts, true); } #endif }
we're not using this header here
#include <iostream> #include "bots.h" #include <boost/asio.hpp> #include <boost/thread/thread.hpp> using boost::asio::ip::tcp; void async_send(tcp::socket &socket, const std::string & str) { boost::asio::async_write(socket, boost::asio::buffer(str + "\n"), boost::asio::transfer_all()); } void pinta_escenario( bots mis_bots, int paso, int cols, int filas) { std::cout << "Paso : " << paso << std::endl; for ( int col = 0; col < cols + 2; col++ ) // Primera fila de X std::cout << 'X'; std::cout << std::endl; for ( int fila = 0; fila < filas; fila++ ) //! Recorre toda la altura { std::cout << 'X'; // Primera X de la fila for ( int col = 0; col < cols; col++ ) // Espacios en blanco { bot * pos_bot = mis_bots.find_at( { col, fila} ); if ( pos_bot == nullptr ) std::cout << ' '; else std::cout << pos_bot->get_team(); } std::cout << 'X'; //! Espacios de 1a altura - fila std::cout << std::endl; } for ( int col = 0; col < cols + 2; col++ ) // Primera fila de X std::cout << 'X'; std::cout << std::endl; } int main (int argc, char* argv[]) { boost::asio::io_service io_service; // Inicia comunicaciones tcp::resolver resolver(io_service); // Resuelve la comunicación auto endpoint_iterator = resolver.resolve({ argv[1], argv[2] }); // Iterador hacia puerto y dirección std::shared_ptr<tcp::socket> socket(new tcp::socket(io_service)); // Puntero compartido hacia el socket boost::asio::connect(*socket, endpoint_iterator); // Conexión io_service.run(); int paso = 0; // Variables de comunicacion boost::mutex state_mutex; bool gameover = false; bool connected = false; bot::team_id id = 6666; bot::field_size field_width; bot::field_size field_height; int win_width = 500; int win_height = 500; // Mi instancia de la clase bots bots mi_bots = bots(field_width, field_height); // Tamaño del campo 10x10, usa la pila //Lee el bufer de comunicaciones boost::asio::streambuf buf; read_until(*socket, buf, "\n"); std::string data; std::istream is(&buf); std::getline(is, data); std::istringstream mi_stream(data); // Lee la primer palabra std::string command; mi_stream >> command; // Lee la información inicial if(command == "welcome") { mi_stream >> id; std::cout << "team id: " << id << std::endl; //ai.set_team(id); mi_stream >> field_width; mi_stream >> field_height; mi_bots.set_size(field_width, field_height); std::cout << "setting field: " << field_width << " x " << field_height << std::endl; } while (!gameover) { { read_until(*socket, buf, "\n"); //Leo el bufer std::istream is2(&buf); // Input Stream (lectura) a la clase buf std::getline(is2, data); // Convierte a String y guarda en data std::istringstream mi_stream2(data); // Input Stream (letura) al string data mi_stream2 >> command; //Lee el estado del escenario if(command == "state") { std::stringstream state; while(!mi_stream2.eof()) { std::string a; mi_stream2 >> a; state << a << " "; } std::cout << state.str() << std::endl; boost::archive::text_iarchive ia(state); { boost::mutex::scoped_lock lock(state_mutex); ia >> mi_bots; paso++; std::cout << "\x1B[2J\x1B[H"; // Limpia pantalla pinta_escenario(mi_bots, paso, field_width, field_height); } } else { std::cout << "GAME OVER " << command << std::endl; } } mi_bots.for_each_bot([&] ( bot & b ) { std::stringstream stream; // Envia movimeinte del bot stream << "move " << b.get_x() << " " << b.get_y() << " " << bot::W; async_send(*socket, stream.str()); }); //while ( std::cin.get() != ' ' ); // Espera entrada espacio } return 0; } Asinc comms OK! #include <iostream> #include "bots.h" #include <boost/asio.hpp> #include <boost/thread/thread.hpp> using boost::asio::ip::tcp; void pinta_escenario( bots & mis_bots, bot::field_size cols, bot::field_size filas) { std::cout << "\x1B[2J\x1B[H"; // Despeja la pantalla del terminal for ( int col = 0; col < cols + 2; col++ ) // Primera fila de X std::cout << 'X'; std::cout << std::endl; for ( int fila = 0; fila < filas; fila++ ) //! Recorre toda la altura { std::cout << 'X'; // Primera X de la fila for ( int col = 0; col < cols; col++ ) // Espacios en blanco { bot * pos_bot = mis_bots.find_at( { col, fila} ); if ( pos_bot == nullptr ) std::cout << ' '; else std::cout << pos_bot->get_team(); } std::cout << 'X'; //! Espacios de 1a altura - fila std::cout << std::endl; } for ( int col = 0; col < cols + 2; col++ ) // Primera fila de X std::cout << 'X'; std::cout << std::endl; } class client_bot { private: tcp::resolver _resolver; tcp::socket _socket; boost::asio::streambuf _packetToSend; boost::asio::streambuf _receiver; bots & _bots; boost::mutex & _state_mutex; bot::team_id & _id; bot::field_size _field_width; bot::field_size _field_height; public: client_bot(boost::asio::io_service& io_service, const std::string& server, const std::string& port, bots & bts, boost::mutex & sm, bot::team_id & id) : _resolver(io_service), _socket(io_service), _bots(bts), _state_mutex(sm), _id(id) { // Start an asynchronous resolve to translate the server and service names // into a list of endpoints. std::cout << "Resolving..." << std::endl; tcp::resolver::query query(server, port); _resolver.async_resolve(query, boost::bind(&client_bot::handle_resolve, this, boost::asio::placeholders::error, boost::asio::placeholders::iterator)); } private: void handle_resolve(const boost::system::error_code& err, tcp::resolver::iterator endpoint_iterator) { if (!err) { // Attempt a connection to the first endpoint in the list. Each endpoint // will be tried until we successfully establish a connection. std::cout << "Connecting to " << endpoint_iterator->host_name() << std::endl; tcp::endpoint endpoint = *endpoint_iterator; _socket.async_connect(endpoint, boost::bind(&client_bot::handle_connect, this, boost::asio::placeholders::error, ++endpoint_iterator)); } else { std::cout << "Error resolving: " << err.message() << "\n"; } } void handle_connect(const boost::system::error_code& err, tcp::resolver::iterator endpoint_iterator) { if (!err) { // The connection was successful. Send the request. std::cout << "Retrieving..." << std::endl; // Read the response status line. boost::asio::async_read_until(_socket, _receiver, "\n", boost::bind(&client_bot::handle_read_command, this, boost::asio::placeholders::error)); } else if (endpoint_iterator != tcp::resolver::iterator()) { // The connection failed. Try the next endpoint in the list. _socket.close(); tcp::endpoint endpoint = *endpoint_iterator; _socket.async_connect(endpoint, boost::bind(&client_bot::handle_connect, this, boost::asio::placeholders::error, ++endpoint_iterator)); } else { std::cout << "Error: " << err.message() << "\n"; } } void handle_read_command(const boost::system::error_code& err) { if (!err) { // Check that response is OK. std::string data; std::istream _receiverstream(&_receiver); std::getline(_receiverstream, data); std::istringstream stream(data); std::string command; stream >> command; // Read the response headers, which are terminated by a blank line. if(command == "welcome") { stream >> _id; stream >> _field_width; stream >> _field_height; std::cout << data << std::endl; //ai.set_team(id); while(!stream.eof()) { std::string a; stream >> a; //state << a << " "; } } else if(command == "state") { std::stringstream state; while(!stream.eof()) { std::string a; stream >> a; state << a << " "; } boost::archive::text_iarchive ia(state); { // mutex: // segfaults if it draws during a state update (drawing + // incomplete state is fatal) boost::mutex::scoped_lock lock(_state_mutex); ia >> _bots; } std::cout << "State updated" << std::endl; pinta_escenario(_bots, _field_width, _field_height); } for(auto b : _bots.team_bots(_id)) { std::ostream _packetToSendstream(&_packetToSend); _packetToSendstream << "move " << b->get_x() << " " << b->get_y() << " 3\n"; boost::asio::async_write(_socket, _packetToSend, boost::bind(&client_bot::handle_write_request, this, boost::asio::placeholders::error)); } boost::asio::async_read_until(_socket, _receiver, "\n", boost::bind(&client_bot::handle_read_command, this, boost::asio::placeholders::error)); } else { std::cout << "Error reading command: " << err << "\n"; } } void handle_write_request(const boost::system::error_code& err) { if (!err) { } else { std::cout << "Error writing: " << err.message() << "\n"; } } }; int main (int argc, char* argv[]) { // Mi instancia de la clase bots bots mi_bots; bot::team_id id = 1001; boost::asio::io_service io_service; // Inicia comunicaciones boost::mutex state_mutex; client_bot mi_cliente_bot(io_service, argv[1], argv[2], mi_bots, state_mutex, id); io_service.run(); return(0); }
#include "catch.hpp" #include "test/test_case_fixture.h" #include <cstdio> #include <cstdlib> #ifdef _MSC_VER #include <atlsafe.h> #include <comutil.h> #ifdef _DEBUG #pragma comment(lib, "comsuppwd.lib") #else #pragma comment(lib, "comsuppw.lib") #endif #endif namespace { struct mssql_fixture : public test_case_fixture { mssql_fixture() : test_case_fixture() { // connection string from command line or NANODBC_TEST_CONNSTR environment variable if (connection_string_.empty()) connection_string_ = get_env("NANODBC_TEST_CONNSTR_MSSQL"); } }; } TEST_CASE_METHOD(mssql_fixture, "test_driver", "[mssql][driver]") { test_driver(); } TEST_CASE_METHOD(mssql_fixture, "test_affected_rows", "[mssql][affected_rows]") { // Skip on SQL Server 2008, see details at // http://help.appveyor.com/discussions/problems/4704-database-cannot-be-autostarted-during-server-shutdown-or-startup if (get_env("DB") == NANODBC_TEXT("MSSQL2008")) { WARN("test_affected_rows skipped on AppVeyor with SQL Server 2008"); return; } // Enable MARS required? #if 0 enum { SQL_COPT_SS_MARS_ENABLED = 1224, SQL_MARS_ENABLED_YES = 1 }; // sqlext.h int rc = ::SQLSetConnectAttr(conn.native_dbc_handle(), SQL_COPT_SS_MARS_ENABLED, (SQLPOINTER)SQL_MARS_ENABLED_YES, SQL_IS_UINTEGER); REQUIRE(rc == 0); #endif auto conn = connect(); auto const current_db_name = conn.database_name(); // CREATE DATABASE|TABLE { execute( conn, NANODBC_TEXT( "IF DB_ID('nanodbc_test_temp_db') IS NOT NULL DROP DATABASE nanodbc_test_temp_db")); nanodbc::result result; result = execute(conn, NANODBC_TEXT("CREATE DATABASE nanodbc_test_temp_db")); REQUIRE(result.affected_rows() == -1); execute(conn, NANODBC_TEXT("USE nanodbc_test_temp_db")); result = execute(conn, NANODBC_TEXT("CREATE TABLE nanodbc_test_temp_table (i int)")); REQUIRE(result.affected_rows() == -1); } // INSERT { nanodbc::result result; result = execute(conn, NANODBC_TEXT("INSERT INTO nanodbc_test_temp_table VALUES (1)")); REQUIRE(result.affected_rows() == 1); result = execute(conn, NANODBC_TEXT("INSERT INTO nanodbc_test_temp_table VALUES (2)")); REQUIRE(result.affected_rows() == 1); } // SELECT { auto result = execute(conn, NANODBC_TEXT("SELECT i FROM nanodbc_test_temp_table")); REQUIRE(result.affected_rows() == -1); } // DELETE { auto result = execute(conn, NANODBC_TEXT("DELETE FROM nanodbc_test_temp_table")); REQUIRE(result.affected_rows() == 2); } // DROP DATABASE|TABLE { nanodbc::result result; result = execute(conn, NANODBC_TEXT("DROP TABLE nanodbc_test_temp_table")); REQUIRE(result.affected_rows() == -1); execute(conn, NANODBC_TEXT("USE ") + current_db_name); result = execute(conn, NANODBC_TEXT("DROP DATABASE nanodbc_test_temp_db")); REQUIRE(result.affected_rows() == -1); } } TEST_CASE_METHOD(mssql_fixture, "test_batch_insert_integral", "[mssql][batch][integral]") { test_batch_insert_integral(); } TEST_CASE_METHOD(mssql_fixture, "test_batch_insert_string", "[mssql][batch][string]") { test_batch_insert_string(); } TEST_CASE_METHOD(mssql_fixture, "test_batch_insert_mixed", "[mssql][batch]") { test_batch_insert_mixed(); } TEST_CASE_METHOD(mssql_fixture, "test_blob", "[mssql][blob][binary][varbinary]") { nanodbc::connection connection = connect(); // Test data size less than the default size of the internal buffer (1024) { create_table(connection, NANODBC_TEXT("test_blob"), NANODBC_TEXT("(data varbinary(max))")); execute( connection, NANODBC_TEXT("insert into test_blob values (CONVERT(varbinary(max), " "'0x010100000000000000000059400000000000005940', 1));")); nanodbc::result results = nanodbc::execute(connection, NANODBC_TEXT("select data from test_blob;")); REQUIRE(results.next()); auto const blob = results.get<std::vector<std::uint8_t>>(0); REQUIRE(blob.size() == 21); REQUIRE(to_hex_string(blob) == "010100000000000000000059400000000000005940"); } // Test data size greater than, but not multiple of, the default size of the internal buffer // (1024) { create_table(connection, NANODBC_TEXT("test_blob"), NANODBC_TEXT("(data varbinary(max))")); execute(connection, NANODBC_TEXT("insert into test_blob values (CRYPT_GEN_RANDOM(1579));")); nanodbc::result results = nanodbc::execute(connection, NANODBC_TEXT("select data from test_blob;")); REQUIRE(results.next()); REQUIRE(results.get<std::vector<std::uint8_t>>(0).size() == 1579); } } TEST_CASE_METHOD( mssql_fixture, "test_blob_with_varchar", "[mssql][blob][binary][varbinary][varchar]") { nanodbc::string s = NANODBC_TEXT( "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" "AAAAAAAAABBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB" "BBBBBBBBBBBBBBBBBBCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC" "CCCCCCCCCCCCCCCCCCCCCCCCCCCDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD" "DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE" "EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF" "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG" "GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGHHHHHHHHHHHHHHHHHHHHHHHHHHHHH" "HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHIIIIIIIIIIIIIIIIIIII" "IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIJJJJJJJJJJJ" "JJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJKKK" "KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK" "KKKKKKLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL" "LLLLLLLLLLLLLLLMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM" "MMMMMMMMMMMMMMMMMMMMMMMNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN" "NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO" "OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP" "PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQ" "QQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR" "RRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRSSSSSSSSSSSSSSSSSSSSSSS" "SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSTTTTTTTTTTTTTTT" "TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTUUUUUU" "UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU" "UUUVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV" "VVVVVVVVVVVVWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW" "WWWWWWWWWWWWWWWWWWWWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY" "YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ" "ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ"); nanodbc::connection connection = connect(); create_table( connection, NANODBC_TEXT("test_blob_with_varchar"), NANODBC_TEXT("(data varbinary(max))")); execute( connection, NANODBC_TEXT("insert into test_blob_with_varchar values (CONVERT(varbinary(max), '") + s + NANODBC_TEXT("'));")); nanodbc::result results = nanodbc::execute(connection, NANODBC_TEXT("select data from test_blob_with_varchar;")); REQUIRE(results.next()); REQUIRE(results.get<nanodbc::string>(0) == s); } TEST_CASE_METHOD( mssql_fixture, "test_block_cursor_with_nvarchar", "[mssql][nvarchar][block][rowset]") { nanodbc::connection conn = connect(); // BLock Cursors: https://technet.microsoft.com/en-us/library/aa172590.aspx std::size_t const rowset_size = 2; create_table( conn, NANODBC_TEXT("test_variable_string"), NANODBC_TEXT("(i int, s nvarchar(256))")); execute( conn, NANODBC_TEXT( "insert into test_variable_string (i, s) values (1, 'this is a shorter text');")); execute( conn, NANODBC_TEXT( "insert into test_variable_string (i, s) values (2, 'this is a longer text of the two " "texts in the table');")); nanodbc::result results = nanodbc::execute( conn, NANODBC_TEXT("select i, s from test_variable_string order by i;"), rowset_size); REQUIRE(results.next()); REQUIRE(results.get<nanodbc::string>(1) == NANODBC_TEXT("this is a shorter text")); REQUIRE(results.next()); REQUIRE( results.get<nanodbc::string>(1) == NANODBC_TEXT("this is a longer text of the two texts in the table")); REQUIRE(!results.next()); } TEST_CASE_METHOD( mssql_fixture, "test_block_cursor_with_nvarchar_and_first_row_null", "[mssql][nvarchar][block][rowset]") { nanodbc::connection conn = connect(); std::size_t const rowset_size = 2; create_table( conn, NANODBC_TEXT("test_variable_string"), NANODBC_TEXT("(i int, s nvarchar(256))")); execute(conn, NANODBC_TEXT("insert into test_variable_string (i, s) values (1, NULL);")); execute( conn, NANODBC_TEXT( "insert into test_variable_string (i, s) values (2, 'this is a longer text of the two " "texts in the table');")); nanodbc::result results = nanodbc::execute( conn, NANODBC_TEXT("select i, s from test_variable_string order by i;"), rowset_size); REQUIRE(results.next()); REQUIRE(results.is_null(1)); REQUIRE(results.get<nanodbc::string>(1, NANODBC_TEXT("nothing")) == NANODBC_TEXT("nothing")); REQUIRE(results.next()); REQUIRE(!results.is_null(1)); REQUIRE( results.get<nanodbc::string>(1) == NANODBC_TEXT("this is a longer text of the two texts in the table")); REQUIRE(!results.next()); } TEST_CASE_METHOD( mssql_fixture, "test_block_cursor_with_nvarchar_and_second_row_null", "[mssql][nvarchar][block][rowset]") { nanodbc::connection conn = connect(); std::size_t const rowset_size = 2; create_table( conn, NANODBC_TEXT("test_variable_string"), NANODBC_TEXT("(i int, s nvarchar(256))")); execute( conn, NANODBC_TEXT( "insert into test_variable_string (i, s) values (1, 'this is a shorter text');")); execute(conn, NANODBC_TEXT("insert into test_variable_string (i, s) values (2, NULL);")); nanodbc::result results = nanodbc::execute( conn, NANODBC_TEXT("select i, s from test_variable_string order by i;"), rowset_size); REQUIRE(results.next()); REQUIRE(!results.is_null(1)); REQUIRE(results.get<nanodbc::string>(1) == NANODBC_TEXT("this is a shorter text")); REQUIRE(results.next()); REQUIRE(results.is_null(1)); REQUIRE(results.get<nanodbc::string>(1, NANODBC_TEXT("nothing")) == NANODBC_TEXT("nothing")); REQUIRE(!results.next()); } TEST_CASE_METHOD(mssql_fixture, "test_catalog_list_catalogs", "[mssql][catalog][catalogs]") { test_catalog_list_catalogs(); } TEST_CASE_METHOD(mssql_fixture, "test_catalog_list_schemas", "[mssql][catalog][schemas]") { test_catalog_list_schemas(); } TEST_CASE_METHOD(mssql_fixture, "test_catalog_columns", "[mssql][catalog][columns]") { test_catalog_columns(); } TEST_CASE_METHOD(mssql_fixture, "test_catalog_primary_keys", "[mssql][catalog][primary_keys]") { test_catalog_primary_keys(); } TEST_CASE_METHOD(mssql_fixture, "test_catalog_tables", "[mssql][catalog][tables]") { test_catalog_tables(); } TEST_CASE_METHOD(mssql_fixture, "test_catalog_table_privileges", "[mssql][catalog][tables]") { test_catalog_table_privileges(); } TEST_CASE_METHOD(mssql_fixture, "test_column_descriptor", "[mssql][columns]") { test_column_descriptor(); } TEST_CASE_METHOD(mssql_fixture, "test_dbms_info", "[mssql][dmbs][metadata][info]") { test_dbms_info(); } TEST_CASE_METHOD(mssql_fixture, "test_get_info", "[mssql][dmbs][metadata][info]") { test_get_info(); } TEST_CASE_METHOD(mssql_fixture, "test_decimal_conversion", "[mssql][decimal][conversion]") { test_decimal_conversion(); } TEST_CASE_METHOD(mssql_fixture, "test_exception", "[mssql][exception]") { test_exception(); } TEST_CASE_METHOD( mssql_fixture, "test_execute_multiple_transaction", "[mssql][execute][transaction]") { test_execute_multiple_transaction(); } TEST_CASE_METHOD(mssql_fixture, "test_execute_multiple", "[mssql][execute]") { test_execute_multiple(); } TEST_CASE_METHOD(mssql_fixture, "test_integral", "[mssql][integral]") { test_integral<mssql_fixture>(); } TEST_CASE_METHOD(mssql_fixture, "test_move", "[mssql][move]") { test_move(); } TEST_CASE_METHOD(mssql_fixture, "test_null", "[mssql][null]") { test_null(); } TEST_CASE_METHOD(mssql_fixture, "test_nullptr_nulls", "[mssql][null]") { test_nullptr_nulls(); } TEST_CASE_METHOD(mssql_fixture, "test_result_iterator", "[mssql][iterator]") { test_result_iterator(); } TEST_CASE_METHOD(mssql_fixture, "test_simple", "[mssql]") { test_simple(); } TEST_CASE_METHOD(mssql_fixture, "test_string", "[mssql][string]") { test_string(); } TEST_CASE_METHOD(mssql_fixture, "test_string_vector", "[mssql][string]") { test_string_vector(); } TEST_CASE_METHOD(mssql_fixture, "test_batch_binary", "[mssql][binary]") { test_batch_binary(); } TEST_CASE_METHOD(mssql_fixture, "test_time", "[mssql][time]") { test_time(); } TEST_CASE_METHOD(mssql_fixture, "test_date", "[mssql][date]") { test_date(); } TEST_CASE_METHOD(mssql_fixture, "test_datetime", "[mssql][datetime]") { auto connection = connect(); create_table(connection, NANODBC_TEXT("test_datetime"), NANODBC_TEXT("d datetime")); // insert // See "CAST and CONVERT" https://msdn.microsoft.com/en-US/library/ms187928.aspx { execute( connection, NANODBC_TEXT("insert into test_datetime(d) values (CONVERT(datetime, " "'2006-12-30T13:45:12.345', 126));")); } // select { auto result = execute(connection, NANODBC_TEXT("select d from test_datetime;")); REQUIRE(result.column_name(0) != NANODBC_TEXT("d")); REQUIRE(result.column_datatype(0) == SQL_TYPE_TIMESTAMP); REQUIRE(result.column_datatype_name(0) == NANODBC_TEXT("datetime")); REQUIRE(result.next()); auto t = result.get<nanodbc::timestamp>(0); REQUIRE(t.year == 2006); REQUIRE(t.month == 12); REQUIRE(t.day == 30); REQUIRE(t.hour == 13); REQUIRE(t.min == 45); REQUIRE(t.sec == 12); REQUIRE(t.fract > 0); } } TEST_CASE_METHOD(mssql_fixture, "test_decimal", "[mssql][decimal]") { auto connection = connect(); create_table(connection, NANODBC_TEXT("test_decimal"), NANODBC_TEXT("(d decimal(19,4))")); // insert { execute( connection, NANODBC_TEXT("insert into test_decimal(d) values (-922337203685477.5808);")); execute(connection, NANODBC_TEXT("insert into test_decimal(d) values (0);")); execute(connection, NANODBC_TEXT("insert into test_decimal(d) values (1.23);")); execute( connection, NANODBC_TEXT("insert into test_decimal(d) values (922337203685477.5807);")); } // select { auto result = execute(connection, NANODBC_TEXT("select d from test_decimal order by d asc;")); REQUIRE(result.next()); auto d = result.get<nanodbc::string>(0); REQUIRE(d == NANODBC_TEXT("-922337203685477.5808")); // Min value of SQL data type REQUIRE(result.next()); d = result.get<nanodbc::string>(0); REQUIRE(d == NANODBC_TEXT(".0000")); REQUIRE(result.next()); d = result.get<nanodbc::string>(0); REQUIRE(d == NANODBC_TEXT("1.2300")); REQUIRE(result.next()); d = result.get<nanodbc::string>(0); REQUIRE(d == NANODBC_TEXT("922337203685477.5807")); // Max value of SQL data type MONEY } } TEST_CASE_METHOD(mssql_fixture, "test_money", "[mssql][decimal][money]") { auto connection = connect(); create_table(connection, NANODBC_TEXT("test_money"), NANODBC_TEXT("(d money)")); // insert { execute( connection, NANODBC_TEXT("insert into test_money(d) values (-922337203685477.5808);")); execute(connection, NANODBC_TEXT("insert into test_money(d) values (0);")); execute(connection, NANODBC_TEXT("insert into test_money(d) values (1.23);")); execute( connection, NANODBC_TEXT("insert into test_money(d) values (922337203685477.5807);")); } // select { auto result = execute(connection, NANODBC_TEXT("select d from test_money order by d asc;")); REQUIRE(result.next()); auto d = result.get<nanodbc::string>(0); REQUIRE(d == NANODBC_TEXT("-922337203685477.5808")); // Min value of SQL data type MONEY REQUIRE(result.next()); d = result.get<nanodbc::string>(0); REQUIRE(d == NANODBC_TEXT(".0000")); REQUIRE(result.next()); d = result.get<nanodbc::string>(0); REQUIRE(d == NANODBC_TEXT("1.2300")); REQUIRE(result.next()); d = result.get<nanodbc::string>(0); REQUIRE(d == NANODBC_TEXT("922337203685477.5807")); // Max value of SQL data type MONEY } } TEST_CASE_METHOD(mssql_fixture, "test_datetime2", "[mssql][datetime]") { auto connection = connect(); create_table(connection, NANODBC_TEXT("test_datetime2"), NANODBC_TEXT("d datetime2")); // insert // See "CAST and CONVERT" https://msdn.microsoft.com/en-US/library/ms187928.aspx { execute( connection, NANODBC_TEXT("insert into test_datetime2(d) values (CONVERT(datetime2, " "'2006-12-30T13:45:12.345', 127));")); } // select { auto result = execute(connection, NANODBC_TEXT("select d from test_datetime2;")); REQUIRE(result.column_name(0) == NANODBC_TEXT("d")); REQUIRE(result.column_datatype(0) == SQL_TYPE_TIMESTAMP); REQUIRE(result.column_datatype_name(0) == NANODBC_TEXT("datetime2")); REQUIRE(result.next()); auto t = result.get<nanodbc::timestamp>(0); REQUIRE(t.year == 2006); REQUIRE(t.month == 12); REQUIRE(t.day == 30); REQUIRE(t.hour == 13); REQUIRE(t.min == 45); REQUIRE(t.sec == 12); REQUIRE(t.fract > 0); } } TEST_CASE_METHOD(mssql_fixture, "test_datetimeoffset", "[mssql][datetime]") { auto connection = connect(); create_table(connection, NANODBC_TEXT("test_datetimeoffset"), NANODBC_TEXT("d datetimeoffset")); // insert // See "CAST and CONVERT" https://msdn.microsoft.com/en-US/library/ms187928.aspx execute( connection, NANODBC_TEXT("insert into test_datetimeoffset(d) values " "(CONVERT(datetimeoffset, '2006-12-30T13:45:12.345-08:00', 127));")); // select { auto result = execute(connection, NANODBC_TEXT("select d from test_datetimeoffset;")); #ifndef SQL_SS_TIMESTAMPOFFSET #define SQL_SS_TIMESTAMPOFFSET (-155) #endif REQUIRE(result.column_name(0) == NANODBC_TEXT("d")); REQUIRE(result.column_datatype(0) == SQL_SS_TIMESTAMPOFFSET); REQUIRE(result.column_datatype_name(0) == NANODBC_TEXT("datetimeoffset")); REQUIRE(result.next()); auto t = result.get<nanodbc::timestamp>(0); REQUIRE(t.year == 2006); REQUIRE(t.month == 12); REQUIRE(t.day == 30); // Currently, nanodbc binds SQL_SS_TIMESTAMPOFFSET as SQL_C_TIMESTAMP, // not as SQL_C_SS_TIMESTAMPOFFSET. // This seems to cause the DBMS or the driver to convert the time to local time // based on time zone // REQUIRE(t.hour == 13); // or 21 (GMT) or 22 (CET) or other client local time REQUIRE(t.hour > 0); REQUIRE(t.min == 45); REQUIRE(t.sec == 12); REQUIRE(t.fract > 0); ; } } TEST_CASE_METHOD(mssql_fixture, "test_transaction", "[mssql][transaction]") { test_transaction(); } TEST_CASE_METHOD(mssql_fixture, "test_while_not_end_iteration", "[mssql][looping]") { test_while_not_end_iteration(); } TEST_CASE_METHOD(mssql_fixture, "test_while_next_iteration", "[mssql][looping]") { test_while_next_iteration(); } #if !defined(NANODBC_DISABLE_ASYNC) && defined(WIN32) TEST_CASE_METHOD(mssql_fixture, "test_async", "[mssql][async]") { HANDLE event_handle = CreateEvent(nullptr, FALSE, FALSE, nullptr); nanodbc::connection conn; if (conn.async_connect(connection_string_, event_handle)) WaitForSingleObject(event_handle, INFINITE); conn.async_complete(); nanodbc::statement stmt(conn); if (stmt.async_prepare(NANODBC_TEXT("select count(*) from sys.tables;"), event_handle)) WaitForSingleObject(event_handle, INFINITE); stmt.complete_prepare(); if (stmt.async_execute(event_handle)) WaitForSingleObject(event_handle, INFINITE); nanodbc::result row = stmt.complete_execute(); if (row.async_next(event_handle)) WaitForSingleObject(event_handle, INFINITE); REQUIRE(row.complete_next()); REQUIRE(row.get<int>(0) >= 0); } #endif #if defined(_MSC_VER) && defined(_UNICODE) TEST_CASE_METHOD(mssql_fixture, "test_bind_variant", "[mssql][variant]") { // Test prepared statement and binding Windows VARIANT data. auto conn = connect(); create_table( conn, NANODBC_TEXT("test_bind_variant"), NANODBC_TEXT("(i int, f float, s varchar(256), d decimal(9, 3), b varbinary(max))")); nanodbc::statement stmt(conn); prepare(stmt, NANODBC_TEXT("insert into test_bind_variant(i,f,s,d,b) values (?,?,?,?,?)")); // NOTE: Some examples with number of round-trips below might seem redundant, // but it has been kept to for illustration purposes. // VT_I4 -> INT static_assert(sizeof(long) == sizeof(std::int32_t), "long is too large"); _variant_t v_i(7L); stmt.bind(0, reinterpret_cast<std::int32_t*>(&v_i.lVal)); // no bind(long) provided // VT_R8 -> FLOAT _variant_t v_f(3.14); stmt.bind(1, &v_f.dblVal); // VT_BSTR -> VARCHAR _variant_t v_s(L"This is a text"); stmt.bind_strings(2, reinterpret_cast<wchar_t*>(v_s.bstrVal), wcslen(v_s.bstrVal), 1); // VT_DECIMAL|VT_CY -> double -> DECIMAL(9,3) _variant_t v_d; { // use input value longer than DECIMAL(9,3) to test SQL will convert it appropriately DECIMAL d; VarDecFromStr(L"3.45612345", 0, LOCALE_NOUSEROVERRIDE, &d); double dbl; ::VarR8FromDec(&d, &dbl); v_d = dbl; } stmt.bind(3, &v_d.dblVal); // SAFEARRAY -> vector<uint8_t> -> VARBINARY // Since, currently, only way to bind binary data is via std::bector<std::uint8_t>, // we need to copy data from SAFEARRAY to intermediate vector. std::vector<std::uint8_t> bytes; { std::uint8_t data[] = {0x00, 0x01, 0x02, 0x03}; CComSafeArray<std::uint8_t> sa; for (auto b : data) sa.Add(b); for (auto i = 0UL; i < sa.GetCount(); ++i) bytes.push_back(sa.GetAt(i)); } std::vector<std::vector<std::uint8_t>> binary_items = {bytes}; stmt.bind(4, binary_items); nanodbc::transact(stmt, 1); { auto result = nanodbc::execute(conn, NANODBC_TEXT("select i,f,s,d,b from test_bind_variant")); std::size_t i = 0; while (result.next()) { REQUIRE(result.get<std::int32_t>(0) == static_cast<std::int32_t>(v_i)); REQUIRE(result.get<double>(1) == static_cast<double>(v_f)); REQUIRE(result.get<nanodbc::string>(2) == v_s.bstrVal); v_d.ChangeType(VT_BSTR); REQUIRE(result.get<nanodbc::string>(3) == nanodbc::string(v_d.bstrVal).substr(0, 5)); REQUIRE(result.get<std::vector<std::uint8_t>>(4) == bytes); ++i; } REQUIRE(i == 1); } } #endif [AppVeyor] REVERT BREAKING TESTS...used for a test #include "catch.hpp" #include "test/test_case_fixture.h" #include <cstdio> #include <cstdlib> #ifdef _MSC_VER #include <atlsafe.h> #include <comutil.h> #ifdef _DEBUG #pragma comment(lib, "comsuppwd.lib") #else #pragma comment(lib, "comsuppw.lib") #endif #endif namespace { struct mssql_fixture : public test_case_fixture { mssql_fixture() : test_case_fixture() { // connection string from command line or NANODBC_TEST_CONNSTR environment variable if (connection_string_.empty()) connection_string_ = get_env("NANODBC_TEST_CONNSTR_MSSQL"); } }; } TEST_CASE_METHOD(mssql_fixture, "test_driver", "[mssql][driver]") { test_driver(); } TEST_CASE_METHOD(mssql_fixture, "test_affected_rows", "[mssql][affected_rows]") { // Skip on SQL Server 2008, see details at // http://help.appveyor.com/discussions/problems/4704-database-cannot-be-autostarted-during-server-shutdown-or-startup if (get_env("DB") == NANODBC_TEXT("MSSQL2008")) { WARN("test_affected_rows skipped on AppVeyor with SQL Server 2008"); return; } // Enable MARS required? #if 0 enum { SQL_COPT_SS_MARS_ENABLED = 1224, SQL_MARS_ENABLED_YES = 1 }; // sqlext.h int rc = ::SQLSetConnectAttr(conn.native_dbc_handle(), SQL_COPT_SS_MARS_ENABLED, (SQLPOINTER)SQL_MARS_ENABLED_YES, SQL_IS_UINTEGER); REQUIRE(rc == 0); #endif auto conn = connect(); auto const current_db_name = conn.database_name(); // CREATE DATABASE|TABLE { execute( conn, NANODBC_TEXT( "IF DB_ID('nanodbc_test_temp_db') IS NOT NULL DROP DATABASE nanodbc_test_temp_db")); nanodbc::result result; result = execute(conn, NANODBC_TEXT("CREATE DATABASE nanodbc_test_temp_db")); REQUIRE(result.affected_rows() == -1); execute(conn, NANODBC_TEXT("USE nanodbc_test_temp_db")); result = execute(conn, NANODBC_TEXT("CREATE TABLE nanodbc_test_temp_table (i int)")); REQUIRE(result.affected_rows() == -1); } // INSERT { nanodbc::result result; result = execute(conn, NANODBC_TEXT("INSERT INTO nanodbc_test_temp_table VALUES (1)")); REQUIRE(result.affected_rows() == 1); result = execute(conn, NANODBC_TEXT("INSERT INTO nanodbc_test_temp_table VALUES (2)")); REQUIRE(result.affected_rows() == 1); } // SELECT { auto result = execute(conn, NANODBC_TEXT("SELECT i FROM nanodbc_test_temp_table")); REQUIRE(result.affected_rows() == -1); } // DELETE { auto result = execute(conn, NANODBC_TEXT("DELETE FROM nanodbc_test_temp_table")); REQUIRE(result.affected_rows() == 2); } // DROP DATABASE|TABLE { nanodbc::result result; result = execute(conn, NANODBC_TEXT("DROP TABLE nanodbc_test_temp_table")); REQUIRE(result.affected_rows() == -1); execute(conn, NANODBC_TEXT("USE ") + current_db_name); result = execute(conn, NANODBC_TEXT("DROP DATABASE nanodbc_test_temp_db")); REQUIRE(result.affected_rows() == -1); } } TEST_CASE_METHOD(mssql_fixture, "test_batch_insert_integral", "[mssql][batch][integral]") { test_batch_insert_integral(); } TEST_CASE_METHOD(mssql_fixture, "test_batch_insert_string", "[mssql][batch][string]") { test_batch_insert_string(); } TEST_CASE_METHOD(mssql_fixture, "test_batch_insert_mixed", "[mssql][batch]") { test_batch_insert_mixed(); } TEST_CASE_METHOD(mssql_fixture, "test_blob", "[mssql][blob][binary][varbinary]") { nanodbc::connection connection = connect(); // Test data size less than the default size of the internal buffer (1024) { create_table(connection, NANODBC_TEXT("test_blob"), NANODBC_TEXT("(data varbinary(max))")); execute( connection, NANODBC_TEXT("insert into test_blob values (CONVERT(varbinary(max), " "'0x010100000000000000000059400000000000005940', 1));")); nanodbc::result results = nanodbc::execute(connection, NANODBC_TEXT("select data from test_blob;")); REQUIRE(results.next()); auto const blob = results.get<std::vector<std::uint8_t>>(0); REQUIRE(blob.size() == 21); REQUIRE(to_hex_string(blob) == "010100000000000000000059400000000000005940"); } // Test data size greater than, but not multiple of, the default size of the internal buffer // (1024) { create_table(connection, NANODBC_TEXT("test_blob"), NANODBC_TEXT("(data varbinary(max))")); execute(connection, NANODBC_TEXT("insert into test_blob values (CRYPT_GEN_RANDOM(1579));")); nanodbc::result results = nanodbc::execute(connection, NANODBC_TEXT("select data from test_blob;")); REQUIRE(results.next()); REQUIRE(results.get<std::vector<std::uint8_t>>(0).size() == 1579); } } TEST_CASE_METHOD( mssql_fixture, "test_blob_with_varchar", "[mssql][blob][binary][varbinary][varchar]") { nanodbc::string s = NANODBC_TEXT( "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" "AAAAAAAAABBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB" "BBBBBBBBBBBBBBBBBBCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC" "CCCCCCCCCCCCCCCCCCCCCCCCCCCDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD" "DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE" "EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF" "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG" "GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGHHHHHHHHHHHHHHHHHHHHHHHHHHHHH" "HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHIIIIIIIIIIIIIIIIIIII" "IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIJJJJJJJJJJJ" "JJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJKKK" "KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK" "KKKKKKLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL" "LLLLLLLLLLLLLLLMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM" "MMMMMMMMMMMMMMMMMMMMMMMNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN" "NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO" "OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP" "PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQ" "QQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR" "RRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRSSSSSSSSSSSSSSSSSSSSSSS" "SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSTTTTTTTTTTTTTTT" "TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTUUUUUU" "UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU" "UUUVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV" "VVVVVVVVVVVVWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW" "WWWWWWWWWWWWWWWWWWWWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY" "YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ" "ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ"); nanodbc::connection connection = connect(); create_table( connection, NANODBC_TEXT("test_blob_with_varchar"), NANODBC_TEXT("(data varbinary(max))")); execute( connection, NANODBC_TEXT("insert into test_blob_with_varchar values (CONVERT(varbinary(max), '") + s + NANODBC_TEXT("'));")); nanodbc::result results = nanodbc::execute(connection, NANODBC_TEXT("select data from test_blob_with_varchar;")); REQUIRE(results.next()); REQUIRE(results.get<nanodbc::string>(0) == s); } TEST_CASE_METHOD( mssql_fixture, "test_block_cursor_with_nvarchar", "[mssql][nvarchar][block][rowset]") { nanodbc::connection conn = connect(); // BLock Cursors: https://technet.microsoft.com/en-us/library/aa172590.aspx std::size_t const rowset_size = 2; create_table( conn, NANODBC_TEXT("test_variable_string"), NANODBC_TEXT("(i int, s nvarchar(256))")); execute( conn, NANODBC_TEXT( "insert into test_variable_string (i, s) values (1, 'this is a shorter text');")); execute( conn, NANODBC_TEXT( "insert into test_variable_string (i, s) values (2, 'this is a longer text of the two " "texts in the table');")); nanodbc::result results = nanodbc::execute( conn, NANODBC_TEXT("select i, s from test_variable_string order by i;"), rowset_size); REQUIRE(results.next()); REQUIRE(results.get<nanodbc::string>(1) == NANODBC_TEXT("this is a shorter text")); REQUIRE(results.next()); REQUIRE( results.get<nanodbc::string>(1) == NANODBC_TEXT("this is a longer text of the two texts in the table")); REQUIRE(!results.next()); } TEST_CASE_METHOD( mssql_fixture, "test_block_cursor_with_nvarchar_and_first_row_null", "[mssql][nvarchar][block][rowset]") { nanodbc::connection conn = connect(); std::size_t const rowset_size = 2; create_table( conn, NANODBC_TEXT("test_variable_string"), NANODBC_TEXT("(i int, s nvarchar(256))")); execute(conn, NANODBC_TEXT("insert into test_variable_string (i, s) values (1, NULL);")); execute( conn, NANODBC_TEXT( "insert into test_variable_string (i, s) values (2, 'this is a longer text of the two " "texts in the table');")); nanodbc::result results = nanodbc::execute( conn, NANODBC_TEXT("select i, s from test_variable_string order by i;"), rowset_size); REQUIRE(results.next()); REQUIRE(results.is_null(1)); REQUIRE(results.get<nanodbc::string>(1, NANODBC_TEXT("nothing")) == NANODBC_TEXT("nothing")); REQUIRE(results.next()); REQUIRE(!results.is_null(1)); REQUIRE( results.get<nanodbc::string>(1) == NANODBC_TEXT("this is a longer text of the two texts in the table")); REQUIRE(!results.next()); } TEST_CASE_METHOD( mssql_fixture, "test_block_cursor_with_nvarchar_and_second_row_null", "[mssql][nvarchar][block][rowset]") { nanodbc::connection conn = connect(); std::size_t const rowset_size = 2; create_table( conn, NANODBC_TEXT("test_variable_string"), NANODBC_TEXT("(i int, s nvarchar(256))")); execute( conn, NANODBC_TEXT( "insert into test_variable_string (i, s) values (1, 'this is a shorter text');")); execute(conn, NANODBC_TEXT("insert into test_variable_string (i, s) values (2, NULL);")); nanodbc::result results = nanodbc::execute( conn, NANODBC_TEXT("select i, s from test_variable_string order by i;"), rowset_size); REQUIRE(results.next()); REQUIRE(!results.is_null(1)); REQUIRE(results.get<nanodbc::string>(1) == NANODBC_TEXT("this is a shorter text")); REQUIRE(results.next()); REQUIRE(results.is_null(1)); REQUIRE(results.get<nanodbc::string>(1, NANODBC_TEXT("nothing")) == NANODBC_TEXT("nothing")); REQUIRE(!results.next()); } TEST_CASE_METHOD(mssql_fixture, "test_catalog_list_catalogs", "[mssql][catalog][catalogs]") { test_catalog_list_catalogs(); } TEST_CASE_METHOD(mssql_fixture, "test_catalog_list_schemas", "[mssql][catalog][schemas]") { test_catalog_list_schemas(); } TEST_CASE_METHOD(mssql_fixture, "test_catalog_columns", "[mssql][catalog][columns]") { test_catalog_columns(); } TEST_CASE_METHOD(mssql_fixture, "test_catalog_primary_keys", "[mssql][catalog][primary_keys]") { test_catalog_primary_keys(); } TEST_CASE_METHOD(mssql_fixture, "test_catalog_tables", "[mssql][catalog][tables]") { test_catalog_tables(); } TEST_CASE_METHOD(mssql_fixture, "test_catalog_table_privileges", "[mssql][catalog][tables]") { test_catalog_table_privileges(); } TEST_CASE_METHOD(mssql_fixture, "test_column_descriptor", "[mssql][columns]") { test_column_descriptor(); } TEST_CASE_METHOD(mssql_fixture, "test_dbms_info", "[mssql][dmbs][metadata][info]") { test_dbms_info(); } TEST_CASE_METHOD(mssql_fixture, "test_get_info", "[mssql][dmbs][metadata][info]") { test_get_info(); } TEST_CASE_METHOD(mssql_fixture, "test_decimal_conversion", "[mssql][decimal][conversion]") { test_decimal_conversion(); } TEST_CASE_METHOD(mssql_fixture, "test_exception", "[mssql][exception]") { test_exception(); } TEST_CASE_METHOD( mssql_fixture, "test_execute_multiple_transaction", "[mssql][execute][transaction]") { test_execute_multiple_transaction(); } TEST_CASE_METHOD(mssql_fixture, "test_execute_multiple", "[mssql][execute]") { test_execute_multiple(); } TEST_CASE_METHOD(mssql_fixture, "test_integral", "[mssql][integral]") { test_integral<mssql_fixture>(); } TEST_CASE_METHOD(mssql_fixture, "test_move", "[mssql][move]") { test_move(); } TEST_CASE_METHOD(mssql_fixture, "test_null", "[mssql][null]") { test_null(); } TEST_CASE_METHOD(mssql_fixture, "test_nullptr_nulls", "[mssql][null]") { test_nullptr_nulls(); } TEST_CASE_METHOD(mssql_fixture, "test_result_iterator", "[mssql][iterator]") { test_result_iterator(); } TEST_CASE_METHOD(mssql_fixture, "test_simple", "[mssql]") { test_simple(); } TEST_CASE_METHOD(mssql_fixture, "test_string", "[mssql][string]") { test_string(); } TEST_CASE_METHOD(mssql_fixture, "test_string_vector", "[mssql][string]") { test_string_vector(); } TEST_CASE_METHOD(mssql_fixture, "test_batch_binary", "[mssql][binary]") { test_batch_binary(); } TEST_CASE_METHOD(mssql_fixture, "test_time", "[mssql][time]") { test_time(); } TEST_CASE_METHOD(mssql_fixture, "test_date", "[mssql][date]") { test_date(); } TEST_CASE_METHOD(mssql_fixture, "test_datetime", "[mssql][datetime]") { auto connection = connect(); create_table(connection, NANODBC_TEXT("test_datetime"), NANODBC_TEXT("d datetime")); // insert // See "CAST and CONVERT" https://msdn.microsoft.com/en-US/library/ms187928.aspx { execute( connection, NANODBC_TEXT("insert into test_datetime(d) values (CONVERT(datetime, " "'2006-12-30T13:45:12.345', 126));")); } // select { auto result = execute(connection, NANODBC_TEXT("select d from test_datetime;")); REQUIRE(result.column_name(0) == NANODBC_TEXT("d")); REQUIRE(result.column_datatype(0) == SQL_TYPE_TIMESTAMP); REQUIRE(result.column_datatype_name(0) == NANODBC_TEXT("datetime")); REQUIRE(result.next()); auto t = result.get<nanodbc::timestamp>(0); REQUIRE(t.year == 2006); REQUIRE(t.month == 12); REQUIRE(t.day == 30); REQUIRE(t.hour == 13); REQUIRE(t.min == 45); REQUIRE(t.sec == 12); REQUIRE(t.fract > 0); } } TEST_CASE_METHOD(mssql_fixture, "test_decimal", "[mssql][decimal]") { auto connection = connect(); create_table(connection, NANODBC_TEXT("test_decimal"), NANODBC_TEXT("(d decimal(19,4))")); // insert { execute( connection, NANODBC_TEXT("insert into test_decimal(d) values (-922337203685477.5808);")); execute(connection, NANODBC_TEXT("insert into test_decimal(d) values (0);")); execute(connection, NANODBC_TEXT("insert into test_decimal(d) values (1.23);")); execute( connection, NANODBC_TEXT("insert into test_decimal(d) values (922337203685477.5807);")); } // select { auto result = execute(connection, NANODBC_TEXT("select d from test_decimal order by d asc;")); REQUIRE(result.next()); auto d = result.get<nanodbc::string>(0); REQUIRE(d == NANODBC_TEXT("-922337203685477.5808")); // Min value of SQL data type REQUIRE(result.next()); d = result.get<nanodbc::string>(0); REQUIRE(d == NANODBC_TEXT(".0000")); REQUIRE(result.next()); d = result.get<nanodbc::string>(0); REQUIRE(d == NANODBC_TEXT("1.2300")); REQUIRE(result.next()); d = result.get<nanodbc::string>(0); REQUIRE(d == NANODBC_TEXT("922337203685477.5807")); // Max value of SQL data type MONEY } } TEST_CASE_METHOD(mssql_fixture, "test_money", "[mssql][decimal][money]") { auto connection = connect(); create_table(connection, NANODBC_TEXT("test_money"), NANODBC_TEXT("(d money)")); // insert { execute( connection, NANODBC_TEXT("insert into test_money(d) values (-922337203685477.5808);")); execute(connection, NANODBC_TEXT("insert into test_money(d) values (0);")); execute(connection, NANODBC_TEXT("insert into test_money(d) values (1.23);")); execute( connection, NANODBC_TEXT("insert into test_money(d) values (922337203685477.5807);")); } // select { auto result = execute(connection, NANODBC_TEXT("select d from test_money order by d asc;")); REQUIRE(result.next()); auto d = result.get<nanodbc::string>(0); REQUIRE(d == NANODBC_TEXT("-922337203685477.5808")); // Min value of SQL data type MONEY REQUIRE(result.next()); d = result.get<nanodbc::string>(0); REQUIRE(d == NANODBC_TEXT(".0000")); REQUIRE(result.next()); d = result.get<nanodbc::string>(0); REQUIRE(d == NANODBC_TEXT("1.2300")); REQUIRE(result.next()); d = result.get<nanodbc::string>(0); REQUIRE(d == NANODBC_TEXT("922337203685477.5807")); // Max value of SQL data type MONEY } } TEST_CASE_METHOD(mssql_fixture, "test_datetime2", "[mssql][datetime]") { auto connection = connect(); create_table(connection, NANODBC_TEXT("test_datetime2"), NANODBC_TEXT("d datetime2")); // insert // See "CAST and CONVERT" https://msdn.microsoft.com/en-US/library/ms187928.aspx { execute( connection, NANODBC_TEXT("insert into test_datetime2(d) values (CONVERT(datetime2, " "'2006-12-30T13:45:12.345', 127));")); } // select { auto result = execute(connection, NANODBC_TEXT("select d from test_datetime2;")); REQUIRE(result.column_name(0) == NANODBC_TEXT("d")); REQUIRE(result.column_datatype(0) == SQL_TYPE_TIMESTAMP); REQUIRE(result.column_datatype_name(0) == NANODBC_TEXT("datetime2")); REQUIRE(result.next()); auto t = result.get<nanodbc::timestamp>(0); REQUIRE(t.year == 2006); REQUIRE(t.month == 12); REQUIRE(t.day == 30); REQUIRE(t.hour == 13); REQUIRE(t.min == 45); REQUIRE(t.sec == 12); REQUIRE(t.fract > 0); } } TEST_CASE_METHOD(mssql_fixture, "test_datetimeoffset", "[mssql][datetime]") { auto connection = connect(); create_table(connection, NANODBC_TEXT("test_datetimeoffset"), NANODBC_TEXT("d datetimeoffset")); // insert // See "CAST and CONVERT" https://msdn.microsoft.com/en-US/library/ms187928.aspx execute( connection, NANODBC_TEXT("insert into test_datetimeoffset(d) values " "(CONVERT(datetimeoffset, '2006-12-30T13:45:12.345-08:00', 127));")); // select { auto result = execute(connection, NANODBC_TEXT("select d from test_datetimeoffset;")); #ifndef SQL_SS_TIMESTAMPOFFSET #define SQL_SS_TIMESTAMPOFFSET (-155) #endif REQUIRE(result.column_name(0) == NANODBC_TEXT("d")); REQUIRE(result.column_datatype(0) == SQL_SS_TIMESTAMPOFFSET); REQUIRE(result.column_datatype_name(0) == NANODBC_TEXT("datetimeoffset")); REQUIRE(result.next()); auto t = result.get<nanodbc::timestamp>(0); REQUIRE(t.year == 2006); REQUIRE(t.month == 12); REQUIRE(t.day == 30); // Currently, nanodbc binds SQL_SS_TIMESTAMPOFFSET as SQL_C_TIMESTAMP, // not as SQL_C_SS_TIMESTAMPOFFSET. // This seems to cause the DBMS or the driver to convert the time to local time // based on time zone // REQUIRE(t.hour == 13); // or 21 (GMT) or 22 (CET) or other client local time REQUIRE(t.hour > 0); REQUIRE(t.min == 45); REQUIRE(t.sec == 12); REQUIRE(t.fract > 0); ; } } TEST_CASE_METHOD(mssql_fixture, "test_transaction", "[mssql][transaction]") { test_transaction(); } TEST_CASE_METHOD(mssql_fixture, "test_while_not_end_iteration", "[mssql][looping]") { test_while_not_end_iteration(); } TEST_CASE_METHOD(mssql_fixture, "test_while_next_iteration", "[mssql][looping]") { test_while_next_iteration(); } #if !defined(NANODBC_DISABLE_ASYNC) && defined(WIN32) TEST_CASE_METHOD(mssql_fixture, "test_async", "[mssql][async]") { HANDLE event_handle = CreateEvent(nullptr, FALSE, FALSE, nullptr); nanodbc::connection conn; if (conn.async_connect(connection_string_, event_handle)) WaitForSingleObject(event_handle, INFINITE); conn.async_complete(); nanodbc::statement stmt(conn); if (stmt.async_prepare(NANODBC_TEXT("select count(*) from sys.tables;"), event_handle)) WaitForSingleObject(event_handle, INFINITE); stmt.complete_prepare(); if (stmt.async_execute(event_handle)) WaitForSingleObject(event_handle, INFINITE); nanodbc::result row = stmt.complete_execute(); if (row.async_next(event_handle)) WaitForSingleObject(event_handle, INFINITE); REQUIRE(row.complete_next()); REQUIRE(row.get<int>(0) >= 0); } #endif #if defined(_MSC_VER) && defined(_UNICODE) TEST_CASE_METHOD(mssql_fixture, "test_bind_variant", "[mssql][variant]") { // Test prepared statement and binding Windows VARIANT data. auto conn = connect(); create_table( conn, NANODBC_TEXT("test_bind_variant"), NANODBC_TEXT("(i int, f float, s varchar(256), d decimal(9, 3), b varbinary(max))")); nanodbc::statement stmt(conn); prepare(stmt, NANODBC_TEXT("insert into test_bind_variant(i,f,s,d,b) values (?,?,?,?,?)")); // NOTE: Some examples with number of round-trips below might seem redundant, // but it has been kept to for illustration purposes. // VT_I4 -> INT static_assert(sizeof(long) == sizeof(std::int32_t), "long is too large"); _variant_t v_i(7L); stmt.bind(0, reinterpret_cast<std::int32_t*>(&v_i.lVal)); // no bind(long) provided // VT_R8 -> FLOAT _variant_t v_f(3.14); stmt.bind(1, &v_f.dblVal); // VT_BSTR -> VARCHAR _variant_t v_s(L"This is a text"); stmt.bind_strings(2, reinterpret_cast<wchar_t*>(v_s.bstrVal), wcslen(v_s.bstrVal), 1); // VT_DECIMAL|VT_CY -> double -> DECIMAL(9,3) _variant_t v_d; { // use input value longer than DECIMAL(9,3) to test SQL will convert it appropriately DECIMAL d; VarDecFromStr(L"3.45612345", 0, LOCALE_NOUSEROVERRIDE, &d); double dbl; ::VarR8FromDec(&d, &dbl); v_d = dbl; } stmt.bind(3, &v_d.dblVal); // SAFEARRAY -> vector<uint8_t> -> VARBINARY // Since, currently, only way to bind binary data is via std::bector<std::uint8_t>, // we need to copy data from SAFEARRAY to intermediate vector. std::vector<std::uint8_t> bytes; { std::uint8_t data[] = {0x00, 0x01, 0x02, 0x03}; CComSafeArray<std::uint8_t> sa; for (auto b : data) sa.Add(b); for (auto i = 0UL; i < sa.GetCount(); ++i) bytes.push_back(sa.GetAt(i)); } std::vector<std::vector<std::uint8_t>> binary_items = {bytes}; stmt.bind(4, binary_items); nanodbc::transact(stmt, 1); { auto result = nanodbc::execute(conn, NANODBC_TEXT("select i,f,s,d,b from test_bind_variant")); std::size_t i = 0; while (result.next()) { REQUIRE(result.get<std::int32_t>(0) == static_cast<std::int32_t>(v_i)); REQUIRE(result.get<double>(1) == static_cast<double>(v_f)); REQUIRE(result.get<nanodbc::string>(2) == v_s.bstrVal); v_d.ChangeType(VT_BSTR); REQUIRE(result.get<nanodbc::string>(3) == nanodbc::string(v_d.bstrVal).substr(0, 5)); REQUIRE(result.get<std::vector<std::uint8_t>>(4) == bytes); ++i; } REQUIRE(i == 1); } } #endif
#include <stdio.h> #include <stdint.h> #include <unistd.h> #include <fcntl.h> #include <sys/mman.h> #include <sys/stat.h> #include <errno.h> #include <string.h> #include <stdlib.h> #include <string> #include <list> #include <map> #include <set> #define PACKED __attribute__((packed)) #define _NO_ELF_CLASS #include <Elf.h> #define STB_LOCAL 0 #define STB_GLOBAL 1 #define STB_WEAK 2 #define STB_LOPROC 13 #define STB_HIPROC 15 typedef void (*entry_point_t)(char*[], char **); typedef void (*init_fini_func_t)(); typedef struct _object_meta { std::string filename; std::string path; entry_point_t entry; void *mapped_file; size_t mapped_file_sz; bool relocated; uintptr_t load_base; bool running; std::list<std::pair<void*, size_t> > memory_regions; ElfProgramHeader_t *phdrs; ElfSectionHeader_t *shdrs; ElfSectionHeader_t *sh_symtab; ElfSectionHeader_t *sh_strtab; ElfSymbol_t *symtab; const char *strtab; ElfSectionHeader_t *sh_shstrtab; const char *shstrtab; ElfProgramHeader_t *ph_dynamic; std::list<std::string> needed; ElfSymbol_t *dyn_symtab; const char *dyn_strtab; size_t dyn_strtab_sz; ElfRela_t *rela; ElfRel_t *rel; size_t rela_sz; size_t rel_sz; bool uses_rela; uintptr_t *got; ElfRela_t *plt_rela; ElfRel_t *plt_rel; uintptr_t init_func; uintptr_t fini_func; size_t plt_sz; ElfHash_t *hash; Elf_Word *hash_buckets; Elf_Word *hash_chains; std::list<struct _object_meta*> preloads; std::list<struct _object_meta*> objects; struct _object_meta *parent; } object_meta_t; #define IS_NOT_PAGE_ALIGNED(x) (((x) & (getpagesize() - 1)) != 0) extern "C" void *pedigree_sys_request_mem(size_t len); bool loadObject(const char *filename, object_meta_t *meta, bool envpath = false); bool loadSharedObjectHelper(const char *filename, object_meta_t *parent); bool findSymbol(const char *symbol, object_meta_t *meta, ElfSymbol_t &sym); bool lookupSymbol(const char *symbol, object_meta_t *meta, ElfSymbol_t &sym, bool bWeak); void doRelocation(object_meta_t *meta); uintptr_t doThisRelocation(ElfRel_t rel, object_meta_t *meta); uintptr_t doThisRelocation(ElfRela_t rel, object_meta_t *meta); std::string symbolName(const ElfSymbol_t &sym, object_meta_t *meta); std::string findObject(std::string name, bool envpath); extern "C" uintptr_t _libload_resolve_symbol(); std::list<std::string> g_lSearchPaths; std::set<std::string> g_LoadedObjects; size_t elfhash(const char *name) { size_t h = 0, g = 0; while(*name) { h = (h << 4) + *name++; g = h & 0xF0000000; h ^= g; h ^= g >> 24; } return h; } extern char **environ; #include <syslog.h> extern "C" int main(int argc, char *argv[]) { // Sanity check: do we actually have a program to load? if(argc == 0) { return 0; } syslog(LOG_INFO, "libload.so starting..."); char *ld_libpath = getenv("LD_LIBRARY_PATH"); char *ld_preload = getenv("LD_PRELOAD"); char *ld_debug = getenv("LD_DEBUG"); g_lSearchPaths.push_back(std::string("/libraries")); g_lSearchPaths.push_back(std::string(".")); if(ld_libpath) { // Parse, write. const char *entry; while((entry = strtok(ld_libpath, ":"))) { g_lSearchPaths.push_back(std::string(entry)); } } if(ld_debug) { fprintf(stderr, "libload.so: search path is\n"); for(std::list<std::string>::iterator it = g_lSearchPaths.begin(); it != g_lSearchPaths.end(); ++it) { printf(" -> %s\n", it->c_str()); } } /// \todo Implement dlopen etc in here. syslog(LOG_INFO, "libload.so loading main object"); // Load the main object passed on the command line. object_meta_t *meta = new object_meta_t; meta->running = false; if(!loadObject(argv[0], meta, true)) { delete meta; return ENOEXEC; } g_LoadedObjects.insert(meta->filename); syslog(LOG_INFO, "libload.so loading preload, if one exists"); // Preload? if(ld_preload) { object_meta_t *preload = new object_meta_t; if(!loadObject(ld_preload, preload)) { printf("Loading preload '%s' failed.\n", ld_preload); } else { preload->parent = meta; meta->preloads.push_back(preload); g_LoadedObjects.insert(preload->filename); } } syslog(LOG_INFO, "libload.so loading dependencies"); // Any libraries to load? if(meta->needed.size()) { for(std::list<std::string>::iterator it = meta->needed.begin(); it != meta->needed.end(); ++it) { if(g_LoadedObjects.find(*it) == g_LoadedObjects.end()) loadSharedObjectHelper(it->c_str(), meta); } } syslog(LOG_INFO, "libload.so relocating dependencies"); // Relocate preloads. for(std::list<struct _object_meta *>::iterator it = meta->preloads.begin(); it != meta->preloads.end(); ++it) { doRelocation(*it); } // Relocate all other loaded objects. for(std::list<struct _object_meta *>::iterator it = meta->objects.begin(); it != meta->objects.end(); ++it) { doRelocation(*it); } syslog(LOG_INFO, "libload.so relocating main object"); // Do initial relocation of the binary (non-GOT entries) doRelocation(meta); syslog(LOG_INFO, "libload.so running entry point"); // All done - run the program! meta->running = true; // Run init functions in loaded objects. for(std::list<struct _object_meta *>::iterator it = meta->objects.begin(); it != meta->objects.end(); ++it) { if((*it)->init_func) { init_fini_func_t init = (init_fini_func_t) (*it)->init_func; init(); } } // Run init function, if one exists. if(meta->init_func) { init_fini_func_t init = (init_fini_func_t) meta->init_func; init(); } meta->entry(argv, environ); return 0; } std::string findObject(std::string name, bool envpath) { std::string fixed_path = name; std::list<std::string>::iterator it = g_lSearchPaths.begin(); do { struct stat st; int l = stat(fixed_path.c_str(), &st); if(l == 0) { return fixed_path; } fixed_path = *it; fixed_path += "/"; fixed_path += name; } while(++it != g_lSearchPaths.end()); if(envpath) { // Check $PATH for the file. char *path = getenv("PATH"); if(path) { // Parse, write. const char *entry; while((entry = strtok(path, ":"))) { g_lSearchPaths.push_back(std::string(entry)); /// \todo Handle environment variables in entry if needed. fixed_path = entry; fixed_path += "/"; fixed_path += name; std::string result = findObject(fixed_path, false); if(result != "<not found>") return result; // Remove from the search paths - wasn't found. g_lSearchPaths.pop_back(); } } } return std::string("<not found>"); } bool loadSharedObjectHelper(const char *filename, object_meta_t *parent) { object_meta_t *object = new object_meta_t; if(!loadObject(filename, object)) { printf("Loading '%s' failed.\n", filename); } else { object->parent = parent; parent->objects.push_back(object); g_LoadedObjects.insert(object->filename); if(object->needed.size()) { for(std::list<std::string>::iterator it = object->needed.begin(); it != object->needed.end(); ++it) { if(g_LoadedObjects.find(*it) == g_LoadedObjects.end()) return loadSharedObjectHelper(it->c_str(), parent); } } } return true; } #include <syslog.h> bool loadObject(const char *filename, object_meta_t *meta, bool envpath) { meta->filename = filename; meta->path = findObject(meta->filename, envpath); // Okay, let's open up the file for reading... int fd = open(meta->path.c_str(), O_RDONLY); if(fd < 0) { fprintf(stderr, "libload.so: couldn't load object '%s' (%s) (%s)\n", filename, meta->path.c_str(), strerror(errno)); return false; } // Check header. ElfHeader_t header; int n = read(fd, &header, sizeof(header)); if(n < 0) { close(fd); return false; } else if(n != sizeof(header)) { close(fd); errno = ENOEXEC; return false; } if(header.ident[1] != 'E' || header.ident[2] != 'L' || header.ident[3] != 'F' || header.ident[0] != 127) { close(fd); errno = ENOEXEC; return false; } // Fairly confident we have an ELF binary now. Valid class? if(!(header.ident[4] == 1 || header.ident[4] == 2)) { close(fd); errno = ENOEXEC; return false; } meta->entry = (entry_point_t) header.entry; // Grab the size of the file - we'll mmap the entire thing, and pull out what we want. struct stat st; fstat(fd, &st); meta->mapped_file_sz = st.st_size; const char *pBuffer = (const char *) mmap(0, meta->mapped_file_sz, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0); if(pBuffer == MAP_FAILED) { close(fd); errno = ENOEXEC; return false; } meta->mapped_file = (void *) pBuffer; meta->phdrs = (ElfProgramHeader_t *) &pBuffer[header.phoff]; meta->shdrs = (ElfSectionHeader_t *) &pBuffer[header.shoff]; if(header.type == ET_REL) { meta->relocated = true; } else if(header.type == ET_EXEC || header.type == ET_DYN) { // First program header zero? if(header.phnum) { meta->relocated = (meta->phdrs[0].vaddr & ~(getpagesize() - 1)) == 0; } } meta->sh_shstrtab = &meta->shdrs[header.shstrndx]; meta->shstrtab = (const char *) &pBuffer[meta->sh_shstrtab->offset]; // Find the symbol and string tables (these are not the dynamic ones). meta->sh_symtab = 0; meta->sh_strtab = 0; for(int i = 0; i < header.shnum; i++) { const char *name = meta->shstrtab + meta->shdrs[i].name; if(meta->shdrs[i].type == SHT_SYMTAB && !strcmp(name, ".symtab")) { meta->sh_symtab = &meta->shdrs[i]; } else if(meta->shdrs[i].type == SHT_STRTAB && !strcmp(name, ".strtab")) { meta->sh_strtab = &meta->shdrs[i]; } } meta->symtab = 0; meta->strtab = 0; if(meta->sh_symtab != 0) { meta->symtab = (ElfSymbol_t *) &pBuffer[meta->sh_symtab->offset]; } if(meta->sh_strtab != 0) { meta->strtab = (const char *) &pBuffer[meta->sh_strtab->offset]; } // Load program headers. meta->load_base = 0; if(header.phnum) { if(meta->relocated) { // Reserve space for the full loaded virtual address space of the process. meta->load_base = meta->phdrs[0].vaddr & ~(getpagesize() - 1); uintptr_t finalAddress = 0; for(size_t i = 0; i < header.phnum; ++i) { uintptr_t endAddr = meta->phdrs[i].vaddr + meta->phdrs[i].memsz; finalAddress = std::max(finalAddress, endAddr); } size_t mapSize = finalAddress - meta->load_base; if(mapSize & (getpagesize() - 1)) { mapSize = (mapSize + getpagesize()) & ~(getpagesize() - 1); } void *p = pedigree_sys_request_mem(mapSize); if(!p) { munmap((void *) pBuffer, meta->mapped_file_sz); errno = ENOEXEC; return false; } meta->load_base = (uintptr_t) p; if(meta->load_base & (getpagesize() - 1)) { meta->load_base = (meta->load_base + getpagesize()) & ~(getpagesize() - 1); } // Patch up section headers, quickly. for(size_t shdx = 0; shdx < header.shnum; ++shdx) { meta->shdrs[shdx].addr += meta->load_base; } } // NEEDED libraries are stored as offsets into the dynamic string table. std::list<uintptr_t> tmp_needed; for(size_t i = 0; i < header.phnum; i++) { if(meta->phdrs[i].type == PT_DYNAMIC) { meta->ph_dynamic = &meta->phdrs[i]; if(meta->relocated) { meta->ph_dynamic->vaddr += meta->load_base; } ElfDyn_t *dyn = (ElfDyn_t *) &pBuffer[meta->phdrs[i].offset]; while(dyn->tag != DT_NULL) { switch(dyn->tag) { case DT_NEEDED: tmp_needed.push_back(dyn->un.ptr); break; case DT_SYMTAB: meta->dyn_symtab = (ElfSymbol_t *) dyn->un.ptr; break; case DT_STRTAB: meta->dyn_strtab = (const char *) dyn->un.ptr; break; case DT_STRSZ: meta->dyn_strtab_sz = dyn->un.val; break; case DT_RELA: meta->rela = (ElfRela_t *) dyn->un.ptr; break; case DT_REL: meta->rel = (ElfRel_t *) dyn->un.ptr; break; case DT_RELASZ: meta->rela_sz = dyn->un.val; break; case DT_RELSZ: meta->rel_sz = dyn->un.val; break; case DT_PLTGOT: meta->got = (uintptr_t *) dyn->un.ptr; break; case DT_JMPREL: if(meta->uses_rela) { meta->plt_rela = (ElfRela_t *) dyn->un.ptr; } else { meta->plt_rel = (ElfRel_t *) dyn->un.ptr; } break; case DT_PLTREL: meta->uses_rela = dyn->un.val == DT_RELA; break; case DT_PLTRELSZ: meta->plt_sz = dyn->un.val; break; case DT_INIT: meta->init_func = dyn->un.val; break; case DT_FINI: meta->fini_func = dyn->un.val; break; } dyn++; } } else if(meta->phdrs[i].type == PT_LOAD) { // Loadable data - use the flags to determine how we'll mmap. int flags = PROT_READ; if(meta->phdrs[i].flags & PF_X) flags |= PROT_EXEC; if(meta->phdrs[i].flags & PF_W) flags |= PROT_WRITE; if((meta->phdrs[i].flags & PF_R) == 0) flags &= ~PROT_READ; if(meta->relocated) { meta->phdrs[i].vaddr += meta->load_base; } uintptr_t phdr_base = meta->phdrs[i].vaddr; size_t pagesz = getpagesize(); size_t base_addend = phdr_base & (pagesz - 1); phdr_base &= ~(pagesz - 1); size_t offset = meta->phdrs[i].offset & ~(pagesz - 1); size_t offset_addend = meta->phdrs[i].offset & (pagesz - 1); size_t mapsz = offset_addend + meta->phdrs[i].memsz; // Already mapped? if((msync((void *) phdr_base, mapsz, MS_SYNC) != 0) && (errno == ENOMEM)) { int mapflags = MAP_ANON | MAP_FIXED; if(meta->relocated) { mapflags |= MAP_USERSVD; } void *p = mmap((void *) phdr_base, mapsz, PROT_READ | PROT_WRITE, mapflags, 0, 0); if(p == MAP_FAILED) { /// \todo cleanup. errno = ENOEXEC; return false; } // It'd be nice to fully mmap the file, but Pedigree's mmap is not very good. memcpy((void *) meta->phdrs[i].vaddr, &pBuffer[meta->phdrs[i].offset], meta->phdrs[i].filesz); meta->memory_regions.push_back(std::pair<void *, size_t>(p, mapsz)); } if(meta->phdrs[i].memsz > meta->phdrs[i].filesz) { uintptr_t vaddr = meta->phdrs[i].vaddr + meta->phdrs[i].filesz; memset((void *) vaddr, 0, meta->phdrs[i].memsz - meta->phdrs[i].filesz); } // mprotect accordingly. size_t alignExtra = meta->phdrs[i].vaddr & (getpagesize() - 1); uintptr_t protectaddr = meta->phdrs[i].vaddr & ~(getpagesize() - 1); mprotect((void *) protectaddr, meta->phdrs[i].memsz + alignExtra, flags); } } if(meta->relocated) { uintptr_t base_vaddr = meta->load_base; // Patch up references. if(meta->dyn_strtab) meta->dyn_strtab += base_vaddr; if(meta->dyn_symtab) meta->dyn_symtab = (ElfSymbol_t *) (((uintptr_t) meta->dyn_symtab) + base_vaddr); if(meta->got) meta->got = (uintptr_t *) (((uintptr_t) meta->got) + base_vaddr); if(meta->rela) meta->rela = (ElfRela_t *) (((uintptr_t) meta->rela) + base_vaddr); if(meta->rel) meta->rel = (ElfRel_t *) (((uintptr_t) meta->rel) + base_vaddr); if(meta->plt_rela) meta->plt_rela = (ElfRela_t *) (((uintptr_t) meta->plt_rela) + base_vaddr); if(meta->plt_rel) meta->plt_rel = (ElfRel_t *) (((uintptr_t) meta->plt_rel) + base_vaddr); if(meta->init_func) meta->init_func += base_vaddr; if(meta->fini_func) meta->fini_func += base_vaddr; } if(meta->dyn_strtab) { for(std::list<uintptr_t>::iterator it = tmp_needed.begin(); it != tmp_needed.end(); ++it) { std::string s(meta->dyn_strtab + *it); meta->needed.push_back(s); it = tmp_needed.erase(it); } } } else { meta->phdrs = 0; } // Do another pass over section headers to try and get the hash table. meta->hash = 0; meta->hash_buckets = 0; meta->hash_chains = 0; for(size_t i = 0; i < header.shnum; i++) { if(meta->shdrs[i].type == SHT_HASH) { uintptr_t vaddr = meta->shdrs[meta->shdrs[i].link].addr; if(((uintptr_t) meta->dyn_symtab) == vaddr) { meta->hash = (ElfHash_t *) &pBuffer[meta->shdrs[i].offset]; meta->hash_buckets = (Elf_Word *) &pBuffer[meta->shdrs[i].offset + sizeof(ElfHash_t)]; meta->hash_chains = (Elf_Word *) &pBuffer[meta->shdrs[i].offset + sizeof(ElfHash_t) + (sizeof(Elf_Word) * meta->hash->nbucket)]; } } } // Patch up the GOT so we can start resolving symbols when needed. if(meta->got) { meta->got[1] = (uintptr_t) meta; meta->got[2] = (uintptr_t) _libload_resolve_symbol; } // mmap complete - don't need the file descriptors open any longer. close(fd); return true; } bool lookupSymbol(const char *symbol, object_meta_t *meta, ElfSymbol_t &sym, bool bWeak) { if(!meta) { return false; } // Allow preloads to override the main object symbol table, as well as any others. for(std::list<object_meta_t*>::iterator it = meta->preloads.begin(); it != meta->preloads.end(); ++it) { if(lookupSymbol(symbol, *it, sym, false)) return true; } std::string sname(symbol); size_t hash = elfhash(symbol); size_t y = meta->hash_buckets[hash % meta->hash->nbucket]; if(y > meta->hash->nchain) { return false; } do { sym = meta->dyn_symtab[y]; if(symbolName(sym, meta) == sname) { if(ST_BIND(sym.info) == STB_GLOBAL || ST_BIND(sym.info) == STB_LOCAL) { if(sym.shndx) { break; } } if(bWeak) { if(ST_BIND(sym.info) == STB_WEAK) { sym.value = (uintptr_t) ~0UL; break; } } } y = meta->hash_chains[y]; } while(y != 0); if(y != 0) { // Patch up the value. if(ST_TYPE(sym.info) < 3 && ST_BIND(sym.info) != STB_WEAK) { if(sym.shndx && meta->relocated) { ElfSectionHeader_t *sh = &meta->shdrs[sym.shndx]; sym.value += meta->load_base; } } } return y != 0; } bool findSymbol(const char *symbol, object_meta_t *meta, ElfSymbol_t &sym) { if(!meta) { return false; } for(std::list<object_meta_t*>::iterator it = meta->preloads.begin(); it != meta->preloads.end(); ++it) { if(lookupSymbol(symbol, *it, sym, false)) return true; } object_meta_t *ext_meta = meta; while(ext_meta->parent) { ext_meta = ext_meta->parent; } for(std::list<object_meta_t*>::iterator it = ext_meta->objects.begin(); it != ext_meta->objects.end(); ++it) { if(lookupSymbol(symbol, *it, sym, false)) return true; } // No luck? Try weak symbols in the main object. if(lookupSymbol(symbol, meta, sym, true)) return true; return false; } std::string symbolName(const ElfSymbol_t &sym, object_meta_t *meta) { if(!meta) { return std::string(""); } else if(sym.name == 0) { return std::string(""); } ElfSymbol_t *symtab = meta->symtab; const char *strtab = meta->strtab; if(meta->dyn_symtab) { symtab = meta->dyn_symtab; } if(ST_TYPE(sym.info) == 3) { strtab = meta->shstrtab; } else if(meta->dyn_strtab) { strtab = meta->dyn_strtab; } const char *name = strtab + sym.name; return std::string(name); } void doRelocation(object_meta_t *meta) { if(meta->rel) { for(size_t i = 0; i < (meta->rel_sz / sizeof(ElfRel_t)); i++) { doThisRelocation(meta->rel[i], meta); } } if(meta->rela) { for(size_t i = 0; i < (meta->rela_sz / sizeof(ElfRela_t)); i++) { doThisRelocation(meta->rela[i], meta); } } // Relocated binaries need to have the GOTPLT fixed up, as each entry points to // a non-relocated address (that is also not relative). if(meta->relocated) { uintptr_t base = meta->load_base; if(meta->plt_rel) { for(size_t i = 0; i < (meta->plt_sz / sizeof(ElfRel_t)); i++) { uintptr_t *addr = (uintptr_t *) (base + meta->plt_rel[i].offset); *addr += base; } } if(meta->plt_rela) { for(size_t i = 0; i < (meta->plt_sz / sizeof(ElfRela_t)); i++) { uintptr_t *addr = (uintptr_t *) (base + meta->plt_rel[i].offset); *addr += base; } } } } #define R_X86_64_NONE 0 #define R_X86_64_64 1 #define R_X86_64_PC32 2 #define R_X86_64_GOT32 3 #define R_X86_64_PLT32 4 #define R_X86_64_COPY 5 #define R_X86_64_GLOB_DAT 6 #define R_X86_64_JUMP_SLOT 7 #define R_X86_64_RELATIVE 8 #define R_X86_64_GOTPCREL 9 #define R_X86_64_32 10 #define R_X86_64_32S 11 #define R_X86_64_PC64 24 #define R_X86_64_GOTOFF64 25 #define R_X86_64_GOTPC32 26 #define R_X86_64_GOT64 27 #define R_X86_64_GOTPCREL64 28 #define R_X86_64_GOTPC64 29 #define R_X86_64_GOTPLT64 30 #define R_X86_64_PLTOFF64 31 #define R_386_NONE 0 #define R_386_32 1 #define R_386_PC32 2 #define R_386_GOT32 3 #define R_386_PLT32 4 #define R_386_COPY 5 #define R_386_GLOB_DAT 6 #define R_386_JMP_SLOT 7 #define R_386_RELATIVE 8 #define R_386_GOTOFF 9 #define R_386_GOTPC 10 uintptr_t doThisRelocation(ElfRel_t rel, object_meta_t *meta) { ElfSymbol_t *symtab = meta->symtab; if(meta->dyn_symtab) { symtab = meta->dyn_symtab; } ElfSymbol_t *sym = &symtab[R_SYM(rel.info)]; ElfSectionHeader_t *sh = 0; if(sym->shndx) { sh = &meta->shdrs[sym->shndx]; } uintptr_t B = meta->load_base; uintptr_t P = rel.offset; if(meta->relocated) { P += B; } uintptr_t A = *((uintptr_t*) P); uintptr_t S = 0; std::string symbolname = symbolName(*sym, meta); // Patch in section header? if(symtab && ST_TYPE(sym->info) == 3) { S = sh->addr; } else if(R_TYPE(rel.info) != R_386_RELATIVE) { if(sym->name == 0) { S = sym->value; } else { ElfSymbol_t lookupsym; if(R_TYPE(rel.info) == R_386_COPY) { // Search anything except the current object. if(!findSymbol(symbolname.c_str(), meta, lookupsym)) { printf("symbol lookup for '%s' failed.\n", symbolname.c_str()); lookupsym.value = (uintptr_t) ~0UL; } } else { // Attempt a local lookup first. if(!lookupSymbol(symbolname.c_str(), meta, lookupsym, false)) { // No local symbol of that name - search other objects. if(!findSymbol(symbolname.c_str(), meta, lookupsym)) { printf("symbol lookup for '%s' (needed in '%s') failed.\n", symbolname.c_str(), meta->path.c_str()); lookupsym.value = (uintptr_t) ~0UL; } } } S = lookupsym.value; } } if(S == (uintptr_t) ~0UL) S = 0; uint32_t result = A; switch(R_TYPE(rel.info)) { case R_386_NONE: break; case R_386_32: result = S + A; break; case R_386_PC32: result = S + A - P; break; case R_386_JMP_SLOT: case R_386_GLOB_DAT: result = S; break; case R_386_COPY: result = *((uint32_t *) S); break; case R_386_RELATIVE: result = B + A; break; } *((uint32_t *) P) = result; return result; } uintptr_t doThisRelocation(ElfRela_t rel, object_meta_t *meta) { ElfSymbol_t *symtab = meta->symtab; const char *strtab = meta->strtab; if(meta->dyn_symtab) { symtab = meta->dyn_symtab; } if(meta->dyn_strtab) { strtab = meta->dyn_strtab; } ElfSymbol_t *sym = &symtab[R_SYM(rel.info)]; ElfSectionHeader_t *sh = 0; if(sym->shndx) { sh = &meta->shdrs[sym->shndx]; } uintptr_t A = rel.addend; uintptr_t S = 0; uintptr_t B = 0; uintptr_t P = rel.offset; if(meta->relocated) { P += (sh ? sh->addr : B); } std::string symbolname = symbolName(*sym, meta); // Patch in section header? if(symtab && ST_TYPE(sym->info) == 3) { S = sh->addr; } else if(R_TYPE(rel.info) != R_X86_64_RELATIVE) { if(sym->name == 0) { S = sym->value; } else { ElfSymbol_t lookupsym; lookupsym.value = 0; if(R_TYPE(rel.info) == R_X86_64_COPY) { // Search anything except the current object. if(!findSymbol(symbolname.c_str(), meta, lookupsym)) { printf("symbol lookup for '%s' failed.\n", symbolname.c_str()); lookupsym.value = (uintptr_t) ~0UL; } } else { // Attempt a local lookup first. if(!lookupSymbol(symbolname.c_str(), meta, lookupsym, false)) { // No local symbol of that name - search other objects. if(!findSymbol(symbolname.c_str(), meta, lookupsym)) { printf("symbol lookup for '%s' (needed in '%s') failed.\n", symbolname.c_str(), meta->path.c_str()); lookupsym.value = (uintptr_t) ~0UL; } } } S = lookupsym.value; } } // Valid S? if((S == 0) && (R_TYPE(rel.info) != R_X86_64_RELATIVE)) { return (uintptr_t) ~0UL; } // Weak symbol. if(S == (uintptr_t) ~0UL) { S = 0; } uintptr_t result = *((uintptr_t *) P); switch(R_TYPE(rel.info)) { case R_X86_64_NONE: break; case R_X86_64_64: result = S + A; break; case R_X86_64_PC32: result = (result & 0xFFFFFFFF00000000) | ((S + A - P) & 0xFFFFFFFF); break; case R_X86_64_COPY: result = *((uintptr_t *) S); break; case R_X86_64_JUMP_SLOT: case R_X86_64_GLOB_DAT: result = S; break; case R_X86_64_RELATIVE: result = B + A; break; case R_X86_64_32: case R_X86_64_32S: result = (result & 0xFFFFFFFF00000000) | ((S + A) & 0xFFFFFFFF); break; } *((uintptr_t *) P) = result; return result; } extern "C" uintptr_t _libload_dofixup(uintptr_t id, uintptr_t symbol) { object_meta_t *meta = (object_meta_t *) id; uintptr_t returnaddr = 0; #ifdef BITS_32 ElfRel_t rel = meta->plt_rel[symbol / sizeof(ElfRel_t)]; #else ElfRela_t rel = meta->plt_rela[symbol / sizeof(ElfRela_t)]; #endif // Verify the symbol is sane. if(meta->hash && (R_SYM(rel.info) > meta->hash->nchain)) { fprintf(stderr, "symbol lookup failed (symbol not in hash table)\n"); abort(); } ElfSymbol_t *sym = &meta->dyn_symtab[R_SYM(rel.info)]; std::string symbolname = symbolName(*sym, meta); uintptr_t result = doThisRelocation(rel, meta); if(result == (uintptr_t) ~0UL) { fprintf(stderr, "symbol lookup failed (couldn't relocate)\n"); abort(); } return result; } libload: fix a bug where even in a non-LocalFirst symbol lookup, we would look locally in the main parent object (which broke R_386_COPY lookups for things like _impure_ptr). #include <stdio.h> #include <stdint.h> #include <unistd.h> #include <fcntl.h> #include <sys/mman.h> #include <sys/stat.h> #include <errno.h> #include <string.h> #include <stdlib.h> #include <string> #include <list> #include <map> #include <set> #define PACKED __attribute__((packed)) #define _NO_ELF_CLASS #include <Elf.h> #define STB_LOCAL 0 #define STB_GLOBAL 1 #define STB_WEAK 2 #define STB_LOPROC 13 #define STB_HIPROC 15 typedef void (*entry_point_t)(char*[], char **); typedef void (*init_fini_func_t)(); enum LookupPolicy { LocalFirst, NotThisObject, }; typedef struct _object_meta { std::string filename; std::string path; entry_point_t entry; void *mapped_file; size_t mapped_file_sz; bool relocated; uintptr_t load_base; bool running; std::list<std::pair<void*, size_t> > memory_regions; ElfProgramHeader_t *phdrs; ElfSectionHeader_t *shdrs; ElfSectionHeader_t *sh_symtab; ElfSectionHeader_t *sh_strtab; ElfSymbol_t *symtab; const char *strtab; ElfSectionHeader_t *sh_shstrtab; const char *shstrtab; ElfProgramHeader_t *ph_dynamic; std::list<std::string> needed; ElfSymbol_t *dyn_symtab; const char *dyn_strtab; size_t dyn_strtab_sz; ElfRela_t *rela; ElfRel_t *rel; size_t rela_sz; size_t rel_sz; bool uses_rela; uintptr_t *got; ElfRela_t *plt_rela; ElfRel_t *plt_rel; uintptr_t init_func; uintptr_t fini_func; size_t plt_sz; ElfHash_t *hash; Elf_Word *hash_buckets; Elf_Word *hash_chains; std::list<struct _object_meta*> preloads; std::list<struct _object_meta*> objects; struct _object_meta *parent; } object_meta_t; #define IS_NOT_PAGE_ALIGNED(x) (((x) & (getpagesize() - 1)) != 0) extern "C" void *pedigree_sys_request_mem(size_t len); bool loadObject(const char *filename, object_meta_t *meta, bool envpath = false); bool loadSharedObjectHelper(const char *filename, object_meta_t *parent); bool findSymbol(const char *symbol, object_meta_t *meta, ElfSymbol_t &sym, LookupPolicy policy = LocalFirst); bool lookupSymbol(const char *symbol, object_meta_t *meta, ElfSymbol_t &sym, bool bWeak, bool bGlobal = true); void doRelocation(object_meta_t *meta); uintptr_t doThisRelocation(ElfRel_t rel, object_meta_t *meta); uintptr_t doThisRelocation(ElfRela_t rel, object_meta_t *meta); std::string symbolName(const ElfSymbol_t &sym, object_meta_t *meta); std::string findObject(std::string name, bool envpath); extern "C" uintptr_t _libload_resolve_symbol(); std::list<std::string> g_lSearchPaths; std::set<std::string> g_LoadedObjects; size_t elfhash(const char *name) { size_t h = 0, g = 0; while(*name) { h = (h << 4) + *name++; g = h & 0xF0000000; h ^= g; h ^= g >> 24; } return h; } extern char **environ; #include <syslog.h> extern "C" int main(int argc, char *argv[]) { // Sanity check: do we actually have a program to load? if(argc == 0) { return 0; } syslog(LOG_INFO, "libload.so starting..."); char *ld_libpath = getenv("LD_LIBRARY_PATH"); char *ld_preload = getenv("LD_PRELOAD"); char *ld_debug = getenv("LD_DEBUG"); g_lSearchPaths.push_back(std::string("/libraries")); g_lSearchPaths.push_back(std::string(".")); if(ld_libpath) { // Parse, write. const char *entry; while((entry = strtok(ld_libpath, ":"))) { g_lSearchPaths.push_back(std::string(entry)); } } if(ld_debug) { fprintf(stderr, "libload.so: search path is\n"); for(std::list<std::string>::iterator it = g_lSearchPaths.begin(); it != g_lSearchPaths.end(); ++it) { printf(" -> %s\n", it->c_str()); } } /// \todo Implement dlopen etc in here. syslog(LOG_INFO, "libload.so loading main object"); // Load the main object passed on the command line. object_meta_t *meta = new object_meta_t; meta->running = false; if(!loadObject(argv[0], meta, true)) { delete meta; return ENOEXEC; } g_LoadedObjects.insert(meta->filename); syslog(LOG_INFO, "libload.so loading preload, if one exists"); // Preload? if(ld_preload) { object_meta_t *preload = new object_meta_t; if(!loadObject(ld_preload, preload)) { printf("Loading preload '%s' failed.\n", ld_preload); } else { preload->parent = meta; meta->preloads.push_back(preload); g_LoadedObjects.insert(preload->filename); } } syslog(LOG_INFO, "libload.so loading dependencies"); // Any libraries to load? if(meta->needed.size()) { for(std::list<std::string>::iterator it = meta->needed.begin(); it != meta->needed.end(); ++it) { if(g_LoadedObjects.find(*it) == g_LoadedObjects.end()) loadSharedObjectHelper(it->c_str(), meta); } } syslog(LOG_INFO, "libload.so relocating dependencies"); // Relocate preloads. for(std::list<struct _object_meta *>::iterator it = meta->preloads.begin(); it != meta->preloads.end(); ++it) { doRelocation(*it); } // Relocate all other loaded objects. for(std::list<struct _object_meta *>::iterator it = meta->objects.begin(); it != meta->objects.end(); ++it) { doRelocation(*it); } syslog(LOG_INFO, "libload.so relocating main object"); // Do initial relocation of the binary (non-GOT entries) doRelocation(meta); syslog(LOG_INFO, "libload.so running entry point"); // All done - run the program! meta->running = true; // Run init functions in loaded objects. for(std::list<struct _object_meta *>::iterator it = meta->objects.begin(); it != meta->objects.end(); ++it) { if((*it)->init_func) { init_fini_func_t init = (init_fini_func_t) (*it)->init_func; init(); } } // Run init function, if one exists. if(meta->init_func) { init_fini_func_t init = (init_fini_func_t) meta->init_func; init(); } meta->entry(argv, environ); return 0; } std::string findObject(std::string name, bool envpath) { std::string fixed_path = name; std::list<std::string>::iterator it = g_lSearchPaths.begin(); do { struct stat st; int l = stat(fixed_path.c_str(), &st); if(l == 0) { return fixed_path; } fixed_path = *it; fixed_path += "/"; fixed_path += name; } while(++it != g_lSearchPaths.end()); if(envpath) { // Check $PATH for the file. char *path = getenv("PATH"); if(path) { // Parse, write. const char *entry; while((entry = strtok(path, ":"))) { g_lSearchPaths.push_back(std::string(entry)); /// \todo Handle environment variables in entry if needed. fixed_path = entry; fixed_path += "/"; fixed_path += name; std::string result = findObject(fixed_path, false); if(result != "<not found>") return result; // Remove from the search paths - wasn't found. g_lSearchPaths.pop_back(); } } } return std::string("<not found>"); } bool loadSharedObjectHelper(const char *filename, object_meta_t *parent) { object_meta_t *object = new object_meta_t; if(!loadObject(filename, object)) { printf("Loading '%s' failed.\n", filename); } else { object->parent = parent; parent->objects.push_back(object); g_LoadedObjects.insert(object->filename); if(object->needed.size()) { for(std::list<std::string>::iterator it = object->needed.begin(); it != object->needed.end(); ++it) { if(g_LoadedObjects.find(*it) == g_LoadedObjects.end()) return loadSharedObjectHelper(it->c_str(), parent); } } } return true; } #include <syslog.h> bool loadObject(const char *filename, object_meta_t *meta, bool envpath) { meta->filename = filename; meta->path = findObject(meta->filename, envpath); // Okay, let's open up the file for reading... int fd = open(meta->path.c_str(), O_RDONLY); if(fd < 0) { fprintf(stderr, "libload.so: couldn't load object '%s' (%s) (%s)\n", filename, meta->path.c_str(), strerror(errno)); return false; } // Check header. ElfHeader_t header; int n = read(fd, &header, sizeof(header)); if(n < 0) { close(fd); return false; } else if(n != sizeof(header)) { close(fd); errno = ENOEXEC; return false; } if(header.ident[1] != 'E' || header.ident[2] != 'L' || header.ident[3] != 'F' || header.ident[0] != 127) { close(fd); errno = ENOEXEC; return false; } // Fairly confident we have an ELF binary now. Valid class? if(!(header.ident[4] == 1 || header.ident[4] == 2)) { close(fd); errno = ENOEXEC; return false; } meta->entry = (entry_point_t) header.entry; // Grab the size of the file - we'll mmap the entire thing, and pull out what we want. struct stat st; fstat(fd, &st); meta->mapped_file_sz = st.st_size; const char *pBuffer = (const char *) mmap(0, meta->mapped_file_sz, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0); if(pBuffer == MAP_FAILED) { close(fd); errno = ENOEXEC; return false; } meta->mapped_file = (void *) pBuffer; meta->phdrs = (ElfProgramHeader_t *) &pBuffer[header.phoff]; meta->shdrs = (ElfSectionHeader_t *) &pBuffer[header.shoff]; if(header.type == ET_REL) { meta->relocated = true; } else if(header.type == ET_EXEC || header.type == ET_DYN) { // First program header zero? if(header.phnum) { meta->relocated = (meta->phdrs[0].vaddr & ~(getpagesize() - 1)) == 0; } } meta->sh_shstrtab = &meta->shdrs[header.shstrndx]; meta->shstrtab = (const char *) &pBuffer[meta->sh_shstrtab->offset]; // Find the symbol and string tables (these are not the dynamic ones). meta->sh_symtab = 0; meta->sh_strtab = 0; for(int i = 0; i < header.shnum; i++) { const char *name = meta->shstrtab + meta->shdrs[i].name; if(meta->shdrs[i].type == SHT_SYMTAB && !strcmp(name, ".symtab")) { meta->sh_symtab = &meta->shdrs[i]; } else if(meta->shdrs[i].type == SHT_STRTAB && !strcmp(name, ".strtab")) { meta->sh_strtab = &meta->shdrs[i]; } } meta->symtab = 0; meta->strtab = 0; if(meta->sh_symtab != 0) { meta->symtab = (ElfSymbol_t *) &pBuffer[meta->sh_symtab->offset]; } if(meta->sh_strtab != 0) { meta->strtab = (const char *) &pBuffer[meta->sh_strtab->offset]; } // Load program headers. meta->load_base = 0; if(header.phnum) { if(meta->relocated) { // Reserve space for the full loaded virtual address space of the process. meta->load_base = meta->phdrs[0].vaddr & ~(getpagesize() - 1); uintptr_t finalAddress = 0; for(size_t i = 0; i < header.phnum; ++i) { uintptr_t endAddr = meta->phdrs[i].vaddr + meta->phdrs[i].memsz; finalAddress = std::max(finalAddress, endAddr); } size_t mapSize = finalAddress - meta->load_base; if(mapSize & (getpagesize() - 1)) { mapSize = (mapSize + getpagesize()) & ~(getpagesize() - 1); } void *p = pedigree_sys_request_mem(mapSize); if(!p) { munmap((void *) pBuffer, meta->mapped_file_sz); errno = ENOEXEC; return false; } meta->load_base = (uintptr_t) p; if(meta->load_base & (getpagesize() - 1)) { meta->load_base = (meta->load_base + getpagesize()) & ~(getpagesize() - 1); } // Patch up section headers, quickly. for(size_t shdx = 0; shdx < header.shnum; ++shdx) { meta->shdrs[shdx].addr += meta->load_base; } } // NEEDED libraries are stored as offsets into the dynamic string table. std::list<uintptr_t> tmp_needed; for(size_t i = 0; i < header.phnum; i++) { if(meta->phdrs[i].type == PT_DYNAMIC) { meta->ph_dynamic = &meta->phdrs[i]; if(meta->relocated) { meta->ph_dynamic->vaddr += meta->load_base; } ElfDyn_t *dyn = (ElfDyn_t *) &pBuffer[meta->phdrs[i].offset]; while(dyn->tag != DT_NULL) { switch(dyn->tag) { case DT_NEEDED: tmp_needed.push_back(dyn->un.ptr); break; case DT_SYMTAB: meta->dyn_symtab = (ElfSymbol_t *) dyn->un.ptr; break; case DT_STRTAB: meta->dyn_strtab = (const char *) dyn->un.ptr; break; case DT_STRSZ: meta->dyn_strtab_sz = dyn->un.val; break; case DT_RELA: meta->rela = (ElfRela_t *) dyn->un.ptr; break; case DT_REL: meta->rel = (ElfRel_t *) dyn->un.ptr; break; case DT_RELASZ: meta->rela_sz = dyn->un.val; break; case DT_RELSZ: meta->rel_sz = dyn->un.val; break; case DT_PLTGOT: meta->got = (uintptr_t *) dyn->un.ptr; break; case DT_JMPREL: if(meta->uses_rela) { meta->plt_rela = (ElfRela_t *) dyn->un.ptr; } else { meta->plt_rel = (ElfRel_t *) dyn->un.ptr; } break; case DT_PLTREL: meta->uses_rela = dyn->un.val == DT_RELA; break; case DT_PLTRELSZ: meta->plt_sz = dyn->un.val; break; case DT_INIT: meta->init_func = dyn->un.val; break; case DT_FINI: meta->fini_func = dyn->un.val; break; } dyn++; } } else if(meta->phdrs[i].type == PT_LOAD) { // Loadable data - use the flags to determine how we'll mmap. int flags = PROT_READ; if(meta->phdrs[i].flags & PF_X) flags |= PROT_EXEC; if(meta->phdrs[i].flags & PF_W) flags |= PROT_WRITE; if((meta->phdrs[i].flags & PF_R) == 0) flags &= ~PROT_READ; if(meta->relocated) { meta->phdrs[i].vaddr += meta->load_base; } uintptr_t phdr_base = meta->phdrs[i].vaddr; size_t pagesz = getpagesize(); size_t base_addend = phdr_base & (pagesz - 1); phdr_base &= ~(pagesz - 1); size_t offset = meta->phdrs[i].offset & ~(pagesz - 1); size_t offset_addend = meta->phdrs[i].offset & (pagesz - 1); size_t mapsz = offset_addend + meta->phdrs[i].memsz; // Already mapped? if((msync((void *) phdr_base, mapsz, MS_SYNC) != 0) && (errno == ENOMEM)) { int mapflags = MAP_ANON | MAP_FIXED; if(meta->relocated) { mapflags |= MAP_USERSVD; } void *p = mmap((void *) phdr_base, mapsz, PROT_READ | PROT_WRITE, mapflags, 0, 0); if(p == MAP_FAILED) { /// \todo cleanup. errno = ENOEXEC; return false; } // It'd be nice to fully mmap the file, but Pedigree's mmap is not very good. memcpy((void *) meta->phdrs[i].vaddr, &pBuffer[meta->phdrs[i].offset], meta->phdrs[i].filesz); meta->memory_regions.push_back(std::pair<void *, size_t>(p, mapsz)); } if(meta->phdrs[i].memsz > meta->phdrs[i].filesz) { uintptr_t vaddr = meta->phdrs[i].vaddr + meta->phdrs[i].filesz; memset((void *) vaddr, 0, meta->phdrs[i].memsz - meta->phdrs[i].filesz); } // mprotect accordingly. size_t alignExtra = meta->phdrs[i].vaddr & (getpagesize() - 1); uintptr_t protectaddr = meta->phdrs[i].vaddr & ~(getpagesize() - 1); mprotect((void *) protectaddr, meta->phdrs[i].memsz + alignExtra, flags); } } if(meta->relocated) { uintptr_t base_vaddr = meta->load_base; // Patch up references. if(meta->dyn_strtab) meta->dyn_strtab += base_vaddr; if(meta->dyn_symtab) meta->dyn_symtab = (ElfSymbol_t *) (((uintptr_t) meta->dyn_symtab) + base_vaddr); if(meta->got) meta->got = (uintptr_t *) (((uintptr_t) meta->got) + base_vaddr); if(meta->rela) meta->rela = (ElfRela_t *) (((uintptr_t) meta->rela) + base_vaddr); if(meta->rel) meta->rel = (ElfRel_t *) (((uintptr_t) meta->rel) + base_vaddr); if(meta->plt_rela) meta->plt_rela = (ElfRela_t *) (((uintptr_t) meta->plt_rela) + base_vaddr); if(meta->plt_rel) meta->plt_rel = (ElfRel_t *) (((uintptr_t) meta->plt_rel) + base_vaddr); if(meta->init_func) meta->init_func += base_vaddr; if(meta->fini_func) meta->fini_func += base_vaddr; } if(meta->dyn_strtab) { for(std::list<uintptr_t>::iterator it = tmp_needed.begin(); it != tmp_needed.end(); ++it) { std::string s(meta->dyn_strtab + *it); meta->needed.push_back(s); it = tmp_needed.erase(it); } } } else { meta->phdrs = 0; } // Do another pass over section headers to try and get the hash table. meta->hash = 0; meta->hash_buckets = 0; meta->hash_chains = 0; for(size_t i = 0; i < header.shnum; i++) { if(meta->shdrs[i].type == SHT_HASH) { uintptr_t vaddr = meta->shdrs[meta->shdrs[i].link].addr; if(((uintptr_t) meta->dyn_symtab) == vaddr) { meta->hash = (ElfHash_t *) &pBuffer[meta->shdrs[i].offset]; meta->hash_buckets = (Elf_Word *) &pBuffer[meta->shdrs[i].offset + sizeof(ElfHash_t)]; meta->hash_chains = (Elf_Word *) &pBuffer[meta->shdrs[i].offset + sizeof(ElfHash_t) + (sizeof(Elf_Word) * meta->hash->nbucket)]; } } } // Patch up the GOT so we can start resolving symbols when needed. if(meta->got) { meta->got[1] = (uintptr_t) meta; meta->got[2] = (uintptr_t) _libload_resolve_symbol; } // mmap complete - don't need the file descriptors open any longer. close(fd); return true; } bool lookupSymbol(const char *symbol, object_meta_t *meta, ElfSymbol_t &sym, bool bWeak, bool bGlobal) { if(!meta) { return false; } // Allow preloads to override the main object symbol table, as well as any others. for(std::list<object_meta_t*>::iterator it = meta->preloads.begin(); it != meta->preloads.end(); ++it) { if(lookupSymbol(symbol, *it, sym, false)) return true; } std::string sname(symbol); size_t hash = elfhash(symbol); size_t y = meta->hash_buckets[hash % meta->hash->nbucket]; if(y > meta->hash->nchain) { return false; } // Try a local lookup first. do { sym = meta->dyn_symtab[y]; if(symbolName(sym, meta) == sname) { if(ST_BIND(sym.info) == STB_LOCAL) { if(sym.shndx) { break; } } if(bWeak) { if(ST_BIND(sym.info) == STB_WEAK) { sym.value = (uintptr_t) ~0UL; break; } } } y = meta->hash_chains[y]; } while(y != 0); // No local symbols found - try a global lookup. if((bGlobal) && (y == 0)) { y = meta->hash_buckets[hash % meta->hash->nbucket]; do { sym = meta->dyn_symtab[y]; if(symbolName(sym, meta) == sname) { if(ST_BIND(sym.info) == STB_GLOBAL) { if(sym.shndx) { break; } } } y = meta->hash_chains[y]; } while(y != 0); } if(y != 0) { // Patch up the value. if(ST_TYPE(sym.info) < 3 && ST_BIND(sym.info) != STB_WEAK) { if(sym.shndx && meta->relocated) { ElfSectionHeader_t *sh = &meta->shdrs[sym.shndx]; sym.value += meta->load_base; } } } return y != 0; } bool findSymbol(const char *symbol, object_meta_t *meta, ElfSymbol_t &sym, LookupPolicy policy) { if(!meta) { return false; } object_meta_t *ext_meta = meta; while(ext_meta->parent) { ext_meta = ext_meta->parent; } // Try preloads. for(std::list<object_meta_t*>::iterator it = ext_meta->preloads.begin(); it != ext_meta->preloads.end(); ++it) { if(lookupSymbol(symbol, *it, sym, false)) return true; } // If we are going to attempt a local lookup first, check for non-weak values locally. if(policy == LocalFirst) { if(lookupSymbol(symbol, meta, sym, false, false)) return true; } // Try the parent object. if((meta != ext_meta) && lookupSymbol(symbol, ext_meta, sym, false)) return true; // Now, try any loaded objects we might have. for(std::list<object_meta_t*>::iterator it = ext_meta->objects.begin(); it != ext_meta->objects.end(); ++it) { if(lookupSymbol(symbol, *it, sym, false)) { return true; } } // No luck? Try weak symbols in the main object. if(lookupSymbol(symbol, meta, sym, true)) return true; return false; } std::string symbolName(const ElfSymbol_t &sym, object_meta_t *meta) { if(!meta) { return std::string(""); } else if(sym.name == 0) { return std::string(""); } ElfSymbol_t *symtab = meta->symtab; const char *strtab = meta->strtab; if(meta->dyn_symtab) { symtab = meta->dyn_symtab; } if(ST_TYPE(sym.info) == 3) { strtab = meta->shstrtab; } else if(meta->dyn_strtab) { strtab = meta->dyn_strtab; } const char *name = strtab + sym.name; return std::string(name); } void doRelocation(object_meta_t *meta) { if(meta->rel) { for(size_t i = 0; i < (meta->rel_sz / sizeof(ElfRel_t)); i++) { doThisRelocation(meta->rel[i], meta); } } if(meta->rela) { for(size_t i = 0; i < (meta->rela_sz / sizeof(ElfRela_t)); i++) { doThisRelocation(meta->rela[i], meta); } } // Relocated binaries need to have the GOTPLT fixed up, as each entry points to // a non-relocated address (that is also not relative). if(meta->relocated) { uintptr_t base = meta->load_base; if(meta->plt_rel) { for(size_t i = 0; i < (meta->plt_sz / sizeof(ElfRel_t)); i++) { uintptr_t *addr = (uintptr_t *) (base + meta->plt_rel[i].offset); *addr += base; } } if(meta->plt_rela) { for(size_t i = 0; i < (meta->plt_sz / sizeof(ElfRela_t)); i++) { uintptr_t *addr = (uintptr_t *) (base + meta->plt_rel[i].offset); *addr += base; } } } } #define R_X86_64_NONE 0 #define R_X86_64_64 1 #define R_X86_64_PC32 2 #define R_X86_64_GOT32 3 #define R_X86_64_PLT32 4 #define R_X86_64_COPY 5 #define R_X86_64_GLOB_DAT 6 #define R_X86_64_JUMP_SLOT 7 #define R_X86_64_RELATIVE 8 #define R_X86_64_GOTPCREL 9 #define R_X86_64_32 10 #define R_X86_64_32S 11 #define R_X86_64_PC64 24 #define R_X86_64_GOTOFF64 25 #define R_X86_64_GOTPC32 26 #define R_X86_64_GOT64 27 #define R_X86_64_GOTPCREL64 28 #define R_X86_64_GOTPC64 29 #define R_X86_64_GOTPLT64 30 #define R_X86_64_PLTOFF64 31 #define R_386_NONE 0 #define R_386_32 1 #define R_386_PC32 2 #define R_386_GOT32 3 #define R_386_PLT32 4 #define R_386_COPY 5 #define R_386_GLOB_DAT 6 #define R_386_JMP_SLOT 7 #define R_386_RELATIVE 8 #define R_386_GOTOFF 9 #define R_386_GOTPC 10 uintptr_t doThisRelocation(ElfRel_t rel, object_meta_t *meta) { ElfSymbol_t *symtab = meta->symtab; if(meta->dyn_symtab) { symtab = meta->dyn_symtab; } ElfSymbol_t *sym = &symtab[R_SYM(rel.info)]; ElfSectionHeader_t *sh = 0; if(sym->shndx) { sh = &meta->shdrs[sym->shndx]; } uintptr_t B = meta->load_base; uintptr_t P = rel.offset; if(meta->relocated) { P += B; } uintptr_t A = *((uintptr_t*) P); uintptr_t S = 0; std::string symbolname = symbolName(*sym, meta); // Patch in section header? if(symtab && ST_TYPE(sym->info) == 3) { S = sh->addr; } else if(R_TYPE(rel.info) != R_386_RELATIVE) { if(sym->name == 0) { S = sym->value; } else { ElfSymbol_t lookupsym; LookupPolicy policy = LocalFirst; if(R_TYPE(rel.info) == R_386_COPY) { policy = NotThisObject; } // Attempt to find the symbol. if(!findSymbol(symbolname.c_str(), meta, lookupsym, policy)) { printf("symbol lookup for '%s' (needed in '%s') failed.\n", symbolname.c_str(), meta->path.c_str()); lookupsym.value = (uintptr_t) ~0UL; } S = lookupsym.value; } } if(S == (uintptr_t) ~0UL) { S = 0; } uint32_t result = A; switch(R_TYPE(rel.info)) { case R_386_NONE: break; case R_386_32: result = S + A; break; case R_386_PC32: result = S + A - P; break; case R_386_JMP_SLOT: case R_386_GLOB_DAT: result = S; break; case R_386_COPY: result = *((uint32_t *) S); break; case R_386_RELATIVE: result = B + A; break; } *((uint32_t *) P) = result; return result; } uintptr_t doThisRelocation(ElfRela_t rel, object_meta_t *meta) { ElfSymbol_t *symtab = meta->symtab; const char *strtab = meta->strtab; if(meta->dyn_symtab) { symtab = meta->dyn_symtab; } if(meta->dyn_strtab) { strtab = meta->dyn_strtab; } ElfSymbol_t *sym = &symtab[R_SYM(rel.info)]; ElfSectionHeader_t *sh = 0; if(sym->shndx) { sh = &meta->shdrs[sym->shndx]; } uintptr_t A = rel.addend; uintptr_t S = 0; uintptr_t B = 0; uintptr_t P = rel.offset; if(meta->relocated) { P += (sh ? sh->addr : B); } std::string symbolname = symbolName(*sym, meta); // Patch in section header? if(symtab && ST_TYPE(sym->info) == 3) { S = sh->addr; } else if(R_TYPE(rel.info) != R_X86_64_RELATIVE) { if(sym->name == 0) { S = sym->value; } else { ElfSymbol_t lookupsym; lookupsym.value = 0; if(R_TYPE(rel.info) == R_X86_64_COPY) { // Search anything except the current object. if(!findSymbol(symbolname.c_str(), meta, lookupsym)) { printf("symbol lookup for '%s' failed.\n", symbolname.c_str()); lookupsym.value = (uintptr_t) ~0UL; } } else { // Attempt a local lookup first. if(!lookupSymbol(symbolname.c_str(), meta, lookupsym, false)) { // No local symbol of that name - search other objects. if(!findSymbol(symbolname.c_str(), meta, lookupsym)) { printf("symbol lookup for '%s' (needed in '%s') failed.\n", symbolname.c_str(), meta->path.c_str()); lookupsym.value = (uintptr_t) ~0UL; } } } S = lookupsym.value; } } // Valid S? if((S == 0) && (R_TYPE(rel.info) != R_X86_64_RELATIVE)) { return (uintptr_t) ~0UL; } // Weak symbol. if(S == (uintptr_t) ~0UL) { S = 0; } uintptr_t result = *((uintptr_t *) P); switch(R_TYPE(rel.info)) { case R_X86_64_NONE: break; case R_X86_64_64: result = S + A; break; case R_X86_64_PC32: result = (result & 0xFFFFFFFF00000000) | ((S + A - P) & 0xFFFFFFFF); break; case R_X86_64_COPY: result = *((uintptr_t *) S); break; case R_X86_64_JUMP_SLOT: case R_X86_64_GLOB_DAT: result = S; break; case R_X86_64_RELATIVE: result = B + A; break; case R_X86_64_32: case R_X86_64_32S: result = (result & 0xFFFFFFFF00000000) | ((S + A) & 0xFFFFFFFF); break; } *((uintptr_t *) P) = result; return result; } extern "C" uintptr_t _libload_dofixup(uintptr_t id, uintptr_t symbol) { object_meta_t *meta = (object_meta_t *) id; uintptr_t returnaddr = 0; #ifdef BITS_32 ElfRel_t rel = meta->plt_rel[symbol / sizeof(ElfRel_t)]; #else ElfRela_t rel = meta->plt_rela[symbol / sizeof(ElfRela_t)]; #endif // Verify the symbol is sane. if(meta->hash && (R_SYM(rel.info) > meta->hash->nchain)) { fprintf(stderr, "symbol lookup failed (symbol not in hash table)\n"); abort(); } ElfSymbol_t *sym = &meta->dyn_symtab[R_SYM(rel.info)]; std::string symbolname = symbolName(*sym, meta); uintptr_t result = doThisRelocation(rel, meta); if(result == (uintptr_t) ~0UL) { fprintf(stderr, "symbol lookup failed (couldn't relocate)\n"); abort(); } return result; }
// $Id$ // The libMesh Finite Element Library. // Copyright (C) 2002-2007 Benjamin S. Kirk, John W. Peterson // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // Local includes #include "boundary_info.h" #include "elem.h" #include "libmesh_logging.h" #include "mesh_communication.h" #include "parallel_mesh.h" #include "parallel.h" // ------------------------------------------------------------ // ParallelMesh class member functions ParallelMesh::ParallelMesh (unsigned int d) : UnstructuredMesh (d), _is_serial(true), _n_nodes(0), _n_elem(0), _max_node_id(0), _max_elem_id(0), _next_free_local_node_id(libMesh::processor_id()), _next_free_local_elem_id(libMesh::processor_id()), _next_free_unpartitioned_node_id(libMesh::n_processors()), _next_free_unpartitioned_elem_id(libMesh::n_processors()) { } ParallelMesh::~ParallelMesh () { this->clear(); // Free nodes and elements } // This might be specialized later, but right now it's just here to // make sure the compiler doesn't give us a default (non-deep) copy // constructor instead. ParallelMesh::ParallelMesh (const ParallelMesh &other_mesh) : UnstructuredMesh (other_mesh) { this->copy_nodes_and_elements(other_mesh); _n_nodes = other_mesh.n_nodes(); _n_elem = other_mesh.n_elem(); _max_node_id = other_mesh.max_node_id(); _max_elem_id = other_mesh.max_elem_id(); } ParallelMesh::ParallelMesh (const UnstructuredMesh &other_mesh) : UnstructuredMesh (other_mesh) { this->copy_nodes_and_elements(other_mesh); _n_nodes = other_mesh.n_nodes(); _n_elem = other_mesh.n_elem(); _max_node_id = other_mesh.max_node_id(); _max_elem_id = other_mesh.max_elem_id(); } // We use cached values for these so they can be called // from one processor without bothering the rest. /* unsigned int ParallelMesh::n_elem() const { unsigned int n_local = this->n_local_elem(); Parallel::sum(n_local); n_local += this->n_unpartitioned_elem(); return n_local; } unsigned int ParallelMesh::max_elem_id() const { unsigned int max_local = _elements.empty() ? 0 : _elements.rbegin()->first + 1; Parallel::max(max_local); return max_local; } unsigned int ParallelMesh::n_nodes() const { unsigned int n_local = this->n_local_nodes(); Parallel::sum(n_local); n_local += this->n_unpartitioned_nodes(); return n_local; } unsigned int ParallelMesh::max_node_id() const { unsigned int max_local = _nodes.empty() ? 0 : _nodes.rbegin()->first + 1; Parallel::max(max_local); return max_local; } */ const Point& ParallelMesh::point (const unsigned int i) const { assert (_nodes[i] != NULL); assert (_nodes[i]->id() != Node::invalid_id); return (*_nodes[i]); } const Node& ParallelMesh::node (const unsigned int i) const { assert (_nodes[i] != NULL); assert (_nodes[i]->id() != Node::invalid_id); return (*_nodes[i]); } Node& ParallelMesh::node (const unsigned int i) { assert (_nodes[i] != NULL); assert (_nodes[i]->id() != Node::invalid_id); return (*_nodes[i]); } const Node* ParallelMesh::node_ptr (const unsigned int i) const { assert (_nodes[i] != NULL); assert (_nodes[i]->id() != Node::invalid_id); return _nodes[i]; } Node* & ParallelMesh::node_ptr (const unsigned int i) { assert (_nodes[i] != NULL); return _nodes[i]; } Elem* ParallelMesh::elem (const unsigned int i) const { assert (_elements[i] != NULL); return _elements[i]; } Elem* ParallelMesh::add_elem (Elem *e) { // Don't try to add NULLs! assert(e); const unsigned int elem_procid = e->processor_id(); if (!e->valid_id()) { unsigned int *next_id = &_next_free_unpartitioned_elem_id; if (elem_procid != DofObject::invalid_processor_id) { assert(e->processor_id() == libMesh::processor_id()); next_id = &_next_free_local_elem_id; } e->set_id (*next_id); *next_id += libMesh::n_processors() + 1; } // Don't try to overwrite existing elems assert (!_elements[e->id()]); _elements[e->id()] = e; // Make the cached elem data more accurate _n_elem++; _max_elem_id = std::max(_max_elem_id, e->id()+1); // Unpartitioned elems should be added on every processor // But we might be just adding on processor 0 to // broadcast later #if 0 #ifdef DEBUG if (elem_procid == DofObject::invalid_processor_id) { unsigned int elem_id = e->id(); Parallel::max(elem_id); assert(elem_id == e->id()); } #endif #endif return e; } Elem* ParallelMesh::insert_elem (Elem* e) { if (_elements[e->id()]) this->delete_elem(_elements[e->id()]); _elements[e->id()] = e; return e; } void ParallelMesh::delete_elem(Elem* e) { assert (e); // Delete the element from the BoundaryInfo object this->boundary_info->remove(e); // But not yet from the container; we might invalidate // an iterator that way! //_elements.erase(e->id()); // Instead, we set it to NULL for now _elements[e->id()] = NULL; // delete the element delete e; } Node* ParallelMesh::add_point (const Point& p, const unsigned int id, const unsigned int proc_id) { Node* n = Node::build(p, id).release(); n->processor_id() = proc_id; return ParallelMesh::add_node(n); } Node* ParallelMesh::add_node (Node *n) { // Don't try to add NULLs! assert(n); const unsigned int node_procid = n->processor_id(); if (!n->valid_id()) { unsigned int *next_id = &_next_free_unpartitioned_node_id; if (node_procid != DofObject::invalid_processor_id) { assert(n->processor_id() == libMesh::processor_id()); next_id = &_next_free_local_node_id; } n->set_id (*next_id); *next_id += libMesh::n_processors() + 1; } // Don't try to overwrite existing nodes assert (!_nodes[n->id()]); _nodes[n->id()] = n; // Make the cached elem data more accurate _n_nodes++; _max_node_id = std::max(_max_node_id, n->id()+1); // Unpartitioned nodes should be added on every processor // But we might be just adding on processor 0 to // broadcast later #if 0 #ifdef DEBUG if (node_procid == DofObject::invalid_processor_id) { unsigned int node_id = n->id(); Parallel::max(node_id); assert(node_id == n->id()); } #endif #endif return n; } Node* ParallelMesh::insert_node (Node* n) { // If we already have this node we cannot // simply delete it, because we may have elements // which are attached to its address. // // Instead, call the Node = Point assignment operator // to overwrite the spatial coordinates (but keep its // address), delete the provided node, and return the // address of the one we already had. if (_nodes.count(n->id())) { Node *my_n = _nodes[n->id()]; *my_n = static_cast<Point>(*n); delete n; n = my_n; } else _nodes[n->id()] = n; return n; } void ParallelMesh::delete_node(Node* n) { assert (n != NULL); assert (_nodes[n->id()] != NULL); // Delete the node from the BoundaryInfo object this->boundary_info->remove(n); // And from the container _nodes.erase(n->id()); // delete the node delete n; } void ParallelMesh::clear () { // Call parent clear function MeshBase::clear(); // Clear our elements and nodes { elem_iterator_imp it = _elements.begin(); const elem_iterator_imp end = _elements.end(); // There is no need to remove the elements from // the BoundaryInfo data structure since we // already cleared it. for (; it != end; ++it) delete *it; _elements.clear(); } // clear the nodes data structure { node_iterator_imp it = _nodes.begin(); node_iterator_imp end = _nodes.end(); // There is no need to remove the nodes from // the BoundaryInfo data structure since we // already cleared it. for (; it != end; ++it) delete *it; _nodes.clear(); } } template <typename T> unsigned int ParallelMesh::renumber_dof_objects (mapvector<T*> &objects) { typedef typename mapvector<T*>::veclike_iterator object_iterator; // In parallel we may not know what objects other processors have. // Start by figuring out how many unsigned int unpartitioned_objects = 0; std::vector<unsigned int> ghost_objects_from_proc(libMesh::n_processors(), 0); object_iterator it = objects.begin(); object_iterator end = objects.end(); for (; it != end;) { T *obj = *it; // Remove any NULL container entries while we're here, // being careful not to invalidate our iterator if (!*it) objects.erase(it++); else { unsigned int obj_procid = obj->processor_id(); if (obj_procid == DofObject::invalid_processor_id) unpartitioned_objects++; else ghost_objects_from_proc[obj_procid]++; ++it; } } std::vector<unsigned int> objects_on_proc(libMesh::n_processors(), 0); Parallel::allgather(ghost_objects_from_proc[libMesh::processor_id()], objects_on_proc); #ifndef NDEBUG unsigned int global_unpartitioned_objects = unpartitioned_objects; Parallel::max(global_unpartitioned_objects); assert(global_unpartitioned_objects == unpartitioned_objects); for (unsigned int p=0; p != libMesh::n_processors(); ++p) assert(ghost_objects_from_proc[p] <= objects_on_proc[p]); #endif // We'll renumber objects in blocks by processor id std::vector<unsigned int> first_object_on_proc(libMesh::n_processors()); for (unsigned int i=1; i != libMesh::n_processors(); ++i) first_object_on_proc[i] = first_object_on_proc[i-1] + objects_on_proc[i-1]; unsigned int next_id = first_object_on_proc[libMesh::processor_id()]; unsigned int first_free_id = first_object_on_proc[libMesh::n_processors()-1] + objects_on_proc[libMesh::n_processors()-1] + 1; // First set new local object ids and build request sets // for non-local object ids // Request sets to send to each processor std::vector<std::vector<unsigned int> > requested_ids(libMesh::n_processors()); // We know how many objects live on each processor, so reseve() space for // each. for (unsigned int p=0; p != libMesh::n_processors(); ++p) if (p != libMesh::processor_id()) requested_ids[p].reserve(ghost_objects_from_proc[p]); end = objects.end(); for (it = objects.begin(); it != end; ++it) { T *obj = *it; if (obj->processor_id() == libMesh::processor_id()) obj->set_id(next_id++); else if (obj->processor_id() != DofObject::invalid_processor_id) requested_ids[obj->processor_id()].push_back(obj->id()); } // Next set ghost object ids from other processors if (libMesh::n_processors() > 1) { for (unsigned int p=1; p != libMesh::n_processors(); ++p) { // Trade my requests with processor procup and procdown unsigned int procup = (libMesh::processor_id() + p) % libMesh::n_processors(); unsigned int procdown = (libMesh::n_processors() + libMesh::processor_id() - p) % libMesh::n_processors(); std::vector<unsigned int> request_to_fill; Parallel::send_receive(procup, requested_ids[procup], procdown, request_to_fill); // Fill those requests std::vector<unsigned int> new_ids(request_to_fill.size()); for (unsigned int i=0; i != request_to_fill.size(); ++i) { assert(objects[request_to_fill[i]]); assert(objects[request_to_fill[i]]->processor_id() == libMesh::processor_id()); new_ids[i] = objects[request_to_fill[i]]->id(); assert(new_ids[i] >= first_object_on_proc[libMesh::processor_id()]); assert(new_ids[i] < first_object_on_proc[libMesh::processor_id()] + objects_on_proc[libMesh::processor_id()]); } // Trade back the results std::vector<unsigned int> filled_request; Parallel::send_receive(procdown, new_ids, procup, filled_request); // And copy the id changes we've now been informed of for (unsigned int i=0; i != filled_request.size(); ++i) { assert (objects[requested_ids[procup][i]]->processor_id() == procup); assert(filled_request[i] >= first_object_on_proc[procup]); assert(filled_request[i] < first_object_on_proc[procup] + objects_on_proc[procup]); objects[requested_ids[procup][i]]->set_id(filled_request[i]); } } } // Next set unpartitioned object ids next_id = 0; for (unsigned int i=0; i != libMesh::n_processors(); ++i) next_id += objects_on_proc[i]; for (it = objects.begin(); it != end; ++it) { T *obj = *it; if (obj->processor_id() == DofObject::invalid_processor_id) obj->set_id(next_id++); } // Finally shuffle around objects so that container indices // match ids end = objects.end(); for (it = objects.begin(); it != end;) { T *obj = *it; if (obj) // don't try shuffling already-NULL entries { T *next = objects[obj->id()]; // If we have to move this object if (next != obj) { // NULL out its original position for now // (our shuffling may put another object there shortly) *it = NULL; // There may already be another object with this id that // needs to be moved itself while (next) { // We shouldn't be trying to give two objects the // same id assert (next->id() != obj->id()); objects[obj->id()] = obj; obj = next; next = objects[obj->id()]; } objects[obj->id()] = obj; } } // Remove any container entries that were left as NULL, // being careful not to invalidate our iterator if (!*it) objects.erase(it++); else ++it; } return first_free_id; } void ParallelMesh::renumber_nodes_and_elements () { START_LOG("renumber_nodes_and_elem()", "ParallelMesh"); std::set<unsigned int> used_nodes; // flag the nodes we need { element_iterator it = elements_begin(); element_iterator end = elements_end(); for (; it != end; ++it) { Elem *elem = *it; for (unsigned int n=0; n != elem->n_nodes(); ++n) used_nodes.insert(elem->node(n)); } } // Nodes not connected to any local elements are deleted { node_iterator_imp it = _nodes.begin(); node_iterator_imp end = _nodes.end(); for (; it != end;) { Node *node = *it; if (!used_nodes.count(node->id())) { // remove any boundary information associated with // this node this->boundary_info->remove (node); // delete the node delete node; _nodes.erase(it++); } else ++it; } } // Finally renumber all the elements _next_free_local_elem_id = this->renumber_dof_objects (_elements); // and all the remaining nodes _next_free_local_node_id = this->renumber_dof_objects (_nodes); // And figure out what IDs we should use when adding new nodes and // new elements unsigned int cycle = libMesh::n_processors()+1; unsigned int offset = _next_free_local_elem_id % cycle; if (offset) _next_free_local_elem_id += cycle - offset; _next_free_unpartitioned_elem_id = _next_free_local_elem_id + libMesh::n_processors(); _next_free_local_elem_id += libMesh::processor_id(); offset = _next_free_local_node_id % cycle; if (offset) _next_free_local_node_id += cycle - offset; _next_free_unpartitioned_node_id = _next_free_local_node_id + libMesh::n_processors(); _next_free_local_node_id += libMesh::processor_id(); STOP_LOG("renumber_nodes_and_elem()", "ParallelMesh"); } void ParallelMesh::delete_remote_elements() { _is_serial = false; MeshCommunication().delete_remote_elements(*this); } void ParallelMesh::allgather() { _is_serial = true; MeshCommunication().allgather(*this); } _next_free_*_id bugfixes git-svn-id: e88a1e38e13faf406e05cc89eca8dd613216f6c4@2363 434f946d-2f3d-0410-ba4c-cb9f52fb0dbf // $Id$ // The libMesh Finite Element Library. // Copyright (C) 2002-2007 Benjamin S. Kirk, John W. Peterson // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // Local includes #include "boundary_info.h" #include "elem.h" #include "libmesh_logging.h" #include "mesh_communication.h" #include "parallel_mesh.h" #include "parallel.h" // ------------------------------------------------------------ // ParallelMesh class member functions ParallelMesh::ParallelMesh (unsigned int d) : UnstructuredMesh (d), _is_serial(true), _n_nodes(0), _n_elem(0), _max_node_id(0), _max_elem_id(0), _next_free_local_node_id(libMesh::processor_id()), _next_free_local_elem_id(libMesh::processor_id()), _next_free_unpartitioned_node_id(libMesh::n_processors()), _next_free_unpartitioned_elem_id(libMesh::n_processors()) { } ParallelMesh::~ParallelMesh () { this->clear(); // Free nodes and elements } // This might be specialized later, but right now it's just here to // make sure the compiler doesn't give us a default (non-deep) copy // constructor instead. ParallelMesh::ParallelMesh (const ParallelMesh &other_mesh) : UnstructuredMesh (other_mesh) { this->copy_nodes_and_elements(other_mesh); _n_nodes = other_mesh.n_nodes(); _n_elem = other_mesh.n_elem(); _max_node_id = other_mesh.max_node_id(); _max_elem_id = other_mesh.max_elem_id(); } ParallelMesh::ParallelMesh (const UnstructuredMesh &other_mesh) : UnstructuredMesh (other_mesh) { this->copy_nodes_and_elements(other_mesh); _n_nodes = other_mesh.n_nodes(); _n_elem = other_mesh.n_elem(); _max_node_id = other_mesh.max_node_id(); _max_elem_id = other_mesh.max_elem_id(); } // We use cached values for these so they can be called // from one processor without bothering the rest. /* unsigned int ParallelMesh::n_elem() const { unsigned int n_local = this->n_local_elem(); Parallel::sum(n_local); n_local += this->n_unpartitioned_elem(); return n_local; } unsigned int ParallelMesh::max_elem_id() const { unsigned int max_local = _elements.empty() ? 0 : _elements.rbegin()->first + 1; Parallel::max(max_local); return max_local; } unsigned int ParallelMesh::n_nodes() const { unsigned int n_local = this->n_local_nodes(); Parallel::sum(n_local); n_local += this->n_unpartitioned_nodes(); return n_local; } unsigned int ParallelMesh::max_node_id() const { unsigned int max_local = _nodes.empty() ? 0 : _nodes.rbegin()->first + 1; Parallel::max(max_local); return max_local; } */ const Point& ParallelMesh::point (const unsigned int i) const { assert (_nodes[i] != NULL); assert (_nodes[i]->id() != Node::invalid_id); return (*_nodes[i]); } const Node& ParallelMesh::node (const unsigned int i) const { assert (_nodes[i] != NULL); assert (_nodes[i]->id() != Node::invalid_id); return (*_nodes[i]); } Node& ParallelMesh::node (const unsigned int i) { assert (_nodes[i] != NULL); assert (_nodes[i]->id() != Node::invalid_id); return (*_nodes[i]); } const Node* ParallelMesh::node_ptr (const unsigned int i) const { assert (_nodes[i] != NULL); assert (_nodes[i]->id() != Node::invalid_id); return _nodes[i]; } Node* & ParallelMesh::node_ptr (const unsigned int i) { assert (_nodes[i] != NULL); return _nodes[i]; } Elem* ParallelMesh::elem (const unsigned int i) const { assert (_elements[i] != NULL); return _elements[i]; } Elem* ParallelMesh::add_elem (Elem *e) { // Don't try to add NULLs! assert(e); const unsigned int elem_procid = e->processor_id(); if (!e->valid_id()) { unsigned int *next_id = &_next_free_unpartitioned_elem_id; if (elem_procid != DofObject::invalid_processor_id) { assert(e->processor_id() == libMesh::processor_id()); next_id = &_next_free_local_elem_id; } e->set_id (*next_id); *next_id += libMesh::n_processors() + 1; } else { if (_next_free_unpartitioned_elem_id <= e->id()) _next_free_unpartitioned_elem_id += libMesh::n_processors() + 1; if (_next_free_local_elem_id <= e->id()) _next_free_local_elem_id += libMesh::n_processors() + 1; } // Don't try to overwrite existing elems assert (!_elements[e->id()]); _elements[e->id()] = e; // Make the cached elem data more accurate _n_elem++; _max_elem_id = std::max(_max_elem_id, e->id()+1); // Unpartitioned elems should be added on every processor // But we might be just adding on processor 0 to // broadcast later #if 0 #ifdef DEBUG if (elem_procid == DofObject::invalid_processor_id) { unsigned int elem_id = e->id(); Parallel::max(elem_id); assert(elem_id == e->id()); } #endif #endif return e; } Elem* ParallelMesh::insert_elem (Elem* e) { if (_elements[e->id()]) this->delete_elem(_elements[e->id()]); _elements[e->id()] = e; return e; } void ParallelMesh::delete_elem(Elem* e) { assert (e); // Delete the element from the BoundaryInfo object this->boundary_info->remove(e); // But not yet from the container; we might invalidate // an iterator that way! //_elements.erase(e->id()); // Instead, we set it to NULL for now _elements[e->id()] = NULL; // delete the element delete e; } Node* ParallelMesh::add_point (const Point& p, const unsigned int id, const unsigned int proc_id) { Node* n = Node::build(p, id).release(); n->processor_id() = proc_id; return ParallelMesh::add_node(n); } Node* ParallelMesh::add_node (Node *n) { // Don't try to add NULLs! assert(n); const unsigned int node_procid = n->processor_id(); if (!n->valid_id()) { unsigned int *next_id = &_next_free_unpartitioned_node_id; if (node_procid != DofObject::invalid_processor_id) { assert(n->processor_id() == libMesh::processor_id()); next_id = &_next_free_local_node_id; } n->set_id (*next_id); *next_id += libMesh::n_processors() + 1; } else { if (_next_free_unpartitioned_node_id <= n->id()) _next_free_unpartitioned_node_id += libMesh::n_processors() + 1; if (_next_free_local_node_id <= n->id()) _next_free_local_node_id += libMesh::n_processors() + 1; } // Don't try to overwrite existing nodes assert (!_nodes[n->id()]); _nodes[n->id()] = n; // Make the cached elem data more accurate _n_nodes++; _max_node_id = std::max(_max_node_id, n->id()+1); // Unpartitioned nodes should be added on every processor // But we might be just adding on processor 0 to // broadcast later #if 0 #ifdef DEBUG if (node_procid == DofObject::invalid_processor_id) { unsigned int node_id = n->id(); Parallel::max(node_id); assert(node_id == n->id()); } #endif #endif return n; } Node* ParallelMesh::insert_node (Node* n) { // If we already have this node we cannot // simply delete it, because we may have elements // which are attached to its address. // // Instead, call the Node = Point assignment operator // to overwrite the spatial coordinates (but keep its // address), delete the provided node, and return the // address of the one we already had. if (_nodes.count(n->id())) { Node *my_n = _nodes[n->id()]; *my_n = static_cast<Point>(*n); delete n; n = my_n; } else _nodes[n->id()] = n; return n; } void ParallelMesh::delete_node(Node* n) { assert (n != NULL); assert (_nodes[n->id()] != NULL); // Delete the node from the BoundaryInfo object this->boundary_info->remove(n); // And from the container _nodes.erase(n->id()); // delete the node delete n; } void ParallelMesh::clear () { // Call parent clear function MeshBase::clear(); // Clear our elements and nodes { elem_iterator_imp it = _elements.begin(); const elem_iterator_imp end = _elements.end(); // There is no need to remove the elements from // the BoundaryInfo data structure since we // already cleared it. for (; it != end; ++it) delete *it; _elements.clear(); } // clear the nodes data structure { node_iterator_imp it = _nodes.begin(); node_iterator_imp end = _nodes.end(); // There is no need to remove the nodes from // the BoundaryInfo data structure since we // already cleared it. for (; it != end; ++it) delete *it; _nodes.clear(); } } template <typename T> unsigned int ParallelMesh::renumber_dof_objects (mapvector<T*> &objects) { typedef typename mapvector<T*>::veclike_iterator object_iterator; // In parallel we may not know what objects other processors have. // Start by figuring out how many unsigned int unpartitioned_objects = 0; std::vector<unsigned int> ghost_objects_from_proc(libMesh::n_processors(), 0); object_iterator it = objects.begin(); object_iterator end = objects.end(); for (; it != end;) { T *obj = *it; // Remove any NULL container entries while we're here, // being careful not to invalidate our iterator if (!*it) objects.erase(it++); else { unsigned int obj_procid = obj->processor_id(); if (obj_procid == DofObject::invalid_processor_id) unpartitioned_objects++; else ghost_objects_from_proc[obj_procid]++; ++it; } } std::vector<unsigned int> objects_on_proc(libMesh::n_processors(), 0); Parallel::allgather(ghost_objects_from_proc[libMesh::processor_id()], objects_on_proc); #ifndef NDEBUG unsigned int global_unpartitioned_objects = unpartitioned_objects; Parallel::max(global_unpartitioned_objects); assert(global_unpartitioned_objects == unpartitioned_objects); for (unsigned int p=0; p != libMesh::n_processors(); ++p) assert(ghost_objects_from_proc[p] <= objects_on_proc[p]); #endif // We'll renumber objects in blocks by processor id std::vector<unsigned int> first_object_on_proc(libMesh::n_processors()); for (unsigned int i=1; i != libMesh::n_processors(); ++i) first_object_on_proc[i] = first_object_on_proc[i-1] + objects_on_proc[i-1]; unsigned int next_id = first_object_on_proc[libMesh::processor_id()]; unsigned int first_free_id = first_object_on_proc[libMesh::n_processors()-1] + objects_on_proc[libMesh::n_processors()-1] + unpartitioned_objects + 1; // First set new local object ids and build request sets // for non-local object ids // Request sets to send to each processor std::vector<std::vector<unsigned int> > requested_ids(libMesh::n_processors()); // We know how many objects live on each processor, so reseve() space for // each. for (unsigned int p=0; p != libMesh::n_processors(); ++p) if (p != libMesh::processor_id()) requested_ids[p].reserve(ghost_objects_from_proc[p]); end = objects.end(); for (it = objects.begin(); it != end; ++it) { T *obj = *it; if (obj->processor_id() == libMesh::processor_id()) obj->set_id(next_id++); else if (obj->processor_id() != DofObject::invalid_processor_id) requested_ids[obj->processor_id()].push_back(obj->id()); } // Next set ghost object ids from other processors if (libMesh::n_processors() > 1) { for (unsigned int p=1; p != libMesh::n_processors(); ++p) { // Trade my requests with processor procup and procdown unsigned int procup = (libMesh::processor_id() + p) % libMesh::n_processors(); unsigned int procdown = (libMesh::n_processors() + libMesh::processor_id() - p) % libMesh::n_processors(); std::vector<unsigned int> request_to_fill; Parallel::send_receive(procup, requested_ids[procup], procdown, request_to_fill); // Fill those requests std::vector<unsigned int> new_ids(request_to_fill.size()); for (unsigned int i=0; i != request_to_fill.size(); ++i) { assert(objects[request_to_fill[i]]); assert(objects[request_to_fill[i]]->processor_id() == libMesh::processor_id()); new_ids[i] = objects[request_to_fill[i]]->id(); assert(new_ids[i] >= first_object_on_proc[libMesh::processor_id()]); assert(new_ids[i] < first_object_on_proc[libMesh::processor_id()] + objects_on_proc[libMesh::processor_id()]); } // Trade back the results std::vector<unsigned int> filled_request; Parallel::send_receive(procdown, new_ids, procup, filled_request); // And copy the id changes we've now been informed of for (unsigned int i=0; i != filled_request.size(); ++i) { assert (objects[requested_ids[procup][i]]->processor_id() == procup); assert(filled_request[i] >= first_object_on_proc[procup]); assert(filled_request[i] < first_object_on_proc[procup] + objects_on_proc[procup]); objects[requested_ids[procup][i]]->set_id(filled_request[i]); } } } // Next set unpartitioned object ids next_id = 0; for (unsigned int i=0; i != libMesh::n_processors(); ++i) next_id += objects_on_proc[i]; for (it = objects.begin(); it != end; ++it) { T *obj = *it; if (obj->processor_id() == DofObject::invalid_processor_id) obj->set_id(next_id++); } // Finally shuffle around objects so that container indices // match ids end = objects.end(); for (it = objects.begin(); it != end;) { T *obj = *it; if (obj) // don't try shuffling already-NULL entries { T *next = objects[obj->id()]; // If we have to move this object if (next != obj) { // NULL out its original position for now // (our shuffling may put another object there shortly) *it = NULL; // There may already be another object with this id that // needs to be moved itself while (next) { // We shouldn't be trying to give two objects the // same id assert (next->id() != obj->id()); objects[obj->id()] = obj; obj = next; next = objects[obj->id()]; } objects[obj->id()] = obj; } } // Remove any container entries that were left as NULL, // being careful not to invalidate our iterator if (!*it) objects.erase(it++); else ++it; } return first_free_id; } void ParallelMesh::renumber_nodes_and_elements () { START_LOG("renumber_nodes_and_elements()", "ParallelMesh"); std::set<unsigned int> used_nodes; // flag the nodes we need { element_iterator it = elements_begin(); element_iterator end = elements_end(); for (; it != end; ++it) { Elem *elem = *it; for (unsigned int n=0; n != elem->n_nodes(); ++n) used_nodes.insert(elem->node(n)); } } // Nodes not connected to any local elements are deleted { node_iterator_imp it = _nodes.begin(); node_iterator_imp end = _nodes.end(); for (; it != end;) { Node *node = *it; if (!used_nodes.count(node->id())) { // remove any boundary information associated with // this node this->boundary_info->remove (node); // delete the node delete node; _nodes.erase(it++); } else ++it; } } // Finally renumber all the elements _next_free_local_elem_id = this->renumber_dof_objects (_elements); // and all the remaining nodes _next_free_local_node_id = this->renumber_dof_objects (_nodes); // And figure out what IDs we should use when adding new nodes and // new elements unsigned int cycle = libMesh::n_processors()+1; unsigned int offset = _next_free_local_elem_id % cycle; if (offset) _next_free_local_elem_id += cycle - offset; _next_free_unpartitioned_elem_id = _next_free_local_elem_id + libMesh::n_processors(); _next_free_local_elem_id += libMesh::processor_id(); offset = _next_free_local_node_id % cycle; if (offset) _next_free_local_node_id += cycle - offset; _next_free_unpartitioned_node_id = _next_free_local_node_id + libMesh::n_processors(); _next_free_local_node_id += libMesh::processor_id(); STOP_LOG("renumber_nodes_and_elements()", "ParallelMesh"); } void ParallelMesh::delete_remote_elements() { _is_serial = false; MeshCommunication().delete_remote_elements(*this); } void ParallelMesh::allgather() { _is_serial = true; MeshCommunication().allgather(*this); }
/* Copyright (c) 2014, Project OSRM, Dennis Luxen, others All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef LRUCACHE_HPP #define LRUCACHE_HPP #include <list> #include <unordered_map> template <typename KeyT, typename ValueT> class LRUCache { private: struct CacheEntry { CacheEntry(KeyT k, ValueT v) : key(k), value(v) {} KeyT key; ValueT value; }; unsigned capacity; std::list<CacheEntry> itemsInCache; std::unordered_map<KeyT, typename std::list<CacheEntry>::iterator> positionMap; public: explicit LRUCache(unsigned c) : capacity(c) {} bool Holds(KeyT key) { if (positionMap.find(key) != positionMap.end()) { return true; } return false; } void Insert(const KeyT key, ValueT &value) { itemsInCache.push_front(CacheEntry(key, value)); positionMap.insert(std::make_pair(key, itemsInCache.begin())); if (itemsInCache.size() > capacity) { positionMap.erase(itemsInCache.back().key); itemsInCache.pop_back(); } } void Insert(const KeyT key, ValueT value) { itemsInCache.push_front(CacheEntry(key, value)); positionMap.insert(std::make_pair(key, itemsInCache.begin())); if (itemsInCache.size() > capacity) { positionMap.erase(itemsInCache.back().key); itemsInCache.pop_back(); } } bool Fetch(const KeyT key, ValueT &result) { if (Holds(key)) { CacheEntry e = *(positionMap.find(key)->second); result = e.value; // move to front itemsInCache.splice(positionMap.find(key)->second, itemsInCache, itemsInCache.begin()); positionMap.find(key)->second = itemsInCache.begin(); return true; } return false; } unsigned Size() const { return itemsInCache.size(); } }; #endif // LRUCACHE_HPP Fix std::list splice usage error /* Copyright (c) 2014, Project OSRM, Dennis Luxen, others All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef LRUCACHE_HPP #define LRUCACHE_HPP #include <list> #include <unordered_map> template <typename KeyT, typename ValueT> class LRUCache { private: struct CacheEntry { CacheEntry(KeyT k, ValueT v) : key(k), value(v) {} KeyT key; ValueT value; }; unsigned capacity; std::list<CacheEntry> itemsInCache; std::unordered_map<KeyT, typename std::list<CacheEntry>::iterator> positionMap; public: explicit LRUCache(unsigned c) : capacity(c) {} bool Holds(KeyT key) { if (positionMap.find(key) != positionMap.end()) { return true; } return false; } void Insert(const KeyT key, ValueT &value) { itemsInCache.push_front(CacheEntry(key, value)); positionMap.insert(std::make_pair(key, itemsInCache.begin())); if (itemsInCache.size() > capacity) { positionMap.erase(itemsInCache.back().key); itemsInCache.pop_back(); } } void Insert(const KeyT key, ValueT value) { itemsInCache.push_front(CacheEntry(key, value)); positionMap.insert(std::make_pair(key, itemsInCache.begin())); if (itemsInCache.size() > capacity) { positionMap.erase(itemsInCache.back().key); itemsInCache.pop_back(); } } bool Fetch(const KeyT key, ValueT &result) { if (Holds(key)) { CacheEntry e = *(positionMap.find(key)->second); result = e.value; // move to front itemsInCache.splice(itemsInCache.begin(), itemsInCache, positionMap.find(key)->second); positionMap.find(key)->second = itemsInCache.begin(); return true; } return false; } unsigned Size() const { return itemsInCache.size(); } }; #endif // LRUCACHE_HPP
/****************************************************************************** The MIT License(MIT) Embedded Template Library. https://github.com/ETLCPP/etl http://www.etlcpp.com Copyright(c) 2014 jwellbelove Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files(the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and / or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions : The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ******************************************************************************/ #include "UnitTest++.h" #include "algorithm.h" #include "container.h" #include <vector> #include <list> #include <algorithm> #include <functional> #include <numeric> namespace { typedef std::vector<int> Data; Data data = { 2, 1, 4, 3, 6, 5, 8, 7, 10, 9 }; SUITE(test_algorithm) { //========================================================================= TEST(minmax_element) { std::pair<Data::iterator, Data::iterator> expected = std::minmax_element(data.begin(), data.end()); std::pair<Data::iterator, Data::iterator> result = etl::minmax_element(data.begin(), data.end()); CHECK_EQUAL(std::distance(data.begin(), expected.first), std::distance(data.begin(), result.first)); CHECK_EQUAL(std::distance(data.begin(), expected.second), std::distance(data.begin(), result.second)); } //========================================================================= TEST(minmax_element_compare) { std::pair<Data::iterator, Data::iterator> expected = std::minmax_element(data.begin(), data.end(), std::greater<int>()); std::pair<Data::iterator, Data::iterator> result = etl::minmax_element(data.begin(), data.end(), std::greater<int>()); CHECK_EQUAL(std::distance(data.begin(), expected.first), std::distance(data.begin(), result.first)); CHECK_EQUAL(std::distance(data.begin(), expected.second), std::distance(data.begin(), result.second)); } //========================================================================= TEST(minmax) { int a = 1; int b = 2; std::pair<int, int> expected = std::minmax(a, b); std::pair<int, int> result = etl::minmax(a, b); CHECK_EQUAL(expected.first, result.first); CHECK_EQUAL(expected.second, result.second); result = etl::minmax(b, a); expected = std::minmax(b, a); CHECK_EQUAL(expected.first, result.first); CHECK_EQUAL(expected.second, result.second); } //========================================================================= TEST(minmax_compare) { int a = 1; int b = 2; std::pair<int, int> expected = std::minmax(a, b, std::greater<int>()); std::pair<int, int> result = etl::minmax(a, b, std::greater<int>()); CHECK_EQUAL(expected.first, result.first); CHECK_EQUAL(expected.second, result.second); result = etl::minmax(b, a, std::greater<int>()); expected = std::minmax(b, a, std::greater<int>()); CHECK_EQUAL(expected.first, result.first); CHECK_EQUAL(expected.second, result.second); } //========================================================================= TEST(is_sorted_until) { int data[] = { 1, 2, 3, 4, 6, 5, 7, 8, 9, 10 }; int* p1 = std::is_sorted_until(std::begin(data), std::end(data)); int* p2 = etl::is_sorted_until(std::begin(data), std::end(data)); CHECK_EQUAL(std::distance(std::begin(data), p1), std::distance(std::begin(data), p2)); } //========================================================================= TEST(is_sorted_until_compare) { int data[] = { 10, 9, 8, 7, 5, 6, 4, 3, 4, 2, 1 }; int* p1 = std::is_sorted_until(std::begin(data), std::end(data), std::greater<int>()); int* p2 = etl::is_sorted_until(std::begin(data), std::end(data), std::greater<int>()); CHECK_EQUAL(std::distance(etl::begin(data), p1), std::distance(std::begin(data), p2)); } //========================================================================= TEST(is_sorted) { int data1[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; bool is_sorted = etl::is_sorted(std::begin(data1), std::end(data1)); CHECK(is_sorted); int data2[] = { 1, 2, 3, 4, 6, 5, 7, 8 , 9, 10}; is_sorted = etl::is_sorted(std::begin(data2), std::end(data2)); CHECK(!is_sorted); } //========================================================================= TEST(is_sorted_compare) { int data1[] = { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 }; bool is_sorted = etl::is_sorted(std::begin(data1), std::end(data1), std::greater<int>()); CHECK(is_sorted); int data2[] = { 10, 9, 8, 7, 5, 6, 4, 3, 2, 1 }; is_sorted = etl::is_sorted(std::begin(data2), std::end(data2), std::greater<int>()); CHECK(!is_sorted); } //========================================================================= TEST(copy_4_parameter_random_iterator) { int data1[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int data2[] = { 1, 2, 3, 4, 5 }; int out1[10]; int out2[5]; int check1[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int check2[] = { 1, 2, 3, 4, 5 }; int check3[] = { 1, 2, 3, 4, 5, 0, 0, 0, 0, 0 }; int* result; // Same size. std::fill(std::begin(out1), std::end(out1), 0); result = etl::copy(std::begin(data1), std::end(data1), std::begin(out1), std::end(out1)); CHECK_EQUAL(std::end(out1), result); bool is_same = std::equal(std::begin(out1), std::end(out1), std::begin(check1)); CHECK(is_same); // Destination smaller. std::fill(std::begin(out2), std::end(out2), 0); result = etl::copy(std::begin(data1), std::end(data1), std::begin(out2), std::end(out2)); CHECK_EQUAL(std::end(out2), result); is_same = std::equal(std::begin(out2), std::end(out2), std::begin(check2)); CHECK(is_same); // Source smaller. std::fill(std::begin(out1), std::end(out1), 0); result = etl::copy(std::begin(data2), std::end(data2), std::begin(out1), std::end(out1)); CHECK_EQUAL(std::begin(out1) + 5, result); is_same = std::equal(std::begin(out1), std::end(out1), std::begin(check3)); CHECK(is_same); } //========================================================================= TEST(copy_4_parameter_non_random_iterator) { std::list<int> data1 = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; std::list<int> data2 = { 1, 2, 3, 4, 5 }; int out1[10]; int out2[5]; int check1[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int check2[] = { 1, 2, 3, 4, 5 }; int check3[] = { 1, 2, 3, 4, 5, 0, 0, 0, 0, 0 }; int* result; // Same size. std::fill(std::begin(out1), std::end(out1), 0); result = etl::copy(std::begin(data1), std::end(data1), std::begin(out1), std::end(out1)); CHECK_EQUAL(std::end(out1), result); bool is_same = std::equal(std::begin(out1), std::end(out1), std::begin(check1)); CHECK(is_same); // Destination smaller. std::fill(std::begin(out2), std::end(out2), 0); result = etl::copy(std::begin(data1), std::end(data1), std::begin(out2), std::end(out2)); CHECK_EQUAL(std::end(out2), result); is_same = std::equal(std::begin(out2), std::end(out2), std::begin(check2)); CHECK(is_same); // Source smaller. std::fill(std::begin(out1), std::end(out1), 0); result = etl::copy(std::begin(data2), std::end(data2), std::begin(out1), std::end(out1)); CHECK_EQUAL(std::begin(out1) + 5, result); is_same = std::equal(std::begin(out1), std::end(out1), std::begin(check3)); CHECK(is_same); } //========================================================================= TEST(copy_n_random_iterator) { int data1[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int data2[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; int data3[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; int* result; std::copy_n(std::begin(data1), 4, std::begin(data2)); result = etl::copy_n(std::begin(data1), 4, std::begin(data3)); CHECK_EQUAL(std::begin(data3) + 4, result); bool is_same = std::equal(std::begin(data2), std::end(data2), std::begin(data3)); CHECK(is_same); } //========================================================================= TEST(copy_n_non_random_iterator) { std::list<int> data1 = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int data2[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; int data3[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; int* result; std::copy_n(std::begin(data1), 4, std::begin(data2)); result = etl::copy_n(std::begin(data1), 4, std::begin(data3)); CHECK_EQUAL(std::begin(data3) + 4, result); bool is_same = std::equal(std::begin(data2), std::end(data2), std::begin(data3)); CHECK(is_same); } //========================================================================= TEST(copy_n_4_parameter) { int data1[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int out1[10]; int out2[5]; int check1[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int check2[] = { 1, 2, 3, 4, 5 }; int check3[] = { 1, 2, 3, 4, 5, 0, 0, 0, 0, 0 }; int* result; // Same size. std::fill(std::begin(out1), std::end(out1), 0); result = etl::copy_n(std::begin(data1), 10, std::begin(out1), std::end(out1)); CHECK_EQUAL(std::end(out1), result); bool is_same = std::equal(std::begin(out1), std::end(out1), std::begin(check1)); CHECK(is_same); // Destination smaller. std::fill(std::begin(out2), std::end(out2), 0); result = etl::copy_n(std::begin(data1), 10, std::begin(out2), std::end(out2)); CHECK_EQUAL(std::end(out2), result); is_same = std::equal(std::begin(out2), std::end(out2), std::begin(check2)); CHECK(is_same); // Source smaller. std::fill(std::begin(out1), std::end(out1), 0); result = etl::copy_n(std::begin(data1), 5, std::begin(out1), std::end(out1)); CHECK_EQUAL(std::begin(out1) + 5, result); is_same = std::equal(std::begin(out1), std::end(out1), std::begin(check3)); CHECK(is_same); } //========================================================================= TEST(copy_2n_4_parameter) { int data1[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int out1[10]; int out2[5]; int check1[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int check2[] = { 1, 2, 3, 4, 5 }; int check3[] = { 1, 2, 3, 4, 5, 0, 0, 0, 0, 0 }; int* result; // Same size. std::fill(std::begin(out1), std::end(out1), 0); result = etl::copy_n(std::begin(data1), 10, std::begin(out1), 10); CHECK_EQUAL(std::end(out1), result); bool is_same = std::equal(std::begin(out1), std::end(out1), std::begin(check1)); CHECK(is_same); // Destination smaller. std::fill(std::begin(out2), std::end(out2), 0); result = etl::copy_n(std::begin(data1), 10, std::begin(out2), 5); CHECK_EQUAL(std::end(out2), result); is_same = std::equal(std::begin(out2), std::end(out2), std::begin(check2)); CHECK(is_same); // Source smaller. std::fill(std::begin(out1), std::end(out1), 0); result = etl::copy_n(std::begin(data1), 5, std::begin(out1), 10); CHECK_EQUAL(std::begin(out1) + 5, result); is_same = std::equal(std::begin(out1), std::end(out1), std::begin(check3)); CHECK(is_same); } //========================================================================= TEST(copy_if) { int data1[] = { 1, 8, 2, 7, 3, 6, 4, 5, 10, 9 }; int data2[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; int data3[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; // Copy everything less than 5. std::copy_if(std::begin(data1), std::end(data1), std::begin(data2), std::bind2nd(std::less<int>(), 5)); etl::copy_if(std::begin(data1), std::end(data1), std::begin(data3), std::bind2nd(std::less<int>(), 5)); bool is_same = std::equal(std::begin(data2), std::end(data2), std::begin(data3)); CHECK(is_same); } //========================================================================= TEST(copy_n_if) { int data1[] = { 1, 8, 2, 7, 3, 6, 4, 5, 10, 9 }; int data2[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; int data3[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; // Copy everything less than 5. int *pout = data2; for (int* pin = std::begin(data1); pin != std::begin(data1) + 6; ++pin) { if (*pin < 5) { *pout++ = *pin; } } etl::copy_n_if(std::begin(data1), 6, std::begin(data3), std::bind2nd(std::less<int>(), 5)); bool is_same = std::equal(std::begin(data2), std::end(data2), std::begin(data3)); CHECK(is_same); } //========================================================================= TEST(copy_if_4_parameter) { int data1[] = { 1, 8, 2, 7, 3, 6, 4, 5, 10, 9 }; int out1[4]; int out2[2]; int out3[10]; int check1[] = { 1, 2, 3, 4 }; int check2[] = { 1, 2 }; int check3[] = { 1, 2, 3, 4, 0, 0, 0, 0, 0, 0 }; int* result; // Exact size. std::fill(std::begin(out1), std::end(out1), 0); result = etl::copy_if(std::begin(data1), std::end(data1), std::begin(out1), std::end(out1), std::bind2nd(std::less<int>(), 5)); CHECK_EQUAL(std::end(out1), result); bool is_same = std::equal(std::begin(out1), std::end(out1), std::begin(check1)); CHECK(is_same); // Destination smaller. std::fill(std::begin(out2), std::end(out2), 0); result = etl::copy_if(std::begin(data1), std::end(data1), std::begin(out2), std::end(out2), std::bind2nd(std::less<int>(), 5)); CHECK_EQUAL(std::end(out2), result); is_same = std::equal(std::begin(out2), std::end(out2), std::begin(check2)); CHECK(is_same); // Destination larger. std::fill(std::begin(out3), std::end(out3), 0); result = etl::copy_if(std::begin(data1), std::end(data1), std::begin(out3), std::end(out3), std::bind2nd(std::less<int>(), 5)); CHECK_EQUAL(std::begin(out3) + 4, result); is_same = std::equal(std::begin(out3), std::end(out3), std::begin(check3)); CHECK(is_same); } //========================================================================= TEST(any_of) { int data1[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; bool expected = std::any_of(std::begin(data1), std::end(data1), std::bind2nd(std::greater<int>(), 4)); bool result = etl::any_of(std::begin(data1), std::end(data1), std::bind2nd(std::greater<int>(), 4)); CHECK_EQUAL(expected, result); expected = std::any_of(std::begin(data1), std::end(data1), std::bind2nd(std::greater<int>(), 0)); result = etl::any_of(std::begin(data1), std::end(data1), std::bind2nd(std::greater<int>(), 0)); CHECK_EQUAL(expected, result); } //========================================================================= TEST(all_of) { int data1[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; bool expected = std::all_of(std::begin(data1), std::end(data1), std::bind2nd(std::greater<int>(), 0)); bool result = etl::all_of(std::begin(data1), std::end(data1), std::bind2nd(std::greater<int>(), 0)); CHECK_EQUAL(expected, result); expected = std::all_of(std::begin(data1), std::end(data1), std::bind2nd(std::greater<int>(), 4)); result = etl::all_of(std::begin(data1), std::end(data1), std::bind2nd(std::greater<int>(), 4)); CHECK_EQUAL(expected, result); } //========================================================================= TEST(none_of) { int data1[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; bool expected = std::none_of(std::begin(data1), std::end(data1), std::bind2nd(std::greater<int>(), 8)); bool result = etl::none_of(std::begin(data1), std::end(data1), std::bind2nd(std::greater<int>(), 8)); CHECK_EQUAL(expected, result); expected = std::none_of(std::begin(data1), std::end(data1), std::bind2nd(std::greater<int>(), 4)); result = etl::none_of(std::begin(data1), std::end(data1), std::bind2nd(std::greater<int>(), 4)); CHECK_EQUAL(expected, result); } struct Compare : public std::binary_function < int, int, bool > { bool operator()(int a, int b) const { return a == b; } }; //========================================================================= TEST(is_permutation) { int data1[] = { 1, 2, 3, 4, 5, 6, 7, 8 }; int permutation[] = { 1, 3, 2, 4, 7, 6, 5, 8 }; int not_permutation[] = { 1, 2, 3, 4, 5, 6, 7, 7 }; bool is_permutation = etl::is_permutation(std::begin(data1), std::end(data1), std::begin(permutation)); CHECK(is_permutation); is_permutation = etl::is_permutation(std::begin(data1), std::end(data1), std::begin(not_permutation)); CHECK(!is_permutation); is_permutation = etl::is_permutation(std::begin(data1), std::end(data1), std::begin(permutation), std::equal_to<int>()); CHECK(is_permutation); is_permutation = etl::is_permutation(std::begin(data1), std::end(data1), std::begin(not_permutation), std::equal_to<int>()); CHECK(!is_permutation); is_permutation = etl::is_permutation(std::begin(data1), std::end(data1), std::begin(permutation), std::end(permutation)); CHECK(is_permutation); is_permutation = etl::is_permutation(std::begin(data1), std::end(data1), std::begin(not_permutation), std::end(not_permutation)); CHECK(!is_permutation); is_permutation = etl::is_permutation(std::begin(data1), std::end(data1), std::begin(permutation), std::end(permutation), std::equal_to<int>()); CHECK(is_permutation); is_permutation = etl::is_permutation(std::begin(data1), std::end(data1), std::begin(not_permutation), std::end(not_permutation), std::equal_to<int>()); CHECK(!is_permutation); } //========================================================================= TEST(is_partitioned) { int data1[] = { 1, 2, 3, 4, 5, 6, 7, 8 }; bool expected = std::is_partitioned(std::begin(data1), std::end(data1), std::bind2nd(std::greater<int>(), 4)); bool result = etl::is_partitioned(std::begin(data1), std::end(data1), std::bind2nd(std::greater<int>(), 4)); CHECK_EQUAL(expected, result); std::partition(std::begin(data1), std::end(data1), std::bind2nd(std::greater<int>(), 4)); expected = std::is_partitioned(std::begin(data1), std::end(data1), std::bind2nd(std::greater<int>(), 4)); result = etl::is_partitioned(std::begin(data1), std::end(data1), std::bind2nd(std::greater<int>(), 4)); CHECK_EQUAL(expected, result); } //========================================================================= TEST(partition_point) { int data1[] = { 1, 2, 3, 4, 5, 6, 7, 8 }; std::partition(std::begin(data1), std::end(data1), std::bind2nd(std::greater<int>(), 4)); int* partition1 = std::partition_point(std::begin(data1), std::end(data1), std::bind2nd(std::greater<int>(), 4)); int* partition2 = etl::partition_point(std::begin(data1), std::end(data1), std::bind2nd(std::greater<int>(), 4)); CHECK_EQUAL(std::distance(std::begin(data1), partition1), std::distance(std::begin(data1), partition2)); std::partition(std::begin(data1), std::end(data1), std::bind2nd(std::greater<int>(), 8)); partition1 = std::partition_point(std::begin(data1), std::end(data1), std::bind2nd(std::greater<int>(), 0)); partition2 = etl::partition_point(std::begin(data1), std::end(data1), std::bind2nd(std::greater<int>(), 0)); CHECK_EQUAL(std::distance(std::begin(data1), partition1), std::distance(std::begin(data1), partition2)); } //========================================================================= TEST(partition_copy) { int data1[] = { 1, 2, 3, 4, 5, 6, 7, 8 }; int data2[] = { 0, 0, 0, 0, 0, 0, 0, 0 }; int data3[] = { 0, 0, 0, 0, 0, 0, 0, 0 }; int data4[] = { 0, 0, 0, 0, 0, 0, 0, 0 }; int data5[] = { 0, 0, 0, 0, 0, 0, 0, 0 }; std::partition_copy(std::begin(data1), std::end(data1), std::begin(data2), std::begin(data3), std::bind2nd(std::greater<int>(), 4)); etl::partition_copy(std::begin(data1), std::end(data1), std::begin(data4), std::begin(data5), std::bind2nd(std::greater<int>(), 4)); bool are_equal; are_equal = std::equal(std::begin(data2), std::end(data2), std::begin(data4)); CHECK(are_equal); are_equal = std::equal(std::begin(data3), std::end(data3), std::begin(data5)); CHECK(are_equal); } //========================================================================= TEST(find_if_not) { int data1[] = { 1, 2, 3, 5, 6, 7, 8 }; // Find the element not less than 4. int* p = std::find_if_not(std::begin(data1), std::end(data1), std::bind2nd(std::less<int>(), 4)); CHECK_EQUAL(5, *p); } //========================================================================= TEST(for_each_if) { int data1[] = { 1, 8, 2, 7, 3, 6, 4, 5, 10, 9 }; struct Sum { Sum() : sum(0) { } Sum& operator()(int i) { sum += i; return *this; } int sum; } accumulator; // For each if everything less than 5. accumulator = etl::for_each_if(std::begin(data1), std::end(data1), accumulator, std::bind2nd(std::less<int>(), 5)); CHECK_EQUAL(10, accumulator.sum); } //========================================================================= TEST(for_each_n) { int data1[] = { 1, 8, 2, 7, 3, 6, 4, 5, 10, 9 }; int data2[] = { 2, 16, 4, 14, 6, 6, 4, 5, 10, 9 }; struct Multiply { void operator()(int& i) { i *= 2; } } multiplier; etl::for_each_n(std::begin(data1), 5, multiplier); bool are_equal = std::equal(std::begin(data1), std::end(data1), std::begin(data2)); CHECK(are_equal); } //========================================================================= TEST(for_each_n_if) { int data1[] = { 1, 8, 2, 7, 3, 6, 4, 5, 10, 9 }; int data2[] = { 2, 8, 4, 7, 6, 6, 4, 5, 10, 9 }; struct Multiply { void operator()(int& i) { i *= 2; } } multiplier; etl::for_each_n_if(std::begin(data1), 5, multiplier, std::bind2nd(std::less<int>(), 5)); bool are_equal = std::equal(std::begin(data1), std::end(data1), std::begin(data2)); CHECK(are_equal); } //========================================================================= TEST(transform_4_parameter) { int input[] = { 1, 8, 2, 7, 3, 6, 4, 5, 10, 9 }; int output[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; int compare[] = { 2, 16, 4, 14, 6, 0, 0, 0, 0, 0 }; // Double everything and copy to output. etl::transform(std::begin(input), std::end(input), std::begin(output), std::begin(output) + (etl::size(output) / 2), std::bind2nd(std::multiplies<int>(), 2)); bool is_same = std::equal(std::begin(output), std::end(output), std::begin(compare)); CHECK(is_same); std::fill(std::begin(output), std::end(output), 0); etl::transform(std::begin(input), std::begin(input) + (etl::size(input) / 2), std::begin(output), std::end(output), std::bind2nd(std::multiplies<int>(), 2)); is_same = std::equal(std::begin(output), std::end(output), std::begin(compare)); CHECK(is_same); } //========================================================================= TEST(transform_n_random_iterator) { int input[] = { 1, 8, 2, 7, 3, 6, 4, 5, 10, 9 }; int output[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; int compare[] = { 2, 16, 4, 14, 6, 12, 8, 0, 0, 0 }; etl::transform_n(std::begin(input), 7, std::begin(output), std::bind2nd(std::multiplies<int>(), 2)); bool is_same = std::equal(std::begin(output), std::end(output), std::begin(compare)); CHECK(is_same); } //========================================================================= TEST(transform_n_non_random_iterator) { std::list<int> input = { 1, 8, 2, 7, 3, 6, 4, 5, 10, 9 }; int output[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; int compare[] = { 2, 16, 4, 14, 6, 12, 8, 0, 0, 0 }; etl::transform_n(std::begin(input), 7, std::begin(output), std::bind2nd(std::multiplies<int>(), 2)); bool is_same = std::equal(std::begin(output), std::end(output), std::begin(compare)); CHECK(is_same); } //========================================================================= TEST(transform_if) { int input[] = { 1, 8, 2, 7, 3, 6, 4, 5, 10, 9 }; int output[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; int compare[] = { 2, 4, 6, 8, 0, 0, 0, 0, 0, 0 }; // Double everything less than 5 and copy to output. etl::transform_if(std::begin(input), std::end(input), std::begin(output), std::bind2nd(std::multiplies<int>(), 2), std::bind2nd(std::less<int>(), 5)); bool is_same = std::equal(std::begin(output), std::end(output), std::begin(compare)); CHECK(is_same); } //========================================================================= TEST(transform_if_2_input_ranges) { int input1[] = { 1, 8, 2, 7, 3, 6, 4, 5, 10, 9 }; int input2[] = { 8, 7, 6, 5, 4, 10, 9, 3, 2, 1 }; int output[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; int compare[] = { 8, 12, 12, 60, 36, 0, 0, 0, 0, 0 }; // Multiply together everything where input1 is less than input2 and copy to output. etl::transform_if(std::begin(input1), std::end(input1), std::begin(input2), std::begin(output), std::multiplies<int>(), std::less<int>()); bool is_same = std::equal(std::begin(output), std::end(output), std::begin(compare)); CHECK(is_same); } //========================================================================= TEST(partition_transform) { int input[] = { 1, 8, 2, 7, 3, 6, 4, 5, 10, 9 }; int output_true[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; int output_false[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; int compare_true[] = { 2, 4, 6, 8, 0, 0, 0, 0, 0, 0 }; int compare_false[] = { -16, -14, -12, -10, -20, -18, 0, 0, 0, 0 }; // Multiply everything less than 5 by 2 and copy to output_true. // Multiply everything not less than 5 by -2 and copy to output_false. etl::partition_transform(std::begin(input), std::end(input), std::begin(output_true), std::begin(output_false), std::bind2nd(std::multiplies<int>(), 2), std::bind2nd(std::multiplies<int>(), -2), std::bind2nd(std::less<int>(), 5)); bool is_same = std::equal(std::begin(output_true), std::end(output_true), std::begin(compare_true)); CHECK(is_same); is_same = std::equal(std::begin(output_false), std::end(output_false), std::begin(compare_false)); CHECK(is_same); } //========================================================================= TEST(partition_transform_2_input_ranges) { int input1[] = { 1, 8, 2, 7, 3, 6, 4, 5, 10, 9 }; int input2[] = { 8, 7, 6, 5, 4, 10, 9, 3, 2, 1 }; int output_true[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; int output_false[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; int compare_true[] = { 8, 12, 12, 60, 36, 0, 0, 0, 0, 0 }; int compare_false[] = { 15, 12, 8, 12, 10, 0, 0, 0, 0, 0 }; // If input1 < input2 multiply else add. etl::partition_transform(std::begin(input1), std::end(input1), std::begin(input2), std::begin(output_true), std::begin(output_false), std::multiplies<int>(), std::plus<int>(), std::less<int>()); bool is_same = std::equal(std::begin(output_true), std::end(output_true), std::begin(compare_true)); CHECK(is_same); is_same = std::equal(std::begin(output_false), std::end(output_false), std::begin(compare_false)); CHECK(is_same); } }; } Additional algorithms. /****************************************************************************** The MIT License(MIT) Embedded Template Library. https://github.com/ETLCPP/etl http://www.etlcpp.com Copyright(c) 2014 jwellbelove Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files(the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and / or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions : The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ******************************************************************************/ #include "UnitTest++.h" #include "algorithm.h" #include "container.h" #include <vector> #include <list> #include <algorithm> #include <functional> #include <numeric> namespace { typedef std::vector<int> Data; Data data = { 2, 1, 4, 3, 6, 5, 8, 7, 10, 9 }; SUITE(test_algorithm) { //========================================================================= TEST(minmax_element) { std::pair<Data::iterator, Data::iterator> expected = std::minmax_element(data.begin(), data.end()); std::pair<Data::iterator, Data::iterator> result = etl::minmax_element(data.begin(), data.end()); CHECK_EQUAL(std::distance(data.begin(), expected.first), std::distance(data.begin(), result.first)); CHECK_EQUAL(std::distance(data.begin(), expected.second), std::distance(data.begin(), result.second)); } //========================================================================= TEST(minmax_element_compare) { std::pair<Data::iterator, Data::iterator> expected = std::minmax_element(data.begin(), data.end(), std::greater<int>()); std::pair<Data::iterator, Data::iterator> result = etl::minmax_element(data.begin(), data.end(), std::greater<int>()); CHECK_EQUAL(std::distance(data.begin(), expected.first), std::distance(data.begin(), result.first)); CHECK_EQUAL(std::distance(data.begin(), expected.second), std::distance(data.begin(), result.second)); } //========================================================================= TEST(minmax) { int a = 1; int b = 2; std::pair<int, int> expected = std::minmax(a, b); std::pair<int, int> result = etl::minmax(a, b); CHECK_EQUAL(expected.first, result.first); CHECK_EQUAL(expected.second, result.second); result = etl::minmax(b, a); expected = std::minmax(b, a); CHECK_EQUAL(expected.first, result.first); CHECK_EQUAL(expected.second, result.second); } //========================================================================= TEST(minmax_compare) { int a = 1; int b = 2; std::pair<int, int> expected = std::minmax(a, b, std::greater<int>()); std::pair<int, int> result = etl::minmax(a, b, std::greater<int>()); CHECK_EQUAL(expected.first, result.first); CHECK_EQUAL(expected.second, result.second); result = etl::minmax(b, a, std::greater<int>()); expected = std::minmax(b, a, std::greater<int>()); CHECK_EQUAL(expected.first, result.first); CHECK_EQUAL(expected.second, result.second); } //========================================================================= TEST(is_sorted_until) { int data[] = { 1, 2, 3, 4, 6, 5, 7, 8, 9, 10 }; int* p1 = std::is_sorted_until(std::begin(data), std::end(data)); int* p2 = etl::is_sorted_until(std::begin(data), std::end(data)); CHECK_EQUAL(std::distance(std::begin(data), p1), std::distance(std::begin(data), p2)); } //========================================================================= TEST(is_sorted_until_compare) { int data[] = { 10, 9, 8, 7, 5, 6, 4, 3, 4, 2, 1 }; int* p1 = std::is_sorted_until(std::begin(data), std::end(data), std::greater<int>()); int* p2 = etl::is_sorted_until(std::begin(data), std::end(data), std::greater<int>()); CHECK_EQUAL(std::distance(etl::begin(data), p1), std::distance(std::begin(data), p2)); } //========================================================================= TEST(is_sorted) { int data1[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; bool is_sorted = etl::is_sorted(std::begin(data1), std::end(data1)); CHECK(is_sorted); int data2[] = { 1, 2, 3, 4, 6, 5, 7, 8 , 9, 10}; is_sorted = etl::is_sorted(std::begin(data2), std::end(data2)); CHECK(!is_sorted); } //========================================================================= TEST(is_sorted_compare) { int data1[] = { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 }; bool is_sorted = etl::is_sorted(std::begin(data1), std::end(data1), std::greater<int>()); CHECK(is_sorted); int data2[] = { 10, 9, 8, 7, 5, 6, 4, 3, 2, 1 }; is_sorted = etl::is_sorted(std::begin(data2), std::end(data2), std::greater<int>()); CHECK(!is_sorted); } //========================================================================= TEST(copy_4_parameter_random_iterator) { int data1[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int data2[] = { 1, 2, 3, 4, 5 }; int out1[10]; int out2[5]; int check1[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int check2[] = { 1, 2, 3, 4, 5 }; int check3[] = { 1, 2, 3, 4, 5, 0, 0, 0, 0, 0 }; int* result; // Same size. std::fill(std::begin(out1), std::end(out1), 0); result = etl::copy(std::begin(data1), std::end(data1), std::begin(out1), std::end(out1)); CHECK_EQUAL(std::end(out1), result); bool is_same = std::equal(std::begin(out1), std::end(out1), std::begin(check1)); CHECK(is_same); // Destination smaller. std::fill(std::begin(out2), std::end(out2), 0); result = etl::copy(std::begin(data1), std::end(data1), std::begin(out2), std::end(out2)); CHECK_EQUAL(std::end(out2), result); is_same = std::equal(std::begin(out2), std::end(out2), std::begin(check2)); CHECK(is_same); // Source smaller. std::fill(std::begin(out1), std::end(out1), 0); result = etl::copy(std::begin(data2), std::end(data2), std::begin(out1), std::end(out1)); CHECK_EQUAL(std::begin(out1) + 5, result); is_same = std::equal(std::begin(out1), std::end(out1), std::begin(check3)); CHECK(is_same); } //========================================================================= TEST(copy_4_parameter_non_random_iterator) { std::list<int> data1 = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; std::list<int> data2 = { 1, 2, 3, 4, 5 }; int out1[10]; int out2[5]; int check1[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int check2[] = { 1, 2, 3, 4, 5 }; int check3[] = { 1, 2, 3, 4, 5, 0, 0, 0, 0, 0 }; int* result; // Same size. std::fill(std::begin(out1), std::end(out1), 0); result = etl::copy(std::begin(data1), std::end(data1), std::begin(out1), std::end(out1)); CHECK_EQUAL(std::end(out1), result); bool is_same = std::equal(std::begin(out1), std::end(out1), std::begin(check1)); CHECK(is_same); // Destination smaller. std::fill(std::begin(out2), std::end(out2), 0); result = etl::copy(std::begin(data1), std::end(data1), std::begin(out2), std::end(out2)); CHECK_EQUAL(std::end(out2), result); is_same = std::equal(std::begin(out2), std::end(out2), std::begin(check2)); CHECK(is_same); // Source smaller. std::fill(std::begin(out1), std::end(out1), 0); result = etl::copy(std::begin(data2), std::end(data2), std::begin(out1), std::end(out1)); CHECK_EQUAL(std::begin(out1) + 5, result); is_same = std::equal(std::begin(out1), std::end(out1), std::begin(check3)); CHECK(is_same); } //========================================================================= TEST(copy_n_random_iterator) { int data1[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int data2[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; int data3[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; int* result; std::copy_n(std::begin(data1), 4, std::begin(data2)); result = etl::copy_n(std::begin(data1), 4, std::begin(data3)); CHECK_EQUAL(std::begin(data3) + 4, result); bool is_same = std::equal(std::begin(data2), std::end(data2), std::begin(data3)); CHECK(is_same); } //========================================================================= TEST(copy_n_non_random_iterator) { std::list<int> data1 = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int data2[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; int data3[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; int* result; std::copy_n(std::begin(data1), 4, std::begin(data2)); result = etl::copy_n(std::begin(data1), 4, std::begin(data3)); CHECK_EQUAL(std::begin(data3) + 4, result); bool is_same = std::equal(std::begin(data2), std::end(data2), std::begin(data3)); CHECK(is_same); } //========================================================================= TEST(copy_n_4_parameter) { int data1[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int out1[10]; int out2[5]; int check1[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int check2[] = { 1, 2, 3, 4, 5 }; int check3[] = { 1, 2, 3, 4, 5, 0, 0, 0, 0, 0 }; int* result; // Same size. std::fill(std::begin(out1), std::end(out1), 0); result = etl::copy_n(std::begin(data1), 10, std::begin(out1), std::end(out1)); CHECK_EQUAL(std::end(out1), result); bool is_same = std::equal(std::begin(out1), std::end(out1), std::begin(check1)); CHECK(is_same); // Destination smaller. std::fill(std::begin(out2), std::end(out2), 0); result = etl::copy_n(std::begin(data1), 10, std::begin(out2), std::end(out2)); CHECK_EQUAL(std::end(out2), result); is_same = std::equal(std::begin(out2), std::end(out2), std::begin(check2)); CHECK(is_same); // Source smaller. std::fill(std::begin(out1), std::end(out1), 0); result = etl::copy_n(std::begin(data1), 5, std::begin(out1), std::end(out1)); CHECK_EQUAL(std::begin(out1) + 5, result); is_same = std::equal(std::begin(out1), std::end(out1), std::begin(check3)); CHECK(is_same); } //========================================================================= TEST(copy_2n_4_parameter) { int data1[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int out1[10]; int out2[5]; int check1[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int check2[] = { 1, 2, 3, 4, 5 }; int check3[] = { 1, 2, 3, 4, 5, 0, 0, 0, 0, 0 }; int* result; // Same size. std::fill(std::begin(out1), std::end(out1), 0); result = etl::copy_n(std::begin(data1), 10, std::begin(out1), 10); CHECK_EQUAL(std::end(out1), result); bool is_same = std::equal(std::begin(out1), std::end(out1), std::begin(check1)); CHECK(is_same); // Destination smaller. std::fill(std::begin(out2), std::end(out2), 0); result = etl::copy_n(std::begin(data1), 10, std::begin(out2), 5); CHECK_EQUAL(std::end(out2), result); is_same = std::equal(std::begin(out2), std::end(out2), std::begin(check2)); CHECK(is_same); // Source smaller. std::fill(std::begin(out1), std::end(out1), 0); result = etl::copy_n(std::begin(data1), 5, std::begin(out1), 10); CHECK_EQUAL(std::begin(out1) + 5, result); is_same = std::equal(std::begin(out1), std::end(out1), std::begin(check3)); CHECK(is_same); } //========================================================================= TEST(copy_if) { int data1[] = { 1, 8, 2, 7, 3, 6, 4, 5, 10, 9 }; int data2[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; int data3[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; // Copy everything less than 5. std::copy_if(std::begin(data1), std::end(data1), std::begin(data2), std::bind2nd(std::less<int>(), 5)); etl::copy_if(std::begin(data1), std::end(data1), std::begin(data3), std::bind2nd(std::less<int>(), 5)); bool is_same = std::equal(std::begin(data2), std::end(data2), std::begin(data3)); CHECK(is_same); } //========================================================================= TEST(copy_n_if) { int data1[] = { 1, 8, 2, 7, 3, 6, 4, 5, 10, 9 }; int data2[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; int data3[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; // Copy everything less than 5. int *pout = data2; for (int* pin = std::begin(data1); pin != std::begin(data1) + 6; ++pin) { if (*pin < 5) { *pout++ = *pin; } } etl::copy_n_if(std::begin(data1), 6, std::begin(data3), std::bind2nd(std::less<int>(), 5)); bool is_same = std::equal(std::begin(data2), std::end(data2), std::begin(data3)); CHECK(is_same); } //========================================================================= TEST(copy_if_4_parameter) { int data1[] = { 1, 8, 2, 7, 3, 6, 4, 5, 10, 9 }; int out1[4]; int out2[2]; int out3[10]; int check1[] = { 1, 2, 3, 4 }; int check2[] = { 1, 2 }; int check3[] = { 1, 2, 3, 4, 0, 0, 0, 0, 0, 0 }; int* result; // Exact size. std::fill(std::begin(out1), std::end(out1), 0); result = etl::copy_if(std::begin(data1), std::end(data1), std::begin(out1), std::end(out1), std::bind2nd(std::less<int>(), 5)); CHECK_EQUAL(std::end(out1), result); bool is_same = std::equal(std::begin(out1), std::end(out1), std::begin(check1)); CHECK(is_same); // Destination smaller. std::fill(std::begin(out2), std::end(out2), 0); result = etl::copy_if(std::begin(data1), std::end(data1), std::begin(out2), std::end(out2), std::bind2nd(std::less<int>(), 5)); CHECK_EQUAL(std::end(out2), result); is_same = std::equal(std::begin(out2), std::end(out2), std::begin(check2)); CHECK(is_same); // Destination larger. std::fill(std::begin(out3), std::end(out3), 0); result = etl::copy_if(std::begin(data1), std::end(data1), std::begin(out3), std::end(out3), std::bind2nd(std::less<int>(), 5)); CHECK_EQUAL(std::begin(out3) + 4, result); is_same = std::equal(std::begin(out3), std::end(out3), std::begin(check3)); CHECK(is_same); } //========================================================================= TEST(any_of) { int data1[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; bool expected = std::any_of(std::begin(data1), std::end(data1), std::bind2nd(std::greater<int>(), 4)); bool result = etl::any_of(std::begin(data1), std::end(data1), std::bind2nd(std::greater<int>(), 4)); CHECK_EQUAL(expected, result); expected = std::any_of(std::begin(data1), std::end(data1), std::bind2nd(std::greater<int>(), 0)); result = etl::any_of(std::begin(data1), std::end(data1), std::bind2nd(std::greater<int>(), 0)); CHECK_EQUAL(expected, result); } //========================================================================= TEST(all_of) { int data1[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; bool expected = std::all_of(std::begin(data1), std::end(data1), std::bind2nd(std::greater<int>(), 0)); bool result = etl::all_of(std::begin(data1), std::end(data1), std::bind2nd(std::greater<int>(), 0)); CHECK_EQUAL(expected, result); expected = std::all_of(std::begin(data1), std::end(data1), std::bind2nd(std::greater<int>(), 4)); result = etl::all_of(std::begin(data1), std::end(data1), std::bind2nd(std::greater<int>(), 4)); CHECK_EQUAL(expected, result); } //========================================================================= TEST(none_of) { int data1[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; bool expected = std::none_of(std::begin(data1), std::end(data1), std::bind2nd(std::greater<int>(), 8)); bool result = etl::none_of(std::begin(data1), std::end(data1), std::bind2nd(std::greater<int>(), 8)); CHECK_EQUAL(expected, result); expected = std::none_of(std::begin(data1), std::end(data1), std::bind2nd(std::greater<int>(), 4)); result = etl::none_of(std::begin(data1), std::end(data1), std::bind2nd(std::greater<int>(), 4)); CHECK_EQUAL(expected, result); } struct Compare : public std::binary_function < int, int, bool > { bool operator()(int a, int b) const { return a == b; } }; //========================================================================= TEST(is_permutation) { int data1[] = { 1, 2, 3, 4, 5, 6, 7, 8 }; int permutation[] = { 1, 3, 2, 4, 7, 6, 5, 8 }; int not_permutation[] = { 1, 2, 3, 4, 5, 6, 7, 7 }; bool is_permutation = etl::is_permutation(std::begin(data1), std::end(data1), std::begin(permutation)); CHECK(is_permutation); is_permutation = etl::is_permutation(std::begin(data1), std::end(data1), std::begin(not_permutation)); CHECK(!is_permutation); is_permutation = etl::is_permutation(std::begin(data1), std::end(data1), std::begin(permutation), std::equal_to<int>()); CHECK(is_permutation); is_permutation = etl::is_permutation(std::begin(data1), std::end(data1), std::begin(not_permutation), std::equal_to<int>()); CHECK(!is_permutation); is_permutation = etl::is_permutation(std::begin(data1), std::end(data1), std::begin(permutation), std::end(permutation)); CHECK(is_permutation); is_permutation = etl::is_permutation(std::begin(data1), std::end(data1), std::begin(not_permutation), std::end(not_permutation)); CHECK(!is_permutation); is_permutation = etl::is_permutation(std::begin(data1), std::end(data1), std::begin(permutation), std::end(permutation), std::equal_to<int>()); CHECK(is_permutation); is_permutation = etl::is_permutation(std::begin(data1), std::end(data1), std::begin(not_permutation), std::end(not_permutation), std::equal_to<int>()); CHECK(!is_permutation); } //========================================================================= TEST(is_partitioned) { int data1[] = { 1, 2, 3, 4, 5, 6, 7, 8 }; bool expected = std::is_partitioned(std::begin(data1), std::end(data1), std::bind2nd(std::greater<int>(), 4)); bool result = etl::is_partitioned(std::begin(data1), std::end(data1), std::bind2nd(std::greater<int>(), 4)); CHECK_EQUAL(expected, result); std::partition(std::begin(data1), std::end(data1), std::bind2nd(std::greater<int>(), 4)); expected = std::is_partitioned(std::begin(data1), std::end(data1), std::bind2nd(std::greater<int>(), 4)); result = etl::is_partitioned(std::begin(data1), std::end(data1), std::bind2nd(std::greater<int>(), 4)); CHECK_EQUAL(expected, result); } //========================================================================= TEST(partition_point) { int data1[] = { 1, 2, 3, 4, 5, 6, 7, 8 }; std::partition(std::begin(data1), std::end(data1), std::bind2nd(std::greater<int>(), 4)); int* partition1 = std::partition_point(std::begin(data1), std::end(data1), std::bind2nd(std::greater<int>(), 4)); int* partition2 = etl::partition_point(std::begin(data1), std::end(data1), std::bind2nd(std::greater<int>(), 4)); CHECK_EQUAL(std::distance(std::begin(data1), partition1), std::distance(std::begin(data1), partition2)); std::partition(std::begin(data1), std::end(data1), std::bind2nd(std::greater<int>(), 8)); partition1 = std::partition_point(std::begin(data1), std::end(data1), std::bind2nd(std::greater<int>(), 0)); partition2 = etl::partition_point(std::begin(data1), std::end(data1), std::bind2nd(std::greater<int>(), 0)); CHECK_EQUAL(std::distance(std::begin(data1), partition1), std::distance(std::begin(data1), partition2)); } //========================================================================= TEST(partition_copy) { int data1[] = { 1, 2, 3, 4, 5, 6, 7, 8 }; int data2[] = { 0, 0, 0, 0, 0, 0, 0, 0 }; int data3[] = { 0, 0, 0, 0, 0, 0, 0, 0 }; int data4[] = { 0, 0, 0, 0, 0, 0, 0, 0 }; int data5[] = { 0, 0, 0, 0, 0, 0, 0, 0 }; std::partition_copy(std::begin(data1), std::end(data1), std::begin(data2), std::begin(data3), std::bind2nd(std::greater<int>(), 4)); etl::partition_copy(std::begin(data1), std::end(data1), std::begin(data4), std::begin(data5), std::bind2nd(std::greater<int>(), 4)); bool are_equal; are_equal = std::equal(std::begin(data2), std::end(data2), std::begin(data4)); CHECK(are_equal); are_equal = std::equal(std::begin(data3), std::end(data3), std::begin(data5)); CHECK(are_equal); } //========================================================================= TEST(find_if_not) { int data1[] = { 1, 2, 3, 5, 6, 7, 8 }; // Find the element not less than 4. int* p = std::find_if_not(std::begin(data1), std::end(data1), std::bind2nd(std::less<int>(), 4)); CHECK_EQUAL(5, *p); } //========================================================================= TEST(for_each_if) { int data1[] = { 1, 8, 2, 7, 3, 6, 4, 5, 10, 9 }; struct Sum { Sum() : sum(0) { } Sum& operator()(int i) { sum += i; return *this; } int sum; } accumulator; // For each if everything less than 5. accumulator = etl::for_each_if(std::begin(data1), std::end(data1), accumulator, std::bind2nd(std::less<int>(), 5)); CHECK_EQUAL(10, accumulator.sum); } //========================================================================= TEST(for_each_n) { int data1[] = { 1, 8, 2, 7, 3, 6, 4, 5, 10, 9 }; int data2[] = { 2, 16, 4, 14, 6, 6, 4, 5, 10, 9 }; struct Multiply { void operator()(int& i) { i *= 2; } } multiplier; etl::for_each_n(std::begin(data1), 5, multiplier); bool are_equal = std::equal(std::begin(data1), std::end(data1), std::begin(data2)); CHECK(are_equal); } //========================================================================= TEST(for_each_n_if) { int data1[] = { 1, 8, 2, 7, 3, 6, 4, 5, 10, 9 }; int data2[] = { 2, 8, 4, 7, 6, 6, 4, 5, 10, 9 }; struct Multiply { void operator()(int& i) { i *= 2; } } multiplier; etl::for_each_n_if(std::begin(data1), 5, multiplier, std::bind2nd(std::less<int>(), 5)); bool are_equal = std::equal(std::begin(data1), std::end(data1), std::begin(data2)); CHECK(are_equal); } //========================================================================= TEST(transform_4_parameter) { int input[] = { 1, 8, 2, 7, 3, 6, 4, 5, 10, 9 }; int output[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; int compare[] = { 2, 16, 4, 14, 6, 0, 0, 0, 0, 0 }; // Double everything and copy to output. etl::transform(std::begin(input), std::end(input), std::begin(output), std::begin(output) + (etl::size(output) / 2), std::bind2nd(std::multiplies<int>(), 2)); bool is_same = std::equal(std::begin(output), std::end(output), std::begin(compare)); CHECK(is_same); std::fill(std::begin(output), std::end(output), 0); etl::transform(std::begin(input), std::begin(input) + (etl::size(input) / 2), std::begin(output), std::end(output), std::bind2nd(std::multiplies<int>(), 2)); is_same = std::equal(std::begin(output), std::end(output), std::begin(compare)); CHECK(is_same); } //========================================================================= TEST(transform_n_random_iterator) { int input[] = { 1, 8, 2, 7, 3, 6, 4, 5, 10, 9 }; int output[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; int compare[] = { 2, 16, 4, 14, 6, 12, 8, 0, 0, 0 }; etl::transform_n(std::begin(input), 7, std::begin(output), std::bind2nd(std::multiplies<int>(), 2)); bool is_same = std::equal(std::begin(output), std::end(output), std::begin(compare)); CHECK(is_same); } //========================================================================= TEST(transform_n_non_random_iterator) { std::list<int> input = { 1, 8, 2, 7, 3, 6, 4, 5, 10, 9 }; int output[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; int compare[] = { 2, 16, 4, 14, 6, 12, 8, 0, 0, 0 }; etl::transform_n(std::begin(input), 7, std::begin(output), std::bind2nd(std::multiplies<int>(), 2)); bool is_same = std::equal(std::begin(output), std::end(output), std::begin(compare)); CHECK(is_same); } //========================================================================= TEST(transform_if) { int input[] = { 1, 8, 2, 7, 3, 6, 4, 5, 10, 9 }; int output[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; int compare[] = { 2, 4, 6, 8, 0, 0, 0, 0, 0, 0 }; // Double everything less than 5 and copy to output. etl::transform_if(std::begin(input), std::end(input), std::begin(output), std::bind2nd(std::multiplies<int>(), 2), std::bind2nd(std::less<int>(), 5)); bool is_same = std::equal(std::begin(output), std::end(output), std::begin(compare)); CHECK(is_same); } //========================================================================= TEST(transform_if_2_input_ranges) { int input1[] = { 1, 8, 2, 7, 3, 6, 4, 5, 10, 9 }; int input2[] = { 8, 7, 6, 5, 4, 10, 9, 3, 2, 1 }; int output[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; int compare[] = { 8, 12, 12, 60, 36, 0, 0, 0, 0, 0 }; // Multiply together everything where input1 is less than input2 and copy to output. etl::transform_if(std::begin(input1), std::end(input1), std::begin(input2), std::begin(output), std::multiplies<int>(), std::less<int>()); bool is_same = std::equal(std::begin(output), std::end(output), std::begin(compare)); CHECK(is_same); } //========================================================================= TEST(transform_n_if) { int input[] = { 1, 8, 2, 7, 3, 6, 4, 5, 10, 9 }; int output[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; int compare[] = { 2, 4, 6, 0, 0, 0, 0, 0, 0, 0 }; // Double everything less than 5 and copy to output. etl::transform_n_if(std::begin(input), 5, std::begin(output), std::bind2nd(std::multiplies<int>(), 2), std::bind2nd(std::less<int>(), 5)); bool is_same = std::equal(std::begin(output), std::end(output), std::begin(compare)); CHECK(is_same); } //========================================================================= TEST(transform_n_if_2_input_ranges) { int input1[] = { 1, 8, 2, 7, 3, 6, 4, 5, 10, 9 }; int input2[] = { 8, 7, 6, 5, 4, 10, 9, 3, 2, 1 }; int output[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; int compare[] = { 8, 12, 12, 0, 0, 0, 0, 0, 0, 0 }; // Multiply together everything where input1 is less than input2 and copy to output. etl::transform_n_if(std::begin(input1), std::begin(input2), 5, std::begin(output), std::multiplies<int>(), std::less<int>()); bool is_same = std::equal(std::begin(output), std::end(output), std::begin(compare)); CHECK(is_same); } //========================================================================= TEST(partition_transform) { int input[] = { 1, 8, 2, 7, 3, 6, 4, 5, 10, 9 }; int output_true[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; int output_false[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; int compare_true[] = { 2, 4, 6, 8, 0, 0, 0, 0, 0, 0 }; int compare_false[] = { -16, -14, -12, -10, -20, -18, 0, 0, 0, 0 }; // Multiply everything less than 5 by 2 and copy to output_true. // Multiply everything not less than 5 by -2 and copy to output_false. etl::partition_transform(std::begin(input), std::end(input), std::begin(output_true), std::begin(output_false), std::bind2nd(std::multiplies<int>(), 2), std::bind2nd(std::multiplies<int>(), -2), std::bind2nd(std::less<int>(), 5)); bool is_same = std::equal(std::begin(output_true), std::end(output_true), std::begin(compare_true)); CHECK(is_same); is_same = std::equal(std::begin(output_false), std::end(output_false), std::begin(compare_false)); CHECK(is_same); } //========================================================================= TEST(partition_transform_2_input_ranges) { int input1[] = { 1, 8, 2, 7, 3, 6, 4, 5, 10, 9 }; int input2[] = { 8, 7, 6, 5, 4, 10, 9, 3, 2, 1 }; int output_true[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; int output_false[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; int compare_true[] = { 8, 12, 12, 60, 36, 0, 0, 0, 0, 0 }; int compare_false[] = { 15, 12, 8, 12, 10, 0, 0, 0, 0, 0 }; // If input1 < input2 multiply else add. etl::partition_transform(std::begin(input1), std::end(input1), std::begin(input2), std::begin(output_true), std::begin(output_false), std::multiplies<int>(), std::plus<int>(), std::less<int>()); bool is_same = std::equal(std::begin(output_true), std::end(output_true), std::begin(compare_true)); CHECK(is_same); is_same = std::equal(std::begin(output_false), std::end(output_false), std::begin(compare_false)); CHECK(is_same); } }; }