Exemple #1
0
Joint * SkeletonData::readJoint(JsonTree joint, Joint * parent) {
	
	Joint * j = new Joint();
	if(parent != nullptr){
		parent->addChild(j);
	}
	std::vector<NodeChild *> children;
	std::vector<Voxel *> voxels;

	j->id = joint.getChild( "id" ).getValue<int>();
	app::console() << "id: " << j->id << std::endl;
	
	// Transform: Object
	JsonTree transform = joint.getChild("transform");

	JsonTree pos = transform.getChild("pos");
	app::console() << " jt_pos: x = " << pos.getChild("x").getValue<float>() << " y = " << pos.getChild("y").getValue<float>() << " pos: z = " << pos.getChild("z").getValue<float>() << std::endl;
	j->setPos(glm::vec3(pos.getChild("x").getValue<float>(), pos.getChild("y").getValue<float>(), pos.getChild("z").getValue<float>()), false);
	app::console() << " pos: x = " << j->getPos().x << " y = " << j->getPos().y << " pos: z = " << j->getPos().z << std::endl;
	
	JsonTree orientation = transform.getChild("orientation");
	j->transform->orientation = glm::quat(orientation.getChild("w").getValue<float>(), orientation.getChild("x").getValue<float>(), orientation.getChild("y").getValue<float>(), orientation.getChild("z").getValue<float>());
	app::console() << " orientation: x = " << j->transform->orientation.x << " y = " << j->transform->orientation.y << " z = " << j->transform->orientation.z << " w = " << j->transform->orientation.w << std::endl;
	
	JsonTree scale = transform.getChild("scaleVector");
	j->transform->scaleVector = glm::vec3(scale.getChild("x").getValue<float>(), scale.getChild("y").getValue<float>(), scale.getChild("z").getValue<float>());
	app::console() << " scale: x = " << j->transform->scaleVector.x << " y = " << j->transform->scaleVector.y << " z = " << j->transform->scaleVector.z << std::endl;
	
	// Voxels: Array
	JsonTree voxelsJson = joint.getChild("voxels");
	unsigned int voxel_index = 0;
	for (JsonTree::ConstIter voxel = voxelsJson.begin(); voxel != voxelsJson.end(); ++voxel) {
		// Apparently, getKey DOESN't return an index if there is no key?
		//JsonTree cJson = childrenJson.getChild(child->getKey());
		JsonTree vJson = voxelsJson.getChild(voxel_index);
		readVoxel(vJson, j);
		voxel_index++;
	}

	// Animations: Objects
	readAnimations(joint.getChild("animations"), j);
	
	// Children: Array
	JsonTree childrenJson = joint.getChild("children");
	unsigned int children_index = 0;
	for( JsonTree::ConstIter child = childrenJson.begin(); child != childrenJson.end(); ++child ) {
		// Apparently, getKey DOESN't return an index if there is no key?
		//JsonTree cJson = childrenJson.getChild(child->getKey());
		JsonTree cJson = childrenJson.getChild(children_index);
		Joint * c = readJoint(cJson, j);
		children.push_back(c);
		children_index++;
	}
	j->children = children;

	return j;
}
Exemple #2
0
void JsonTestApp::setup()
{

    JsonTree value( "key", "value" );
    console() << value << endl;

    JsonTree doc( loadResource( RES_JSON ) );
    JsonTree musicLibrary( doc.getChild( "library" ) );

    JsonTree owner = doc.getChild( "library.owner" );
    for( JsonTree::ConstIter item = owner.begin(); item != owner.end(); ++item ) {
        console() << "Node: " << item->getKey() << " Value: " << item->getValue<string>() << endl;
    }

    JsonTree tracks = doc.getChild( "library.albums[0].tracks" );
    for( JsonTree::ConstIter track = tracks.begin(); track != tracks.end(); ++track ) {
        console() << track->getChild( "id" ).getValue<int>() << endl;
    }

    for( JsonTree::ConstIter trackIt = tracks.begin(); trackIt != tracks.end(); ++trackIt ) {
        JsonTree track = * trackIt;
        console() << track["id"].getValue<int>() << endl;
    }

    JsonTree firstAlbum = doc.getChild( "library.albums[0]" );
    for( JsonTree::Iter child = firstAlbum.begin(); child != firstAlbum.end(); ++child ) {
        if ( !child->hasChildren() ) {
            console() << "Key: " << child->getKey() << "  Value: " << child->getValue<string>() << endl;
        }
    }

    console() << doc.getChild( "library.owner" );
    JsonTree &ownerCity = doc.getChild( "library.owner.city" );
    string s = ownerCity.getPath();
    console() << "Path: " << ownerCity.getPath() << "\n  Value: " << ownerCity.getValue<string>() << std::endl;
    console() << doc;

    JsonTree firstTrackCopy = doc.getChild( "library.albums[0].tracks[0].title" );
    firstTrackCopy = JsonTree( firstTrackCopy.getKey(), string( "Replacement name" ) );
    console() << doc.getChild( "library.albums[0].tracks[0]['title']" ) << std::endl;

    JsonTree &firstTrackRef = doc.getChild( "library.albums[0].tracks[2].title" );
    console() << firstTrackRef.getPath() << std::endl;
    firstTrackRef = JsonTree( firstTrackRef.getKey(), string( "Replacement name" ) );
    console() << doc.getChild( "library.albums[0].tracks[0].title" ) << std::endl;

    try {
        JsonTree invalid( "%%%%%%%%" );
    } catch ( JsonTree::ExcJsonParserError ex ) {
        console() << ex.what() << std::endl;
    }

}
Exemple #3
0
std::vector<Joint *> SkeletonData::LoadSkeleton(std::string filePath) {
	//Not sure about this error catching setup
	std::vector<Joint*> joints;

	if( PathFileExistsA(filePath.c_str()) == TRUE)  { 
		try{
			JsonTree doc = JsonTree(loadFile(filePath));

			JsonTree jointsJson = doc.getChild( "joints" );
			Joint * parent = nullptr;
			unsigned int i = 0;
			for( JsonTree::ConstIter joint = jointsJson.begin(); joint != jointsJson.end(); ++joint ) {
				// Apparently, getKey DOESN't return an index if there is no key? (Even though it says it will in the json.h header...)
				//JsonTree jJson = jointsJson.getChild(joint->getKey());
				JsonTree jJson = jointsJson.getChild(i);
				Joint * j = readJoint(jJson);
				joints.push_back(j);
				i++;
			}
		}catch (std::exception ex) {
			//throw ex;
			throw std::exception("Invalid File Format. File may be out of date.");
		}
	}else{
		throw std::exception("File does not exist!");
	}
	return joints;
}
Exemple #4
0
JsonTree::JsonTree( const JsonTree &jsonTree )
	: mParent( NULL )
{
	mKey = jsonTree.mKey;
	mNodeType = jsonTree.mNodeType;
	mValue = jsonTree.mValue;
	mValueType = jsonTree.mValueType;

	for( ConstIter childIt = jsonTree.begin(); childIt != jsonTree.end(); ++childIt ) {
		pushBack( *childIt );
    }
}
Exemple #5
0
// Function the background thread lives in
void TweetStream::serviceTweets()
{
	ThreadSetup threadSetup;
	std::string nextQueryString = "?q=" + Url::encode( mSearchPhrase );
	JsonTree searchResults;
	JsonTree::ConstIter resultIt = searchResults.end();

	// This function loops until the app quits. Each iteration a pulls out the next result from the Twitter API query.
	// When it reaches the last result of the current query it issues a new one, based on the "refresh_url" property
	// of the current query.
	// The loop doesn't spin (max out the processor) because ConcurrentCircularBuffer.pushFront() non-busy-waits for a new
	// slot in the circular buffer to become available.
	while( ! mCanceled ) {
		if( resultIt == searchResults.end() ) { 		// are we at the end of the results of this JSON query?
			// issue a new query
			try {
				JsonTree queryResult = queryTwitter( nextQueryString );
				// the next query will be the "refresh_url" of this one.
				nextQueryString = queryResult["refresh_url"].getValue();
				searchResults = queryResult.getChild( "results" );
				resultIt = searchResults.begin();
			}
			catch( ci::Exception &exc ) {
				// our API query failed: put up a "tweet" with our error
				CI_LOG_W( "exception caught parsing query: " << exc.what() );
				mBuffer.pushFront( Tweet( "Twitter API query failed", "sadness", SurfaceRef() ) );
				ci::sleep( 2000 ); // try again in 2 seconds
			}
		}
		if( resultIt != searchResults.end() ) {
			try {
				// get the URL and load the image for this profile
				Url profileImgUrl = (*resultIt)["profile_image_url"].getValue<Url>();
				SurfaceRef userIcon = Surface::create( loadImage( loadUrl( profileImgUrl ) ) );
				// pull out the text of the tweet and replace any XML-style escapes
				string text = replaceEscapes( (*resultIt)["text"].getValue() );
				string userName = (*resultIt)["from_user"].getValue();
				mBuffer.pushFront( Tweet( text, userName, userIcon ) );
			}
			catch( ci::Exception &exc ) {
				CI_LOG_W( "exception caught parsing search results: " << exc.what() );
			}
			++resultIt;
		}
	}
}
void OculusSocketServerApp::setup()
{
    mServerPort = 9005;

    string configPath = getAppPath().string() + "/config.json";
    
    if(fs::exists(configPath)) {
        JsonTree::ParseOptions options;
        options.ignoreErrors(true);

        try{
            JsonTree config = JsonTree( loadFile( configPath ));
            
            for( JsonTree::ConstIter cIt = config.begin(); cIt != config.end(); ++cIt )
            {
                if( "port" == (*cIt).getKey()){
                    mServerPort = std::stoi((*cIt).getValue());
                    console() << "Port found: " << mServerPort << std::endl;
                }
            }
            
        } catch(JsonTree::Exception ex){
            console() << "Unable to parse config file." << std::endl;
        }
    } else {
        console() << "No config file found." << std::endl;
    }

    mOculusConnected = false;
    mSocketConnected = false;
    
    mServer.addConnectCallback( &OculusSocketServerApp::onConnect, this );
	mServer.addDisconnectCallback( &OculusSocketServerApp::onDisconnect, this );
   
    mServer.listen(mServerPort);
    mOculusVR = Oculus::create();
    
    mBackgroundTexture = gl::Texture( loadImage( loadResource( RES_BACKGROUND_TEX ) ) );
}
void FaceController::loadFaces()
{
	/*

	JsonTree faces( doc.getChild( "faces" ) );
	
	facesStoreVector.clear();

	for( JsonTree::ConstIter face = faces.begin(); face != faces.end(); ++face ) {
		
		FaceObject newFace;	
		vector<Vec2f> points;

		string name =  face->getChild( "texname" ).getValue<string>();
		gl::Texture tex;
		try{
			tex = loadImage(getAppPath() /FACE_STORAGE_FOLDER/name);
		}
		catch(...)
		{
			continue;
		}



		JsonTree datas =JsonTree( face->getChild( "data" ));
		for( JsonTree::ConstIter data = datas.begin(); data != datas.end(); ++data ) {
			float x =  data->getChild( "x" ).getValue<float>();
			float y =  data->getChild( "y" ).getValue<float>();

			points.push_back(Vec2f(x,y));
		}
		newFace.setPoints(points);

		
		newFace.setTexName(name);

		
		newFace.setTexture(tex);
		
		facesStoreVector.push_back(newFace);
	}	*/


	facesStoreVector.clear();

	string path = getAppPath().string() + JSON_STORAGE_FOLDER;
	fs::path p(path);

	

	for (fs::directory_iterator it(p); it != fs::directory_iterator(); ++it)
	{
		if (fs::is_regular_file(*it))
		{
			JsonTree doc;
			try{
				 doc = JsonTree(loadFile(getAppPath() / JSON_STORAGE_FOLDER / it->path().filename().string()));
			}
			catch(...)
			{
				return;
			}

			JsonTree faces( doc.getChild( "faces" ) );

			for( JsonTree::ConstIter face = faces.begin(); face != faces.end(); ++face )
			{		
				FaceObject newFace;	
				vector<Vec2f> points;

				string name =  face->getChild( "texname" ).getValue<string>();
				gl::Texture tex;
				try{
					tex = loadImage(getAppPath() /FACE_STORAGE_FOLDER/name);
				}
				catch(...)
				{
					continue;
				}

				JsonTree datas =JsonTree( face->getChild( "data" ));
				for( JsonTree::ConstIter data = datas.begin(); data != datas.end(); ++data )
				{
					float x =  data->getChild( "x" ).getValue<float>();
					float y =  data->getChild( "y" ).getValue<float>();

					points.push_back(Vec2f(x,y));
				}

				newFace.setPoints(points);		
				newFace.setTexName(name);

				newFace.setTexture(tex);		
				facesStoreVector.push_back(newFace);
			}
		}
	}

}
Exemple #8
0
// Function the background thread lives in
void InstagramStream::serviceGrams(string url)
{
	ThreadSetup threadSetup;
	std::string nextQueryString = url;
	
	JsonTree searchResults;
	JsonTree::ConstIter resultIt = searchResults.end();
	
	// This function loops until the app quits. Each iteration a pulls out the next result from the Twitter API query.
	// When it reaches the last result of the current query it issues a new one, based on the "refresh_url" property
	// of the current query.
	// The loop doesn't spin (max out the processor) because ConcurrentCircularBuffer.pushFront() non-busy-waits for a new
	// slot in the circular buffer to become available.
	JsonTree queryResult;
	while( ! mCanceled ) {
		if( resultIt == searchResults.end() ) {			// are we at the end of the results of this JSON query?
			// issue a new query
			try {
				queryResult = queryInstagram( nextQueryString );
				// the next query will be the "refresh_url" of this one.
				
				try {
					nextQueryString = queryResult["pagination"].getChild("next_url").getValue();
				}
				catch(...) {
					
				}
				
				searchResults = queryResult.getChild("data");
				resultIt = searchResults.begin();
				mIsConnected = true;
			}
			catch( ... ) {
				
				console() << "something broke" << endl;
				console() << queryResult << endl;
				console() << nextQueryString << endl;
				
				// check if it's a 420 error
				if(queryResult.getChild("meta").getChild("code").getValue() == "420"){
					console() << "420 error" << endl;
					mIsConnected = false;
				}
				
				ci::sleep( 1000 ); // try again in 1 second
			}
		}
		if( resultIt != searchResults.end() ) {
			try {
				
				string userName = (*resultIt)["user"]["username"].getValue();
				
				// get the URL and load this instagram image
				string imageUrl = (*resultIt)["images"]["standard_resolution"]["url"].getValue();
				Surface image( loadImage( loadUrl( imageUrl ) ) );
				// string imageUrl = "http://distilleryimage5.s3.amazonaws.com/1dd174cca14611e1af7612313813f8e8_7.jpg"; // Test image
				mBuffer.pushFront( Instagram( userName, imageUrl, image ) );
			}
			catch( ... ) { // just ignore any errors
				console() << "ERRORS FOUND" << endl;
			}
			++resultIt;
		}
	}
}
Exemple #9
0
void JsonTestApp::mouseDown( MouseEvent event )
{

    JsonTree doc;
    JsonTree library = JsonTree::makeObject( "library" );
    JsonTree album = JsonTree::makeArray( "album" );

    album.pushBack( JsonTree( "musician", string( "Sufjan Stevens" ) ) );
    album.pushBack( JsonTree( "year", string( "2004" ) ) );
    album.pushBack( JsonTree( "title", string( "Seven Swans" ) ) );

    JsonTree tracks = JsonTree::makeArray( "tracks" );

    for ( int32_t i = 0; i < 6; i ++ ) {

        JsonTree track;
        track.pushBack( JsonTree( "id", i + 1 ) );

        JsonTree title;
        switch ( i ) {
        case 0:
            title = JsonTree( "title", "All the Trees of the Field Will Clap Their Hands" );
            break;
        case 1:
            title = JsonTree( "title", "The Dress Looks Nice on You" );
            break;
        case 2:
            title = JsonTree( "title", "In the Dev Hole's Territory" );
            break;
        case 3:
            title = JsonTree( "title", "To Be a Clone With You" );
            break;
        case 4:
            title = JsonTree( "title", "To Be Removed" );
            break;
        case 5:
            title = JsonTree( "title", "To Be Removed" );
            break;
        }

        track.pushBack( title );
        tracks.pushBack( track );

    }

    for ( JsonTree::Iter trackIt = tracks.begin(); trackIt != tracks.end(); ++trackIt ) {
        if ( trackIt->getChild( "id" ).getValue<int>() == 3 ) {
            JsonTree track;
            track.pushBack( JsonTree( "id", 3 ) );
            track.pushBack( JsonTree( "title", "In the Devil's Territory" ) );
            tracks.replaceChild( trackIt, track );
        }
    }

    JsonTree track;
    track.pushBack( JsonTree( "id", 4 ) );
    track.pushBack( JsonTree( "title", "To Be Alone With You" ) );
    tracks.replaceChild( 3, track );

    tracks.removeChild( 4 );

    for ( JsonTree::Iter trackIt = tracks.begin(); trackIt != tracks.end(); ) {
        if ( trackIt->getChild( "id" ).getValue<int>() == 6 ) {
            trackIt = tracks.removeChild( trackIt );
        } else {
            ++trackIt;
        }
    }

    album.pushBack( tracks );
    library.pushBack( album );
    doc.pushBack( library );

    console() << doc;

    doc.write( writeFile( getDocumentsDirectory() + "testoutput.json" ), false );

}
void ReymentaServerApp::fileDrop(FileDropEvent event)
{
	int index;
	string ext = "";
	// use the last of the dropped files
	const fs::path &mPath = event.getFile(event.getNumFiles() - 1);
	string mFile = mPath.string();
	int dotIndex = mFile.find_last_of(".");
	int slashIndex = mFile.find_last_of("\\");

	if (dotIndex != std::string::npos && dotIndex > slashIndex) ext = mFile.substr(mFile.find_last_of(".") + 1);
	index = (int)(event.getX() / (margin + mParameterBag->mPreviewFboWidth + inBetween));// +1;
	//mBatchass->log(mFile + " dropped, currentSelectedIndex:" + toString(mParameterBag->currentSelectedIndex) + " x: " + toString(event.getX()) + " PreviewFboWidth: " + toString(mParameterBag->mPreviewFboWidth));

	if (ext == "wav" || ext == "mp3")
	{
		//mAudio->loadWaveFile(mFile);
	}
	else if (ext == "png" || ext == "jpg")
	{
		if (index < 1) index = 1;
		if (index > 3) index = 3;
		//mTextures->loadImageFile(mParameterBag->currentSelectedIndex, mFile);
		mBatchass->getTexturesRef()->loadImageFile(index, mFile);
	}
	else if (ext == "glsl")
	{
		if (index < 4) index = 4;
		int rtn = mBatchass->getShadersRef()->loadPixelFragmentShaderAtIndex(mFile, index);
		if (rtn > -1 && rtn < mBatchass->getShadersRef()->getCount())
		{
			mParameterBag->controlValues[22] = 1.0f;
			// TODO  send content via websockets
			/*fs::path fr = mFile;
			string name = "unknown";
			if (mFile.find_last_of("\\") != std::string::npos) name = mFile.substr(mFile.find_last_of("\\") + 1);
			if (fs::exists(fr))
			{

			std::string fs = loadString(loadFile(mFile));
			if (mParameterBag->mOSCEnabled) mOSC->sendOSCStringMessage("/fs", 0, fs, name);
			}*/
			// save thumb
			//timeline().apply(&mTimer, 1.0f, 1.0f).finishFn([&]{ saveThumb(); });
		}
	}
	else if (ext == "mov" || ext == "mp4")
	{
		/*
		if (index < 1) index = 1;
		if (index > 3) index = 3;
		mBatchass->getTexturesRef()->loadMovieFile(index, mFile);*/
	}
	else if (ext == "fs")
	{
		//mShaders->incrementPreviewIndex();
		mBatchass->getShadersRef()->loadFragmentShader(mPath);
	}
	else if (ext == "xml")
	{
		mBatchass->getWarpsRef()->loadWarps(mFile);
	}
	else if (ext == "patchjson")
	{
		// try loading patch
		try
		{
			JsonTree patchjson;
			try
			{
				patchjson = JsonTree(loadFile(mFile));
				mParameterBag->mCurrentFilePath = mFile;
			}
			catch (cinder::JsonTree::Exception exception)
			{
				CI_LOG_V("patchjsonparser exception " + mFile + ": " + exception.what());

			}
			//Assets
			int i = 1; // 0 is audio
			JsonTree jsons = patchjson.getChild("assets");
			for (JsonTree::ConstIter jsonElement = jsons.begin(); jsonElement != jsons.end(); ++jsonElement)
			{
				string jsonFileName = jsonElement->getChild("filename").getValue<string>();
				int channel = jsonElement->getChild("channel").getValue<int>();
				if (channel < mBatchass->getTexturesRef()->getTextureCount())
				{
					CI_LOG_V("asset filename: " + jsonFileName);
					mBatchass->getTexturesRef()->setTexture(channel, jsonFileName);
				}
				i++;
			}

		}
		catch (...)
		{
			CI_LOG_V("patchjson parsing error: " + mFile);
		}
	}
	else if (ext == "txt")
	{
		// try loading shader parts
		if (mBatchass->getShadersRef()->loadTextFile(mFile))
		{

		}
	}
	else if (ext == "")
	{
		// try loading image sequence from dir
		if (index < 1) index = 1;
		if (index > 3) index = 3;
		mBatchass->getTexturesRef()->createFromDir(mFile + "/", index);
		// or create thumbs from shaders
		mBatchass->getShadersRef()->createThumbsFromDir(mFile + "/");
	}
}