Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Custom material #14

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ const renderer = new GCodeRenderer(gcodeString, 800, 600, new Color(0x808080))
// * SimpleColorizer (default) - sets all lines to the same color
// * SpeedColorizer - colorizes based on the speed / feed rate
// * TempColorizer - colorizes based on the temperature
// * LineColorizer - colorizes based on the gcodeLine
renderer.colorizer = new SpeedColorizer(this.renderer.getMinMaxValues().minSpeed || 0, this.renderer.getMinMaxValues().maxSpeed)

document.getElementById("gcode-viewer").append(renderer.element())
Expand Down Expand Up @@ -71,3 +72,28 @@ You can change the line width of travel lines:
renderer. travelWidth = 0.1
```
The default is `0.01`. `0` is also possible to completely hide them.

### Access three.js
Both, the scene and the whole three.js is exported, so you can use it.
For example you can customize the scene setup:

```js
renderer.setupScene = () => {
// Set up some lights. (use different lights in this example)
const ambientLight = new gcodeViewer.THREE.AmbientLight(0xff0000, 0.5);
renderer.scene.add(ambientLight);

const spotLight = new gcodeViewer.THREE.SpotLight(0x00ff00, 0.9);
spotLight.position.set(200, 400, 300);
spotLight.lookAt(new gcodeViewer.THREE.Vector3(0, 0, 0))

const spotLight2 = new gcodeViewer.THREE.SpotLight(0x0000ff, 0.9);
spotLight2.position.set(-200, -400, -300);
spotLight2.lookAt(new gcodeViewer.THREE.Vector3(0, 0, 0))
renderer.scene.add(spotLight);
renderer.scene.add(spotLight2);

renderer.fitCamera()
}
renderer.render().then(() => console.log("rendering finished"))
```
57 changes: 53 additions & 4 deletions example/index.html

Large diffs are not rendered by default.

4 changes: 3 additions & 1 deletion src/LinePoint.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,12 @@ export class LinePoint {
public readonly point: Vector3
public readonly radius: number
public readonly color: Color
public readonly alpha: number

constructor(point: Vector3, radius: number, color: Color = new Color("#29BEB0")) {
constructor(point: Vector3, radius: number, color: Color = new Color("#29BEB0"), alpha: number = 1.0) {
this.point = point
this.radius = radius
this.color = color
this.alpha = alpha
}
}
31 changes: 19 additions & 12 deletions src/LineTubeGeometry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ interface PointData {
vertices: number[]
normals: number[]
colors: number[]
alpha: number
}

/**
Expand All @@ -38,8 +39,9 @@ export class LineTubeGeometry extends BufferGeometry {
private vertices: number[] = []
private normals: number[] = []
private colors: number[] = []
private uvs: number[] = [];
private indices: number[] = [];
private alphas: number[] = []
private uvs: number[] = []
private indices: number[] = []

private segmentsRadialNumbers: number[] = []

Expand All @@ -56,6 +58,7 @@ export class LineTubeGeometry extends BufferGeometry {
this.normals = []
this.vertices = []
this.colors = []
this.alphas = []
this.uvs = []
this.indices = []
this.segmentsRadialNumbers = []
Expand Down Expand Up @@ -83,10 +86,11 @@ export class LineTubeGeometry extends BufferGeometry {
this.generateSegment(1);
}

console.log(this.alphas.filter(a => a === 0).length, this.alphas.filter(a => a === 1).length)
this.setAttribute('position', new Float32BufferAttribute(this.vertices, 3));
this.setAttribute('normal', new Float32BufferAttribute(this.normals, 3));
this.setAttribute('color', new Float32BufferAttribute(this.colors, 3));

this.setAttribute('alpha', new Float32BufferAttribute(this.alphas, 1));
this.generateUVs();
this.setAttribute('uv', new Float32BufferAttribute(this.uvs, 2));

Expand All @@ -100,6 +104,7 @@ export class LineTubeGeometry extends BufferGeometry {
// these are now in the attribute buffers - can be deleted
this.normals = []
this.colors = []
this.alphas = []
this.uvs = []

// The vertices are needed to slice. For now they need to be kept.
Expand Down Expand Up @@ -162,7 +167,7 @@ export class LineTubeGeometry extends BufferGeometry {

const lastRadius = this.pointsBuffer[i-1]?.radius || 0

function createPointData(pointNr: number, radialNr: number, normal: Vector3, point: Vector3, radius: number, color: Color): PointData {
function createPointData(pointNr: number, radialNr: number, normal: Vector3, point: Vector3, radius: number, color: Color, alpha: number): PointData {
return {
pointNr,
radialNr,
Expand All @@ -172,7 +177,8 @@ export class LineTubeGeometry extends BufferGeometry {
point.y + radius * normal.y,
point.z + radius * normal.z
],
colors: color.toArray()
colors: color.toArray(),
alpha,
}
}

Expand Down Expand Up @@ -200,27 +206,28 @@ export class LineTubeGeometry extends BufferGeometry {
// When the previous point doesn't exist, create one with the radius 0 (lastRadius is set to 0 in this case),
// to create a closed starting point.
if (prevPoint === undefined) {
segmentsPoints[0].push(createPointData(i, j, normal, point.point, lastRadius, point.color))
segmentsPoints[0].push(createPointData(i, j, normal, point.point, lastRadius, point.color, point.alpha))
}

// Then insert the current point with the current radius
segmentsPoints[1].push(createPointData(i, j, normal, point.point, point.radius, point.color))
segmentsPoints[1].push(createPointData(i, j, normal, point.point, point.radius, point.color, point.alpha))

// And also the next point with the current radius to finish the current line.
segmentsPoints[2].push(createPointData(i, j, normal, nextPoint.point, point.radius, point.color))
segmentsPoints[2].push(createPointData(i, j, normal, nextPoint.point, point.radius, point.color, point.alpha))

// if the next point is the last one, also finish the line by inserting one with zero radius.
if (nextNextPoint === undefined) {
segmentsPoints[3].push(createPointData(i+1, j, normal, nextPoint.point, 0, point.color))
segmentsPoints[3].push(createPointData(i+1, j, normal, nextPoint.point, 0, point.color, point.alpha))
}
}

// Save everything into the buffers.
segmentsPoints.forEach((p) => {
p.forEach((pp) => {
pp.normals && this.normals.push(...pp.normals);
pp.vertices && this.vertices.push(...pp.vertices);
pp.colors && this.colors.push(...pp.colors);
this.normals.push(...pp.normals);
this.vertices.push(...pp.vertices);
this.colors.push(...pp.colors);
this.alphas.push(pp.alpha);
});
this.segmentsRadialNumbers.push(...p.map((cur) => cur.radialNr))
})
Expand Down
36 changes: 34 additions & 2 deletions src/SegmentColorizer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,49 @@ export interface SegmentMetadata {
temp: number
speed: number

// TODO: Linetype based on comments in gcode
gCodeLine: number
}

const DEFAULT_COLOR = new Color("#29BEB0")

export interface SegmentColorizer {
getColor(meta: SegmentMetadata): Color
}


export interface LineColorizerOptions {
defaultColor: Color
}

export type LineColorConfig = {toLine: number, color: Color}[]

export class LineColorizer {
// This assumes that getColor is called ordered by gCodeLine.
private currentConfigIndex: number = 0

constructor(
private readonly lineColorConfig: LineColorConfig,
private readonly options?: LineColorizerOptions
) {}

getColor(meta: SegmentMetadata): Color {
// Safeguard check if the config is too short.
if (this.lineColorConfig[this.currentConfigIndex] === undefined) {
return this.options?.defaultColor || DEFAULT_COLOR
}

if (this.lineColorConfig[this.currentConfigIndex].toLine < meta.gCodeLine) {
this.currentConfigIndex++
}

return this.lineColorConfig[this.currentConfigIndex].color || this.options?.defaultColor || DEFAULT_COLOR
}
}

export class SimpleColorizer implements SegmentColorizer {
private readonly color

constructor(color = new Color("#29BEB0")) {
constructor(color = DEFAULT_COLOR) {
this.color = color
}

Expand Down
85 changes: 65 additions & 20 deletions src/gcode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,28 +9,83 @@ import {
AmbientLight,
SpotLight,
MeshPhongMaterial,
RawShaderMaterial,
ShaderMaterial,
TangentSpaceNormalMap,
Vector2,
MultiplyOperation,
UniformsUtils,
ShaderLib,
Blending,
NormalBlending,
} from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'
import { lineMaterialFragmentShader } from './meshphong_frag.glsl'
import { lineMaterialVertexShader } from './meshphong_vert.glsl'
import { GCodeParser } from './parser'
import { SegmentColorizer } from './SegmentColorizer'

class LineMaterial extends ShaderMaterial {
constructor() {
super({
name: 'line-material',
vertexShader: lineMaterialVertexShader,
fragmentShader: lineMaterialFragmentShader,
lights: true,
vertexColors: true,
blending: NormalBlending,
})

this.setValues({
uniforms: UniformsUtils.merge([
ShaderLib.phong.uniforms,
{ diffuse: { value: new Color('#ffffff') } },
{ time: { value: 0.0 } }
])
})
}
}

/**
* GCode renderer which parses a GCode file and displays it using
* three.js. Use .element() to retrieve the DOM canvas element.
*/
export class GCodeRenderer {
private readonly scene: Scene
public readonly scene: Scene
private readonly renderer: WebGLRenderer
private cameraControl?: OrbitControls

private camera: PerspectiveCamera

private lineMaterial = new MeshPhongMaterial({ vertexColors: true } )
private lineMaterial = new LineMaterial()

private readonly parser: GCodeParser

// Public configurations:


/**
* Here you can replace the default scene setup (called after adding the model).
* You can use renderer.scene to get access to it and do whatever you want with it.
* The default implementation just adds some lights and then calls renderer.fitCamera().
*/
public setupScene: () => void = () => {
// Set up some lights.
const ambientLight = new AmbientLight(0xffffff, 0.5);
this.scene.add(ambientLight);

const spotLight = new SpotLight(0xffffff, 0.9);
spotLight.position.set(200, 400, 300);
spotLight.lookAt(new Vector3(0, 0, 0))

const spotLight2 = new SpotLight(0xffffff, 0.9);
spotLight2.position.set(-200, -400, -300);
spotLight2.lookAt(new Vector3(0, 0, 0))
this.scene.add(spotLight);
this.scene.add(spotLight2);

this.fitCamera()
}

/**
* Width of travel-lines. Use 0 to hide them.
*
Expand All @@ -57,6 +112,7 @@ export class GCodeRenderer {
public get colorizer(): SegmentColorizer {
return this.parser.colorizer
}

/**
* Set any colorizer implementation to change the segment color based on the segment
* metadata. Some default implementations are provided.
Expand All @@ -78,6 +134,7 @@ export class GCodeRenderer {
public get radialSegments(): number {
return this.parser.radialSegments
}

/**
* The number of radial segments per line.
* Less (e.g. 3) provides faster rendering with less memory usage.
Expand All @@ -102,6 +159,7 @@ export class GCodeRenderer {
public get pointsPerObject(): number {
return this.parser.pointsPerObject
}

/**
* Internally the rendered object is split into several. This allows to reduce the
* memory consumption while rendering.
Expand All @@ -127,7 +185,7 @@ export class GCodeRenderer {
*/
constructor(gCode: string, width: number, height: number, background: Color) {
this.scene = new Scene()
this.renderer = new WebGLRenderer()
this.renderer = new WebGLRenderer({alpha: true})
this.renderer.setSize(width, height)
this.renderer.setClearColor(background, 1)
this.camera = this.newCamera(width, height)
Expand Down Expand Up @@ -168,7 +226,7 @@ export class GCodeRenderer {
return camera
}

private fitCamera() {
public fitCamera() {
const boundingBox = new Box3(this.parser.min, this.parser.max);
const center = new Vector3()
boundingBox.getCenter(center)
Expand All @@ -194,28 +252,15 @@ export class GCodeRenderer {
this.scene.add(new Mesh(g, this.lineMaterial))
});

// Set up some lights.
const ambientLight = new AmbientLight(0xffffff, 0.5);
this.scene.add(ambientLight);

const spotLight = new SpotLight(0xffffff, 0.9);
spotLight.position.set(200, 400, 300);
spotLight.lookAt(new Vector3(0, 0, 0))

const spotLight2 = new SpotLight(0xffffff, 0.9);
spotLight2.position.set(-200, -400, -300);
spotLight2.lookAt(new Vector3(0, 0, 0))
this.scene.add(spotLight);
this.scene.add(spotLight2);

this.fitCamera()
this.setupScene()
}

private draw() {
if (this.parser.getGeometries().length === 0 || this.camera === undefined) {
return
}

this.renderer.clear()
this.renderer.render(this.scene, this.camera)
}

Expand Down
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export * from './gcode'
export * from './SegmentColorizer'
export { Color } from 'three'
export * as THREE from 'three'
Loading