Converting CGPoint to GLKVector2 in Objective-C - ios

Simple question. What is the best way to turn a CGPoint into a GLKVector?
These structures are identical so it would be nice to be able to reinterpret_cast or memcpy or something like that. My solution below works but hardly seems optimum. I'm creating a GLKVector2 on the stack assigning each member then returning this as a value which is then assigned to another GLKVector.
It's not going to break the bank or anything but there must be a neater way to do this?
GLKVector2 Vector2FromPoint(CGPoint point)
{
GLKVector2 v;
v.x = point.x;
v.y = point.y;
return v;
}

You could try using memcpy in a function like this:
bool vector2ToCGPoint(GLKVector2* s, CGPoint* d) {
memcpy(d, s, sizeof(*d));
}
but then it is probably better to have:
bool copyVector2ToCGPoint(GLKVector2* s, CGPoint* d) {
d.x = s.x;
d.y = s.x;
}
if you really want optimization, you could go for a macro:
#define copyS2D(S,D) (D.x = S.x, D.y = S.y)
so you can do:
CGPoint b;
GLKVector2 a;
vector2FromCGPoint(a, b);
of course, as you know, macros will not be that much type-safe...

GLKVector2 v = GLKVector2Make(point.x, point.y);

Related

Detection of duplicate code

I am working on a project where i want to detect duplicate code.
Example:
function sumOfTwoNumbers(a, b){
return a + b;
}
function AddTwoNumbers(a, b){
var x = a;
var y = b;
return x + y;
}
These both function return sum of 2 numbers, as these both functions return same result, is there any way to detect that these functions are similar.
Can u please suggest what technology should i learn to solve this problem.
Thanks in advance

How to map OSMSharp view point to Geo coordinate?

I am using OSMSharp for an iOS project.
I'll like to be able to convert a given point in the view/map to GeoCoordinates (based on the current MapCenter, view size, zoom, etc).
I thought mapView.Map.Project.ToGeoCoordinates would do that, but the result is not correct. The inverse function (mapView.Map.Project.ToPixel) returns values in a coordinate system that doesn't correspond to the actual view (it returns value up to 10000 or so, and the size of my view is 1024x768).
So, how do I convert a given pixel coordinate in a OsmSharp.iOS.UI.MapView to its corresponding GeoCoordinate?.
Right now there's no method to get it. But it's easy to get
Add below method to MapView class in OsmSharp.iOS.UI project
public GeoCoordinate PointToCoordinate(int PointX, int PointY)
{
View2D view = _cacheRenderer.Create(this.Width, this.Height, this.Map,
(float)this.Map.Projection.ToZoomFactor(this.MapZoom), this.MapCenter, false, true);
// get scene coordinates.
double x, y;
var fromMatrix = view.CreateFromViewPort(this.Width, this.Height);
fromMatrix.Apply(PointX, PointY, out x, out y);
return this.Map.Projection.ToGeoCoordinates(x, y);
}
If you want the Point from Geocoordinate, add below method to the same class
public Point CoordinateToPoint(GeoCoordinate gc)
{
var gcPx = this.Map.Projection.ToPixel(gc);
View2D view = _cacheRenderer.Create(this.Width, this.Height, this.Map,
(float)this.Map.Projection.ToZoomFactor(this.MapZoom), this.MapCenter, false, true);
// get scene coordinates.
double x, y;
var fromMatrix = view.CreateFromViewPort(this.Width, this.Height);
fromMatrix.Remove(gcPx[0], gcPx[1], out x, out y);
return new Point((int)System.Math.Round(x, 0), (int)System.Math.Round(y, 0));
}
And below method to Matrix2D class in OsmSharp.UI.Renderer project
public void Remove(double x, double y, out double xNew, out double yNew)
{
xNew = (x * this.E11 - this.E02 * this.E11 + this.E01 * this.E12 - this.E01 * y) / (this.E00 * this.E11 - this.E01 * this.E10);
yNew = (y - this.E12 - this.E10 * xNew) / this.E11;
}

Is there anything like a struct in dart?

In javascript it always bothered me people use objects as vectors like {x: 1, y: 2} instead of using an array [1,2]. Access time for the array is much faster than the object but accessing by index is more confusing especially if you need a large array. I know dart has fixed arrays but is there a way to name the offsets of an array like you would a struct or a tuple/record in another language? Define enum/constants maybe?
I'd want something like
List<int> myVector = new List([x,y]);
myVector.x = 5;
is there an equivalent or idiomatic way to do this?
That sounds like a class.
class MyVector {
int x;
int y;
MyVector(this.x, this.y);
}
There is no simpler and more efficient way to create a name-indexed structure at runtime. For simplicity you could usually use a Map, but it's not as efficient as a real class.
A class should be at least as efficient (time and memory) as a fixed length list, after all it doesn't have to do an index bounds check.
In Dart 3.0, the language will introduce records. At that point, you can use a record with named fields instead of creating a primitive class:
var myVector = (x: 42, y: 37);
print(myVector.x);
A record is unmodifiable, so you won't be able to update the values after it has been created.
For me, i see 2 way to do this. I will sort by best in my point of view
Class based method
Here, the approach is to encapsulate your need, in a dedicated object
Pros:
It's encapsultate
You can propose several way to access variable, depend of the need
You can extend functionality without break everything
I love it :p
Cons
More time spend to create class, etc.
Do you really need what i say in pros ?
Maybe weird for js people
example :
class Vector {
int x;
int y;
static final String X = "x";
static final String Y = "y";
Vector({this.x, this.y});
Vector.fromList(List<int> listOfCoor) {
this.x = listOfCoor[0];
this.y = listOfCoor[1];
}
// Here i use String, but you can use [int] an redefine static final member
int operator[](String coor) {
if (coor == "x") {
return this.x;
} else if (coor == "y") {
return this.y;
} else {
// Need to be change by a more adapt exception :)
throw new Exception("Wrong coor");
}
}
}
void main() {
Vector v = new Vector(x: 5, y: 42);
Vector v2 = new Vector.fromList([12, 24]);
print(v.x); // print 5
print(v["y"]); // print 42
print(v2.x); // print 12
print(v2[Vector.Y]); // print 24
}
Enum based method:
You can also defined a "enum" (actually not really implement but will be in the future version) that will contains "shortcut" to your value
Pros
More simple to implement
Is more like your example ;p
Cons
Less extendable
i think is not very pretty
Not OOP think
example:
class Vector {
static final int x = 0;
static final int y = 1;
}
void main() {
List<int> myVector = new List(2);
myVector[Vector.x] = 5;
myVector[Vector.y] = 42;
}
Make your choice ;p
This is only possible with a class in Dart.
There are some open feature requests at http://dartbug.com
introduce struct (lightweight class)
Give us a way to structure Bytedata
If you have reasonably big data structure, you can use "dart:typed_data" as a model and provide lightweight view for the stored data. This way the overhead should be minimal.
For example, if you need 4X4 matrix of Uint8 values:
import "dart:typed_data";
import "dart:collection";
import "package:range/range.dart";
class Model4X4Uint8 {
final Uint8List _data;
static const int objectLength = 4 * 4;
final Queue<int> _freeSlotIndexes;
Model4X4Uint8(int length): _data = new Uint8List((length) * objectLength),
_freeSlotIndexes = new Queue<int>.from(range(0, length));
int get slotsLeft => _freeSlotIndexes.length;
num operator [](int index) => _data[index];
operator []=(int index, int val) => _data[index] = val;
int reserveSlot() =>
slotsLeft > 0 ? _freeSlotIndexes.removeFirst() : throw ("full");
void delete(int index) => _freeSlotIndexes.addFirst(index);
}
class Matrix4X4Uint8 {
final int offset;
final Model4X4Uint8 model;
const Matrix4X4Uint8(this.model, this.offset);
num operator [](int index) => model[offset + index];
operator []=(int index, int val) => model[offset + index] = val;
void delete() => model.delete(offset);
}
void main() {
final Model4X4Uint8 data = new Model4X4Uint8(100);
final Matrix4X4Uint8 mat = new Matrix4X4Uint8(data, data.reserveSlot())
..[14] = 10
..[12] = 256; //overlow;
print("${mat[0]} ${mat[4]} ${mat[8]} ${mat[12]} \n"
"${mat[1]} ${mat[5]} ${mat[9]} ${mat[13]} \n"
"${mat[2]} ${mat[6]} ${mat[10]} ${mat[14]} \n"
"${mat[3]} ${mat[7]} ${mat[11]} ${mat[15]} \n");
mat.delete();
}
But this is very low level solution and can easily create sneaky bugs with memory management and overflows.
You could also use an extension on List to create aliases to specific indexes.
Although it will be difficult to set up mutually exclusive aliases, in some cases, it may be a simple solution.
import 'package:test/test.dart';
extension Coordinates<V> on List<V> {
V get x => this[0];
V get y => this[1];
V get z => this[2];
}
void main() {
test('access by property', () {
var position = [5, 4, -2];
expect(position.x, 5);
expect(position.y, 4);
expect(position.z, -2);
});
}
The Tuple package https://pub.dev/packages/tuple might be what you are looking for when a class is too heavy.
import 'package:tuple/tuple.dart';
const point = Tuple2<int, int>(1, 2);
print(point.item1); // print 1
print(point.item2); // print 2

Local integer values changing randomly inside while loop

I have a function which does some array manipulation on an NSMutableArray. Somehow after a couple of loops of the while function the values inside 2 local variables are total garbage. They are not being assigned or manipulated anywhere. Here's how:
Here's the function:
-(void) normalize_path:(NSMutableArray *)path tool:(Tool)tool
{
NSUInteger last_accepted_point_index = 0;
NSUInteger current_point_index = 1;
while(current_point_index < [path count]){
VPoint * p1, * p2;
[[path objectAtIndex:last_accepted_point_index] getValue:&p1];
[[path objectAtIndex:current_point_index] getValue:&p2];
//float distance = [self distance_between:p1 and:p2];
// if(distance < MIN_POINT_DISTANCE){
// [path removeObjectAtIndex:current_point_index];
// }else{
// float opacity = tool.max_opacity - distance * tool.opacity_sensitivity;
// opacity = opacity <= tool.min_opacity ? tool.min_opacity : opacity;
// p2->opacity = opacity;
// float thickness = tool.max_thickness - distance * tool.thickness_sensitivity;
// thickness = thickness <= tool.min_thickness ? tool.min_thickness : thickness;
// p2->thickness = thickness;
// last_accepted_point_index = current_point_index;
// //current_point_index++;
// }
}
}
And it's called only in one place like so:
//...
[self normalize_path:opath tool:pen];
//...
Every run creates different values. I am confounded! What is going on here?
I think that this may be a memory issue which you can fix by removing the & from in front of p1 and p2 in the getValue: call. It's difficult to be totally sure as you haven't said what VPoint is, but normally this code would look like this:
VPoint p1, p2;
[[path objectAtIndex:last_accepted_point_index] getValue:&p1];
[[path objectAtIndex:current_point_index] getValue:&p2];
This would then set p1 and p2 to the actual values. Your distance between function would then not take references but the actual values of p1 and p2 (if you want to pass references as you are doing now, you'd put & in front of p1 and p2 in the distance callBetween method call.

Deleting a node from the middle of a link list, function prototype is: int particle_remove(struct particle* p);

I have been working on this for like 10 hours.
int particle_remove(struct particle* p);
How do I find the head when I'm passing the location of the "node-to-be-deleted" to the function?
I know that:
prev->next = curr->next;
free(curr);
how do I find the location of the head to traverse down to (curr -1)?
This is what I have so far:
int particle_remove(struct particle *p){
struct particle *curr = p;
struct particle *prev = *head; /* should point to the head */
if (p != NULL){
while (prev != curr){
prev=curr->next;
}
prev->next = curr->next;
free(curr);
}
return 0;
}
I have been over this a million times and I can't think of how to get to the head node, without passing a parameter of the location of the head node into the function. Is it possible to do this with the current function "signature" or do I have to add a reference to the head?
OK I have figured it out by creating a new function that takes both the current node to be destroyed and a pointer to the head, as I don't believe that just using a function to the node to be deleted will work as there is no reference to the head. (Unless someone can prove me wrong, please do!)
I ended up with a prototype that looks like this: (for those that are looking for a hint)
int particle_remove(struct particle *p, struct particle **head);
The problem is: you have to change the head pointer if the pointer to be deleted (p) happens to be first in the list. Using a pointer-to-pointer (a pointer to the head pointer) is the easiest way:
int particle_remove(struct particle *p){
struct particle **pp; /* should point to the head */
for(pp = &head; *pp; pp = &(*pp)->next){
if (*pp != p) continue;
*pp = p->next;
free(p);
break;
}
return 0;
}
If head is not a gobal pointer, you indeed end up with a function where the pointer to head is passed as an argument:
int particle_remove(struct particle **pphead, struct particle *p){
for( ; *pphead; pphead = &(*pphead)->next){
if (*pphead != p) continue;
*pphead = p->next;
free(p);
break;
}
return 0;
}
BTW: the return value is nonsense. If there is no useful return for the function, it could just as well return void.
OK, so the way to solve this using the original function prototype is if you use:
if(p->next != NULL){
/* do something */
}
You are checking to see if the next node is to be deleted. This gives you access to the previous node and the next node (to be deleted).

Resources