openapi-generator icon indicating copy to clipboard operation
openapi-generator copied to clipboard

[REQ] [cpp-ue4] consider upgrading objects to UObjects and eventually, Blueprint (BP) support

Open leith-bartrich opened this issue 5 years ago • 8 comments

This request is a place to discuss the potential for substantially changing the cpp-ue4 client generator towards the goal of supporting Blueprints eventually.

However, the start of that process may run through upgrading a number of objects from standard c++ objects into UObjects. Actually, BP exposure is rather trivial compared to the initial UObject exposure.

I have put some thought into various alternative approaches. Such as turning the API into a static function library that in turn, could be exposed as a blueprint function library. However, I'm not in favor of that particular approach.

Another alternative might be creating an entirely new generator (e.g. [cpp-ue-bp]) for the purpose of generating an alternative client that is more tailored to supporting UObjects and Blueprints. But that might needlessly split resources.

Another alternative might be generating a bunch of new files\UObjects that wrap the existing ones, rather than adapt the existing objects. Which might be somewhat redundant?

Anyhow, toward this goal I did some local hacking about to see just how plausible it is to adapt the existing objects. Would most of the code compile with some simple changes?

  • I had to remove the cppNamespace support; because unreal UObjects cannot live in a namespace. There's some significant ramifications to that. But that's something that unreal developers have been stuck dealing with for some time. I haven't checked if Unreal5 early access changes this need at all.

  • I had to refactor some names because unreal requires "U" prepended to UObjects.

  • I had to change some internal delegate binding to now bind to a UObject. (not a public facing change)

But ultimately, I did succeed in getting the basic API object exposed as a BP relatively easily and was able to call some basic functions. Just as a proof of concept. In other words, it does compile and it does run. I didn't need to start deleting blocks of code and functionality, besides the namespaces themselves.

Screen Shot 2021-08-23 at 3 19 37 PM

But these are big breaking changes to the public interface of generated code. Even to do something as simple as instantiate the API object and set a URL.

The kinds of changes needed to expose models, requests and responses are likely to be just as much a breaking change as the API object, if not more-so.

One big hurdle for example, is that TOptional cannot be exposed as a UPROPERTY() it seems.

Anyhow, I thought a feature request was the right place to at least talk about this and potential alternative approaches.

tagging @Kahncode

leith-bartrich avatar Aug 23 '21 20:08 leith-bartrich

My thoughts about this and the original intent behind the generator:

  • In most professional scenarios, you would likely not expose HTTP calls to the blueprints, but rather wrap that into higher level concepts for high level script and technical designers, as well as abstracting game logic from backend implementation details.
  • This is why the purpose of the generator was primarily to generate optimal c++ code and intentionally avoids the UOBJECT system. As it stands, the c++ approach is more performant, requires less allocations, is less verbose and more user friendly. Avoiding allocations is also why nested objects are implemented as variables rather than pointers, which prevents the use of recursive models, but makes the large majority of models better optimized for runtime performance, as well as the code simpler.
  • I agree that creating a second generator is a bad idea as both generators will surely share a sizeable amount of code. I would recommend adding this as an option in this generator, and build on top of the existing C++ API, wrapping it as much as possible, without breaking current API and syntax, and creating other sets of models where incompatibilities arise.
  • Redundancy in this case is not a real problem. The code is generated so maintenance of slight duplication (of relatively trivial serialization code) is not an issue, and it would not impact the performance and behavior of the existing and future c++ code.
  • In fact I don't expect this to be too much work. I'd be happy to help you with this, we could discuss verbally and/or share a branch.

This would provide the flexibility to use it in blueprints although I would certainly advise against it in most practical scenarios.

Kahncode avatar Aug 23 '21 21:08 Kahncode

I'll mock that up a bit in my fork, as a branch and see what it reveals.

The more I think about it, the more it probably makes sense to wrap.

Once I have something to talk about or look at, I'll bring your attention to it. It may be a while. It's a bit of a side-quest.

leith-bartrich avatar Aug 23 '21 21:08 leith-bartrich

  • You can add new mustache files to be processed when the option is activated by changing the java code in relatively few places.
  • I'd try to work with USTRUCT rather than objects to avoid allocations.
  • In order to declare UPROPERTYs you will have to create new models so I don't think you can really wrap those easily. The API can easily be wrapped and new blueprint callable functions with dynamic delegates added there.

Kahncode avatar Aug 23 '21 23:08 Kahncode

Just updating with a WIP branch. For anyone who's interested.

https://github.com/leith-bartrich/openapi-generator/tree/feature-BPUObjects-01

I'm not suggesting this for merge any time soon. I'm taking a "eat your own dog-food" approach here and using it with my local code-base to help me flush it out. It's probably got big problems that need working through. And there are large parts unimplemented.

For example, right now I'm sure the Enum section is broken and I need to develop some server side code to help flush it out.

Also, currently it doesn't use "<#generateBP>" to blank out the BP files, if no generateBPType is provided.

But I have replaced all my older ClientView code with code that consumes this new code, and it's running ATM. Which means it might be useful to someone.

@Kahncode

Your first point is taken and executed. The changes I made to the java generator code are minimal as you thought. Though I"ll likely revise some of the additional command-line flags a bit shortly. I just noticed a mistake in there anyway.

The second point is something I'm deferring for the moment. In so much as I've reserved space for alternate styled implementations (see: "generateBPType" flag). I'm implementing a "generateBPType=UObjects" which almost certainly isn't what you meant by your second point. I'd hope to be able to also implement a "generateBPType=UStructs" as well once I better understand your suggestion. Or, it might be something you'd have an active hand in. I felt the best thing to do here is to reserve space for multiple supported/styled BP implementations as a place to figure it all out.

In the UObjects implementation, I am making heap allocations and clones to make it be BP-like and GC'd. Whereas a purely method based solution probably could avoid heap allocations altogether in favor of stack variables. I'd need a bit more guidance as to what you mean though, to implement it myself. If I'm even understanding the gist of what you meant.

Regarding your third point, I'm just defining Getter and Setter UFUNCTIONS and avoiding UPROPERTIES.

So far, here's what it's gotten me.

I can author a ClientView object in CPP or in BP fairly easily. Which mostly hides the API from consumers of the ClientView, with the exception of the models themselves. The models are freely passed in and out of the ClientView, though they don't have to be. Response handling can be done in CPP easily, as lambdas. Though there are other ways.

Response handling can be handled via CPP or BP subclasses by overriding the BlueprintNativeEvent OnResponse of the request.

Response handling can be handled via binding to a BP and CPP accessible Dynamic Multicast event of the request.

Response handling can be handled via binding to a CPP accessible Multicast event of the request.

e.g. a simple CPP ClientView from my code-base.

header:

DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FOnProvideLegalEntities,const TArray<UFPLLegalEntity*> &, entities);

/**
 * 
 */
UCLASS(BlueprintType,meta=(Category="LegalEntitiesManagerView"))
class FPIPELITE_CLIENT_PLUGIN_API ULegalEntitiesManagerView : public URESTView
{
	GENERATED_BODY()

	public:

	UFUNCTION(BlueprintCallable,Category="LegalEntitiesManagerView")
	void RequestRefreshLegalEntitiesList();


	
	UFUNCTION(BlueprintCallable,Category="LegalEntitiesManagerView")
	void RequestDeleteLegalEntity(FGuid id);


	UFUNCTION(BlueprintCallable, Category="LegalEntitiesManagerView")
	void RequestUpdateLegalEntity(UFPLLegalEntity * entry);


	UPROPERTY(BlueprintAssignable,Category="LegalEntitiesManagerView")
	FOnProvideLegalEntities OnProvideLegalEntities;

	UPROPERTY(EditAnywhere, BlueprintReadWrite, Meta=(ExposeOnSpawn=TRUE,Category="LegalEntitiesManagerView"))
	FString login_name;


	virtual void StartClient() override;
	virtual void StopClient() override;

	
	private:
	UPROPERTY()
	UFPLOrgbuilderApi * api;
	
};

source:

void ULegalEntitiesManagerView::RequestRefreshLegalEntitiesList()
{
	auto request = NewObject<UFPLOrgbuilderApiListLegalEntitysRequest>();
	request->OnResponseEvent.AddLambda([this](UFPLOrgbuilderApiListLegalEntitysRequest * request, UFPLOrgbuilderApiListLegalEntitysResponse * response)
	{
		if (!response->IsSuccessful())
		{
			this->LogError(TEXT("List LegalEntities request failed.  REST Error code: " + FString::FromInt(response->GetHttpResponseCode()) + " ServerResponse: " + response->GetResponseString() ));
			return;
		}
		this->OnProvideLegalEntities.Broadcast(response->GetContent());
	});
	request->ExecuteRequest(this->api);
}


void ULegalEntitiesManagerView::RequestDeleteLegalEntity(FGuid id)
{
	auto request = NewObject<UFPLOrgbuilderApiDestroyLegalEntityRequest>();
	request->SetId(id.ToString());
	request->OnResponseEvent.AddLambda([this](UFPLOrgbuilderApiDestroyLegalEntityRequest * request, UFPLOrgbuilderApiDestroyLegalEntityResponse * response)
	{
		if (!response->IsSuccessful())
		{
			this->LogError(TEXT("Failed to delete LegalEntity: " + request->GetId() + ": ServerResponse: " + response->GetResponseString()));
		}
		this->RequestRefreshLegalEntitiesList();
	});
	request->ExecuteRequest(this->api);

	
}


void ULegalEntitiesManagerView::RequestUpdateLegalEntity(UFPLLegalEntity* entry)
{
	auto request = NewObject<UFPLOrgbuilderApiUpdateLegalEntityRequest>();
	request->SetId(entry->GetId().ToString());
	request->SetLegalEntity(entry);
	request->OnResponseEvent.AddLambda([this](UFPLOrgbuilderApiUpdateLegalEntityRequest * request, UFPLOrgbuilderApiUpdateLegalEntityResponse * response)
	{
		if (!response->IsSuccessful())
		{
			this->LogError(TEXT("Failed to update LegalEntity: " + request->GetLegalEntity()->GetId().ToString()) + " ServerResponse: " + response->GetResponseString());
		}
		this->RequestRefreshLegalEntitiesList();
	});
	request->ExecuteRequest(this->api);
}


void ULegalEntitiesManagerView::StartClient()
{
	this->api = NewObject<UFPLOrgbuilderApi>();
	FLoginDataStruct login_data;
	auto login_data_manager = NewObject<ULoginsData>();
	if (!login_data_manager->LoadLogin(this->login_name,login_data))
	{
		this->LogError(TEXT("Failed to load login token from user's home directory.  Looking for login named: " + this->login_name));
	} else
	{
		this->LogInformation(TEXT("Loaded login token. name: " + this->login_name + " token: " + "<REDACTED>" ));
	}
	this->api->SetURL(login_data.url);
	if (login_data.url.ToLower().StartsWith("http:"))
	{
		this->LogWarning("The login URL uses HTTP rather than HTTPS.  This is a potential security risk because your login token will be visible in an unencrypted data stream.");
	}
	this->api->AddHeaderParameter("Authorization","Apikey " + login_data.token);
}

void ULegalEntitiesManagerView::StopClient()
{
}

This ClientView is instantiated and runs inside a widget (UI). The firing of the OnProvideLegalEntities event is consumed in the widget and the provided models are handed to a ListView.

The widget and listItems call the higher level Requests on the ClientView upon button presses, etc.

Also, for reference, my command-line for the generator currently is:

openapi-generator generate -g cpp-ue4 -i ./openapi-schema.yml --additional-properties cppNamespace=fpipelite::client --additional-properties unrealModuleName=fpipelite_client --additional-properties generateBP --additional-properties generateBPType=UObjects --additional-properties BPAPIPrefix=FPL --additional-properties modelNamePrefix=

Of note here:

  • Since the BP objects must exist outside namespaces, I added BPAPIPrefix= to help avoid collisions. Multiple APIs that might use common names can be prefixed differently, and avoid collisions.
  • Since BP is handled by the prefix, and the other code is handled via namespaces, setting modelNamePrefix to "" keeps the names short and reasonable, removing the redundant "OpenAPI" prefix completely from both filenames and object names.

High priority for me next, is considering some kind of triggered/event based 'OnChanged' behavior for the model's properties. Mostly to avoid any unnecessary Tick bound Getter calls.

leith-bartrich avatar Aug 30 '21 22:08 leith-bartrich

  • Are these client views handwritten or generated? I believe the purpose of the generators is to provide a direct mapping to the API calls and not necessarily a higher level layer as such, but if I understand you correctly this is what you did.

  • The only difference between the USTRUCT and UOBJECT approach is that USTRUCT is a lot nicer to use in BP and avoids the allocation. You can create "member functions" on USTRUCT as static methods that take the struct as mutable reference. For instance: static void SetXXX(UPARAM(ref) FStructXXX& StructRef, int Value); In that way you can generate a BPFL for all of the generated structs and essentially wrap everything nicely. -In order to avoid the TOptional incompatibility with UPROPERTY, another approach could be to simply contain the current cpp models generated in the USTRUCTS, and to only use the accessors for them. In this case, what's left is to wrap the API with methods taking the USTRUCT and dynamic delegates to allow them to be called in blueprints

  • Basically the USTRUCT and UOBJECT versions for me are almost identically generated code, it's just that one is more performant and more elegant to use in BP (MakeStruct/BreakStruct vs Construct + series of setter calls).

Kahncode avatar Aug 31 '21 16:08 Kahncode

The client view is hand-written. It is consuming the generated UObjects (which are also BP exposed). Anything that is named UFPL* in this example is a generated BP object that's being consumed by the hand-written code.

I wanted to demonstrate the usage of the generated BP objects rather than dump a large code listing of their contents. To provide an idea of what it's like to work with them. The templates in the referenced branch are a good place to just see what they are internally.

I am trying to maintain a solution where you can choose to consume them either from CPP or BP. And in this case, it's easy to provide some CPP code that I adapted quickly from an older solution, as a first demo.

The same client view can be constructed in BP however. Instead of lambdas, you'd likely Bind custom events to the "OnResponseDynamic" EventDispatcher which is visible in the BP editor.

Though, alternatively, you could actually "Create Child Bluprint Class" from the Request BPs, and implement their OnResponse events.

Or, you could Subclass them in c++ and override the default OnResponse implementation.

This provides a path to prototype in BP and re-implement in c++ later if need be.

Regarding points 2&3:

Okay, I do understand what you were getting at then. It's not so much USTRUCTS as it is a functional programming library that uses USTRUCTS for passing complex data and pointers about. Which helps guarantee that everything is on the stack rather than the heap. And your suggestion of passing around Dynamic delegates for callbacks is probably the missing piece.

As I said, I've reserved the space to make such thing. So I'll also start to work that in and see where I can take advantage of commonalities. For example, its likely the accessors you suggested can share the template code I've already implemented.

leith-bartrich avatar Aug 31 '21 17:08 leith-bartrich

If you look at it from the lens of C++ yes it's a function-based API however usage from the blueprints will behave the same for the USTRUCTS as member functions do for UOBJECTS. The resulting blueprint code is much more elegant and lean, and you benefit from Make/Break nodes, all the while avoiding heap allocations. The simplest API calls could be just 3 nodes: Create API, MakeParamStruct, call API method on the API Object with event attached.

UFUNCTION(BlueprintCallable) void ApiCall(const FParamUStruct& Param, UPARAM(DisplayName = "CallbackEvent") const FDynamicReturnDelegate& Delegate);

Obviously you can and should use the same sort of signature for UObjects if you do generate UObjects. If you do go for UObjects and full encapsulation, then you should be wrapping internally to the existing C++ API as it's fully encapsulated you won't have to deal with the problem of TOptional not being a UPROPERTY.

By doing this I believe both APIs could sit in parallel. I actually would like to avoid the case where generation is either/or, because the existing API might be implemented already in a codebase where you end up also needing the blueprint API later, so activating it should not break existing C++ code. Naturally, the blueprint API can also be used from C++ directly although less efficiently/elegantly.

Kahncode avatar Aug 31 '21 21:08 Kahncode

going a different direction

leith-bartrich avatar Sep 12 '21 15:09 leith-bartrich