Skip to content

Instantly share code, notes, and snippets.

@jbush001
Created May 14, 2017 13:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jbush001/e885d4c14f0b02bed87963fdc20772d8 to your computer and use it in GitHub Desktop.
Save jbush001/e885d4c14f0b02bed87963fdc20772d8 to your computer and use it in GitHub Desktop.
Create 3D model of a Torus
#!/usr/bin/env python
#
# Copyright 2011-2015 Jeff Bush
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
#
# Generate a C header file with vertices and indices for a 3D torus.
#
import math
OUTER_STEPS = 12
INNER_STEPS = 12
INNER_DIAMETER = 0.2
OUTER_DIAMETER = 0.5
print('// Autogenerated by mktorus.py')
print('const int kNumTorusVertices = %d;' % (OUTER_STEPS * INNER_STEPS))
print('const float kTorusVertices[] = {')
for outer_step in range(OUTER_STEPS):
outer_r = outer_step * 2.0 * math.pi / OUTER_STEPS
for inner_step in range(INNER_STEPS):
inner_r = inner_step * 2.0 * math.pi / INNER_STEPS
inner_dist = math.cos(inner_r) * INNER_DIAMETER
x = math.sin(outer_r) * (inner_dist + OUTER_DIAMETER)
y = math.cos(outer_r) * (inner_dist + OUTER_DIAMETER)
z = math.sin(inner_r) * INNER_DIAMETER
center_x = math.sin(outer_r) * OUTER_DIAMETER
center_y = math.cos(outer_r) * OUTER_DIAMETER
normal_x = (x - center_x) / INNER_DIAMETER
normal_y = (y - center_y) / INNER_DIAMETER
normal_z = z / INNER_DIAMETER
print('\t%#0.10gf, %#0.10gf, %#0.10gf, %#0.10gf, %#0.10gf, %#0.10gf,' %
(x, y, z, normal_x, normal_y, normal_z))
print('};')
#
# Build index list
#
print('const int k_num_torus_indices = %d;' % (OUTER_STEPS * INNER_STEPS * 6))
print('const int k_torus_indices[] = {')
def step_wrapping_outer(x):
return (x + 1) % OUTER_STEPS
def step_wrapping_inner(x):
return (x + 1) % INNER_STEPS
for outer_step in range(OUTER_STEPS):
for inner_step in range(INNER_STEPS):
print('\t%d, %d, %d,' % (
(outer_step * INNER_STEPS) + inner_step,
(outer_step * INNER_STEPS) + step_wrapping_inner(inner_step),
step_wrapping_outer(outer_step) * INNER_STEPS + step_wrapping_inner(inner_step)))
print('\t%d, %d, %d,' % (
step_wrapping_outer(outer_step) * INNER_STEPS +
step_wrapping_inner(inner_step),
step_wrapping_outer(outer_step) * INNER_STEPS + inner_step,
outer_step * INNER_STEPS + inner_step))
print('};')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment