Find crossing lines in drawing engine - algorithm

i am working on a little multimedia - project in which the user, amongst other things, can draw shapes on a canvas (2d) by connecting points with a line.
but i need to prohibit the user from crossing lines.
what i am looking for would be a small algorithm that can find intersecting lines.
the project is done in AS3/Flash but i guess the answer would be universal.
anyone can give me a clue?
thanks

Here is an example in Java but I think you can easily adapt to AS3 :
public static boolean intersects(double ax, double ay, double bx, double by,
double cx, double cy, double dx, double dy) {
double denum = ((bx-ax)*(dy-cy)-(by-ay)*(dx-cx));
if (denum == 0) return false; // parallel segments
double r = ((ay-cy)*(dx-cx)-(ax-cx)*(dy-cy)) / denum;
double s =
((ay-cy)*(bx-ax)-(ax-cx)*(by-ay)) / denum;
return 0<=r && r<=1 && 0<=s && s<=1;
}
It should return true if the segments [AB] and [CD] intersect.
You can find reference here

You can use the methods Point, hitTest, hitTestObject or hitTestPoint. I don't know if Super Chafouin's answer is helpful, but I believe that the code looks quite different in AS3 though.
To explain what they mean, I'll quote Aaron Beall from actionscript.org, giving a nice explanation:
hitTestObject checks the bounding box rectangle of two display
objects. It always checks rectangle-vs-rectangle.
hitTestPoint checks a point (x,y) against a display object:
- With shapeFlag true it checks point-vs-shape
- With shapeFlag false it checks point-vs-rectangle
BitmapData/hitTest checks a bitmap against a point, rectangle, or
other bitmapdata. Using a check of bitmapdata-vs-bitmapdata means you
can perform alpha channel based shape-vs-shape checks. See here:
http://www.mikechambers.com/blog/200...ion-detection/
(Also, not to nitpick but just to make sure you understand, neither
hitTestObject or hitTestPoint are "triggered" -- you must manually
call them when you want to check something.)
Asking for a whole algorithm is quite something, it depends on your app too.
See for more examples and documentation here, here
I hope this will help!

Related

Parameters for dlib::find_min_bobyqa

I'm working on the C++ version of Matt Zucker's Page dewarping. So far everything works fine, but I have a problem with optimization. In line 748 of Github repo Matt uses optimize function from Scipy. My C++ equivalent is find_min_bobyqa from dlib.net. The code is:
auto f = [&](const column_vector& ppts) { return objective( dstpoints, ppts, keypoint_index); };
dlib::find_min_bobyqa(f,
params,
2 * params.nr() + 1, // npt - number of interpolation points: x.size() + 2 <= npt && npt <= (x.size()+1)*(x.size()+2)/2
dlib::uniform_matrix<double>(params.nr(), 1, -2), // lower bound constraint
dlib::uniform_matrix<double>(params.nr(), 1, 2), // upper bound constraint
1, // initial trust region radius
1e-5, // stopping trust region radius
4000 // max number of objective function evaluations
);
In my concrete example params is a dlib::column_vector with double values and length = 189. Every element of params is less than 2.0 and greater than -2.0. Function objective() returns double value and "alone" it works properly because I get the same value as in the Python version. But after running fin_min_bobyqa function I usually get the message:
Terminate called after throwing an instance of 'dlib:bobyqa_failure', return from BOBYQA because the objective function has been called max_f_evals times.
I set max_f_evals to quite big value to see if it optimizes at all, but it doesn't. I did some tweaking with parameters but without good results. How should I set the parameters of find_min_bobyqa to get the right solution?
I am very interested in this issue as well. Zucker's work, with very minor tweaks, is ideal for straightening sheet music images, and I was looking for ways to implement it in a mobile platform when I came across your question.
My research so far suggests that BOBYQA is not the equivalent of Powell's method in scipy. BOBYQA is constrained, and the one in scipy is not.
See these links for more information, and a possible way to compile the right supporting library - I would try UOBYQA or NEWUOA.
https://github.com/jacobwilliams/PowellOpt
https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html#rdd2e1855725e-3
(See the Notes section)
EDIT: see C version here:
https://github.com/emmt/Algorithms/tree/master/newuoa
I wanted to post this as a comment, but I don't have enough points for that.
I am very interested in your progress. If you're willing, please keep me posted.
I finally solved this problem. I used PRAXIS library, because it doesn't need derivative information and is fast.
I modified the code a little to my needs and now it is faster around few seconds than original version written in Python.

GameMaker studio 2. Player Knockback

trying to create a player damage indication when a collision with an enemy occurs.
I used this code within a collision event of the player object:
direction = point_direction(other.x,other.y,x,y);
hsp = lengthdir_x(6,direction);
vsp = lengthdir_y(4,direction)-2;
if (sign(hsp) !=0) image_xscale = sign(hsp);
However, the player object is simply pushed upward vertically rather than backwards in a parabola.
Any, ideas on how to implement a basic knockback system?
If you want a parabola, you can add an upward force afterward, like so:
direction = point_direction(other.x, other.y, x , y);
speed = 6
motion_add(90, 3)
If you don't and you'd rather a more "repeatable" parabola that always look the same, maybe you should use another method, something like
if other.x>x {hdirection=1}else{hdirection=-1}
hspeed = hdirection*6
vspeed = -2
I believe this would work better for what you're trying to achieve, unless you want to implement knockback variable depending on the angle of collision.
So I would need to see all the rest of your player physics to be sure, but I can tell you right now that direction = point_direction(other.x,other.y,x,y); is probable not what you mean, and same goes for lengthdir(). The exact origins of the colliding objects at the moment of collision have a huge effect on what that direction is, which can cause a lot of screwiness. For example: if the line is perfectly horizontal (because other.y == y) then lengthdir_y() will always be equal to zero for any input value no matter how huge.
But more importantly direction is a built-in variable of GameMaker, so using it with a custom physics system can also cause some screwiness. Fox's answer might help if you are using built-ins, but based on the fact that you have an "hsp" and "vsp" instead of hspeed and vspeed, my guess is you want to avoid built-ins.
If you just want to get the horizontal direction of the collision, you should use sign(x - other.x). Then, instead of using lengthdir(), you can just use a constant. Here it is all together:
var dir = sign(x - other.x)
hsp = 6*dir; //I'm assuming that 6 is how much horizontal you wanted
vsp = -4;
if (sign(hsp) !=0) image_xscale = sign(hsp); //This line could just go in your step event
Hope that helps! Feel free to comment if you have more questions.

dlib: extract_histogram_descriptors inside extract_highdim_face_lbp_descriptors returns vector with zeros

I'm trying to extract this features, but it is returning a vector with all zeros. I called the function dlib::extract_highdim_face_lbp_descriptors and followed the code and it seems that is extract_histogram_descriptors is what it is returning zeros.
So I hope anyone can help, it would be highly appreciated.
Thanks
This are the important lines of my code:
std::vector features;
dlib::array2d<unsigned char> grayFace;
dlib::assign_image(grayFace, face);
dlib::extract_highdim_face_lbp_descriptors<dlib::array2d<unsigned char>, double>(grayFace, shape, features);
face is an array2D containing the recognized face, shape is of type dlib::full_object_detection.
I have also check that grayFace and shape are correct.
Ok, finally I could solve this problem, I post the answer in case someone has the same problem.
The thing is that as first argument, dlib::extract_highdim_face_lbp_descriptors expects the hole frame image, not just the found face which is what I was given to it.

THREE.js Migration r60 to r70: now cannot write: mesh.position = myVector3()

I am migrating a THREE.js app from r60 to r70. Amongst other changes I notice that r60 constructs of the following form no longer work in r70.
mesh.position.set(0,0,0);
myVector3 = new THREE.Vector3 (100,200,300);
mesh.position = myVector3;
This applies to meshes, pointLights, presumably to all Object3D's but I havent tested further.
In the above example the mesh.position x,y,z values remain unchanged at (0,0,0). For illustration see this JSFiddle and compare lines 70 and 73.
//...The next line DOES NOT update Sphere_mesh.position.x
Sphere_mesh.position = NewPos_vector3;//...
//...The next line DOES update Sphere_mesh.position.x
Sphere_mesh.position.x = NewPos_vector3.x
In a debugger no console warning is given during execution that the assignment has not worked. In the very brief THREE.js migration notes for (r68 --> r69) I see something about an Object3D's position no longer being immutable but I don't know what that means.
Anyway, my question
Is there a standard THREE construct or function I can use to copy x,y,z values from a Vector3 object to the x,y,z values of a mesh.position rather than the effective, but verbose, form such as
mesh.position.x = myVector3.x;
mesh.position.y = myVector3.y;
mesh.position.z = myVector3.z; ?
e.g. something such as
mesh.position = F_Get_Object3DPosition_from_Vector3(myVector3); ?
I know it would be easy to write my own function but a standard THREE function would be more likely to evolve smoothly with future versions of THREE.
position beeing immutable means that the position property can not be changed.
so
mesh.position = anything;
won't work (but you already discovered this)
what you can do is not change the position, but you have to change position values.
in your case, the easiest way is
mesh.position.copy (myVector3);
I think you meant myVector3 not myVector3() in the last line... Anyway, I though that would work too but the thing is, you are applying a Vector to something that supposed to be a point/Vertex. Even if that worked in my opinion it wasn't the right way to do it. How about using a simple array:
mesh.position.set(0,0,0);
new_position = [100,200,300]
mesh.position.fromArray(new_position,0)
in which 0 is the starting index. So you can have multiple position sets in one array

Validation testing: how to validate a UI?

I have been asked to implement validation tests on the javascript part of our website. I've been considering using selenium WebDriver. One of the things we want to test is the UI: check whether it "looks" good (things that must be aligned are aligned, boxes are in the right position).
For the moment, the only option I found was to take a snapshot using Selenium, and either compare it to a test snapshot manually taken beforehand, or check the snapshots manually. The snapshot comparison is not very maintainable, as any change in the layout requires all the test snapshots to be taken again, and the manual check is very time consuming.
Does anyone know of any way (in Selenium or other) to achieve this?
It's not nice, but it can be done to some extent.
For positioning, you can use WebElement's getLocation() (Java doc, but the same method exists in all Selenium bindings). Note that most browsers render slightly differently, so do not expect things to be pixel-perfect when working with older IE. Also, things might be positioned slightly differently when e.g. the first font defined in CSS was not found and an alternative was used. Don't rely heavily on this method. But if you'll be able to make your tests sane and your environment stable, it will work.
For aligning, I wrote a simple Java method for WebDriver that asserts that an element is visually inside of another element.
There should be no false negatives, but there could be some false positives in the case when the inner element is visually inside, but its (invisible) actual borders "peek out". I haven't bumped into this problem, however, in my real experience, since nice websites behave nicely and don't need such hacks :). Still, it's kinda hackish and Selenium wasn't designed for this type of work, so it might be harder to implement more complex checks.
public static void assertContains(WebElement outerElem, WebElement innerElem) {
// get borders of outer element
Point outerLoc = outerElem.getLocation();
Dimension outerDim = outerElem.getSize();
int outerLeftX = outerLoc.getX();
int outerRightX = outerLeftX + outerDim.getWidth();
int outerTopY = outerLoc.getY();
int outerBottomY = outerTopY + outerDim.getHeight();
// get borders of inner element
Point innerLoc = innerElem.getLocation();
Dimension innerDim = innerElem.getSize();
int innerLeftX = innerLoc.getX();
int innerRightX = innerLeftX + innerDim.getWidth();
int innerTopY = innerLoc.getY();
int innerBottomY = innerTopY + innerDim.getHeight();
// assures the inner borders don't cross the outer borders
final String errorMsg = "ughh, some error message";
final boolean contains = (outerLeftX <= innerLeftX)
&& (innerRightX <= outerRightX)
&& (outerTopY <= innerTopY)
&& (innerBottomY <= outerBottomY);
assertTrue(errorMsg, contains);
}
If you use term validation in meaning: "Test that we have built the right thing", I would say it is nearly impossible to automate this. How will you judge if it looks pleasing or that it is easy to use, if not by having some people to really use it?
This kind of visual checks are also something humans are good at. If you use the website at all while developing it, you will notice quite easily if there is something fishy with the layouts and such.
For functionalities automated tests are good idea.

Resources