I'm writing a script to make a simple flute in SketchUp (free version, Mac). I want to make a tube and and then cylinders which poke through the tube, draw the intersection lines between the tube and the cylinders, then erase the cylinders, leaving circles to cut out of the tube.
This works if I do it with the mouse, but I found it difficult to be precise about placement and measurement with the mouse. So far, though, I haven't been able to make it work with a script. Currently I am stuck with it drawing incomplete circles on the tube, so I am unable to find the face and erase it. You should be able to run the following script in the ruby console and see what I mean. What am I doing wrong?
entities = Sketchup.active_model.entities
# make tube
tube = entities.add_group
tube_inner = tube.entities.add_circle Geom::Point3d.new(0,0,0), Geom::Vector3d.new(0,0,1), 5, 360
tube_outer = tube.entities.add_circle Geom::Point3d.new(0,0,0), Geom::Vector3d.new(0,0,1), 6, 360
cross_section_face = tube.entities.add_face tube_outer
inner_face = tube.entities.add_face tube_inner
tube.entities.erase_entities inner_face
cross_section_face.pushpull -10, false
# make a cylinder that punches through the wall
hole_punch = entities.add_group
hole_outer = hole_punch.entities.add_circle Geom::Point3d.new(0,0, 5), Geom::Vector3d.new(0,1,0), 3, 360
face = hole_punch.entities.add_face hole_outer
face.pushpull 10, false
# draw the intersection lines and erase the hole punch
entities.intersect_with true, hole_punch.transformation, tube, tube.transformation, true, hole_punch
hole_punch.erase!
Determining the correct faces to erase after intersecting can be very tricky.
But since you are working with cylinder shapes - which are solids - I would recommend you use the solid boolean operations that was introduced in SketchUp 8 Pro. You can use Group.subtract for instance. http://www.sketchup.com/intl/en/developer/docs/ourdoc/group#subtract
However, is you are not using SketchUp 8 Pro or newer then you won't have these methods available.
Alternative solution - avoiding the Solid Tools methods of the Pro version:
entities = Sketchup.active_model.entities
# (!) You created a circle with so many edges that at the scale
# you drew it they where pushing the boundary of how small
# units SketchUp can handle. (1/1000th inch).
# If you has Edge Outline style enabled you could see that
# not all edges where fully merged.
# I reduced the curve segments from 360 to 180.
# (Do you really need such a high mesh density anyway?)
# make tube
tube = entities.add_group
tube_inner = tube.entities.add_circle Geom::Point3d.new(0,0,0), Geom::Vector3d.new(0,0,1), 5, 180
tube_outer = tube.entities.add_circle Geom::Point3d.new(0,0,0), Geom::Vector3d.new(0,0,1), 6, 180
cross_section_face = tube.entities.add_face tube_outer
inner_face = tube.entities.add_face tube_inner
tube.entities.erase_entities inner_face
cross_section_face.pushpull -10, false
# make a cylinder that punches through the wall
hole_punch = entities.add_group
hole_outer = hole_punch.entities.add_circle Geom::Point3d.new(0,0, 5), Geom::Vector3d.new(0,1,0), 3, 180
face = hole_punch.entities.add_face hole_outer
face.pushpull 10, false
# draw the intersection lines and erase the hole punch
entities.intersect_with true, hole_punch.transformation, tube, tube.transformation, true, hole_punch
hole_punch.erase!
# Find all the edges that belong to the Circle elements drawn
# earlier (including the ones push-pulled).
# (Could also collect these earlier before intersecting by
# collecting all non-smooth edges.)
circles = tube.entities.grep(Sketchup::Edge).select { |e| e.curve }.uniq
# Then we pick out all the faces that isn't connected to these edges and erase them.
new_faces = tube.entities.grep(Sketchup::Face).select { |f| (f.edges & circles).empty? }
entities.erase_entities( new_faces )
If you really want 360 segment circles you can scale the content of the group up - while you scale the group instance down. That way the group definition is at a much bigger scale. (See this article on instances and definitions in SketchUp: http://www.thomthom.net/thoughts/2012/02/definitions-and-instances-in-sketchup/)
Also, if you want faces to fill the hole between the inner and outer skin you need to intersect that part as well.
Note about the Entities.intersect_with description - the current docs doesn't explain well all the arguments. There are two entities arguments.
The first one should be a Sketchup::Entities object where the intersected objects should appear. (I'm a bit surprised it worked by feeding it a Sketchup::Group object.)
The second should not be Sketchup::Entities - that will fail. It must be an Sketchup:Entity or array of Sketchup:Entity objects.
Related
I think this is ultimately a pretty simple question, but it's hard to describe, thus, I provide a working example here (in the sample press 'z' to see rotation with unwanted translation and 'x' keys to rotate with a compensating re-position).
Basically, I am trying to rotate an object (a thumbstick) about the z-axis of a complex model loaded via gltf (a model of the oculus rift touch controller). It's easy to rotate about the x-axis because it's 90 deg. orthogonal to the x-axis. About the z-axis, it's harder because the plane the thumbstick is attached to is angled at 30 deg. I realize that if the thumbstick were using local coordinates, this wouldn't be a problem, but 'thumb.rotation.z' does not seem to be using local coordinates and is rotating about the model's (as a whole), or maybe even the scene's global y and z (?). Anyway, after a bunch of futzing around, I was able to get things to work by doing the following:
// occulus plane is angle at 30 deg, which corresponds to
// 5 units forward to 3 units down.
var axis = new THREE.Vector3(0, 5, -3).normalize();
factory.thumbstick.geometry.center();
var dir = (evt.key === 'x' ? 1 : -1);
thumb.rotateOnAxis(axis, factory.ONE_DEG * 5.0 * dir);
Basically, I'm rotating about a "tilted" axis, and then calling 'center' to make thumbstick centered on the pivot point, so it rotates about the pivot point, rather than around the pivot point (like the earth orbiting the sun).
Only problem is that when you call 'geometry.center()' and then call 'rotateOnAxis', it translates the thumbstick to the pivot point:
Note: the position on the thumbstick object is (0,0,0) before and after the calls.
I have empirically determined that if I alter the position of the thumbstick after the translation like so:
// magic numbers compensating position
var zDisp = 0.0475;
var yDisp = zDisp / 6.0
thumb.position.x = 0.001;
thumb.position.y = -yDisp;
thumb.position.z = zDisp;
Then it (almost) returns back to it's original position:
Problem is these numbers were just determined by interactively and repeatedly trying to re-position the thumbstick i.e. empirically. I simply cannot find a programmatic, analytical, api kind of way to restore the original position. Note: saving the original position doesn't work, because it's zero before and after the translation. Some of the things I tried were taking the difference between the bounding spheres of the global object and the thumbstick object, trying to come up with some 'sin x- cos x' relation on one distance etc. but nothing works.
My question is, how can I progammatically reverse the offset due to calling 'geometry.center()' and rotateOnAxis (which translates to the pivot point), without having to resort to hacked, empircal "magic" numbers, that could conceivably change if the gltf model changes.
Of course, if someone can also come up with a better way to achieve this rotation, that would be great too.
What's throwing me is the (peceived?) complexity of the gltf model itself. It's confusing because I have a hard time interpreting it and it's various parts: I'm really not sure where the "center" is, and in certain cases, it appears with the 'THREE.AxesHelper' I'm attaching that what it shows as 'y' is actually 'z' and sometimes 'up' is really 'down' etc, and it gets confusing fast.
Any help would be appreciated.
The breakthrough for me on this was to re-frame the problem as how do I change the pivot point for the thumbstick, rather than how do I move the thumbstick to the (default and pre-existing) pivot point. To paraphrase JFK, "ask not how you can move to the pivot, but ask how the pivot can move to you" :-)
After changing my angle of attack, I pretty quickly found the aforementioned link, which yielded my solution.
I posted an updated glitch here, so now pressing z works as I expected. Here is the relevant code portion:
factory.onModelLoaded = function(evt) {
console.log(`onModelLoaded: entered`);
factory.thumbstick = this.scene.children[1].children[2]
let thumb = factory.thumbstick;
// make the thumb red so it's easier to see
thumb.material = (new THREE.MeshBasicMaterial({color: 0xFF7777}));
// use method from https://stackoverflow.com/questions/28848863/threejs-how-to-rotate-around-objects-own-center-instead-of-world-center/28860849#28860849
// to translate the pivot point of the thumbstick to the the thumbstick center
factory.thumbParent = thumb.parent;
let thumbParent = factory.thumbParent;
thumbParent.remove(thumb);
var box = new THREE.Box3().setFromObject( thumb );
box.getCenter( thumb.position ); // this basically yields my prev. "magic numbers"
// thumb.position.multiplyScalar( - 1 );
var pivot = new THREE.Group();
thumbParent.add( pivot );
pivot.add( thumb );
thumb.geometry.center();
// add axeshelp after centering, otherwise the axes help, as a child of thumb,
// will increase the bounding box of thumb, and positioning will be wrong.
axesHelper = new THREE.AxesHelper();
thumb.add(axesHelper);
}
Which allows my "z" handler to just rotate without having to do translation:
case 'z':
case 'Z':
var axis = new THREE.Vector3(0, 5, -3).normalize();
var dir = (evt.key === 'z' ? 1 : -1);
thumb.rotateOnAxis(axis, factory.ONE_DEG * 5.0 * dir);
break;
Interestingly, it's the call to box.getCenter() that generates numbers very close to my "magic numbers":
box.getCenter()
Vector3 {x: 0.001487499801442027, y: -0.007357006114165027, z: 0.04779449797522323}
My empirical guess was {x: 0.001, y: -0.00791666666, z: 0.0475} which is %error {x: 32.7%, y: 7.6%, z: 0.61%}, so I was pretty close esp. on the z component, but still not the "perfect" numbers of box.getCenter().
I need to generate a cube that has the horizontal grid of one cube and the vertical grid of another (to make a cube for pressure on rho levels from a temperature cube and a u wind cube). The documentation is lacking context and I can't find anything useful by googling. I image doing something like copying the temperature cube, fidding with the sigma and delta in the cube and then running factory.update on the cube, but I can't quite work out the syntax.
A HybridHeightFactory is attached to a cube, and produces an "altitude" coordinate on request.
It needs to be linked to a suitable surface-altitude coordinate to work
-- which means it's not so simple to move it to a cube with a different horizontal grid.
So I think "factory.update" is not a great route, it is simpler to just make + attach a new one.
The plan will go something like...
orog = hgrid_cube.coord('surface_altitude')
sigma = vgrid_cube.coord('sigma')
delta = vgrid_cube.coord('level_height')
factory = iris.aux_factory.HybridHeightFactory(delta=delta, sigma=sigma, orography=orog)
new_cube = ...
new_cube.add_aux_coord(orog, (2, 3)) # or whatever dimensions
new_cube.add_aux_coord(sigma, (0,)) # or whatever dimensions
new_cube.add_aux_coord(delta, (0,)) # or whatever dimensions
new_cube.add_aux_factory(factory)
Note: in making "new_cube" from the old data, you may need to remove the existing aux factory too.
def make_p_rho_cube(temp, u_wind):
'''
Given a temperature cube (on p level but theta levels)
and a u_wind cube (on rho levels but staggered)
create a cube for pressure on rho levels - on p points
but not non-staggered horizontal grid
'''
# make a pressure cube. Grid is a new one - horizontal grid
# is as temperature, but
# vertical grid is like u_wind. copy temperature cube then change
# name and units and vertical grid. NB need to set stash code as well
p_rho_cube = temp.copy()
p_rho_cube.rename('air_pressure')
p_rho_cube.units = 'Pa'
p_rho_cube.attributes['STASH'] = iris.fileformats.pp.STASH(1, 0, 407)
# now create and use a new hybrid height factory
# surface altitude on theta pts
surface_alt = temp.coord('surface_altitude')
# vertical grid from wind field
sigma = u_wind.coord('sigma')
delta = u_wind.coord('level_height')
# make a hybrid height factory with these variables
factory = iris.aux_factory.HybridHeightFactory(delta=delta, sigma=sigma,
orography=surface_alt)
# delete the old co-ordinates after saving their dimensions
surface_altitude_dim = p_rho_cube.coord_dims('surface_altitude')
p_rho_cube.remove_coord('surface_altitude')
sigma_dim = p_rho_cube.coord_dims('sigma')
p_rho_cube.remove_coord('sigma')
level_height_dim = p_rho_cube.coord_dims('level_height')
p_rho_cube.remove_coord('level_height')
p_rho_cube.remove_aux_factory(p_rho_cube.aux_factories[0])
# add the new ones
p_rho_cube.add_aux_coord(surface_alt, surface_altitude_dim)
p_rho_cube.add_aux_coord(sigma, sigma_dim)
p_rho_cube.add_aux_coord(delta, level_height_dim)
p_rho_cube.add_aux_factory(factory)
return p_rho_cube
I'm using the blender game engine and python I made a script that makes an empty follow my cursor in 3D space. (I use the keyboard for height for now).
Now I wanted to implement a LookAt function for a general object rather than a camera, using python. I want the object to look exactly at the point I'm hovering (the empty position) at the screen. For now I'm using a cube so basically one face of the cube should always face the empty.
So, I thought of using matrices or quaternions but the problem is that All I have is a direction vector and I chose the x axis for the local look direction. So either way I need to calculate the euler angles and convert them to axis-rotation angles. (theta*[axis^]).
The resources I have in the Blender Game Engine is: mathutils (provide quarternions, euler based rotations (via axis-angles), matrices) - though it doesn't have any updated documentation which is just annyoingly horrible! I have to print help to get some sort of info!
Now I've been able to make the object look at the empty when I rotate only the Z axis. I used a little trick that handles the angle sign for me using simple trigonometry, so sign is handled and I don't need any matrix trickery or quarternions. The problem begins when I try to rotate once again - I want to rotate the Y axis for the up-down look (as known in 3D we need two sorts of rotations to face someone, the third is just for rotating the view upside-down - "rolling the camrea") since this rotation axis is the look direction vector.
Here's my script:
import bge
from mathutils import Vector, Matrix
import math
# Basic stuff
cont = bge.logic.getCurrentController()
own = cont.owner
scene = bge.logic.getCurrentScene()
c = scene.objects["Cube"]
e = scene.objects["Empty"]
# axises (we're using localOrientation)
x = Vector((1.0,0.0,0.0))
y = Vector((0.0,1.0,0.0))
z = Vector((0.0,0.0,1.0))
vec = Vector(e.worldPosition - c.worldPosition) # direction vector
# Converting direction vector into euler angles
# Using trigonometry we get: tan(psi) = cos(phi2)/cos(phi1)
# Where phi1 is the angle between x axises (euler angle)
# and phi2 is the euler of the y axises.
# psi is the z rotation angle.
# get cos(euler_angle)
phi1 = vec.dot(x)/vec.length # = cos p1
phi2 = vec.dot(y)/vec.length # = cos p2
phi3 = vec.dot(z)/vec.length # = cos p3
# get the rotation/steer angles
zAngle = math.atan(phi2/phi1)
yAngle = math.atan2(phi3,phi1)
xAngle = math.atan(phi2/phi3)
# use only 2 as the third must adapt (also: view concept - x is the looking direction, rotating it would make rolling)
r = c.localOrientation.to_euler()
r.z = zAngle
r.y = -yAngle
#r.x = xAngle
c.localOrientation = r
Seperately each axis works perfectly, but when combined, there are little jump glitches when I get through the global Y axis.
Also, it seems that the "local" orientation in blender is just the same as the "worldOrientation" which is also annoying cause I'm not sure anymore in what frame of reference I'm working anymore. If anyone knows, please help !
Edit 1:
Appearantely there's a built in logic block that handles this for me and when I press "3D" it tracks AND succeeds on rotating BOTH axises. Though, I still want to know what's the problem with my script! What did the 3D button do that I didn't?
Edit 2:
I tried stop making trigo tricks and found out that when I use local orientation I ALWAYS get a gimbal lock in one axis. That's probably what happened behind the scenes. Thanks for anyone interested, if you have any good trick I'd still be glad to hear =]!
I have a youtube tutorial on how to make the camera look at specific objects. It may help.
https://www.youtube.com/watch?v=hwbObDkiJrE
But the concept, when using the gui, is to open the object->relations panel and for the object you want to be doing the LookAt, you make it the child of the object you want it to follow (the parent). You then select 'Vertex' as the relationship. This will then affect the rotation angles of the child object only.
Try this,
bpy.data.objects['child'].parent = bpy.data.objects['parent']
bpy.data.objects['child'].parent_type = 'VERTEX'
and actually there is more info here
https://blender.stackexchange.com/questions/26108/how-do-i-parent-objects
I am starting with Three.js so I might have misunderstood some basics of the concept. I have a usual 3d scene with a hierarchy like this:
.
+-container #(0,0,0) (Object3d, no own geometry)
+-child 1 #(1,1,1)
+-child 2 #(1, -2, 5)
+-child 3 #(-4, -2, -3)
.
.
. more should come
all »children« of the »container« are imported models from Blender. What I would like to do is to rotate the whole container around a pivot axis based on the current selection, which should be one of the children.
Image three cubes in Blender, all selected with the 3d cursor at center of first in location and center of transformation. A rotation transforms all cubes, but the rotation is relative to the first in selection.
In terms of three.js, what would like to do is to rotate the container, so that the rotation is applied to all children.
To do that I think that the following steps should do the trick:
create a matrix,
translate that matrix by the negative of the selected objects position
rotate that matrix
translate the matrix back to the selected objects position
apply the transform to the container
I have tried the following code but the result is just wrong:
var sp = selection.position.clone(),
m = new THREE.Matrix4();
selection.localToWorld(sp);
m.setPosition(sp.clone().negate());
//I've used makeRotationX for testing purposes, should be replaced with quaternion rotation later on…
m = m.multiply(new THREE.Matrix4().makeRotationX(2*180/Math.PI));
m = m.multiply(new THREE.Matrix4().makeTranslation(sp.x,sp.y,sp.z));
this._container.applyMatrix(m);
Thanks for help!
UPDATE
sign error—this works:
var sp = selection.position.clone(),
m = new THREE.Matrix4();
m.makeTranslation(sp.x,sp.y,sp.z);
m.multiply(new THREE.Matrix4().makeRotationX(0.1));
m.multiply(new THREE.Matrix4().makeTranslation(-sp.x,-sp.y,-sp.z));
this._container.applyMatrix(m);
BUT that code does not really look that good, creating three matrices for that single operating seems to bit of overhead, what is the usual »three.js-way«?
UPDATE #2
Due to the comment here is an image describing what I would like to do:
The »arrows« at the origin stand for the parent container and the cube, the sphere and the cone are its »children«. The red line shows the line I would like rotate the parent around, this way the rotation is applied to all children.
rotateOnAxis() takes a Vector as axis, so the line the objects rotates around crosses its origin.
I need to create a 3D model of a cube with a circular hole punched at the center of one face passing completely through the cube to the opposite side. I am able to generate the vertices for the faces and for the holes.
Four of the faces (untouched by the hole) can be modeled as a single triangle strip. The inside of the hole can also be modeled as a single triangle strip.
How do I generate the index buffer for the faces with the holes? Is there a standard algorithm(s) to do this?
I am using Direct3D but ideas from elsewhere are welcome.
To generate the index-buffer you want, you could do like this. Thinking in 2D with the face in question as a square with vertices (±1, ±1), and the hole as a circle in the middle.
You walk along the edge of the circle, dividing it into some number of segments.
For each vertex, you project it onto the surrounding square with (x/M,y/M), where M is max(abs(x),abs(y)). M is the absolute value of the biggest coordinate, so this will scale (x,y) so that the biggest coordinate is ±1.
This line you also divide into some number of segments.
The segments of two succeeding lines you join pairwise as faces.
This is an example, subdividing the circle into 64 segments, and each ray into 8 segments. You can choose the numbers to match your requirements.
alt text http://pici.se/pictures/AVhcssRRz.gif
Here is some Python code that demonstrates this:
from math import sin, cos, pi
from itertools import izip
def pairs(iterable):
"""Yields the previous and the current item on each iteration.
"""
last = None
for item in iterable:
if last is not None:
yield last, item
last = item
def circle(radius, subdiv):
"""Yields coordinates of a circle.
"""
for angle in xrange(0,subdiv+1):
x = radius * cos(angle * 2 * pi / subdiv)
y = radius * sin(angle * 2 * pi / subdiv)
yield x, y
def line(x0,y0,x1,y1,subdiv):
"""Yields coordinates of a line.
"""
for t in xrange(subdiv+1):
x = (subdiv - t)*x0 + t*x1
y = (subdiv - t)*y0 + t*y1
yield x/subdiv, y/subdiv
def tesselate_square_with_hole((x,y),(w,h), radius=0.5, subdiv_circle=64, subdiv_ray=8):
"""Yields quads of a tesselated square with a circluar hole.
"""
for (x0,y0),(x1,y1) in pairs(circle(radius,subdiv_circle)):
M0 = max(abs(x0),abs(y0))
xM0, yM0 = x0/M0, y0/M0
M1 = max(abs(x1),abs(y1))
xM1, yM1 = x1/M1, y1/M1
L1 = line(x0,y0,xM0,yM0,subdiv_ray)
L2 = line(x1,y1,xM1,yM1,subdiv_ray)
for ((xa,ya),(xb,yb)),((xc,yc),(xd,yd)) in pairs(izip(L1,L2)):
yield ((x+xa*w/2,y+ya*h/2),
(x+xb*w/2,y+yb*h/2),
(x+xc*w/2,y+yc*h/2),
(x+xd*w/2,y+yd*h/2))
import pygame
def main():
"""Simple pygame program that displays the tesselated figure.
"""
print('Calculating faces...')
faces = list(tesselate_square_with_hole((150,150),(200,200),0.5,64,8))
print('done')
pygame.init()
pygame.display.set_mode((300,300))
surf = pygame.display.get_surface()
running = True
while running:
need_repaint = False
for event in pygame.event.get() or [pygame.event.wait()]:
if event.type == pygame.QUIT:
running = False
elif event.type in (pygame.VIDEOEXPOSE, pygame.VIDEORESIZE):
need_repaint = True
if need_repaint:
print('Repaint')
surf.fill((255,255,255))
for pa,pb,pc,pd in faces:
# draw a single quad with corners (pa,pb,pd,pc)
pygame.draw.aalines(surf,(0,0,0),True,(pa,pb,pd,pc),1)
pygame.display.flip()
try:
main()
finally:
pygame.quit()
You want to look up Tessellation which is the area of math that deals with what MizardX is showing.Folks in 3D Graphcs have to deal with this all the time and there are a variety of tessellation algorithms to take a face with a hole and calculate the triangles needed to render it.
Modern hardware usually can't render concave polygons correctly.
Specifically, there usually isn't even a way to define a polygon with a hole.
You'll need to find a triangulation of the plane around the hole somehow. The best way is probably to create triangles from a vertex of the hole to the nearest vertices of the rectangular face. This will probably create some very thin triangles. if that's not a problem then you're done. if it is then you'll need some mesh fairing/optimization algorithm to create nice looking triangles.
Is alpha blending out of the question? If not, just texture the sides with holes using a texture that has transparency in the middle. You have to do more rendering of polygons since you can't take advantage of drawing front-to-back and ignoring covered faces, but it might be faster than having a lot tiny triangles.
I'm imagining 4 triangle fans coming from the 4 corners of the square.
Just a thought -
If you're into cheating (as done many times in games), you can always construct a regular cube but have the texture for the two faces you desire with a hole (alpha = 0), you can then either clip it in the shader, or blend it (in which case you need to render with Z sort).
You get the inside hole by constructing an inner cylinder facing inwards and with no caps.
Of course this will only work if the geometry is not important to you.