How Can I merge complex shapes stored in an ArrayList with Geomerative Library - arraylist

I store shapes of this class:
class Berg{
int vecPoint;
float[] shapeX;
float[] shapeY;
Berg(float[] shapeX, float[] shapeY, int vecPoint){
this.shapeX = shapeX;
this.shapeY = shapeY;
this.vecPoint = vecPoint;
}
void display(){
beginShape();
curveVertex(shapeX[vecPoint-1], shapeY[vecPoint-1]);
for(int i=0;i<vecPoint;i++){
curveVertex(shapeX[i], shapeY[i]);
}
curveVertex(shapeX[0],shapeY[0]);
curveVertex(shapeX[1],shapeY[1]);
endShape();
}
}
in an ArrayList with
shapeList.add(new Berg(xBig,yBig,points));
The shapes are defined with eight (curveVertex-)points (xBig and yBig) forming a shape around a randomly positioned center.
After checking if the shapes are intersecting I want to merge the shapes that overlap each other. I already have the detection of the intersection working but struggle to manage the merging.
I read that the library Geomerative has a way to do something like that with union() but RShapes are needed as parameters.
So my question is: How can I change my shapes into the required RShape type? Or more general (maybe I did some overall mistakes): How Can I merge complex shapes stored in an ArrayList with or without Geomerative Library?

Take a look at the API for RShape: http://www.ricardmarxer.com/geomerative/documentation/geomerative/RShape.html
That lists the constructors and methods you can use to create an RShape out of a series of points. It might look something like this:
class Berg{
public RShape toRShape(){
RShape rShape = new rShape();
for(int i = 0; i < shapeX; i++){
rShape.addLineto(shapeX[i], shapeY[i]);
}
}
}

Related

How to efficiently marshal array of objects to native function using C++/CLI

I have array of objects holding primitive types and enums; how do I marshal a pointer to this data to a native function with the signature native_func(void* ptr[]).
array<System::Object^>^ values = gcnew array<System::Object>(64);
// ... populate the managed array with primitives ...
// data is pinned and won't be moved by the GC
pin_ptr<object> pinned = &values[0];
// not sure what do here... data is corrupted in the native code
native_func((void**)pinned);
Thanks!
EDIT. My second attempt was to do the following:
pin_ptr<object> pinned = &values[0];
void* testArray[64];
for (auto i = 0; i < values->Length; i++)
{
testArray[i] = (void*)Marshal::UnsafeAddrOfPinnedArrayElement(values, i);
}
native_func(testArray);
Now, the addresses stored in testArray are getting passed correctly to the native side but the contents of the memory is not what I am expecting. What am I doing wrong now?
Enums are not blittable so marshaling an array of objects require special consideration (i.e. you can't just pin_ptr the array and pass it over the native/managed boundary). I decided to use a VARIANT to hold the primitive & enum values and did so with the following code:
// allocate a managed array of size 64 (it's enough for my application)
array<System::Object^>^ values = gcnew array<System::Object>(64);
// stack allocate a native array of size 64
VARIANT nativeValueArray[64] = {};
// ... populate the managed array ...
for (auto i = 0; i < values->Length; i++)
{
Marshal::GetNativeVariantForObject(values[i], (IntPtr)(void*)&nativeValueArray[i]);
}
// pass the array of native VARIANTS to the native function "native_function"
native_function(nativeValueArray);
The native function's signature became
void native_function(VARIANT values[]);
There might be a more efficient way to do this but this is what I was able to come up with. Please let me know if you have a more efficient way to accomplish what am I doing.

Built-in variables not usable in certain cases (Processing 3)

I've been building a program with Processing 3 the last several days (first time going back to Processing since Intro to Computer Science in 2009) and kept having this issue:
public class PolarMap {
...
PVector[][] mapping = new PVector[width][height];
PVector[][] cartesian = new PVector[width][height];
PVector cart = new PVector();
PVector polar = new PVector();
/**
Maps every pixel on the cartesian plane to a polar coordinate
relative to some origin point.
*/
public void Map(float originX, float originY){
for (int x=0; x < width; x++){
for (int y=0; y < height; y++){
...
cart.add(x, y);
polar.add(r, theta);
mapping[x][y] = polar; ***
cartesian[x][y] = cart;
}
}
}
...
}
On the line with the ***, I would always get an Array Index Out Of Bounds thrown. I searched SO, Reddit, and Processing's own documentation to figure out why. If you're not familiar with Processing, width and height are both built-in variables and are equal to the number of pixels high and across your canvas is as declared in the setup() method (800x800 in my case). For some reason, both arrays were not being initialized to this value--instead, they were initializing to the default value of those variables: 100.
So, because it made no sense but it was one of those times, I tried declaring new variables:
int high = height;
int wide = width;
and initialized the array with those variables. And wouldn't you know it, that solved the problem. I now have two 800x800 arrays.
So here's my question: WHY were the built-in variables not working as expected when used to initialize the arrays, but did exactly what they were supposed to when assigned to a defined variable?
Think about when the width and height variables get their values. Consider this sample sketch:
int value = width;
void setup(){
size(500, 200);
println(value);
}
If you run this program, you'll see that it prints 100, even though the window is 500 pixels wide. This is because the int value = width; line is happening before the width is set!
For this to work how you'd expect, you have to set the value variable after the size() function is called. So you could do this:
int value;
void setup(){
size(500, 200);
value = width;
println(value);
}
Move any initializations to inside the setup() function, after the size() function is called, and you'll be fine.

remove objects from arraylist is doing strange things

In the code below, i want the balls to change from ArrayList ballList to another ArrayList oldBalls as soon as their age turns higher than a threshold value.
This code should be very simple but i can't figure out why when the age is same as the threshold (not larger) they disappear and then they come back 2 frames later.
I have checked related questions using iterators for ArrayLists in java but i think there should be a way to do this in processing without java.
Also i cant seem to post any question on the processing forum even though i can sign in, no idea why...
I have reduced the code to the minimum able to reproduce the error.
ArrayList <Ball> ballList;
ArrayList <Ball> oldBalls;
int threshold=4;
PFont font;
void setup(){
size(400,400);
frameRate(0.5);
font=createFont("Georgia", 18);
textFont(font);
textAlign(CENTER, CENTER);
ballList=new ArrayList<Ball>();
oldBalls=new ArrayList<Ball>();
noFill();
strokeWeight(2);
}
void draw(){
background(0);
Ball b=new Ball(new PVector(10, random(height/10,9*height/10)),new PVector(10,0),0);
ballList.add(b);
stroke(0,0,200);
for(int i=0;i<oldBalls.size();i++){
Ball bb=oldBalls.get(i);
bb.update();
bb.render();
text(bb.age,bb.pos.x,bb.pos.y);
}
stroke(200,0,0);
for(int i=0;i<ballList.size();i++){
Ball bb=ballList.get(i);
bb.update();
bb.render();
bb.migrate();
text(bb.age,bb.pos.x,bb.pos.y);
}
}
class Ball{
PVector pos;
PVector vel;
int age;
Ball(PVector _pos, PVector _vel, int _age){
pos=_pos;
vel=_vel;
age=_age;
}
void migrate(){
if(age>threshold){
oldBalls.add(this);
ballList.remove(this);
}
}
void update(){
pos.add(vel);
age+=1;
}
void render(){
ellipse(pos.x,pos.y,24,24);
}
}
Note how balls labelled with age=threshold suddenly disappear...
i guess the problem is here:
for(int i=0;i<ballList.size();i++){
Ball bb=ballList.get(i);
bb.update();
bb.render();
//add this
if(bb.migrate())
i--;
text(bb.age,bb.pos.x,bb.pos.y);
}
and
boolean migrate(){
if(age>threshold){
oldBalls.add(this);
ballList.remove(this);
//and this
return true;
}
return false;
}
migrate() will remove the object from the ballList and reduce it's size by 1.
What it looks like is happening here is because you're altering the List's whilst iterating through them. Consider this for loop you have here
for(int i=0;i<ballList.size();i++){
Ball bb=ballList.get(i);
bb.update();
bb.render();
bb.migrate();
text(bb.age,bb.pos.x,bb.pos.y);
}
Say ballList has 2 balls in it both age 3, the first loops gets ball[0] and then removes it from the list, i will increment and the loop will immediately exit because ballList.size() is now 1. So it's not the ball which gets to age 4 that vanishes but the subsequent one.

MultiScaleImageSource GetTileLayers Explanation

I have been doing reading on MultiScaleImage source, and finding anything useful has proven to be quite difficult, thus I turn to the experts here. The specific knowledge I would like to have pertains to the GetTileLayers method. I know this method is used to get the image tiles. But I have no idea where this method is called from, or where the parameters come from or how I would use it if I subclassed the MultiScaleTileSource Class. Any insight into this method or the MSI model would be amazing but I have 3 main questions:
1. Where should/is the method GetTileLayers called from?
2. How should I change this method if I wanted to draw png's from a non-local URI?
3. Where can I find some reading to help with this?
In order to create a custom tile source, you would subclass MultiScaleTileSource and override the GetTileLayers method, as shown in the example below, which defines an image consisting of 1000*1000 tiles of size 256x256 pixels each.
public class MyTileSource : MultiScaleTileSource
{
public MyTileSource()
: base(1000 * 256, 1000 * 256, 256, 256, 0)
{
}
protected override void GetTileLayers(
int tileLevel, int tilePositionX, int tilePositionY,
IList<object> tileImageLayerSources)
{
// create an appropriate URI for tileLevel, tilePositionX and tilePositionY
// and add it to the tileImageLayerSources collection
var uri = new Uri(...);
tileImageLayerSources.Add(uri);
}
}
Now you would assign an instance of your MyTileSource class to your MultiScaleImage control:
MultiScaleImage msImage = ...
msImage.Source = new MyTileSource();

How do I use Strategy Pattern in this context?

Let me begin by saying I am a mathematician and not a coder. I am trying to code a linear solver. There are 10 methods which I coded. I want the user to choose which solver she wishes to use, like options.solver_choice='CG'.
Now, I have all 10 methods coded in a single class. How do I use the strategy pattern in this case?
Previously, I had 10 different function files which I used to use in the main program using a switch case.
if options.solver_choice=='CG'
CG(A,x,b);
if options.solver_choice=='GMRES'
GMRES(A,x,b);
.
.
.
This isn't the most exact of answers, but you should get the idea.
Using the strategy pattern, you would have a solver interface that implements a solver method:
public interface ISolver {
int Solve();
}
You would implement each solver class as necessary:
public class Solver1 : ISolver {
int Solve() {
return 1;
}
}
You would then pass the appropriate solver class when it's time to do the solving:
public int DoSolve(ISolver solver) {
return solver.solve();
}
Foo.DoSolve(new Solver1());
TL;DR
As I've always understood the strategy pattern, the idea is basically that you perform composition of a class or object at run-time. The implementation details vary by language, but you should be able to swap out pieces of behavior by "plugging in" different modules that share an interface. Here I present an example in Ruby.
Ruby Example
Let's say you want to use select a strategy for how the #action method will return a set of results. You might begin by composing some modules named CG and GMRES. For example:
module CG
def action a, x, b
{ a: a, x: x, b: b }
end
end
module GMRES
def action a, x, b
[a, x, b]
end
end
You then instantiate your object:
class StrategyPattern
end
my_strategy = StrategyPattern.new
Finally, you extend your object with the plug-in behavior that you want. For example:
my_strategy.extend GMRES
my_strategy.action 'q', nil, 1
#=> ["q", nil, 1]
my_strategy.extend GMRES
my_strategy.action 'q', nil, 1
#=> {:a=>"q", :x=>nil, :b=>1}
Some may argue that the Strategy Pattern should be implemented at the class level rather than by extending an instance of a class, but this way strikes me as easier to follow and is less likely to screw up other instances that need to choose other strategies.
A more orthodox alternative would be to pass the name of the module to include into the class constructor. You might want to read Russ Olsen's Design Patterns in Ruby for a more thorough treatment and some additional ways to implement the pattern.
Other answers present the pattern correctly, however I don't feel they are clear enough. Unfortunately the link I've provided does the same, so I'll try to demonstrate what's the Strategy's spirit, IMHO.
Main thing about strategy is to have a general procedure, with some of its details (behaviours) abstracted, allowing them to be changed transparently.
Consider an gradient descent optimization algorithm - basically, it consists of three actions:
gradient estimation
step
objective function evaluation
Usually one chooses which of these steps they need abstracted and configurable. In this example it seems that evaluation of the objective function is not something that you can do in more than one way - you always just ... evaluate the function.
So, this introduces two different strategy (or policy) families then:
interface GradientStrategy
{
double[] CalculateGradient(Function objectiveFunction, double[] point);
}
interface StepStrategy
{
double[] Step(double[] gradient, double[] point);
}
where of course Function is something like:
interface Function
{
double Evaluate(double[] point);
}
interface FunctionWithDerivative : Function
{
double[] EvaluateDerivative(double[] point);
}
Then, a solver using all these strategies would look like:
interface Solver
{
double[] Maximize(Function objectiveFunction);
}
class GradientDescentSolver : Solver
{
public Solver(GradientStrategy gs, StepStrategy ss)
{
this.gradientStrategy = gs;
this.stepStrategy = ss;
}
public double[] Maximize(Function objectiveFunction)
{
// choosing starting point could also be abstracted into a strategy
double[] currentPoint = ChooseStartingPoint(objectiveFunction);
double[] bestPoint = currentPoint;
double bestValue = objectiveFunction.Evaluate(bestPoint);
while (...) // termination condition could also
// be abstracted into a strategy
{
double[] gradient = this.gradientStrategy.CalculateGradient(
objectiveFunction,
currentPoint);
currentPoint = this.stepStrategy.Step(gradient, currentPoint);
double currentValue = objectiveFunction.Evaluate(currentPoint);
if (currentValue > bestValue)
{
bestValue = currentValue;
bestPoint = currentPoint;
}
else
{
// terminate or step back and reduce step size etc.
// this could also be abstracted into a strategy
}
}
return bestPoint;
}
private GradientStrategy gradientStrategy;
private StepStrategy stepStrategy;
}
So the main point is that you have some algorithm's outline, and you delegate particular, general steps of this algorithm to strategies or policies. Now you could implement GradientStrategy which works only for FunctionWithDerivative (casts down) and just uses function's analytical derivative to obtain the gradient. Or you could have another one implementing stochastic version of gradient estimation. Note, that the main solver does not need to know about how the gradient is being calculated, it just needs the gradient. The same thing goes for the StepStrategy - it can be a typical step policy with single step-size:
class SimpleStepStrategy : StepStrategy
{
public SimpleStepStrategy(double stepSize)
{
this.stepSize = stepSize;
}
double[] Step(double[] gradient, double[] point)
{
double[] result = new double[point.Length];
for (int i = 0;i < result.Length;++i)
{
result[i] = point[i] + this.stepSize * gradient[i];
}
return result;
}
private double stepSize;
}
, or a complicated algorithm adjusting the step-size as it goes.
Also think about the behaviours noted in the comments in the code: TerminationStrategy, DeteriorationPolicy.
Names are just examples - they're probably not the best, but I hope they give the intent. Also, usually best to stick with one version (Strategy or Policy).
PHP Examples
You'd define your strategies that implement only singular method called solve()
class CG
{
public function solve($a, $x, $y)
{
//..implementation
}
}
class GMRES
{
public function solve($a, $x, $y)
{
// implementation..
}
}
Usage:
$solver = new Solver();
$solver->setStratery(new CG());
$solver->solve(1,2,3); // the result of CG
$solver->setStrategy(new GMRES());
$solver->solve(1,2,3); // the result of GMRES
class Solver
{
private $strategy;
public function setStrategy($strategy)
{
$this->strategy = $strategy;
}
public function solve($a, $x, $y)
{
return $this->strategy->solve($a, $x, $y);
}
}