Beispiel #1
0
//==============================================================================
void ICACHE_FLASH_ATTR Lcd_Init(void){
  
  
  //P3DIR |= (BIT0 | BIT1 | BIT2 | BIT3);

  easygpio_pinMode(pinSclk,   EASYGPIO_NOPULL, EASYGPIO_OUTPUT);
  easygpio_pinMode(pinSdin,   EASYGPIO_NOPULL, EASYGPIO_OUTPUT);
  easygpio_pinMode(pinSce,   EASYGPIO_NOPULL, EASYGPIO_OUTPUT);
  easygpio_pinMode(pinReset,   EASYGPIO_NOPULL, EASYGPIO_OUTPUT);

  cs(0);// = 0;
  rst(0);// = 0;
  os_delay_us(10000);			// 5mS so says the stop watch(less than 5ms will not work)
  rst(1);// = 1;
  
  // STE2007 controller initialization
  
  spi(CMD, 0x2F);//Включение дисплея
  spi(CMD, 0x38);//Включение термокомпенсации
  spi(CMD, 0xA0);//Инверсия отображения
  spi(CMD, 0xA6);//0xA7 - инверсия отображения
  spi(CMD, 0x9f);//Установка контраста
  spi(CMD, 0xEC);//Установка частоты обновления 80 Гц

  //spi(CMD,0xC8); // mirror Y axis (about X axis)
  //spi(CMD,0xA1);

  spi(CMD, 0xAF);//Разрешение работы LCD
  spi(CMD, 0xA4);//Очистка экрана

  Lcd_Clear(); // clear LCD
  //LINES();
}
dvar_vector model_parameters::cnorm(const double& x, const dvar_vector& mu, const dvar_vector& sd)
{
	dvar_vector rst(sage,nage);
	dvar_vector stx(sage,nage);
	for(int a= sage; a<= nage; a++)
	{
		stx(a) = (x-mu( a ))/sd( a );
		rst(a) = cumd_norm(stx( a ));
	}
	return(rst);
}
Beispiel #3
0
cv::Mat mylib::BinomialKernel(int size, int nDataType)
{
	cv::Mat rst(size,size,nDataType);
	if (nDataType == CV_32F)
	{	
		vector<float> kernel(2,0.5);
		vector<float> temp(2,0.5);
		for (int n=0;n<size-2;n++)
		{
			temp = conv(temp,kernel,0);
		}
		rst = mylib::VecToMat(crossproduct(temp,temp),nDataType);
		return rst;
	}
	else
	{
		vector<double> kernel(2,0.5);
		vector<double> temp(2,0.5);

		for (int n=0;n<size-2;n++)
		{
			temp = conv(temp,kernel,0);
		}
		rst = mylib::VecToMat(crossproduct(temp,temp),nDataType);
	//mylib::DisplayMat(rst,"binomial kernal");	
		return rst;
	}
}
big_data_int operator /(const big_data_int &a, const big_data_int &b) {
    big_data_int result("0");
    big_data_int first(a), second(b);
    
    if (b.is_zero()) {
        cout << "[ERROR]:!!!Divided By Zero!!!" << endl;
        return big_data_int("");
    }

    while (first.gt(second)) {
        string rst("");
        for (int i = 0; i < (first.length() - second.length() - 1); i++) {
            rst += string("0");
        }

        if (rst.length()) {
            rst = string("1") + rst;
            big_data_int step(rst);
            while (first.gt(step * second)) {
                first = first - step * second;
                result = result + step;
            }
        } else {
            break;
        }
    }

    while (first.gt(second)) {
        first = first - second;
        result = result + big_data_int("1");
    }

    return result;
}
Beispiel #5
0
void data_gen::verifica() {
	int i=0;
	int it = ITERACOES;
	
	cout << "\treset\n\nTesting "<< it << " values per key\n";
	rst();
	
	while(!erros){
		
		cout << "\n\n\n\tStarting Test # " << i << "\n\n\n";	
			
		
		
		cout << "\tnew Key \n";
		
		novaChave();
		
		wait(clk.posedge_event());	cout << "\tcrypting\n";		
		cifra(ITERACOES);	
				
		wait(clk.posedge_event());	cout << "\tdecrypting them\n";		
		decifra(ITERACOES);
					
		cout << "\tChecking \n";
		erros= check(ITERACOES);
		
		if(erros) dump(ITERACOES);
		i++;
		cout << "=================================\n";
		wait(clk.posedge_event());	
	}
}
Beispiel #6
0
void xbee::Reset() {
	DigitalOut rst(_reset);
	rst = 0;
	wait_ms(10);
	rst = 1;
	wait_ms(1);
}
Beispiel #7
0
yggr::math::vector3d<ValL, BaseL> operator*(const yggr::math::vector3d<ValL, BaseL>& l, 
												const yggr::math::matrix3d<ValR, Array, BaseR>& r)
{
	typedef yggr::math::vector3d<ValL, BaseL> ret_type;

	ret_type rst(l[0] * r[0][0] + l[1] * r[1][0] + l[2] * r[2][0] + l[3] * r[3][0],
						l[0] * r[0][1] + l[1] * r[1][1] + l[2] * r[2][1] + l[3] * r[3][1],
						l[0] * r[0][2] + l[1] * r[1][2] + l[2] * r[2][2] + l[3] * r[3][2]);
	rst[3] = l[0] * r[0][3] + l[1] * r[1][3] + l[2] * r[2][3] + l[3] * r[3][3];
	return rst;
}
Beispiel #8
0
static int32_t
cecwrite(Chan *c, void *a, int32_t n, int64_t mm)
{
	Proc *up = externup();
	Cmdbuf *cb;
	Cmdtab *cp;

	if(c->qid.path == Qctl){
		cb = parsecmd(a, n);
		if(waserror()){
			free(cb);
			nexterror();
		}
		cp = lookupcmd(cb, ceccmd, nelem(ceccmd));
		switch(cp->index){
		case CMsetname:
			strecpy(name, name+sizeof name-1, cb->f[1]);
			break;
		case CMtraceon:
			tflag = 1;
			break;
		case CMtraceoff:
			tflag = 0;
			break;
		case CMsetpasswd:
			strcpy(passwd, cb->f[1]);
			break;
		case CMcecon:
			cecon(cb->f[1]);
			break;
		case CMcecoff:
			cecoff(cb->f[1]);
			break;
		case CMsetshelf:
			shelf = atoi(cb->f[1]);
			break;
		case CMwrite:
			cecputs((char*)a+6,n-6);
			break;
		case CMreset:
			rst(connidx(atoi(cb->f[1])));
			break;
		default:
			cmderror(cb, "bad control message");
			break;
		}
		free(cb);
		poperror();
		return n;
	}
	error(Egreg);
	return 0;
}
Beispiel #9
0
cv::Mat mylib::FreqComplexFilter(const cv::Mat& src, cv::Mat& kernel, bool conj)
{
	//must make sure the both of src and kernel are complex
	cv::Mat rst(src.size(),src.type());
	if (src.channels()!= kernel.channels())
		cout<<"error, the src and kerenl are not with same channels\n";
	else if (src.channels() == 2 || src.channels() ==6)
		cv::mulSpectrums(kernel,src,rst,CV_DXT_ROWS,conj);
	else
		cout<<"error, the input are not complex image\n";
	return rst;
}
Beispiel #10
0
uint8_t SR165Class::read() {
  rst();
  uint8_t res = 0;
  uint8_t i = 0;
  for (i = 0; i < 8; i++) {
    res <<= 1;
    res |= IS_BIT_SET8(SR165_DATA_PIN, SR165_OUT);
    clk();
  }

  return res;
}
Beispiel #11
0
uint16_t SR165Class::read16() {
  rst();

  uint16_t res = 0;
  uint8_t i = 0;
  for (i = 0; i < 16; i++) {
    res <<= 1;
    res |= IS_BIT_SET8(SR165_PIN_PORT, SR165_OUT);
    clk();
  }

  return res;
}
Beispiel #12
0
	mat44 mat44::look_at(const vec3& eye, const vec3& look, const vec3& up)
	{
		vec3 forward = (look - eye).normalize();
		vec3 real_up = (up - forward * dot(forward, up.normalized())).normalize();
		vec3 right = cross(real_up, forward).normalize();
		mat44 rst(
			vec4(right, -dot(eye, right)),
			vec4(real_up, -dot(eye, real_up)),
			vec4(forward, -dot(eye, forward)),
			vec4(0, 0, 0, 1)
			);

		return rst;
	}
 vector<string> letterCombinations(string digits) {
     vector<string> rst(1);
     for(int i=0; i<digits.size(); ++i) {
         int n = rst.size();
         string word = tables[digits[i]-'0'];
         for(int j=0; j<word.size(); ++j)
         for(int k=0; k<n; ++k) {
             rst.push_back(rst[k]);
             rst.back().push_back(word[j]);
         }
         rst.erase(rst.begin(), rst.begin()+n);
     }
     return rst;
 }
Beispiel #14
0
/*void mylib::CombineImage(const vector<string>& infilenames, string& outfilename, int step)
{
	int count = infilenames.size();
	vector<Tensor<uchar,3>> t(count);
	int maxheight = 0;
	int totalwidth = 0;
	for (int i=0; i< count; i++)
	{
		t[i].Load(infilenames[i]);
		if (t[i].size().height > maxheight)
			maxheight = t[i].size().height;
		totalwidth+= t[i].size().width;
	}
	Tensor<uchar,3> r(Size3(maxheight,totalwidth + (count-1)*step,1));
	for (int i=0; i< count; i++)
		r.SetBlock(Point3i(0,i*step+i*t[i].size().width,0),t[i]);
	r.SaveBlock(outfilename);
	r.Display(3000,1);

}
*/
cv::Mat mylib::readMatFromTxt(string filename, int H, int W)
{
  CV_DbgAssert(H!=0&&W!=0);
  cv::Mat rst(H,W,CV_64F);
  ifstream fp(filename,ios::in);
  double temp;
  int count=0;
  while(count<H*W)
  {
    fp>>temp;
    rst.at<double>(count/W,count%W)=temp;
    count++;
  }
  return rst;
}
int minPathSum(vector<vector<int>>& grid) {
	auto rows = grid.size(), cols = grid[0].size();
	vector<vector<int>> rst(rows + 1, vector<int>(cols + 1, INT_MAX));
	for (int i = 1; i <= rows; ++i)
	{
		for (int j = 1; j <= cols; ++j)
		{
			if (i == 1 && j == 1)
				rst[1][1] = grid[0][0];
			else
				rst[i][j] = min(rst[i - 1][j], rst[i][j - 1]) + grid[i - 1][j - 1];
		}
	}
	return rst[rows][cols];
}
Beispiel #16
0
	mat44 mat44::perspective(float fov, float aspect, float near, float far)
	{
		float near_top = tanf(fov * 0.5f);
		float near_right = near_top * aspect;

		float z_range = near - far;
		mat44 rst(
			1.0f / near_right, 0, 0, 0,
			0, 1.0f / near_top, 0, 0,
			0, 0, -far / z_range, far * near / z_range,
			0, 0, 1, 0);


		return rst;
	}
Beispiel #17
0
RVector3 MeshEntity::grad(const RVector3 & xyz, const RVector & u) const {

    RVector3 rst(shape_->rst(xyz));

    RMatrix MdNdL;
    MdNdL.push_back(dNdL(rst, 0));
    MdNdL.push_back(dNdL(rst, 1));
    MdNdL.push_back(dNdL(rst, 2));

    RVector up(u(this->ids()));
    RVector3 gr;
    gr[0] = sum(up * MdNdL.transMult(shape_->invJacobian().col(0)));
    gr[1] = sum(up * MdNdL.transMult(shape_->invJacobian().col(1)));
    gr[2] = sum(up * MdNdL.transMult(shape_->invJacobian().col(2)));
    return gr;
}
Beispiel #18
0
//With O(n) time complexity and constant extra space require
vector<int> productExceptSelf(vector<int>& nums)
{
    int product = 1;
    vector<int> rst(nums.size(), 1);
    size_t i = 0;
    std::for_each(nums.begin(), nums.end(), [&](int elem){
        rst[i] *= product;
        product *= elem;
        i++;
    });
    product = 1;
    std::for_each(nums.rbegin(), nums.rend(), [&](int elem){
        i--;
        rst[i] *= product;
        product *= elem;
    });
    return rst;
}
Beispiel #19
0
BOOL CDlgManualTask::DoSearch()
{

	m_vSearchData.clear();

	CString strSql;
	strSql = TEXT("select * from T_IncomingTaskPool ");
	CString strOpt;
	if (CollectSearchOpt(strOpt))
	{
		strSql += strOpt;
	}
	
	strSql += TEXT(" order by SubmitDateTime");
	CTxADORecordSet rst(DBKEY_EMB);
	if (!rst.ExecuteSQL(strSql))
	{
		CFWriteLog(0,"search sql failed! %s", strSql);
		AfxMessageBox(TEXT("查询失败,请查看日志"));
	}

	while(!rst.IsEOF())
	{
		ST_INPOOLTASKDATA tmpData;
		tmpData.strPgmCode = rst.GetVal(TEXT("PGMCode")).GetAsString();
		tmpData.strClipName = rst.GetVal(TEXT("PGMName")).GetAsString();
		tmpData.nClipType = ExternalClipType2Local(rst.GetVal(TEXT("nClipType")).GetAsString());
		tmpData.nClipSrctype = ExternalClipSourceId2Local(rst.GetVal(TEXT("SourceID")).GetAsString());
		tmpData.strChID =  ExternalChId2LocalChid(rst.GetVal(TEXT("ChnID")).GetAsString());
		tmpData.nDuration = rst.GetVal(TEXT("nDuration")).GetAsInt64();
		tmpData.nPriority = rst.GetVal(TEXT("nPRI")).GetAsInt();
		tmpData.tmSubmit = rst.GetVal(TEXT("SubmitDateTime")).GetAsInt64();
		tmpData.tmPlayTime = rst.GetVal(TEXT("PlayDateTime")).GetAsInt64();
		tmpData.strTaskXml = rst.GetVal(TEXT("SourceStrXML")).GetAsString();
		tmpData.nVersion = rst.GetVal(TEXT("Version")).GetAsInt();
		tmpData.strTaskId = rst.GetVal(TEXT("TaskID")).GetAsString();
		tmpData.nErrcode = rst.GetVal(TEXT("nErrcode")).GetAsInt();

		m_vSearchData.push_back(tmpData);
		rst.MoveNext();
	}
	RefreshTaskList();
	return TRUE;	
}
yggr::geometry::geo_polygon<Position, Alloc, Base>
	operator*(const yggr::geometry::geo_polygon<Position, Alloc, Base>& l, const Matrix& r)
{
	typedef yggr::geometry::geo_polygon<Position, Alloc, Base> polygon_type;
	typedef Matrix matrix_type;
	typedef typename polygon_type::base_type base_type;
	typedef typename base_type::iterator iter_type;
	typedef typename polygon_type::pos_type pos_type;
	BOOST_MPL_ASSERT((boost::mpl::equal_to<boost::mpl::size_t<pos_type::E_ARRAY_LENGTH>,
											boost::mpl::size_t<matrix_type::E_MAX_RANK> >));

	base_type rst(l);

	for(iter_type i = rst.begin(), isize = rst.end(); i != isize; ++i)
	{
		(*i) *= r;
	}
	return polygon_type(rst);
}
Beispiel #21
0
//////////// 感知哈希算法 ////////////
//pHash算法
string Filter::PHashValue(Mat &src) {
	Mat clone = src.clone();
	Mat img, dst;
	if (clone.channels() == 3) {
		cvtColor(clone, clone, CV_BGR2GRAY);
		img = Mat_<double>(clone);
	} else {
		img = Mat_<double>(clone);
	}     
	 
    /* 第一步,缩放尺寸,可以为Size(32,32)或Size(8,8),也可以更高,主要是为了提高计算效率*/
	resize(img, img, Size(32,32));

    // 顺时针旋转图像90度
    transpose(img, dst);  
    flip(dst, img, 1);
        
    /* 第二步,离散余弦变换,DCT系数求取*/
	dct(img, dst);	

    /* 第三步,求取DCT系数均值(左上角8*8区块的DCT系数,频率最低的部分,即图像信息的大部分)*/
    double dIdex[64];
    double mean = 0.0;
    int k = 0;
	for (int i = 0; i < 8; ++i) {
		for (int j = 0; j < 8; ++j) {
			dIdex[k] = dst.at<double>(i, j);
			mean += dst.at<double>(i, j)/64;
			++k;
		}
	}
        
    /* 第四步,计算哈希值。*/
    string rst(64,' ');
	for (int i = 0; i < 64; ++i) {
		if (dIdex[i] >= mean) {
			rst[i] = '1';
		} else {
			rst[i] = '0';
		}
	}
	return rst;
}
vector<int> btwEncode(const vector<int> &src) {
    // O(n*lgn*lgn). probably faster than O(n*lgn) version
    int len = src.size();
    vector<int> sa(len), rank(len);
    for(int i=0; i<len; ++i) rank[sa[i] = i] = src[i];
    for(int ll=1, cnt=0; cnt!=len; ll<<=1, cnt=rank[sa.back()]+1) {
        auto cmp = [&](const int l, const int r) {
            if( rank[l]!=rank[r] ) return rank[l] < rank[r];
            return rank[(l+ll)%len] < rank[(r+ll)%len];
        };
        sort(sa.begin(), sa.end(), cmp);
        vector<int> tmp = rank;
        tmp[sa[0]] = 0;
        for(int i=1; i<sa.size(); ++i)
            tmp[sa[i]] = tmp[sa[i-1]] + cmp(sa[i-1], sa[i]);
        rank = tmp;
    }
    vector<int> rst(len);
    for(int i=0; i<len; ++i) rst[i] = src[(sa[i]+len-1)%len];
    return rst;
}
Beispiel #23
0
bool Redis::Call(const s64 id, const char* proc, const s32 keyCount, const OArgs& args, const std::function<bool(IKernel *, const IRedisResult *)>& f) {
	if (s_contexts.empty())
		return false;

	Ping(s_kernel, id);

	if (!LoadScript(s_kernel, id, proc))
		return false;

	CommandBuff buf;
	buf.size = 0;

	const char * scriptId = s_contexts[id % s_contexts.size()].scriptIds[proc].GetString();
	s32 len = (s32)strlen(scriptId);
	SafeSprintf(buf.data + buf.size, sizeof(buf.data) - buf.size, "*%d\r\n$7\r\nEVALSHA\r\n$%d\r\n%s\r\n", args.Count() + 2, len, scriptId);
	buf.size += (s32)strlen(buf.data + buf.size);

	Append(buf, args);

	s_contexts[id % s_contexts.size()].ctx->obuf = buf.data;
	redisReply * reply = NULL;
	redisGetReply(s_contexts[id % s_contexts.size()].ctx, (void**)&reply);
	if (NULL == reply) {
		return false;
	}

	if (REDIS_REPLY_ERROR == reply->type || REDIS_REPLY_NIL == reply->type) {
		freeReplyObject(reply);
		return false;
	}

	bool ret = true;
	if (f) {
		RedisCallResult rst(reply);
		ret = f(s_kernel, &rst);
	}

	freeReplyObject(reply);
	return ret;
}
Beispiel #24
0
void testDataPath(){
    
    bus clk ("P"); // Clock pulse
    bus rst ("0");
    bus a_bus("1010"); // 10
    bus b_bus("0011"); // 3
    bus en_quoCount("1");
    bus r_bus, q_bus;
    bus greater, equal, lesser;
    
    DividerDatapath * DP = new DividerDatapath(clk, rst,
                                               a_bus, b_bus,
                                               r_bus, q_bus,
                                               en_quoCount, greater, equal, lesser);
    
    DP->eval();
    DP->printValues();
    
    DP->eval();
    DP->printValues();
        
}
Beispiel #25
0
void testController(){
    
    /* Initally values */
    bus clk ("P"); // Clock pulse
    bus rst ("0");
    bus go("P");
    bus gtr("1");
    bus eql("0");
    bus les("0");
    bus en_quo, ready;
    
    DividerController * DC = new DividerController(clk, rst, go, gtr, eql, les, en_quo, ready);
    
    std::cout << "The inital values:\n";
    DC->printValues();
    
    DC->eval();
    std::cout << "\nAfter evaluation:\n";
    DC->printValues();
    
    DC->eval();
    std::cout << "\nAfter evaluation:\n";
    DC->printValues();
    
    /* Next values */
    clk = "P";
    rst = "0";
    go = "0";
    gtr = "0";
    eql = "1";
    les = "0";
    
    DC->eval();
    std::cout << "\nAfter evaluation:\n";
    DC->printValues();
    
}
Beispiel #26
0
int main(int argc, char** argv)
{
	static_cast<void>(testReadingInput); // suppress unused warning

 	// read benchmark
	try {
		auto opts = parseOpts(argc, argv);
		auto problem = readRoutingInstFromPath(opts.inputBenchmark);
		RoutingSolver rst(problem);

		rst.useNetDecomposition = opts.useNetDecomposition;
		rst.useNetOrdering = opts.useNetOrdering;
		rst.timeLimit = std::chrono::minutes(13);
		rst.emitSVG = opts.emitSVG;
		rst.costFunction = opts.costFunction;

		if (opts.useNetOrdering)
			rst.reorderNets(problem.nets);
		else
			printf("Not using ordering\n");

		// run actual routing
		rst.solveRouting();

		if(opts.useNetOrdering || opts.useNetDecomposition)
			rst.rrr();

		// write the result
		writeToPath(opts.outputFile, problem);
		return 0;
	}
	catch (std::exception& ex) {
		printf("Error: %s\n", ex.what());
		return 1;
	}
}
Beispiel #27
0
bool Redis::Exec(const s64 id, const char* command, const OArgs& args, const std::function<bool(IKernel *, const IRedisResult *)>& f) {
	if (s_contexts.empty())
		return false;

	Ping(s_kernel, id);

	CommandBuff buf;
	buf.size = 0;

	SafeSprintf(buf.data + buf.size, sizeof(buf.data) - buf.size, "*%d\r\n$%d\r\n%s\r\n", args.Count() + 1, strlen(command), command);
	buf.size += (s32)strlen(buf.data + buf.size);

	Append(buf, args);

	s_contexts[id % s_contexts.size()].ctx->obuf = buf.data;
	redisReply * reply = NULL;
	redisGetReply(s_contexts[id % s_contexts.size()].ctx, (void**)&reply);
	if (NULL == reply) {
		return false;
	}

	if (REDIS_REPLY_ERROR == reply->type || REDIS_REPLY_NIL == reply->type) {
		freeReplyObject(reply);
		return false;
	}

	bool ret = true;
	if (f) {
		RedisCallResult rst(reply);
		ret = f(s_kernel, &rst);
	}

	freeReplyObject(reply);
	return ret;

}
Beispiel #28
0
void MainWindow::OpenFile(QString FilePath, bool addToRecentList)
{
    if(m_isFileReloading) return;
    m_isFileReloading = true;
    BoolReseter rst(&m_isFileReloading); Q_UNUSED(rst);

    if(!m_isAppInited) return;
    qApp->setActiveWindow(this);

    //Check if data configs are valid
    if( configs.check() )
    {
        LogCritical(QString("Error! *.INI configs not loaded"));
        QMessageBox::warning(this,
                             tr("Configuration is loaded with errors"),
                             tr("Cannot open file:\n"
                                "Configuration package loaded with errors.")
                                        .arg(ConfStatus::configPath));
        //Show configuration status window
        on_actionCurConfig_triggered();
        return;
    }

    QMdiSubWindow *newSubWin = NULL;
    QMdiSubWindow *existing = findOpenedFileWin(FilePath);
            if (existing) {
                ui->centralWidget->setActiveSubWindow(existing);
                return;
            }

    QFile file(FilePath);
    if (!file.open(QIODevice::ReadOnly))
    {
        QMessageBox::critical(this, tr("File open error"),
        tr("Can't open the file: %1").arg(file.errorString()), QMessageBox::Ok);
        return;
    }

    QFileInfo in_1(FilePath);

    GlobalSettings::openPath = in_1.absoluteDir().absolutePath();

    if((in_1.suffix().toLower() == "lvl")||(in_1.suffix().toLower() == "lvlx"))
    {
        LevelData FileData;

        LogDebug("> parsing level file format");
        if( !FileFormats::OpenLevelFile(FilePath, FileData) )
        {
            formatErrorMsgBox(FilePath, FileData.meta.ERROR_info, FileData.meta.ERROR_linenum, FileData.meta.ERROR_linedata);
            return;
        }
        LogDebug("File was read!");
        FileData.meta.filename   = util::getBaseFilename(in_1.fileName());
        FileData.meta.path       = in_1.absoluteDir().absolutePath();
        FileData.playmusic  = GlobalSettings::autoPlayMusic;
        file.close();

        LogDebug("Creating of sub-window");
        LevelEdit *child = createLvlChild(&newSubWin);
        if ( child->loadFile(FilePath, FileData, configs, GlobalSettings::LvlOpts) )
        {
            child->show();
            updateMenus(newSubWin, true);
            child->updateGeometry();
            child->ResetPosition();
            dock_LvlItemBox->setLvlItemBoxes(false, false);
            statusBar()->showMessage(tr("Level file loaded"), 2000);
            SetCurrentLevelSection(0);
            dock_LvlWarpProps->init();
            dock_LvlLayers->setLayersBox();

            if(GlobalSettings::autoPlayMusic) ui->actionPlayMusic->setChecked(true);
            on_actionPlayMusic_triggered(ui->actionPlayMusic->isChecked());

        } else {
            LogDebug(">>File loading aborted");
            //child->show();
            child->LvlData.meta.modified = false;
            newSubWin->close();
            LogDebug(">>Windows closed");
        }
    }
    else
    if((in_1.suffix().toLower() == "wld")||(in_1.suffix().toLower() == "wldx"))
    {
        WorldData FileData;
        if( !FileFormats::OpenWorldFile( FilePath, FileData ) )
        {
            formatErrorMsgBox(FilePath, FileData.meta.ERROR_info, FileData.meta.ERROR_linenum, FileData.meta.ERROR_linedata);
            return;
        }
        file.close();

        WorldEdit *child = createWldChild(&newSubWin);
        if ( child->loadFile(FilePath, FileData, configs, GlobalSettings::LvlOpts) ) {
            child->show();
            updateMenus(newSubWin, true);
            child->updateGeometry();
            child->ResetPosition();
            dock_WldItemBox->setWldItemBoxes(false, false);
            dock_WldSettingsBox->setCurrentWorldSettings();
            if(FileData.HubStyledWorld)
            {
                dock_WldSettingsBox->setVisible(true);
                dock_WldSettingsBox->raise();
            }
            statusBar()->showMessage(tr("World map file loaded"), 2000);
        } else {
            LogDebug(">>File loading aborted");
            child->close();
            newSubWin->close();
            LogDebug(">>Windows closed");
        }
    }
    else
    if(in_1.suffix().toLower() == "txt")
    {
        NPCConfigFile FileData;
        if( !FileFormats::ReadNpcTXTFileF(FilePath, FileData) )
        {
            QMessageBox::critical(this, QObject::tr("File open error"), tr("Can't read the file"), QMessageBox::Ok);
            return;
        }

        if( !FileData.unknownLines.isEmpty() )
        {
            QMessageBox::warning(this,
                                 QObject::tr("Unknown values are presented"),
                                 QObject::tr("Your file have an unknown values which will be removed\n"
                                             " when you will save file") +
                                 QString("\n====================================\n"
                                         "%1").arg(FileData.unknownLines),
                                 QMessageBox::Ok);
        }

        NpcEdit *child = createNPCChild(&newSubWin);
        if (child->loadFile(FilePath, FileData)) {
            statusBar()->showMessage(tr("NPC Config loaded"), 2000);
            child->show();
            updateMenus(newSubWin, true);
        } else {
            child->close();
            newSubWin->close();
        }
    }
    else
    if(in_1.suffix().toLower() == "sav")
    {
        GamesaveData FileData;

        QString statistics;
        if(!FileFormats::ReadSMBX64SavFileF( FilePath, FileData))
        {
            formatErrorMsgBox( FilePath, FileData.meta.ERROR_info, FileData.meta.ERROR_linenum, FileData.meta.ERROR_linedata );
            return;
        }

        statistics+= QString("SMBX Game Save file version %1\n\n").arg(FileData.meta.RecentFormatVersion);
        if(FileData.gameCompleted)
            statistics+= "      ====This game was completed====\n\n";
        statistics+= QString("Lives: %1,   Coins:%2,   ").arg(FileData.lives).arg(FileData.coins);
        statistics+= QString("Total stars: %1,   Gotten stars: %2\n")
                .arg(FileData.totalStars)
                .arg(FileData.gottenStars.size());
        statistics+= QString("Position X=%1, Y=%2\n")
                .arg(FileData.worldPosX)
                .arg(FileData.worldPosY);

        if(FileData.musicID>0)
        {
            long item=configs.getMusWldI(FileData.musicID);
            if(item>=0)
            {
                statistics+= QString("Current music: %1\n\n").arg(configs.main_music_wld[item].name);
            }
        }

        statistics += "\n===========Players:============\n";
        for(int i=0; i<FileData.characterStates.size();i++)
        {
            if(i<configs.main_characters.size())
                statistics += QString("%1:\n").arg(configs.main_characters[i].name);
            else
                statistics += QString("<unknown character>:\n");
            statistics += QString("Health: %1,    ").arg(FileData.characterStates[i].health);
            statistics += QString("Power-UP: %1,    ").arg(FileData.characterStates[i].state);
            switch(FileData.characterStates[i].mountType)
            {
            case 0:
                break;
            case 1:
                statistics += QString("Mounted vehicle: Shoe - ");
                switch(FileData.characterStates[i].mountID)
                {
                case 1:
                    statistics += QString("Kuribo's (green)");break;
                case 2:
                    statistics += QString("Podoboo's (red)");break;
                case 3:
                    statistics += QString("Lakitu's (blue)");break;
                default:
                    statistics += QString("of God Power :D");break;
                }
                break;
            case 3:
                statistics += QString("Mounted vehicle: Yoshi");break;
            default:
                statistics += QString("Mounted vehicle: <unknown>");break;
            }

            if( (FileData.characterStates[i].itemID>0) && configs.main_npc.contains(FileData.characterStates[i].itemID) )
            {
                statistics += QString("%2Has item: %1")
                                .arg(configs.main_npc[FileData.characterStates[i].itemID].setup.name)
                                .arg(FileData.characterStates[i].mountType > 0 ? ",    ":"");
            }

            if(i<FileData.characterStates.size()-1)
                statistics += "\n----------------------------\n";
        }
        statistics += "\n=========================\n";

        if( !FileData.meta.ReadFileValid )
            return;

        QMessageBox::information(this,
                                 tr("Game save statistics"),
                                 statistics,
                                 QMessageBox::Ok);
    }
    else
    {
        QMessageBox::warning(this,
                             tr("Bad file"),
                             tr("This file have unknown extension"),
                             QMessageBox::Ok);
        return;
    }

    // Add to recent fileList
    if(addToRecentList){
        AddToRecentFiles(FilePath);
        SyncRecentFiles();
    }
}
Beispiel #29
0
//Reload opened file data
void MainWindow::on_actionReload_triggered()
{
    if(_is_reloading) return;
    _is_reloading=true;
    BoolReseter rst(&_is_reloading);
    Q_UNUSED(rst);

    QString filePath;
    QRect wnGeom;

    if (activeChildWindow()==1)
    {
        LevelData FileData;
        filePath = activeLvlEditWin()->curFile;

        if(activeLvlEditWin()->isUntitled)
        {
                    QMessageBox::warning(this, tr("File not saved"),
                    tr("File doesn't saved on disk."), QMessageBox::Ok);
                        return;
        }

        if (!QFileInfo(filePath).exists() ) {
            QMessageBox::critical(this, tr("File open error"),
            tr("Can't open the file.\nFile not exist."), QMessageBox::Ok);
                return;
        }

        if(activeLvlEditWin()->LvlData.modified)
        {
            QMessageBox::StandardButton ret = QMessageBox::question(this, tr("Reload file and custom stuff"),
            tr("Do you want to save before reload stuff?"), QMessageBox::Yes|QMessageBox::No|QMessageBox::Cancel);
            if((ret==QMessageBox::Cancel)||(ret==0))
                return;
            else
              if(ret==QMessageBox::Yes)
                save();
        }

        //Open level file
        FileData = FileFormats::OpenLevelFile(filePath);

        if( !FileData.ReadFileValid ){
            statusBar()->showMessage(tr("Reloading error"), 2000);
            return;}

        FileData.playmusic = GlobalSettings::autoPlayMusic;
        activeLvlEditWin()->LvlData.modified = false;

        QFile file(filePath+".meta");
        if(QFileInfo(filePath+".meta").exists())
        {
            if (file.open(QIODevice::ReadOnly))
            {
                QString metaRaw;
                QTextStream meta(&file);
                meta.setCodec("UTF-8");
                metaRaw = meta.readAll();
                if(FileData.metaData.script)
                {
                    delete FileData.metaData.script;
                    FileData.metaData.script = NULL;
                }
                FileData.metaData = FileFormats::ReadNonSMBX64MetaData(metaRaw, filePath+".meta");
            }
            else
            {
                QMessageBox::critical(this, tr("File open error"),
                tr("Can't open the file."), QMessageBox::Ok);
            }
        }

        //Remember last section ID and positions!
        int lastSection=0;
        QMap<int, QPair<long, long> > sectionPoss;
        lastSection = activeLvlEditWin()->LvlData.CurSection;
        SetCurrentLevelSection(lastSection);//Need to remember position of current section
        for(int i=0; i<activeLvlEditWin()->LvlData.sections.size(); i++)
        {
            LevelSection sct = activeLvlEditWin()->LvlData.sections[i];
            sectionPoss[sct.id]=QPair<long, long >(sct.PositionX, sct.PositionY);
        }

        activeLvlEditWin()->close();//Close old widget without closing of sub-window

        //Get pointer to current sub-window
        QMdiSubWindow *window = ui->centralWidget->activeSubWindow();

        //Get geometry of current subwindow
        wnGeom = ui->centralWidget->activeSubWindow()->geometry();
        //delete window->widget();
        LevelEdit *chLvlWin = new LevelEdit(window);
        connect(chLvlWin, SIGNAL(forceReload()), this, SLOT(on_actionReload_triggered()));
        window->setWidget(chLvlWin);
        GraphicsWorkspace* gr = static_cast<GraphicsWorkspace *>(chLvlWin->getGraphicsView());
        connect(gr, SIGNAL(zoomValueChanged(QString)), zoom, SLOT(setText(QString)));

        //ui->centralWidget->activeSubWindow()->close();
        LevelEdit *child = chLvlWin;//createLvlChild();
        LvlMusPlay::setNoMusic();
        setMusic(false);
        if ((bool) (child->loadFile(filePath, FileData, configs, GlobalSettings::LvlOpts)))
        {
            child->show();
            ui->centralWidget->activeSubWindow()->setGeometry(wnGeom);
            child->updateGeometry();
            child->ResetPosition();
            statusBar()->showMessage(tr("Level file reloaded"), 2000);
            LvlMusPlay::musicForceReset=true; //reset musics
            updateMenus(true);

            child->setFocus();
            //Restore saved section positions
            for(int i=0; i<child->LvlData.sections.size(); i++)
            {
                if(sectionPoss.contains(child->LvlData.sections[i].id))
                {
                    child->LvlData.sections[i].PositionX=sectionPoss[child->LvlData.sections[i].id].first;
                    child->LvlData.sections[i].PositionY=sectionPoss[child->LvlData.sections[i].id].second;
                }
            }

            SetCurrentLevelSection(lastSection);

            if(GlobalSettings::autoPlayMusic) ui->actionPlayMusic->setChecked(true);
        } else {
                WriteToLog(QtDebugMsg, ">>File loading aborted");
            child->show();
                WriteToLog(QtDebugMsg, ">>Window showed");
            if(activeChildWindow()==1) activeLvlEditWin()->LvlData.modified = false;
                WriteToLog(QtDebugMsg, ">>Option set");
            ui->centralWidget->activeSubWindow()->close();
                WriteToLog(QtDebugMsg, ">>Windows closed");
        }
    }
    else
    if (activeChildWindow()==2)
    {
        filePath = activeNpcEditWin()->curFile;
        QFile fileIn(filePath);

        if(activeNpcEditWin()->isUntitled)
        {
                    QMessageBox::warning(this, tr("File not saved"),
                    tr("File doesn't saved on disk."), QMessageBox::Ok);
                        return;
        }

        if(activeNpcEditWin()->isModyfied)
        {
            QMessageBox::StandardButton ret = QMessageBox::question(this, tr("Reload file and custom stuff"),
            tr("Do you want to save before reload stuff?"), QMessageBox::Yes|QMessageBox::No|QMessageBox::Cancel);
            if((ret==QMessageBox::Cancel)||(ret==0))
                return;
            else
              if(ret==QMessageBox::Yes)
                save();
        }

        if (!fileIn.open(QIODevice::ReadOnly)) {
        QMessageBox::critical(this, tr("File open error"),
        tr("Can't open the file."), QMessageBox::Ok);
            return;
        }

        NPCConfigFile FileData = FileFormats::ReadNpcTXTFile(fileIn);
        if( !FileData.ReadFileValid ) return;
        wnGeom = ui->centralWidget->activeSubWindow()->geometry();
        activeNpcEditWin()->isModyfied = false;
        activeNpcEditWin()->close();
        //NpcEdit *child = createNPCChild();

        QMdiSubWindow *npcWindow = ui->centralWidget->activeSubWindow();
        NpcEdit *child = new NpcEdit(&configs, npcWindow);
        npcWindow->setWidget(child);

        if (child->loadFile(filePath, FileData)) {
            statusBar()->showMessage(tr("NPC Config reloaded"), 2000);
            child->show();
            ui->centralWidget->activeSubWindow()->setGeometry(wnGeom);
            updateMenus(true);
        } else {
            child->close();
            npcWindow->close();
        }
    }
    else
    if (activeChildWindow()==3)
    {
        WorldData FileData;
        filePath = activeWldEditWin()->curFile;

        if(activeWldEditWin()->isUntitled)
        {
                    QMessageBox::warning(this, tr("File not saved"),
                    tr("File doesn't saved on disk."), QMessageBox::Ok);
                        return;
        }

        if (!QFileInfo(filePath).exists() ) {
            QMessageBox::critical(this, tr("File open error"),
            tr("Can't open the file.\nFile not exist."), QMessageBox::Ok);
                return;
        }

        if(activeWldEditWin()->WldData.modified){
            QMessageBox::StandardButton ret = QMessageBox::question(this, tr("Reload file and custom stuff"),
            tr("Do you want to save before reload stuff?"), QMessageBox::Yes|QMessageBox::No|QMessageBox::Cancel);
            if((ret==QMessageBox::Cancel)||(ret==0))
                return;
            else
              if(ret==QMessageBox::Yes)
                save();
        }

        FileData = FileFormats::OpenWorldFile(filePath);

        if( !FileData.ReadFileValid ){
            statusBar()->showMessage(tr("Reloading error"), 2000);
            return;}

        FileData.filename = QFileInfo(filePath).baseName();
        FileData.path = QFileInfo(filePath).absoluteDir().absolutePath();
        FileData.playmusic = GlobalSettings::autoPlayMusic;
        activeWldEditWin()->WldData.modified = false;

        QFile file(filePath+".meta");
        if(QFileInfo(filePath+".meta").exists())
        {
            if (file.open(QIODevice::ReadOnly))
            {
                QString metaRaw;
                QTextStream meta(&file);
                meta.setCodec("UTF-8");
                metaRaw = meta.readAll();
                FileData.metaData = FileFormats::ReadNonSMBX64MetaData(metaRaw, filePath+".meta");
            }
            else
            {
                QMessageBox::critical(this, tr("File open error"),
                tr("Can't open the file."), QMessageBox::Ok);
            }
        }

        wnGeom = ui->centralWidget->activeSubWindow()->geometry();
        QMdiSubWindow *worldWindow = ui->centralWidget->activeSubWindow();
        long posX = activeWldEditWin()->scene->_viewPort->horizontalScrollBar()->value();
        long posY = activeWldEditWin()->scene->_viewPort->verticalScrollBar()->value();

        activeWldEditWin()->close();

        WorldEdit *child = new WorldEdit(worldWindow);
        connect(child, SIGNAL(forceReload()), this, SLOT(on_actionReload_triggered()));
        worldWindow->setWidget(child);
        GraphicsWorkspace* gr = static_cast<GraphicsWorkspace *>(child->getGraphicsView());

        connect(gr, SIGNAL(zoomValueChanged(QString)), zoom, SLOT(setText(QString)));
        if ( (bool)(child->loadFile(filePath, FileData, configs, GlobalSettings::LvlOpts)) ) {
            child->show();
            ui->centralWidget->activeSubWindow()->setGeometry(wnGeom);
            child->updateGeometry();
            child->ResetPosition();
            updateMenus(true);
            dock_WldSettingsBox->setCurrentWorldSettings();
            if(FileData.HubStyledWorld)
            {
                dock_WldSettingsBox->setVisible(true);
                dock_WldSettingsBox->raise();
            }

            child->scene->_viewPort->horizontalScrollBar()->setValue(posX);
            child->scene->_viewPort->verticalScrollBar()->setValue(posY);

            statusBar()->showMessage(tr("World map file loaded"), 2000);
        } else {
            WriteToLog(QtDebugMsg, ">>File loading aborted");
            child->show();
            WriteToLog(QtDebugMsg, ">>Window showed");
            if(activeChildWindow()==3) activeWldEditWin()->WldData.modified = false;
            WriteToLog(QtDebugMsg, ">>Option set");
            ui->centralWidget->activeSubWindow()->close();
            WriteToLog(QtDebugMsg, ">>Windows closed");
        }

    }

    dock_LvlItemBox->clearFilter();
}
Beispiel #30
0
dms SkyObject::riseSetTimeLST( const KStarsDateTime &dt, const GeoLocation *geo, bool riseT ) {
	KStarsDateTime rst( dt.date(), riseSetTimeUT( dt, geo, riseT) );
	return geo->GSTtoLST( rst.gst() );
}