Executing Func over a specific domain in generator - halide

I have this example generator that fills a region (0,0,100,100) with black:
class MyGen : public Generator<MyGen>
{
public:
Var x, y;
Output<Func> output { "output", Int(32), 2 };
void generate()
{
output(x, y) = x + y;
RDom dom = RDom(0, 100, 0, 100);
output(dom.x, dom.y) = 0;
}
void schedule()
{
}
};
The region is filled correctly, but because of the pure definition, the rest of the image is a gradient (x+y).
Is there a way to write a pure definition that's not going to be executed (e.g. output(x,y) = output(x,y))?
Can I execute a Func over a specific domain (e.g. Input<int>s that define the region) without impacting the rest of the image?

Here's how you write an unexecuted pure definition:
output(x, y) = undef<int>();
It's a bit dangerous though for anything other than outputs, because Halide doesn't statically check for use-of-undefined values. valgrind is your friend.

Related

Issue Converting Processing (JAVA based library) into P5.JS code (ECMAScript based library)

I am having issues converting a piece of JAVA based code into ECMAScript/TypeScript, may someone can help. There are two parts I struggle to convert a) a constructor overload I think and b) a self referencing push. Maybe there is a different way to write this?
class Finder {
PVector location;
PVector velocity;
float diameter;
Pvector origin = new PVector(width / 2, height/2);
Finder(int x, int y) {
location = new PVector(width/2, height/2);
velocity = new PVector(x, y);
diameter = 8;
}
// this is a) where I struggle to convert
Finder(Finder parent) {
location = parent.location.get();
velocity = parent.velocity.get();
float area = PI*sq(parent.diameter/2);
float newDiam = sqrt(area/2/PI)*2;
diameter = newDiam;
parent.diameter = newDiam;
}
void update() {
if(origin.dist(location)> 300){
// nothing
} else if (diameter>0.5) {
location.add(velocity);
PVector bump = new PVector(random(-1, 1), random(-1, 1));
bump.mult(0.1);
velocity.add(bump);
velocity.normalize();
if (random(0, 1)<0.02) {
// this is b) where I struggle to convert
paths = (Finder[]) append(paths, new Finder(this));
}
}
}
}
Finder[] paths;
Regarding part a, treat is a function that returns a copy (new instance with copied properties from argument instance):
(JS doesn't support overloaded constructors, hence simply using a method instead of a constructor should suffice)
e.g.
copy(parent) {
location = parent.location.copy();
velocity = parent.velocity.copy();
let area = PI*sq(parent.diameter/2);
let newDiam = sqrt(area/2/PI)*2;
diameter = newDiam;
// this looks a bit sus to me: why should we change the parent ?
parent.diameter = newDiam;
}
Regarding part b I can infer that paths is a Finder[] in the global scope (e.g. main sketch variables). Is so, that will be a plain js array when you port to p5.js and in js arrays are dynamic so you should be able to simply do use paths.push(this.copy()) instead.
(If you want to test in the Processing sketch, swap the Finder[] paths line to ArrayList<Finder> paths = new ArrayList<Finder>() and use paths.add(New Finder(this)); instead paths = (Finder[]) append(paths, new Finder(this));)

Changing the Speed of a motor in Processing/box2D

I've been making some simple games using processing and box2D using The Nature of Code as a resource.
My problem is I have gotten to a point where I have these windmills that go clockwise/counterclockwise depending on the speed of the motor (I am using PI/2 and -PI*2). I want to have it so that the user can change this speed from positive and negative by pressing a key or mouse button. Looking around online people and the box2D documentation are saying to use the function void SetMotorSpeed(float speed);, however I am not having luck figuring out how to implement this. I've tried a few ways I can think but no luck.
Currently I have this in my main file ("s" is the name of the instance of the windmill):
// Click the mouse to switch speed of motor
void mousePressed() {
s.SetMotorSpeed(s.speed);
}
And I have this in the file for the windmill:
//Set Motor Speed
void SetMotorSpeed(float speed){
speed = speed * -1;
}
This doesn't work though.
I'm fairly new to coding and this is my first post on stack-overflow so my apologies if I have done anything wrong in how I'm asking or presenting this question. I'm open to suggestions both code and etiquette wise!
Here is the code for the entire windmill:
class Seesaw {
// object is two boxes and one joint
RevoluteJoint joint;
// float speed = PI*2;
Box box1;
Box box2;
float speed = PI*2;
Seesaw(float x, float y) {
// Initialize locations of two boxes
box1 = new Box(x, y-20, 120, 10, false);
box2 = new Box(x, y, 10, 40, true);
// Define joint as between two bodies
RevoluteJointDef rjd = new RevoluteJointDef();
Vec2 offset = box2d.vectorPixelsToWorld(new Vec2(0, 60));
rjd.initialize(box1.body, box2.body, box1.body.getWorldCenter());
// Turning on a motor (optional)
rjd.motorSpeed = PI*2; // how fast?
rjd.maxMotorTorque = 1000.0; // how powerful?
rjd.enableMotor = true; // is it on?
// Create joint
joint = (RevoluteJoint) box2d.world.createJoint(rjd);
}
// Turn the motor on or off
void toggleMotor() {
joint.enableMotor(!joint.isMotorEnabled());
}
boolean motorOn() {
return joint.isMotorEnabled();
}
void SetMotorSpeed(float speed){
speed = -speed;
}
void display() {
box2.display();
box1.display();
// Draw anchor just for debug
Vec2 anchor = box2d.coordWorldToPixels(box1.body.getWorldCenter());
fill(255, 0, 0);
stroke(0);
ellipse(anchor.x, anchor.y, 4, 4);
}
}
The change in speed should be communicated to the joint. Try this:
void SetMotorSpeed(float speed) {
s.joint.setMotorSpeed(speed); // edited, processing/java uses camel-case
}
you might also be a bit more careful about naming variables. In your original post you use the same name for the local variable and the member variable, which has not the wanted effect. Most people use some naming convention for member variable to avoid this kind of very common error. Like for instance have all member variables all start with "_"
void SetMotorSpeed(float speed) {
_speed = -speed; // speed is local!
}

why does object.variable work in the main class and in other classes?

I am currently building Space Invaders in Processing and I do not absolutely understand why this happens, it is hard to explain, so here is all the code that goes with the game:
SpaceInvaders.pde:
/* Jordan Green
April 11th, 2018
This is the main class for the game
Space Invaders.
This is what sets up the game.
*/
//My objects declared.
Alien aliens;
Player player;
Score score;
PImage img;
//sets up the variables and gives them values.
void setup() {
aliens = new Alien();
player = new Player();
score = new Score();
size (600, 600);
img = loadImage("Space Background.jpg");
}
//draws out the program.
void draw() {
background(0);
image(img, 0, 0, height, width);
player.show();
player.move();
player.playerLives();
player.alienDie();
aliens.show();
aliens.move();
score.show();
if (player.playerLife == 0) {
}
}
void keyPressed() {
if (key == ' ') {
player.shoot();
}
}
My question is why does an object.variable work on Processing? It's something I do not understand.
Jordan
Why wouldn't it work?
This is a fundamental feature of objects in Java, which Processing is built on top of. If you have a class that contains variables or functions, you can reference those variables or functions using the . dot operator.
Here's an example:
class MyClass{
int x = 42;
void sayHello(){
println("hello");
}
}
MyClass myInstanceOfMyClass = new MyClass();
println(myInstanceOfMyClass.x);
myInstanceOfMyClass.sayHello();
In Java you can mark variables and functions as private to restrict access, but this is less common in Processing.
You can read more about classes in the reference or in this tutorial.

Unity: How to get y axis in run time generated zigzag path

I am create a runner game like Hilclimb, But i don't know how to generated coin in the surface of zigzag path.
This is my Path
it is generated in random. But how to get y position in path in run time, because when coin generated in random position then coin is some time below the and some time above the path.
So please help me how to get path y position in run time so generate coin in the surface.
Path generate code is this, and coin also.
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class TerrainGenerator : MonoBehaviour {
public chunk previousChunk;
public chunk currentChunk;
public chunk nextChunk;
public ManagePower power;
public GameObject character;
public Resize resize;
public Coin coin;
private PickupResize rise;
private pickupPower pick;
private PickupCoin pCoin;
// Use this for initialization
void Start () {
rise=FindObjectOfType<PickupResize>();
pick=FindObjectOfType<pickupPower>();
pCoin=FindObjectOfType<PickupCoin>();
float widthprefabs = previousChunk.WidthGroundPrefab;
previousChunk.RepositionChunk (new Vector3(-widthprefabs*chunk.CHUNK_SIZE,0,0));
currentChunk.RepositionChunk (Vector3.zero);
nextChunk.RepositionChunk (new Vector3(widthprefabs*chunk.CHUNK_SIZE,0,0));
power.RepositionPower (new Vector3(widthprefabs*chunk.CHUNK_SIZE,-0.1f,0));
resize.ResizeSquire (new Vector3(25f,-0.1f,0));
coin.ResetCoin (new Vector3(5f,-0.17f,0));
}
// Update is called once per frame
void Update () {
if(playerReachedNextChunk()){
reassineChunk();
}
if (rise.rePick) {
resize.ResizeSquire(new Vector3 (rise.distancere, -0.1f, 0));
rise.rePick=false;
}
if (pick.poPick) {
power.RepositionPower (new Vector3 (pick.powerdist, -0.1f, 0));
pick.poPick=false;
}
if (pCoin.distancere < ObjectScript.distance) {
int random = Random.Range (1, 10);
pCoin.distancere += random;
pCoin.reCoin = true;
}
if (pCoin.reCoin) {
coin.ResetCoin (new Vector3 (pCoin.distancere, -0.1f, 0));
pCoin.reCoin=false;
}
//print ("ddhdhdhdhhd"+ObjectScript.distance);
}
private bool playerReachedNextChunk(){
bool playerReachedNextChunk = false;
float distance = character.transform.position.x - nextChunk.transform.position.x;
//print ("Distance " +distance);
if (distance > 0) {
playerReachedNextChunk=true;
}
return playerReachedNextChunk;
}
private void reassineChunk(){
chunk refToprivesChunk = previousChunk;
previousChunk = currentChunk;
currentChunk = nextChunk;
nextChunk = refToprivesChunk;
float xPosition = nextChunk.transform.position.x+3 * nextChunk.WidthGroundPrefab * chunk.CHUNK_SIZE;
nextChunk.RepositionChunk (new Vector3(xPosition,0,0));
}
}
If you do not have access to exact points on your path, but you are using a collider, that approximates the path, then you can use a Physics.Raycast or Physics2D.Raycast to determine the y-coordinate of the path given x (and if you are in 3D space z).
Given x (assuming you are in 2D space) you could proceed as follows:
1. Choose a value for y that is guaranteed to be below/above your path
2. If you select a value for y that is above, then perform a Physics.Raycast starting from (x,y) in direction Vector2.down. You can also utilize layer masks to make sure, you only hit the collider of your path.
3. The y-component of the hit point is the value for y of the path you are looking for

Processing 'It looks like you're mixing "active" and "static" modes.'

Processing keeps giving me this error when I run it even though it is just a print command. When I delete the comment block it works fine. Here's the code:
/*
float[] cortToPolar(int xcorr, int ycorr) {
float returns[] = new float[2];
returns[0]= degrees(tan(ycorr/xcorr));
returns[1]= sqrt(pow(xcorr,2)+pow(ycorr,2));
return returns;
}
float lawCos(int a, int b, int c) {
return degrees(
acos(
(pow(a,2)+pow(b,2)-pow(c,2))/
(2*a*b)
)
);
}
*/
print(0);
Why doesn't it like my comment?
Processing runs in two separate modes: static or active
Static mode simply means it's a list of instructions/calls to existing functions (e.g. draw a bunch of lines then exit)
Active mode uses the setup() and draw() calls and runs continuously (gets updated every 'frame').
Only in active mode you are allowed to define own functions like cortToPolar and lawCos (regardless of the fact they are commented - this could be a Processing editor bug).
Use the setup() call to print because using setup will bring Processing into active mode.
/*
float[] cortToPolar(int xcorr, int ycorr) {
float returns[] = new float[2];
returns[0]= degrees(tan(ycorr/xcorr));
returns[1]= sqrt(pow(xcorr,2)+pow(ycorr,2));
return returns;
}
float lawCos(int a, int b, int c) {
return degrees(
acos(
(pow(a,2)+pow(b,2)-pow(c,2))/
(2*a*b)
)
);
}
*/
void setup(){
print(0);
}
(Should you need to use active mode and control how draw() is called you can use noLoop() and loop().)
The message could be shown when the actual problem is a syntax error. I encountered this error with the following (silly) code:
boolean state = false;
setup() {
size(200, 800);
}
void draw() {
}
It is missing the 'void' modifier for the setup function. This is a syntax error (at least, it should be). But the Processing IDE gives you this "active vs. static" message instead.
So in this case, it should be void setup() { } rather than just setup() { }.

Resources