I would like to create a landscape from scratch in unreal engine 4.27 using C++ only. I have only a simple notion of the process, which revolves around GetWorld()->SpawnActor<ALandscape>, ALandscapeProxy::Import(...) and importing a height/weight map.
I used the LandscapeEditorDetailCustomization_NewLandscape::OnCreateButtonClicked() method as a learning ground, but unfortunately I am at an impasse.
From what I have gathered from my searches there not a lot of examples on the matter. Does anyone have a suggestion or an example?
This is the solution I came up with, with many thanks to ChenHP (or chpsemail) who gave me a solution to this. Firstly, declare the following variables. A better understanding can be found here.
FQuat InRotation
FVector InTranslation
FVector InScale
FTransform LandscapeTransform{InRotation, InTranslation, InScale}
int32 QuadsPerSection
int32 SectionsPerComponent
int32 ComponentCountX
int32 ComponentCountY
int32 QuadsPerComponent
int32 SizeX
int32 SizeY
Create containers for the heights and materials of the landscape:
TArray<FLandscapeImportLayerInfo> MaterialImportLayers
TMap<FGuid, TArray<uint16>> HeightDataPerLayers
TMap<FGuid, TArray<FLandscapeImportLayerInfo>> MaterialLayerDataPerLayers
It is important to note that heights in UE4 are of uint16 type, with 0 the deepest and 65'534 the highest. So for a flat map all height entries should be 32768.
The number of heights is the resolution of the map which is dependent on SizeX and SizeY.
TArray<uint16> HeightData;
HeightData.SetNum(SizeX * SizeY);
for (int32 i = 0; i < HeightData.Num(); i++)
{
HeightData[i] = 32768;
}
Height and material information should then be placed in the corresponding containers and be given a valid FGuid.
HeightDataPerLayers.Add(FGuid(), MoveTemp(HeightData))
MaterialLayerDataPerLayers.Add(FGuid(), MoveTemp(MaterialImportLayers))
At this point the base parameters for the landscape have been set. The ALandscape* Landscape = SpawnActor<ALandscape>() could be called at either point since it just spawns an object that doesn't actually have any information about it. This also applies for setting landscape's fields. Fields that need to be set are presented bellow:
Landscape->bCanHaveLayersContent
Landscape->LandscapeMaterial
Landscape->SetActorTransform
Landscape->StaticLightingLOD
ULandscapeInfo* LandscapeInfo = Landscape->GetLandscapeInfo()
LandscapeInfo->UpdateLayerInfoMap(Landscape)
Landscape->RegisterAllComponents()
Landscape->GetClass()
Landscape->PostEditChangeProperty(MaterialPropertyChangedEvent)
Landscape->PostEditChange()
The actual part where landscape is given form, happens with the invocation of Landscape->Import(...).
A detailed explanation about what the script could look like can be found here with more information on landscape (check the answer for the cpp code).
Related
I asked for help about an OpenGL ES 2.0 Problem in this question.
What seems to be the answer is very odd to me.
Therefore I decided to ask this question in hope of being able to understand what is going on.
Here is the piece of faulty vertex-shader code:
// a bunch of uniforms and stuff...
uniform int u_lights_active;
void main()
{
// some code...
for ( int i = 0; i < u_lights_active; ++i )
{
// do some stuff using u_lights_active
}
// some other code...
}
I know this looks odd but this is really all code that is needed to explain the problem / faulty behavior.
My question is: Why is the loop not getting executed when I pass in some value greater 0 for u_lights_active?
When I hardcode some integer e.g. 4, instead of using the uniform u_lights_active, it is working just fine.
One more thing, this only appears on Android but not on the Desktop. I use LibGDX to run the same code on both platforms.
If more information is needed you can look at the original question but I didn't want to copy and paste all the stuff here.
I hope that this approach of keeping it short is appreciated, otherwise I will copy all the stuff over.
Basically GLSL specifies that implementations may restrict loops to have "constant" bounds on them. This is to make it simpler to optimize the code to run in parallel (different loop counts for different pixels would be complex). I believe on some implementations the constants even have to be small. Note that the spec just specifies the "minimum" behavior, so some devices might support more complex loop controls than the spec requires.
Here's a nice summary of the constraints:
http://www.khronos.org/webgl/public-mailing-list/archives/1012/msg00063.html
Here's the GLSL spec (look at section 4 of Appendix A):
http://www.khronos.org/registry/gles/specs/2.0/GLSL_ES_Specification_1.0.17.pdf
http://www.opengl.org/discussion_boards/showthread.php/171437-can-for-loops-terminate-with-a-uniform
http://www.opengl.org/discussion_boards/showthread.php/177051-GLSL-loop-problem-on-Radeon-HD-cards
http://www.opengl.org/discussion_boards/showthread.php/162722-Problem-when-using-uniform-variable-as-a-loop-count-in-fragment-shader
https://www.opengl.org/discussion_boards/showthread.php/162535-variable-controlled-for-loops
If you have a static loop it can be unrolled and made into static constant lookups. If you absolutely need to make it dynamic, you'll need to store indexed data into a 1D texture and sample that instead.
I'm guessing that the hardware on the desktop is more advanced than on the tablet. Hope this helps!
Kind of a fun half-answer, and-or, the solution to the underlying problem that I have chosen.
The following function called with 'id' passed as the ID of the shader's script block and 'swaps' filled with an array of 2 component arrays in the format of [[ThingToReplace, ReplaceWith],] strings. Called before the shader is created.
In the javascript:
var ReplaceWith = 6;
function replaceinID(id,swaps){
var thingy = document.getElementById(id);
for(var i=0;i<swaps.length;i++){
thingy.innerHTML = thingy.innerHTML.replace(swaps[i][0], swaps[i][1]);
}
}
replaceinID("My_Shader",[['ThingToReplace',ReplaceWith],]);
Coming from C, this is a very Macro like approach, in that it simulates a preprocessor.
In the GLSL:
for(int i=0;i<ThingToReplace;i++){
;//whatever goes here
}
Or;
const int val = ThingToReplace;
for(int i=0;i<val;i++){
;//whatever goes here
}
Embarcadero C++Builder 10.3.2 Enterprise
Searching the internet, I could not find any FMX code for this. Based on Delphi code, this should have worked but the compiler does not like it
if (Application->FormFactor->Orientations == Fmx::Types::TScreenOrientations::Landscape) {
//Landscape
}
Also, the value of Application->FormFactor->Orientations is the same whatever the orientation of the iphone. {System::SetBase = {Data = {[0] = 11 '\v'}}}
How does one determine the orientation?
The Orientations property is a TFormOrientations, which is a System::Set of TFormOrientation values. You can't use Set::operator== to compare it to a single value, which is why you are getting a compiler error. However, you can use the Set::Contains() method to check if it has a given value, eg:
if (Application->FormFactor->Orientations.Contains(Fmx::Forms::TFormOrientation::Landscape)) {
//...
}
In any case, the Orientations property specifies which orientation(s) the application's Forms are allowed to take (a value of 11 has its 1st, 2nd, and 4th bits set to 1, which correspond to the Portrait, Landscape, and InvertedLandscape orientations being enabled). It does not report what the device's current orientation is. For that, use the IFMXScreenService::GetScreenOrientation() method instead, eg:
_di_IFMXScreenService ScreenService;
if (TPlatformServices::Current->SupportsPlatformService(__uuidof(IFMXScreenService), &ScreenService)) {
if (ScreenService->GetScreenOrientation() == Fmx::Types::TScreenOrientation::Landscape) {
//...
}
}
I'm still confused about unit testing. Suppose I have something as trivial as this:
class x {
zzz someMethod(some input...) {
BufferedImage image = getter.getImageFromFile(...);
// determine resize mode:
int width = image.getWidth();
int height = image.getHeight();
Scalr.Mode resizeMode = (width > height) ? Scalr.Mode.FIT_TO_WIDTH : Scalr.Mode.FIT_TO_HEIGHT;
return ScalrWrapper.resize(image, resizeMode);
}
}
Going by rules, Scalr.Mode resizeMode = should probably be a in a separate class for better unit testability of the aforementioned method, like so:
class xxx {
mode getResizeMode(int width, int height)
{
return (width > height) ? Scalr.Mode.FIT_TO_WIDTH : Scalr.Mode.FIT_TO_HEIGHT;
}
}
class x {
zzz someMethod(some input...) {
BufferedImage image = getter.getImageFromFile(...);
// determine resize mode:
int width = image.getWidth();
int height = image.getHeight();
Scalr.Mode resizeMode = xxx.getResizeMode(width, height);
return ScalrWrapper.resize(image, resizeMode);
}
}
But it looks like such an overkill... I'm not sure which one is better but I guess this way is better. Suppose I go this route, would it be even better to do it this way?
class xxx {
mode getResizeMode(Image image)
{
return (image.getWidth() > image.getHeight()) ? Scalr.Mode.FIT_TO_WIDTH : Scalr.Mode.FIT_TO_HEIGHT;
}
}
class x {
void someMethod(some input...) {
BufferedImage image = getter.getImageFromFile(...);
// determine resize mode:
Scalr.Mode resizeMode = xxx.getResizeMode(image);
return ScalrWrapper.resize(image, resizeMode);
}
}
From what I understand, the correct way is the one where getResizeMode accepts integers as it is decoupled from the type of data whose properties are width and height. However, personally to me, the use of getResizeMode(BufferedImage) actually justifies the creation of a separate class better as some more work is removed from the main method. And since I am not going to be using getResizeMode for any sort of data other than BufferedImage in my application anyway, there is no problem of reusability. Also, I don't think I should be doing getResizeMode(int, int) simply for reusability if I see no need for it due to YAGNI principle.
So my question is: would getResizeMode(BufferedImage) be a good way according to OOD in real world? I understand it's text book good OOD, but then I have been lead to believe that 100% text book OOD is impracticle in real world. So as I am trying to learn OOD, I just want to know which path I should follow.
...Or maybe I should I just leave everything in one method like in the very first code snippet?
I don't think that resize mode calculation influences testability a lot.
As to Single Responsibility:
"A class should have only one reason to change" (https://en.wikipedia.org/wiki/Single_responsibility_principle).
Do you think that resizing mode calculation is going to change?
If not then just put in the class where this mode is needed.
This won't add any reasons to change for that class.
If the calculation is likely to change (and/or may have several versions)
then move it to a separate class (make it a strategy)
Achieving the Single Responsibility Principle (SRP) is not about creating new classes every time, one extracting a method. Moreover the SRP depends on the context.
A module should concern to the SRP.
A class should concern to the SRP.
A method should concern to the SRP.
The message from Uncle Bob is: Extract till you Drop
Beyond he said:
Perhaps you think this is taking things too far. I used to think so too. But after programming for over 40+ years, I’m beginning to come to the conclusion that this level of extraction is not taking things too far at all.
When it comes to the decision to create new classes, keep the metric high cohesion in mind. Cohesion is the degree to which the elements of a module belong together. If all methods work in one specific context and on the same set of variables, they belong to one class.
Back to your case. I would extract all the methods and put them in on class. And this one class is also nicely testable.
Little bit late to the party, but here's my 2c.
To my mind, class x is not adhering to the SRP for a different reason.
It's currently responsible for
Getting an image from a file (getter.getImageFromFile)
Resizing that image
TL;DR
The TL;DR on this is that both of your approaches are fine and both do in fact stick - with varying degrees of stickiness - to the SRP. However if you want to adhere very tightly to the SRP (which tends to lead to very testable code), you could split this into three classes first:
Orchestrator
class imageResizeService
{
ImageGetter _getter;
ImageResizer _resizer;
zzz ResizeImage(imageName)
{
image=_getter.GetImage(imageName);
resizedImage=_resizer.ResizeImage(image);
return resizedImage;
}
}
This class has a single responsibility; namely, given an image name,
return a resized version of it based on some criteria.
To do so, it orchestrates two dependencies. But it only has a single reason to change which is that the process used to get and resize an image in
general , has changed.
You can easily unit test this by mocking the getter and resizer and testing that they are called in order, that the resizer is called with the data given by the getter, and that the final return value equals that returned by the resizer, and so on (i.e. "White Box" testing)
ImageGetter
class ImageGetter
{
BufferedImage GetImage(imageName)
{
image=io.LoadFromDisk(imageName) or explode;
return image;
}
}
Again, we have a single responsiblity (load an image from disk, and return it).
The only reason to change this class would be if the mechanics of loading the image were to change - e.g. you are loading from a Database, not a Disk.
An interesting note here is that this class is ripe for further generalisation - for example to be able to compose it using a BufferedImageBuilder and a RawImageDataGetter abstraction which could have multiple implementations for Disk, Database, Http, etc. But that's YAGNI right now and a conversation for another day :)
Note on testability
In terms of unit testing this, you may run into a small problem, namely that you can't quite "unit test" it - unless your framework as a mock for the file system. In that case, you can either further abstract the loading of the raw data (as per the previous paragraph) or accept it and just perform an integration test off a known good file. Both approaches are perfectly valid and you should not worry about which you choose - whatever is easier for you.
ImageResizer
class ImageResizer
{
zzz ResizeImage(image)
{
int width = image.getWidth();
int height = image.getHeight();
Scalr.Mode resizeMode = getResizeMode(width, height);
return ScalrWrapper.resize(image, resizeMode);
}
private mode getResizemode(width, height)
{
return (width > height) ? Scalr.Mode.FIT_TO_WIDTH : Scalr.Mode.FIT_TO_HEIGHT;
}
}
This class also has but a single job, to resize an image.
The question of whether or not the getResizeMode method - currently just a private method to keep the code clean - should be a separate responsiblity has to be answered in the context of whether or not that operation is somehow independent of the image resizing.
Even if it's not, then the SRP is still being followed, because it's part of the single responsibility "Resize an Image".
Test-wise this is also really easy to test, and because it doesn't even cross any boundaries (you can create and supply the sole dependency - the image - during test runtime) you probably won't even need mocks.
Personally I would extract it to a separate class, just so that I could, in isolation, verify that given a width larger than a height, I was returned a Scalr.Mode.FIT_TO_WIDTH and vice-versa; it would also mean I could adhere to the Open Closed Principle whereby new scaling modes could be introduced without having to modify the ImageResizer class.
But really
The answer here has to be that that it depends; for example if you have a simple way to verify that, given a width of 100 and a height of 99, then the resized image is indeed scaled to "Fit to Width" then you really don't need to.
That being said I suspect you'll have an easier time testing this if you do extract that to a separate method.
Just bear in mind that if you're using a decent IDE with good refactoring tools, that should really not take you more than a couple of keystrokes, so don't worry about the overhead.
I am not sure how you are supposed to control a player character in Bullet. The methods that I read were to use the provided btKinematicCharacterController. I also saw methods that use btDynamicCharacterController from the demos. However, in the manual it is stated that kinematic controller has several outstanding issues. Is this still the preferred path? If so, are there any tutorials or documentations for this? All I found are snippets of code from the demo, and the usage of controllers with Ogre, which I do not use.
If this is not the path that should be tread, then someone point me to the correct solution. I am new to bullet and would like a straightforward, easy solution. What I currently have is hacked together bits of a btKinematicCharacterController.
This is the code I used to set up the controller:
playerShape = new btCapsuleShape(0.25, 1);
ghostObject= new btPairCachingGhostObject();
ghostObject->setWorldTransform(btTransform(btQuaternion(0,0,0,1),btVector3(0,20,0)));
physics.getWorld()->getPairCache()->setInternalGhostPairCallback(new btGhostPairCallback());
ghostObject->setCollisionShape(playerShape);
ghostObject->setCollisionFlags(btCollisionObject::CF_CHARACTER_OBJECT);
controller = new btKinematicCharacterController(ghostObject,playerShape,0.5);
physics.getWorld()->addCollisionObject(ghostObject,btBroadphaseProxy::CharacterFilter, btBroadphaseProxy::StaticFilter|btBroadphaseProxy::DefaultFilter);
physics.getWorld()->addAction(controller);
This is the code I use to access the controller's position:
trans = controller->getGhostObject()->getWorldTransform();
camPosition.z = trans.getOrigin().z();
camPosition.y = trans.getOrigin().y()+0.5;
camPosition.x = trans.getOrigin().x();
The way I control it is through setWalkDirection() and jump() (if canJump() is true).
The issue right now is that the character spazzes out a little, then drops through the static floor. Clearly this is not intended. Is this due to the lack of a rigid body? How does one integrate that?
Actually, now it just falls as it should, but then slowly sinks through the floor.
I have moved this line to be right after the dynamic world is created
physics.getWorld()->getPairCache()->setInternalGhostPairCallback(new btGhostPairCallback());
It is now this:
broadphase->getOverlappingPairCache()->setInternalGhostPairCallback(new btGhostPairCallback());
I am also using a .bullet file imported from blender, if that is relevant.
The issue was with the bullet file, which has since been fixed(the collision boxes weren't working). However, I still experience jitteryness, unable to step up occasionally, instant step down from to high a height, and other issues.
My answer to this question here tells you what worked well for me and apparently also for the person who asked.
Avoid ground collision with Bullet
The character controller implementations in bullet are very "basic" unfortunately.
To get good character controller, you'll need to invest this much.
Can somebody point me in the right direction of how to draw a multiple lines that seem connected? I found vtkLine and its SetPoint1 and SetPoint2 functions. Then I found vtkPolyLine, but there doesn't seem to be any add, insert or set function for this. Same for vtkPolyVertex.
Is there a basic function that allows me to just push some point at the end of its internal data and the simply render it? Or if there's no such function/object, what is the way to go here?
On a related topic: I don't like vtk too much. Is there a visualization toolkit, maybe with limited functionality, that is easier to use?
Thanks in advance
For drawing multiple lines, you should first create a vtkPoints class that contains all the points, and then add in connectivity info for the points you would like connected into lines through either vtkPolyData or vtkUnstructuredGrid (which is your vtkDataSet class; a vtkDataSet class contains vtkPoints as well as the connectivity information for these points). Once your vtkDataSet is constructued, you can take the normal route to render it (mapper->actor->renderer...)
For example:
vtkPoints *pts = vtkPoints::New();
pts->InsertNextPoint(1,1,1);
...
pts->InsertNextPoint(5,5,5);
vtkPolyData *polydata = vtkPolyData::New();
polydata->Allocate();
vtkIdType connectivity[2];
connectivity[0] = 0;
connectivity[1] = 3;
polydata->InsertNextCell(VTK_LINE,2,connectivity); //Connects the first and fourth point we inserted into a line
vtkPolyDataMapper *mapper = vtkPolyDataMapper::New();
mapper->SetInput(polydata);
// And so on, need actor and renderer now
There are plenty of examples on the documentation site for all the classes
Here is vtkPoints : http://www.vtk.org/doc/release/5.4/html/a01250.html
If you click on the vtkPoints (Tests) link, you can see the tests associated with the class. It provides a bunch of different sample code.
Also, the vtk mailing list is probably going to be much more useful than stack overflow.