How to transition between two images using a grayscale transition map - language-agnostic

Imagine you have two images A and B, and a third grayscale image T. A and B contain just about anything, but let's assume they're two scenes from a game.
Now, assume that T contains a diamond gradient. Being grayscale, it goes from black on the outside to white on the inside.
Over time, let's assume 256 not further elaborated on "ticks" to match the grayscales, A should transition into B giving a diamond-wipe effect. If T instead contained a grid of smaller rectangular gradients, it would be like each part of the image by itself did a rectangular wipe.
You might recognize this concept if you've ever worked with RPG Maker or most visual novel engines.
The question ofcourse is how this is done. I know it involves per-pixel blending between A and B, but that's all I got.
For added bonus, what about soft edges?
And now, the conclusion
Final experiment, based on eJames's code
Sample from final experiment -- waves up, 50% http://helmet.kafuka.org/TransitionsSample.png

The grayscale values in the T image represent time offsets. Your wipe effect would work essentially as follows, on a per-pixel basis:
for (timeIndex from 0 to 255)
{
for (each pixel)
{
if (timeIndex < T.valueOf[pixel])
{
compositeImage.colorOf[pixel] = A.colorOf[pixel];
}
else
{
compositeImage.colorOf[pixel] = B.colorOf[pixel];
}
}
}
To illustrate, imagine what happens at several values of timeIndex:
timeIndex == 0 (0%): This is the very start of the transition. At this point, most of the pixels in the composite image will be those of image A, except where the corresponding pixel in T is completely black. In those cases, the composite image pixels will be those of image B.
timeIndex == 63 (25%): At this point, more of the pixels from image B have made it into the composite image. Every pixel at which the value of T is less than 25% white will be taken from image B, and the rest will still be image A.
timeIndex == 255 (100%): At this point, every pixel in T will negate the conditional, so all of the pixels in the composite image will be those of image B.
In order to "smooth out" the transition, you could do the following:
for (timeIndex from 0 to (255 + fadeTime))
{
for (each pixel)
{
blendingRatio = edgeFunction(timeIndex, T.valueOf[pixel], fadeTime);
compositeImage.colorOf[pixel] =
(1.0 - blendingRatio) * A.colorOf[pixel] +
blendingRatio * B.colorOf[pixel];
}
}
The choice of edgeFunction is up to you. This one produces a linear transition from A to B:
float edgeFunction(value, threshold, duration)
{
if (value < threshold) { return 0.0; }
if (value >= (threshold + duration)) { return 1.0; }
// simple linear transition:
return (value - threshold)/duration;
}

I'd say you start with image A, then on every step I you use the pixels of image A for every position where T is smaller than I, and pixels of the image B otherwise.
For a soft edge you might define another parameter d, and calculate you pixels P like so:
For every point (x,y) you decide between the following three options:
I < T(x,y) - d then the point is equal to the point of A
T(x,y) - d <= I < T(x,y) + d then let z = I - (T(x,y) -d) and the point is equal to A(x,y)(1-z/(2d)) + B(x,y)(z/(2d))
I < T(x,y) + d then the point is equal to the point of B
This produces a linear edge, of course you can chose between an arbitrary number of functions for the edge.

Related

How to rotate triangle such that its base is flat straight?

considering my English is not very good. I will try to use picture
Hopefully you can get what I mean. Basically what I want is I want to rotate the triangle such that the base of the triangle is flat straight ( horizontally straight). Keep in mind, that the triangle is a shape. and I know the coordinate of each point, and each midpoint of each edges. How would I do that?
(1)
"Basically what I want is to rotate the triangle such that the
base of the triangle is flat straight (horizontally straight)."
You can simply set as point_C.y = point_B.y (this will put point C on same vertical height as point B so that now, a horizontal line between those two points will be a straight line.
(2)
"The point the triangle is formed by mouse click. Each mouse click, I
make point at (mouseX, mouseY). So, the triangle could be totally random."
I would make a var to keep count of clicks...
//# count clicks to know when straight line is needed
public var count_Clicks :uint = 0;
//# straight line via "IF" statement
private function draw_Triangle_Point (evt :MouseEvent) : void
{
count_Click += 1; //add plus 1
if (count_Clicks == 3)
{
point_C.x = stage.mouseX;
point_C.y = point_B.y; //straight (horiz) line
count_Clicks = 0; //reset
}
else
{
//draw your other two points
}
}
Hope it helps.
This seems to be an equilateral triangle so could you not just rotate the triangle 120 degrees?
If not you could use Math.atan. So plainly put you can get the x and y coordinates of a and c. Use the difference between the x's and y's to give you two vectors. Then x = adjacent, y = opposite and so Math.atan(Opp, Adj) = angle. Then select your object and rotate it an extra value of angle.
https://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/Math.html#atan()
Think thats what you're after
Edit
So this image is what I think you are after. I randomly drew a triangle. Now you want B.y = C.y. So if you get the angle of r you should be able to use that to rotate the triangle the correct amount so that B.y = C.y.
You will have to consider what if B.y > C.y and adapt this to make it work 100%, but in this example this should work.

Does a programming language with the following features exist?

Is there a language which will support the following concept or is there a pattern to achieve something similar with existing one?
Concept
I want to define a Rectangle with the following properties: Length, Height, Area, Perimeter; where Area = Length * Height and Perimeter = (2 * Length) + (2 * Height).
Given the statement above, if I want to create a Rectangle by giving it a Length and a Height, it should of course automatically fill out the rest of the properties.
However, it should go further and automatically allow you to create a Rectangle with any two properties (say Height and Perimeter) because that is also mathematically enough to create the same Rectangle.
Example
To help explain the idea, take this example:
//Declaration
Rectangle
{
Height, Length, Area, Perimeter;
Area = Height * Length;
Perimeter = (2 * Length) + (2 * Height);
}
//Usage
main()
{
var rectangleA = new Rectangle(Height, Length);
var rectangleB = new Rectangle(Height, Area);
Assert(rectangleA == rectangleB);
}
Notice how I didn't need to define constructors for Rectangle. Notice I did not need specify the specific logic needed if a Rectangle was created using Height and Area.
Edit: Should be rectangle and not a square for a proper example.
What you are looking for is a language with an integrated computer algebra system. It has to be able to resolve equations with respect to different variables.
While it would be possible to implement something like this, I doubt that it would make sense because in many cases there will be either no solution or multiple solutions.
Even your simple example will not work if only area and perimeter are given because there will usually be two solutions. (I assume that your class actually represents a rectangle and not a square, otherwise you should not have separate variables for length and height.)
Example:
Input: area = 2, perimeter = 6
Solution 1: length = 2, height = 1
Solution 2: length = 1, height = 2
Another remark not really related to your question: Your class obviously contains redundant member variables. This is a bad thing for various reasons, the most important being the possibility of inconsistencies. Unless you have very strict performance constraints, you should store only two of them, say length and width, and provide methods to calculate the others when needed.
Of course such a language exists. Many do, as you've now pointed out in your own comment to this answer.
In the example below I'll be using the Powerloom representation system, implemented in a language called STELLA.
You can play with it from within a Common Lisp environment.
Once you have everything installed you can load the language by running:
(cl:load "load-powerloom.lisp")
(in-package "STELLA")
(in-dialect "KIF")
That's about all you need to start building awesome geometrical objects.
Within STELLA you may define a concept with the primitive defconcept:
(defconcept Rectangle (?r)
:documentation "Curious geometrical objects that live on a plane.")
And define its properties with deffunction:
(deffunction rect-height ((?t Rectangle)) :-> (?n INTEGER))
(deffunction rect-length ((?t Rectangle)) :-> (?n INTEGER))
(deffunction area ((?t Rectangle)) :-> (?n INTEGER))
(deffunction perimeter ((?t Rectangle)) :-> (?n INTEGER))
To make the relations between area, perimeter and the sides of your rectangle, you'll have to make some assertions. That's what you'll have assert for.
(assert (forall (?t Rectangle)
(= (area ?t) (* (rect-height ?t) (rect-length ?t)))))
(assert (forall (?t Rectangle)
(= (perimeter ?t) (+ (* 2 (rect-height ?t))
(* 2 (rect-length ?t))))))
You are telling STELLA that for all rectangles, the area is the product of height and length, and that for all rectangles, the perimeter is twice the height plus twice the length.
Now you can instantiate your objects, and it doesn't matter what properties you give it, as long as they make sense.
(definstance rect1 :Rectangle true :rect-height 10 :rect-length 10)
(definstance rect2 :Rectangle true :area 40 :rect-height 20)
Here you instantiate rect1 with height and length as parameters, and rect2 with area and height.
But its always good to check that the language is doing what you expect:
STELLA> (retrieve all ?x (= (area rect1) ?x))
There is 1 solution:
#1: ?X=100
STELLA> (retrieve all ?x (= (rect-length rect2) ?x))
There is 1 solution:
#1: ?X=2
If you ever get tired of rectangles and decide to build a beautiful square, why not derive a concept?
(defconcept Square ((?r Rectangle))
:documentation "Weird rectangles that fascinated the Greeks"
:<=> (= (rect-height ?r) (rect-length ?r)))
Simply tell STELLA that squares are rectangles where height and length are equal.
Now try it out:
STELLA> (definstance nice-rectangle :Rectangle true :rect-length 10 :area 100)
|i|NICE-RECTANGLE
STELLA> (ask (Square nice-rectangle))
TRUE
I'm not an expert at all, but I find the language fascinating. It's sad that there is so little information about it on the internet. Even the manual is incomplete.
For more information I'd suggest starting with these slides.
The famous book SICP teaches how to build a nondeterministic evaluator for such a language here.
And finally, a wonderful write up describing motivations and applications behind these ideas can be seen here.
In C#, you can use properties, which have implicit getters and setters. That way you can write something like:
public class Square {
public int Length {
get { return length; }
set { length = value; }
}
public int Area {
get { return length * length; }
set { length = Math.Sqrt(value); }
}
public int Perimeter {
get { return length * 4; }
set { length = value / 4; }
}
private int length;
}
Now you can write:
Square square = new Square();
square.Length = 2;
Console.WriteLine(square.Length); // "2"
Console.WriteLine(square.Area); // "4"
Console.WriteLine(square.Perimeter); // "8"
square.Area = 9;
Console.WriteLine(square.Length); // "3"
Console.WriteLine(square.Area); // "9"
Console.WriteLine(square.Perimeter); // "12"
Edit:
C# also allows you name properties at your choosing when instantiating an object:
Square square1 = new Square { Perimeter = 12 };
Square square2 = new Square { Length = 4 };
I don't think something like this does exist in the form of a programming language.
Ontology
However the first approach I can think about is defining an Ontology, I mean a set of rules about
Entities: Rectangle, Square, Dog, Car, etc...
Attributes: Area, Height, Number of Wheels, etc...
Relations between (1) and (2): Rectangle's Area is Height * Width, ...
Now given a list of attributes and the required output Entity
I have height and width and I need a Rectangle
the system could search for a path through the rules graph to produce the required outcome based on the provided inputs.
Real world example
Wolfram Alpha probably follows the technique described above

How to create infinitive random platform in endless running game?

I'm making a 2d endless running game. I have a platform that is formed by many blocks. Every block has one of three color: red, blue, green. I don't know exactly how to random blocks with different color at runtime. I have used an array to store block rectangles like the example Drop(Simple game) on wiki page. In render class I have this code to change color of block at runtime:
public void drawBlock() {
TextureRegion region = new TextureRegion();
for (Rectangle rec : colorBlock.getBlocksRec()) {
if (colorBlock.isRed()) {
region = red;
}
if (colorBlock.isGreen())
region = green;
if (colorBlock.isBlue())
region = blue;
batch.draw(region, rec.x, rec.y, rec.width, rec.height);
}
}
But it seems to be failed because it changes all blocks on screen into one color at the same time.
I also have some problems in making blocks move continuously. They moved but they looked like hundred of blocks overlapped each other. I don't know how to control the blocks in the right way. I used TimeUtils for check when the next block should be created, but it was totally failed.
You can use an Array or your ground blocks that adds a new one when it about to appear on the screen, and removes the oldest entry when it will not be seen on the screen anymore. I had a similar question, check it out: HERE
For random colors you can use the MathUtils.random(float f) when you about to add a new block to the array.
For example something like this, or with switch :
float res = MathUtils.random(8f);
//this returns a random float between 0 (inclusive) and 8 (exclusive)
if(res <= 2) { //[0-2]
//add green
}
if(res > 2 && res <= 5){//(2-5]
//add blue
}
if(res>5){//(5-8)
//add red
}

CanvasPixelArray - how many index spots for one color value?

For a personal project, I'm re-implementing some Javascript code to Java. One particular thing that is tripping me up at this point is whether a Color is represented by three or four index values in the HTML5 CanvasPixelArray object.
The page linked above states that an offset value of 4 is used. However, one graphic effect that I'm re-implementing has this function:
function getPixelValue(x, y) {
var offset = (x + y * width) * 4;
var r = imageData[offset];
var g = imageData[offset + 1];
var b = imageData[offset + 2];
return ( ((255 << 8) | r) << 8 | g) << 8 | b;
}
to return an color integer value for a given pixel. The code works in the browser, but I'm confused by the fact that r, g, b are all contained in a given 3 block segment of the array, while offset is 4. This same value for offset is shown in the code example at the page linked above.
What is the reason for the difference? If a pixel color value is contained within a 3 block segment, shouldn't offset include 3 as a constant?
Canvas always returns RGBA but you can skip the alpha channel (index 3) if you don't need it but will always have to skip 4 positions in the byte array.
Typically for photos the alpha value is always 255 (non-transparent) so it isn't needed. For other types of graphics which already contain an alpha channel (for example PNG icons etc.) the alpha channel becomes more important.
Your getPixelValue simply ignores the alpha channel and returns the RGB value independent on the value of the alpha channel (which is correct when you want a color value from the source - the color value (from source) will be the same regardless of the alpha value).

What does the mask parameter do in the threshold method of the BitmapData class?

I'm trying to replace a color and colors near it in a bitmap.
threshold() seems to work but it seems to be that you have to specify the exact color "==" or all colors before or after the exact color "<" & ">" plus "<=" and ">=". I am hoping that the mask parameter will help me find a way to find a color and a dynamic range of colors before and after it to be replaced. What is its intended usage?
Per the comment below Example 1 and 2:
bit.threshold(bit, bit.rect, point, ">", 0xff000000, 0xffff0000, 0x00FF0000);
bit.threshold(bit, bit.rect, point, ">", 0xff000000, 0xffff0000, 0x00EE0000);
If you're trying to do a flood fill, I don't think the mask parameter will help you. The mask parameter lets you ignore parts of the color in the test. In your case, you want to take into account all the channels of the color, you just want the matching to be fuzzy.
e.g. If you want to replace all pixels where the red component is 0, you can set mask to 0x00FF0000, so it will ignore the other channels.
The implementation pseudo-code probably looks something like this:
input = readPixel()
value = input & mask
if(value operation threshold)
{
writePixel(color)
}
Neither of your samples will produce anything because the mask limits the values to be between 0x00000000 and 0x00FF0000, then tests if they're greater than 0xFF000000.
I have also done this and eventually, I have found it best to create my own threshold-method. You can find it below. Everything is explained in comment.
//_snapshot is a bitmapData-object
for(var i:int = 0; i <= _snapshot.width; i++)
{
for(var j:int = 0; j <= _snapshot.height; j++)
{
//We get the color of the current pixel.
var _color:uint = _snapshot.getPixel(i, j);
//If the color of the selected pixel is between certain values set by the user,
//set the filtered pixel data to green.
//Threshold is a number (can be quite high, up to 50000) to look for adjacent colors in the colorspace.
//_colorToCompare is the color you want to look for.
if((_colorToCompare - (100 * _threshold)) <= _color && _color <= (_colorToCompare + (100 * _threshold)))
{
//This sets the pixel value.
_snapshot.setPixel(i, j, 0x00ff00);
}
else
{
//If the pixel color is not within the desired range, set it's value to black.
_snapshot.setPixel(i, j, 0x000000);
}
}
}