예제 #1
0
파일: JSON.cpp 프로젝트: kolyden/mirror
NAMESPACE_UPP

Value ParseJSON(CParser& p)
{
	p.UnicodeEscape();
	if(p.IsDouble())
		return p.ReadDouble();
	if(p.IsString()) {
		bool dt = p.IsChar2('\"', '\\');
		String s = p.ReadString();
		if(dt) {
			CParser p(s);
			if(p.Char('/') && p.Id("Date") && p.Char('(') && p.IsInt()) {
				int64 n = p.ReadInt64();
				if(!IsNull(n))
					return Time(1970, 1, 1) + n / 1000;
			}
		}
		return s;
	}
	if(p.Id("null"))
		return Null;
	if(p.Id("true"))
		return true;
	if(p.Id("false"))
		return false;
	if(p.Char('{')) {
		ValueMap m;
		while(!p.Char('}')) {
			String key = p.ReadString();
			p.PassChar(':');
			m.Add(key, ParseJSON(p));
			if(p.Char('}')) // Stray ',' at the end of list is allowed...
				break;
			p.PassChar(',');
		}
		return m;
	}
	if(p.Char('[')) {
		ValueArray va;
		while(!p.Char(']')) {
			va.Add(ParseJSON(p));
			if(p.Char(']')) // Stray ',' at the end of list is allowed...
				break;
			p.PassChar(',');
		}
		return va;		
	}
	p.ThrowError("Unrecognized JSON element");
	return Null;
}
예제 #2
0
JSON *ParseJSONFromFile(const char *filename){
    FILE *pFile;
    long lSize;
    char * buffer;
    size_t result;

    pFile = fopen( filename, "rb" );
    if (pFile==NULL) { fputs("File error", stderr); exit(1);}

    // obtain file size:
    fseek( pFile, 0, SEEK_END);
    lSize = ftell(pFile);
    rewind(pFile);

    // allocate memory to contain the whole file:
    buffer = (char*) malloc (sizeof(char)*lSize);
    if (buffer == NULL) {fputs("Memory error", stderr); exit(2);}

    //copy the file into the buffer
    result = fread(buffer, 1, lSize, pFile);
    if (result != lSize) {fputs("Reading error", stderr); exit(2);}

    /* the whole file is now loaded in the memory buffer */

    /* parse */
    JSON *obj = ParseJSON(buffer);

    fclose(pFile);
    free(buffer);
    return obj;
}
wchar_t *BabylonWindow::FindTranslatedText(wchar_t* html)
{
	if (!ParseJSON(html, L"\"translatedText\":\"", NULL))
		return NULL;
	for (wchar_t *p = html; p = wcsstr(p, L"\",\""); memcpy(p, L"  \n", 3*sizeof(wchar_t)));
	UnescapeHtml(html, 0);
	return html;
}
예제 #4
0
파일: JSON.cpp 프로젝트: kolyden/mirror
Value ParseJSON(const char *s)
{
	try {
		CParser p(s);
		return ParseJSON(p);
	}
	catch(CParser::Error e) {
		return ErrorValue(e);
	}
}
예제 #5
0
int main(int argc, char **argv) {
	if (argc > 1) {
		if (FILE *f = fopen(argv[1], "rb")) {
			fseek(f, 0, SEEK_END);
			size_t size = ftell(f);
			fseek(f, 0, SEEK_SET);
			if (char *buffer = (char*)malloc(size)) {
				fread(buffer, size, 1, f);
				fclose(f);
				ParseJSON(strref(buffer, size), json_test_print, nullptr);
				free(buffer);
			} else
				fclose(f);
		}
	} else {
		if (!ParseJSON(strref(json_tests, sizeof(json_tests)), json_test_print, nullptr))
			return 1;
	}

	return 0;
}
예제 #6
0
파일: Main.cpp 프로젝트: efpies/KG
//---------------------------------------------------------------------------
void __fastcall TMainForm::OpenClick(TObject *Sender)
{
	if (OpenJSON->Execute()) {
		if (FileExists(OpenJSON->FileName, true)) {
			points.clear();
			edges.clear();
			objects.clear();
			angleX = 0.6154797142073631;
			angleY = -M_PI/4.0;
			ParseJSON(OpenJSON->FileName);
		}
	}
}
예제 #7
0
파일: JSON.cpp 프로젝트: pedia/raidget
NAMESPACE_UPP

Value ParseJSON(CParser& p)
{
	p.UnicodeEscape();
	if(p.IsNumber())
		return p.ReadDouble();
	if(p.IsString())
		return p.ReadString();
	if(p.Id("null"))
		return Null;
	if(p.Id("true"))
		return true;
	if(p.Id("false"))
		return false;
	if(p.Char('{')) {
		ValueMap m;
		if(!p.IsChar('}'))
			do {
				String key = p.ReadString();
				p.PassChar(':');
				m.Add(key, ParseJSON(p));
			}
			while(p.Char(','));
		p.PassChar('}');
		return m;
	}
	if(p.Char('[')) {
		ValueArray va;
		if(!p.IsChar(']'))
			do
				va.Add(ParseJSON(p));
			while(p.Char(','));
		p.PassChar(']');
		return va;		
	}
	p.ThrowError("Unrecognized JSON element");
	return Null;
}
bool USpriterImporterFactory::FactoryCanImport(const FString& Filename)
{
	FString FileContent;
	if (FFileHelper::LoadFileToString(/*out*/ FileContent, *Filename))
	{
		TSharedPtr<FJsonObject> DescriptorObject = ParseJSON(FileContent, FString(), /*bSilent=*/ true);
		if (DescriptorObject.IsValid())
		{
			FSpriterSCON GlobalInfo;
			GlobalInfo.ParseFromJSON(DescriptorObject, Filename, /*bSilent=*/ true, /*bPreparseOnly=*/ true);

			return GlobalInfo.IsValid();
		}
	}

	return false;
}
예제 #9
0
파일: JSON.c 프로젝트: JoshOY/C-JSON-joshoy
JSON *ParseJSONFromFile(const char* file_name)
{
    FILE  *fp     = NULL;
    char  *data   = NULL;
    JSON  *rtn    = NULL;
    long   l_size = 0;
    char  *buffer = NULL;
    size_t result = 0;

    fp = fopen(file_name, "r");
    if (fp == NULL) {
        printf("Exception: Cannot open file \"%s\".\n", file_name);
        exit(1);
    }

    /*Get the size of the file*/
    fseek(fp, 0, SEEK_END);
    l_size = ftell(fp);
    rewind(fp);

    buffer = (char *)malloc(sizeof(char) * l_size);
    if (buffer == NULL) {
        printf("Exception: Memory error.\n");
        exit(2);
    }

    result = fread(buffer, 1, l_size, fp);
    if (result != l_size) {
        printf("Exception: Reading error.\n");
        exit(3);
    }

    char *tmp = DeleteSpaces(buffer);
    free(buffer);
    buffer = tmp;

    rtn = ParseJSON(buffer);

    free(buffer);
    fclose(fp);
    return rtn;
}
예제 #10
0
CScriptValRooted ScriptInterface::ReadJSONFile(const VfsPath& path)
{
	if (!VfsFileExists(path))
	{
		LOGERROR(L"File '%ls' does not exist", path.string().c_str());
		return CScriptValRooted();
	}

	CVFSFile file;

	PSRETURN ret = file.Load(g_VFS, path);

	if (ret != PSRETURN_OK)
	{
		LOGERROR(L"Failed to load file '%ls': %hs", path.string().c_str(), GetErrorString(ret));
		return CScriptValRooted();
	}

	std::string content(file.DecodeUTF8()); // assume it's UTF-8

	return ParseJSON(content);
}
예제 #11
0
void ScriptInterface::ReadJSONFile(const VfsPath& path, JS::MutableHandleValue out)
{
	if (!VfsFileExists(path))
	{
		LOGERROR("File '%s' does not exist", path.string8());
		return;
	}

	CVFSFile file;

	PSRETURN ret = file.Load(g_VFS, path);

	if (ret != PSRETURN_OK)
	{
		LOGERROR("Failed to load file '%s': %s", path.string8(), GetErrorString(ret));
		return;
	}

	std::string content(file.DecodeUTF8()); // assume it's UTF-8

	if (!ParseJSON(content, out))
		LOGERROR("Failed to parse '%s'", path.string8());
}
예제 #12
0
wxString RaceAnalyzerComm::GetLogfile(){
	wxMutexLocker lock(_commMutex);
	wxString logfileData;
	try{
		CComm *serialPort = GetSerialPort();
		if (NULL==serialPort) throw CommException(CommException::OPEN_PORT_FAILED);
		wxString rsp = SendCommand(serialPort, "{\"getLogfile\":0}",1000);
		try{
			if (rsp.Len() > 0 ){
				Object root = ParseJSON(rsp);
				const String &val = root["logfile"];
				logfileData = val.Value();
				}
			}
			catch (const Exception& e){
				ERROR(FMT("could not parse logfile response: %s",rsp));
			}
	}
	catch(CommException &e){
		CloseSerialPort();
		throw e;
	}
	return logfileData;
}
예제 #13
0
int main()
{
	printf("\n********************************\n");
	printf("box_conf_change : start\n");
	printf("********************************\n");
		
	char url[1024] = {0};
	ghttp_request *req;
	char http_body[1024] = {0};

	sqlite3 *db = NULL;
    sqlite3_stmt *ppstmt = NULL;
    int rc = 0;
    char sql_cmd[100] = {0};
	char *errorMsg = NULL;
	const char *box_id = NULL;
    char box_id_tmp[10] = {0};
	int db_cnt = 0;

	while(db_cnt < 20)
	{
		rc = sqlite3_open(box_db, &db);
		if(rc == SQLITE_ERROR)
            printf("open box.db failed");

        ppstmt = NULL;
        memset(sql_cmd, 0, sizeof(sql_cmd));
        strcpy(sql_cmd, "select box_id from box_info");
        sqlite3_prepare(db, sql_cmd, -1, &ppstmt, 0);
        rc = sqlite3_step(ppstmt);
        if(rc == SQLITE_ROW)
        {
            box_id = sqlite3_column_text(ppstmt, 0);
            strcpy(box_id_tmp, box_id);
            printf("box_id : %s\n", box_id_tmp);
			sqlite3_finalize(ppstmt);
			sqlite3_close(db);
			break;
		}
		else
		{
			printf("select box_id failure!\n");
			sqlite3_finalize(ppstmt);
			sqlite3_close(db);
			sleep(1);
			db_cnt++;
		}
	}

	printf("----------------send http request-------------\n");
	sprintf(url, "http://www.ailvgobox.com/box_manage_2/box_conf_change_1.php?box_id=%s", box_id_tmp);
	printf("request_url : %s\n",url);

	req = ghttp_request_new();
	strcpy(http_body, send_http_request(req, url));
    ghttp_request_destroy(req);
	
	printf("http_body : %s\n", http_body);
    printf("length of http_body : %d\n", strlen(http_body));
        
	cJSON *node;

    if(strlen(http_body) <= 2)
		printf("HTTP failure!\n");
    else
    {
        printf("HTTP success!\n");

        if(strcmp(http_body, "null") == 0)
            printf("http_body : null, no box_conf_change!\n");
        else
        {
	        node = cJSON_Parse(http_body);
            ParseJSON(node);
        }
    }
	
	printf("box_conf_chanage : complete!\n");

	if(change_flag == 1)
	{
		printf("reboot due to conf change!\n");
		sleep(5);
		system("reboot");
	}
}
예제 #14
0
파일: Client.cpp 프로젝트: koz4k/soccer
RpcGet RpcRequest::Execute()
{
	if(!shouldExecute)
		return RpcGet();
	shouldExecute = false;
	String request;
	if(json) {
		ContentType("application/json");
		static Atomic id;
		Json json;
		json("jsonrpc", "2.0")
		    ("method", method);
		if(data.out.GetCount()) {
			JsonArray a;
			for(int i = 0; i < data.out.GetCount(); i++) {
				const Value& v = data.out[i];
				if(v.Is<RawJsonText>())
					a.CatRaw(v.To<RawJsonText>().json);
				else
					a << JsonRpcData(v);
			}
			json("params", a);
		}
		else
		if(data.out_map.GetCount()) {
			Json m;
			for(int i = 0; i < data.out_map.GetCount(); i++) {
				const Value& v = data.out_map.GetValue(i);
				String key = (String)data.out_map.GetKey(i);
				if(v.Is<RawJsonText>())
					m.CatRaw(key, v.To<RawJsonText>().json);
				else
					m(key, JsonRpcData(v));
			}
			json("params", m);
		}
		json("id", id);
		AtomicInc(id);
		request = ~json;
	}
	else {
		ContentType("text/xml");
		request = XmlHeader();
		request << XmlTag("methodCall")(XmlTag("methodName")(method) + FormatXmlRpcParams(data.out));
	}
	if(sLogRpcCalls) {
		if(sLogRpcCallsCompress)
			RLOG("=== XmlRpc call request:\n" << CompressLog(request));
		else
			RLOG("=== XmlRpc call request:\n" << request);
	}
	String response;
	New();
	if(shorted)
		response = RpcExecuteShorted(request);
	else
		response = Post(request).Execute();
	if(sLogRpcCalls) {
		if(sLogRpcCallsCompress)
			RLOG("=== XmlRpc call response:\n" << CompressLog(response));
		else
			RLOG("=== XmlRpc call response:\n" << response);
	}
	RpcGet h;
	if(IsNull(response)) {
		faultCode = RPC_CLIENT_HTTP_ERROR;
		faultString = GetErrorDesc();
		error = "Http request failed: " + faultString;
		LLOG(error);
		h.v = ErrorValue(error);
		return h;
	}
	if(json) {
		try {
			Value r = ParseJSON(response);
			if(IsValueMap(r)) {
				ValueMap m = r;
				Value result = m["result"];
				if(!result.IsVoid()) {
					data.in.Clear();
					data.in.Add(result);
					data.ii = 0;
					h.v = result;
					return h;
				}
				Value e = m["error"];
				if(IsValueMap(e)) {
					Value c = e["code"];
					Value m = e["message"];
					if(IsNumber(c) && IsString(m)) {
						faultCode = e["code"];
						faultString = e["message"];
						error.Clear();
						error << "Failed '" << faultString << "' (" << faultCode << ')';
						LLOG(s);
						h.v = ErrorValue(error);
						return h;
					}
				}
			}
			String s;
			faultString = "Invalid response";
			faultCode = RPC_CLIENT_RESPONSE_ERROR;
			error = faultString;
			LLOG(error);
			h.v = ErrorValue(error);
			return h;
		}
		catch(CParser::Error e) {
			String s;
			faultString = e;
			faultCode = RPC_CLIENT_JSON_ERROR;
			error.Clear();
			error << "JSON Error: " << faultString;
			LLOG(error);
			h.v = ErrorValue(error);
			return h;
		}
	}
	else {
		XmlParser p(response);
		try {
			p.ReadPI();
			p.PassTag("methodResponse");
			if(p.Tag("fault")) {
				Value m = ParseXmlRpcValue(p);
				if(IsValueMap(m)) {
					ValueMap mm = m;
					faultString = mm["faultString"];
					faultCode = mm["faultCode"];
					error.Clear();
					error << "Failed '" << faultString << "' (" << faultCode << ')';
					LLOG(s);
					h.v = ErrorValue(error);
					return h;
				}
			}
			else {
				data.in = ParseXmlRpcParams(p);
				data.ii = 0;
				p.PassEnd();
			}
		}
		catch(XmlError e) {
			String s;
			faultString = e;
			faultCode = RPC_CLIENT_XML_ERROR;
			error.Clear();
			error << "XML Error: " << faultString;
			LLOG(error << ": " << p.GetPtr());
			h.v = ErrorValue(error);
			return h;
		}
		h.v = data.in.GetCount() ? data.in[0] : Null;
		return h;
	}
}
bool FPaperJsonSpriteSheetImporter::ImportFromArchive(FArchive* Archive, const FString& NameForErrors)
{
	TSharedPtr<FJsonObject> SpriteDescriptorObject = ParseJSON(Archive, NameForErrors);
	return SpriteDescriptorObject.IsValid() &&
		Import(SpriteDescriptorObject, NameForErrors);
}
bool FPaperJsonSpriteSheetImporter::ImportFromString(const FString& FileContents, const FString& NameForErrors)
{
	TSharedPtr<FJsonObject> SpriteDescriptorObject = ParseJSON(FileContents, NameForErrors);
	return SpriteDescriptorObject.IsValid() &&
		Import(SpriteDescriptorObject, NameForErrors);
}
UObject* USpriterImporterFactory::FactoryCreateText(UClass* InClass, UObject* InParent, FName InName, EObjectFlags Flags, UObject* Context, const TCHAR* Type, const TCHAR*& Buffer, const TCHAR* BufferEnd, FFeedbackContext* Warn)
{
	Flags |= RF_Transactional;

	FEditorDelegates::OnAssetPreImport.Broadcast(this, InClass, InParent, InName, Type);

 	FAssetToolsModule& AssetToolsModule = FModuleManager::GetModuleChecked<FAssetToolsModule>("AssetTools");
 
 	bool bLoadedSuccessfully = true;
 
 	const FString CurrentFilename = UFactory::GetCurrentFilename();
 	FString CurrentSourcePath;
 	FString FilenameNoExtension;
 	FString UnusedExtension;
 	FPaths::Split(CurrentFilename, CurrentSourcePath, FilenameNoExtension, UnusedExtension);
 
 	const FString LongPackagePath = FPackageName::GetLongPackagePath(InParent->GetOutermost()->GetPathName());
 
 	const FString NameForErrors(InName.ToString());
 	const FString FileContent(BufferEnd - Buffer, Buffer);
 	TSharedPtr<FJsonObject> DescriptorObject = ParseJSON(FileContent, NameForErrors);

	UPaperSpriterImportData* Result = nullptr;
 
	// Parse the file 
	FSpriterSCON DataModel;
	if (DescriptorObject.IsValid())
	{
		DataModel.ParseFromJSON(DescriptorObject, NameForErrors, /*bSilent=*/ false, /*bPreParseOnly=*/ false);
	}

	// Create the new 'hub' asset and convert the data model over
	if (DataModel.IsValid())
	{
		const bool bSilent = false;

		Result = NewObject<UPaperSpriterImportData>(InParent, InName, Flags);
		Result->Modify();

		//@TODO: Do some things here maybe?
		Result->ImportedData = DataModel;


		// Import the assets in the folders
		for (const FSpriterFolder& Folder : DataModel.Folders)
		{
			for (const FSpriterFile& File : Folder.Files)
			{
				const FString RelativeFilename = File.Name.Replace(TEXT("\\"), TEXT("/"), ESearchCase::CaseSensitive);
				const FString SourceSpriterFilePath = FPaths::Combine(*CurrentSourcePath, *RelativeFilename);

				FString RelativeDestPath;
				FString JustFilename;
				FString JustExtension;
				FPaths::Split(RelativeFilename, /*out*/ RelativeDestPath, /*out*/ JustFilename, /*out*/ JustExtension);

				if (File.FileType == ESpriterFileType::Sprite)
				{
					const FString TargetTexturePath = LongPackagePath / TEXT("Textures") / RelativeDestPath;
					const FString TargetSpritePath = LongPackagePath / TEXT("Sprites") / RelativeDestPath;

					// Import the texture
					UTexture2D* ImportedTexture = ImportTexture(SourceSpriterFilePath, TargetTexturePath);

					if (ImportTexture == nullptr)
					{
						SPRITER_IMPORT_ERROR(TEXT("Failed to import texture '%s' while importing '%s'"), *SourceSpriterFilePath, *CurrentFilename);
					}

					// Create a sprite from it
					UPaperSprite* ImportedSprite = CastChecked<UPaperSprite>(CreateNewAsset(UPaperSprite::StaticClass(), TargetSpritePath, JustFilename, Flags));

					const ESpritePivotMode::Type PivotMode = ConvertNormalizedPivotPointToPivotMode(File.PivotX, File.PivotY);
					const double PivotInPixelsX = File.Width * File.PivotX;
					const double PivotInPixelsY = File.Height * File.PivotY;

					ImportedSprite->SetPivotMode(PivotMode, FVector2D((float)PivotInPixelsX, (float)PivotInPixelsY));

					FSpriteAssetInitParameters SpriteInitParams;
					SpriteInitParams.SetTextureAndFill(ImportedTexture);
					GetDefault<UPaperImporterSettings>()->ApplySettingsForSpriteInit(SpriteInitParams);
					SpriteInitParams.SetPixelsPerUnrealUnit(1.0f);
					ImportedSprite->InitializeSprite(SpriteInitParams);
				}
				else if (File.FileType == ESpriterFileType::Sound)
				{
					// Import the sound
					const FString TargetAssetPath = LongPackagePath / RelativeDestPath;
					UObject* ImportedSound = ImportAsset(SourceSpriterFilePath, TargetAssetPath);
				}
				else if (File.FileType != ESpriterFileType::INVALID)
				{
					ensureMsgf(false, TEXT("Importer was not updated when a new entry was added to ESpriterFileType"));
				}
					// 		TMap<FString, class UTexture2D*> ImportedTextures;
					// 		TMap<FString, class UPaperSprite> ImportedSprites;

			}
		}

		for (const FSpriterEntity& Entity : DataModel.Entities)
		{
			// Extract the common/shared skeleton
			FBoneHierarchyBuilder HierarchyBuilder;
			HierarchyBuilder.ProcessHierarchy(Entity);

			// Create the skeletal mesh
			const FString TargetMeshName = Entity.Name + TEXT("_SkelMesh");
			const FString TargetMeshPath = LongPackagePath;
			USkeletalMesh* SkeletalMesh = CastChecked<USkeletalMesh>(CreateNewAsset(USkeletalMesh::StaticClass(), TargetMeshPath, TargetMeshName, Flags));

			// Create the skeleton
			const FString TargetSkeletonName = Entity.Name + TEXT("_Skeleton");
			const FString TargetSkeletonPath = LongPackagePath;
			USkeleton* EntitySkeleton = CastChecked<USkeleton>(CreateNewAsset(USkeleton::StaticClass(), TargetSkeletonPath, TargetSkeletonName, Flags));

			// Initialize the mesh asset
			FSkeletalMeshResource* ImportedResource = SkeletalMesh->GetImportedResource();
			check(ImportedResource->LODModels.Num() == 0);
			ImportedResource->LODModels.Empty();
			FStaticLODModel& LODModel = *new (ImportedResource->LODModels) FStaticLODModel();

			SkeletalMesh->LODInfo.Empty();
			SkeletalMesh->LODInfo.AddZeroed();
			SkeletalMesh->LODInfo[0].LODHysteresis = 0.02f;
			FSkeletalMeshOptimizationSettings Settings;
			// set default reduction settings values
			SkeletalMesh->LODInfo[0].ReductionSettings = Settings;

			// Create initial bounding box based on expanded version of reference pose for meshes without physics assets. Can be overridden by artist.
// 			FBox BoundingBox(SkelMeshImportDataPtr->Points.GetData(), SkelMeshImportDataPtr->Points.Num());
// 			FBox Temp = BoundingBox;
// 			FVector MidMesh = 0.5f*(Temp.Min + Temp.Max);
// 			BoundingBox.Min = Temp.Min + 1.0f*(Temp.Min - MidMesh);
// 			BoundingBox.Max = Temp.Max + 1.0f*(Temp.Max - MidMesh);
// 			// Tuck up the bottom as this rarely extends lower than a reference pose's (e.g. having its feet on the floor).
// 			// Maya has Y in the vertical, other packages have Z.
// 			//BEN const int32 CoordToTuck = bAssumeMayaCoordinates ? 1 : 2;
// 			//BEN BoundingBox.Min[CoordToTuck]	= Temp.Min[CoordToTuck] + 0.1f*(Temp.Min[CoordToTuck] - MidMesh[CoordToTuck]);
// 			BoundingBox.Min[2] = Temp.Min[2] + 0.1f*(Temp.Min[2] - MidMesh[2]);
// 			SkeletalMesh->Bounds = FBoxSphereBounds(BoundingBox);

			// Store whether or not this mesh has vertex colors
// 			SkeletalMesh->bHasVertexColors = SkelMeshImportDataPtr->bHasVertexColors;

			// Pass the number of texture coordinate sets to the LODModel.  Ensure there is at least one UV coord
			LODModel.NumTexCoords = 1;// FMath::Max<uint32>(1, SkelMeshImportDataPtr->NumTexCoords);


			// Create the reference skeleton and update LOD0
			FReferenceSkeleton& RefSkeleton = SkeletalMesh->RefSkeleton;
			HierarchyBuilder.CopyToRefSkeleton(RefSkeleton);
			SkeletalMesh->CalculateRequiredBones(LODModel, RefSkeleton, /*BonesToRemove=*/ nullptr);
			SkeletalMesh->CalculateInvRefMatrices();

			// Initialize the skeleton asset
			EntitySkeleton->MergeAllBonesToBoneTree(SkeletalMesh);

			// Point the mesh and skeleton at each other
			SkeletalMesh->Skeleton = EntitySkeleton;
			EntitySkeleton->SetPreviewMesh(SkeletalMesh);

			// Create the animations
			for (const FSpriterAnimation& Animation : Entity.Animations)
			{
				//@TODO: That thing I said...

				const FString TargetAnimationName = Animation.Name;
				const FString TargetAnimationPath = LongPackagePath / TEXT("Animations");
				UAnimSequence* AnimationAsset = CastChecked<UAnimSequence>(CreateNewAsset(UAnimSequence::StaticClass(), TargetAnimationPath, TargetAnimationName, Flags));

				AnimationAsset->SetSkeleton(EntitySkeleton);

				// if you have one pose(thus 0.f duration), it still contains animation, so we'll need to consider that as MINIMUM_ANIMATION_LENGTH time length
				const float DurationInSeconds = Animation.LengthInMS * 0.001f;
				AnimationAsset->SequenceLength = FMath::Max<float>(DurationInSeconds, MINIMUM_ANIMATION_LENGTH);

				const bool bSourceDataExists = (AnimationAsset->SourceRawAnimationData.Num() > 0);
				TArray<struct FRawAnimSequenceTrack>& RawAnimationData = bSourceDataExists ? AnimationAsset->SourceRawAnimationData : AnimationAsset->RawAnimationData;




				int32 TotalNumKeys = 0;
				for (const FSpriterTimeline& Timeline : Animation.Timelines)
				{
					if (Timeline.ObjectType != ESpriterObjectType::Bone)
					{
						continue;
					}

					const FName BoneName = Entity.Objects[Timeline.ObjectIndex].ObjectName;

					const int32 RefBoneIndex = EntitySkeleton->GetReferenceSkeleton().FindBoneIndex(BoneName);
					check(RefBoneIndex != INDEX_NONE);

					FRawAnimSequenceTrack RawTrack;
					RawTrack.PosKeys.Empty();
					RawTrack.RotKeys.Empty();
					RawTrack.ScaleKeys.Empty();

					int32 NumKeysForTrack = 0;

					//@TODO: Quick and dirty resampling code that needs to be replaced (totally ignores curve type, edge cases, etc...)
					const float ResampleFPS = 30.0f;
					int32 DesiredNumKeys = FMath::CeilToInt(ResampleFPS * DurationInSeconds);
					const float TimePerKey = 1.0f / ResampleFPS;
					
					float CurrentSampleTime = 0.0f;
					for (int32 FrameIndex = 0; FrameIndex < DesiredNumKeys; ++FrameIndex)
					{
						int32 LowerKeyIndex = 0;
						for (; LowerKeyIndex < Timeline.Keys.Num(); ++LowerKeyIndex)
						{
							if (Timeline.Keys[LowerKeyIndex].TimeInMS * 0.001f > CurrentSampleTime)
							{
								--LowerKeyIndex;
								break;
							}
						}
						if (LowerKeyIndex >= Timeline.Keys.Num())
						{
							LowerKeyIndex = Timeline.Keys.Num() - 1;
						}

						int32 UpperKeyIndex = LowerKeyIndex + 1;
						float UpperKeyTime = 0.0f;
						if (UpperKeyIndex >= Timeline.Keys.Num())
						{
							UpperKeyTime = DurationInSeconds;
							if (Animation.bIsLooping)
							{
								UpperKeyIndex = 0;
							}
							else
							{
								UpperKeyIndex = Timeline.Keys.Num() - 1;
							}
						}
						else
						{
							UpperKeyTime = Timeline.Keys[UpperKeyIndex].TimeInMS * 0.001f;
						}

						const FSpriterFatTimelineKey& TimelineKey0 = Timeline.Keys[LowerKeyIndex];
						const FSpriterFatTimelineKey& TimelineKey1 = Timeline.Keys[UpperKeyIndex];
						const float LowerKeyTime = TimelineKey0.TimeInMS * 0.001f;

						const FTransform LocalTransform0 = TimelineKey0.Info.ConvertToTransform();
						const FTransform LocalTransform1 = TimelineKey1.Info.ConvertToTransform();

						FTransform LocalTransform = LocalTransform0;
						if (LowerKeyIndex != UpperKeyIndex)
						{
							const float Alpha = (CurrentSampleTime - LowerKeyTime) / (UpperKeyTime - LowerKeyTime);

							LocalTransform.Blend(LocalTransform0, LocalTransform1, Alpha);
						}

						RawTrack.ScaleKeys.Add(LocalTransform.GetScale3D());
						RawTrack.PosKeys.Add(LocalTransform.GetTranslation());
						RawTrack.RotKeys.Add(LocalTransform.GetRotation());
						++NumKeysForTrack;

						CurrentSampleTime += TimePerKey;
					}
// 
// 					for (const FSpriterFatTimelineKey& TimelineKey : Timeline.Keys)
// 					{
// 						//@TODO: Ignoring TimeInMS
// 						const FTransform LocalTransform = TimelineKey.Info.ConvertToTransform();
// 
// 						RawTrack.ScaleKeys.Add(LocalTransform.GetScale3D());
// 						RawTrack.PosKeys.Add(LocalTransform.GetTranslation());
// 						RawTrack.RotKeys.Add(LocalTransform.GetRotation());
// 
// 						++NumKeysForTrack;
// 					}
// 



					RawAnimationData.Add(RawTrack);
					AnimationAsset->AnimationTrackNames.Add(BoneName);

					// add mapping to skeleton bone track
					AnimationAsset->TrackToSkeletonMapTable.Add(FTrackToSkeletonMap(RefBoneIndex));

					TotalNumKeys = FMath::Max(TotalNumKeys, NumKeysForTrack);
				}
				AnimationAsset->NumFrames = TotalNumKeys;

				AnimationAsset->MarkRawDataAsModified();

				// compress animation
				{
					GWarn->BeginSlowTask(LOCTEXT("BeginCompressAnimation", "Compress Animation"), true);
					GWarn->StatusForceUpdate(1, 1, LOCTEXT("CompressAnimation", "Compressing Animation"));
					// if source data exists, you should bake it to Raw to apply
					if (bSourceDataExists)
					{
						AnimationAsset->BakeTrackCurvesToRawAnimation();
					}
					else
					{
						// otherwise just compress
						AnimationAsset->PostProcessSequence();
					}

					// run debug mode
					GWarn->EndSlowTask();
				}


// 					NewAnimation = FFbxImporter->ImportAnimations(Skeleton, Outer, SortedLinks, AnimName, TemplateImportData, FBXMeshNodeArray);
// 
// 					if (NewAnimation)
// 					{
// 						// since to know full path, reimport will need to do same
// 						UFbxAnimSequenceImportData* ImportData = UFbxAnimSequenceImportData::GetImportDataForAnimSequence(NewAnimation, TemplateImportData);
// 						ImportData->SourceFilePath = FReimportManager::SanitizeImportFilename(UFactory::CurrentFilename, NewAnimation);
// 						ImportData->SourceFileTimestamp = IFileManager::Get().GetTimeStamp(*UFactory::CurrentFilename).ToString();
// 					}


			}
		}

		Result->PostEditChange();
	}
 	else
 	{
 		// Failed to parse the JSON
 		bLoadedSuccessfully = false;
 	}

	if (Result != nullptr)
	{
		//@TODO: Need to do this
		// Store the current file path and timestamp for re-import purposes
// 		UAssetImportData* ImportData = UTileMapAssetImportData::GetImportDataForTileMap(Result);
// 		ImportData->SourceFilePath = FReimportManager::SanitizeImportFilename(CurrentFilename, Result);
// 		ImportData->SourceFileTimestamp = IFileManager::Get().GetTimeStamp(*CurrentFilename).ToString();
	}

	FEditorDelegates::OnAssetPostImport.Broadcast(this, Result);

	return Result;
}
예제 #18
0
int remote_control()
{
	ghttp_request *req;
	char *http_body = NULL;
	req = ghttp_request_new();
	sqlite3 *db = NULL;
        int rc = 0;
        sqlite3_stmt *ppstmt = NULL;
        char sql_cmd[100] ={0};
        const char *box_id;
        char box_id_tmp[10] = {0};
        const char *wan_state;
        char *errorMsg = NULL;
	char request_url[200] = {0};

	printf("****************************************\n");
        printf("remote_control : start\n");
        printf("****************************************\n");

        rc = sqlite3_open(box_db, &db);
        if(rc == SQLITE_ERROR)
        {
                printf("cannot open box.db!\n");
                return 0;
        }

        strcpy(sql_cmd, "select box_id from box_info");
        sqlite3_prepare(db, sql_cmd, -1, &ppstmt, 0);
        rc = sqlite3_step(ppstmt);
	if(rc == SQLITE_ROW)
        {
                box_id = sqlite3_column_text(ppstmt, 0);
                strcpy(box_id_tmp, box_id);
                printf("box_id : %s\n", box_id_tmp);
        }
	
        sqlite3_finalize(ppstmt);
        sqlite3_close(db);

	printf("send http request...\n");
        sprintf(request_url, "http://www.ailvgobox.com/box_manage/remote_control.php?box_id=%s", box_id_tmp);
        printf("request_url  : %s\n", request_url);
	http_body = send_http_request(req, request_url);
	fprintf(stderr, "http_body : %s\n", http_body);

	cJSON *node;
	
        if(http_body)
        {
        	printf("HTTP success!\n");

                if(strcmp(http_body, "null") == 0)
                     printf("http_body : null, no remote_control!\n");
                else
                {
                     node = cJSON_Parse(http_body);
                     ParseJSON(node, box_id_tmp);
                }
        }
	else
        {
                printf("HTTP failure!\n");
        }

        if(http_body)
               free(http_body);

        ghttp_request_destroy(req);
        free(request_url);
        printf("remote_control : complete!\n");
        return 1;
}
예제 #19
0
파일: JSON.c 프로젝트: JoshOY/C-JSON-joshoy
JSON *ParseJSON(const char *value)
{
    JSON       *rtn               = NULL;
    StrSlice   *ss                = NULL;
    StrSlice   *iter              = NULL;
    int         len               = strlen(value);
    int         index             = 0;
    char       *value_deletespace = DeleteSpaces(value);

    switch(value[0]) {
    case '-':
    case '1':
    case '2':
    case '3':
    case '4':
    case '5':
    case '6':
    case '7':
    case '8':
    case '9':
    case '0':
        //To number
        return CreateNumber(FormatNumber(value_deletespace));
        free(value_deletespace);
        break;

    case '\"':
        // To string
        return CreateString(FormatString(value));
        break;

    case '{':
        rtn  =  CreateObject();
        ss   =  GetObjectSlices(value);
        iter =  ss;
        if (ss->length == 0) {
            DeleteStrSlice(ss);
            return rtn;
        }
        while (iter != NULL) {
            AddItemToObject(rtn, FormatString(iter->str), ParseJSON(DeleteSpaces(iter->next->str)));
            iter = iter->next->next;
        }
        DeleteStrSlice(ss);
        return rtn;
        break;

    case '[':
        rtn  =  CreateArray();
        ss   =  GetArraySlices(value);
        iter =  ss;
        if (ss->length == 0) {
            DeleteStrSlice(ss);
            return rtn;
        }
        while (iter != NULL) {
            AddItemToArray(rtn, ParseJSON(DeleteSpaces(iter->str)));
            iter = iter->next;
        }
        DeleteStrSlice(ss);
        return rtn;
        break;

    case 'n':
        if (strcmp(value_deletespace, "null") == 0) {
            free(value_deletespace);
            return CreateNULL();
        }
        else {
            printf("Exception: Invalid Syntax \"%s\"", value);
            return NULL;
        }

    case 't':
        if (strcmp(value_deletespace, "true") == 0) {
            free(value_deletespace);
            return CreateTrue();
        }
        else {
            printf("Exception: Invalid Syntax \"%s\"", value);
            return NULL;
        }
        break;

    case 'f':
        if (strcmp(value_deletespace, "false") == 0) {
            free(value_deletespace);
            return CreateFalse();
        }
        else {
            printf("Exception: Invalid Syntax \"%s\"", value);
            return NULL;
        }
        break;
    }
}