Skip to content

[tutorials] <brick-viewer> tutorial #775

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

Open
wants to merge 3 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
381 changes: 358 additions & 23 deletions package-lock.json

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,8 @@
}
},
"devDependencies": {
"@material/mwc-icon-button": "^0.25.3",
"@material/mwc-slider": "^0.25.3",
"lerna": "^4.0.0",
"npm-run-all": "^4.1.5",
"prettier": "^2.1.2",
Expand Down
3 changes: 2 additions & 1 deletion packages/lit-dev-content/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,8 @@
"rollup-plugin-minify-html-literals": "^1.2.6",
"rollup-plugin-summary": "^1.2.3",
"rollup-plugin-terser": "^7.0.2",
"slugify": "^1.3.6"
"slugify": "^1.3.6",
"three": "^0.139.0"
},
"dependencies": {
"@lion/combobox": "^0.8.3",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,204 @@
import { ifDefined } from "lit/directives/if-defined.js";
import { LitElement,PropertyValues, css, html } from 'lit';
import { customElement, query, property } from 'lit/decorators.js';

// @ts-ignore
import * as THREE from "three";
// @ts-ignore
import { LDrawLoader } from "three/examples/jsm/loaders/LDrawLoader.js";
// @ts-ignore
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";

import "@material/mwc-icon-button";
import "@material/mwc-slider";
// @ts-ignore
import { Slider } from "@material/mwc-slider";

@customElement("brick-viewer")
export class BrickViewer extends LitElement {
static styles = css`
:host {
display: block;
position: relative;
}
#controls {
position: absolute;
bottom: 0;
width: 100%;
display: flex;
}
mwc-slider {
flex-grow: 1;
}
`;

@property({ type: String })
src: string | null = null;

@property({ type: Number, reflect: true })
step: number = 1;

@query("mwc-slider")
slider!: Slider | null;

private _scene = new THREE.Scene();
private _renderer = new THREE.WebGLRenderer({ antialias: true });
private _camera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 0.01, 10);
private _controls = new OrbitControls(this._camera, this._renderer.domElement);
private _loader = new LDrawLoader();
private _model: any;
private _numConstructionSteps?: number;

async firstUpdated() {
this._camera = new THREE.PerspectiveCamera(
45,
this.clientWidth / this.clientHeight,
1,
10000
);
this._camera.position.set(150, 200, 250);

this._scene = new THREE.Scene();
this._scene.background = new THREE.Color(0xdeebed);

const ambientLight = new THREE.AmbientLight(0xdeebed, 0.4);
this._scene.add(ambientLight);

const directionalLight = new THREE.DirectionalLight(0xffffff, 1);
directionalLight.position.set(-1000, 1200, 1500);
this._scene.add(directionalLight);

this._renderer = new THREE.WebGLRenderer({ antialias: true });
this._renderer.setPixelRatio(window.devicePixelRatio);
this._renderer.setSize(this.offsetWidth, this.offsetHeight);

this._controls = new OrbitControls(this._camera, this._renderer.domElement);
this._controls.addEventListener("change", () =>
requestAnimationFrame(this._animate)
);

(this._loader as any).separateObjects = true;

this._animate();

const resizeObserver = new ResizeObserver(this._onResize);
resizeObserver.observe(this);

// Buttons are loading after slider, so slider's initial width calculation is wrong.
if (this.slider) {
await this.slider.updateComplete;
this.slider.layout();
}
}

private _onResize = (entries: ResizeObserverEntry[]) => {
const { width, height } = entries[0].contentRect;
this._renderer.setSize(width, height);
this._camera.aspect = width / height;
this._camera.updateProjectionMatrix();
requestAnimationFrame(this._animate);
};

private _restart() {
this.step! = 1;
}

private _stepBack() {
this.step! -= 1;
}

private _stepForward() {
this.step! += 1;
}

private _resetCamera() {
this._controls.reset();
}

render() {
return html`
${this._renderer.domElement}

<div id="controls">
<mwc-icon-button
@click=${this._restart}
icon="replay"
></mwc-icon-button>
<mwc-icon-button
@click=${this._stepBack}
icon="navigate_before"
></mwc-icon-button>
<mwc-slider
step="1"
pin
markers
min="1"
max=${ifDefined(this._numConstructionSteps)}
?disabled=${this._numConstructionSteps === undefined}
value=${ifDefined(this.step)}
@input=${(e: CustomEvent) => (this.step = e.detail.value)}
></mwc-slider>
<mwc-icon-button
@click=${this._stepForward}
icon="navigate_next"
></mwc-icon-button>
<mwc-icon-button
@click=${this._resetCamera}
icon="center_focus_strong"
></mwc-icon-button>
</div>
`;
}

update(changedProperties: PropertyValues) {
if (changedProperties.has("src")) {
this._loadModel();
}
if (changedProperties.has("step")) {
this._updateBricksVisibility();
}
super.update(changedProperties);
}

private _loadModel() {
if (this.src === null) {
return;
}
// @ts-ignore
this._loader.setPath("").load(this.src, newModel => {
if (this._model !== undefined) {
this._scene.remove(this._model);
this._model = undefined;
}

this._model = newModel;

// Convert from LDraw coordinates: rotate 180 degrees around OX
this._model.rotation.x = Math.PI;
this._scene.add(this._model);

this._numConstructionSteps = this._model.userData.numConstructionSteps;
this.step = this._numConstructionSteps!;

// Adjust camera
const bbox = new THREE.Box3().setFromObject(this._model);
this._controls.target.copy(bbox.getCenter(new THREE.Vector3()));
this._controls.update();
this._controls.saveState();
});
}

private _updateBricksVisibility() {
this._model &&
this._model.traverse((c: any) => {
if (c.isGroup && this.step) {
c.visible = c.userData.constructionStep <= this.step;
}
});
requestAnimationFrame(this._animate);
}

private _animate = () => {
this._renderer.render(this._scene, this._camera);
};
}
Original file line number Diff line number Diff line change
@@ -1 +1,54 @@
<div>Hello world step 1 completed!</div>
<!DOCTYPE html>
<html>
<head>
<script type="module" src="brick-viewer.js"></script>
<link href="https://fonts.googleapis.com/css?family=Material+Icons&display=block" rel="stylesheet">
<style>
body {
margin: 0;
padding: 20px;
font-family: sans-serif;
}
brick-viewer {
margin: 20px 0;
height: 300px;
}
</style>
</head>
<body>
<h1>Brick Viewer</h1>

<mwc-select id="select">
<mwc-list-item
selected
value="https://raw.githubusercontent.com/mrdoob/three.js/dev/examples/models/ldraw/officialLibrary/models/car.ldr_Packed.mpd"
>Car</mwc-list-item
>
<mwc-list-item
value="https://raw.githubusercontent.com/mrdoob/three.js/dev/examples/models/ldraw/officialLibrary/models/4915-1-MiniConstruction.mpd_Packed.mpd"
>Bulldozer</mwc-list-item
>
<mwc-list-item
value="https://raw.githubusercontent.com/mrdoob/three.js/dev/examples/models/ldraw/officialLibrary/models/889-1-RadarTruck.mpd_Packed.mpd"
>Radar Truck</mwc-list-item
>
</mwc-select>

<brick-viewer
src="https://raw.githubusercontent.com/mrdoob/three.js/dev/examples/models/ldraw/officialLibrary/models/car.ldr_Packed.mpd"
>
</brick-viewer>

<p>
The &lt;brick-viewer&gt; element sits in your HTML like any other HTML
element!
</p>

<script>
const brickViewer = document.querySelector("brick-viewer");
select.addEventListener("action", function(e) {
brickViewer.src = e.target.selected.value;
});
</script>
</body>
</html>
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
{
"extends": "/samples/base.json",
"files": {
"brick-viewer.ts": {},
"index.html": {}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { LitElement, html } from 'lit';
import { customElement } from 'lit/decorators.js';

@customElement('brick-viewer')
class BrickViewer extends LitElement {
render() {
return html`<div>Brick viewer</div>`;
}
}
Original file line number Diff line number Diff line change
@@ -1 +1,19 @@
<div>Hello world step 1!</div>
<!DOCTYPE html>
<html>
<head>
<script type="module" src="brick-viewer.js"></script>
<link href="https://fonts.googleapis.com/css?family=Material+Icons&display=block" rel="stylesheet">
<style>
body {
font-family: 'Open Sans', sans-serif;
font-size: 1.5em;
padding-left: 0.5em;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<brick-viewer></brick-viewer>
</body>
</html>
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
{
"extends": "/samples/base.json",
"files": {
"brick-viewer.ts": {},
"index.html": {}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { LitElement, html } from 'lit';
import { customElement, property } from 'lit/decorators.js';

@customElement('brick-viewer')
class BrickViewer extends LitElement {
@property({type: String})
src: string|null = null;

render() {
return html`<div>Brick model: ${this.src}</div>`;
}
}
Original file line number Diff line number Diff line change
@@ -1 +1,19 @@
<div>Hello world completed!</div>
<!DOCTYPE html>
<html>
<head>
<script type="module" src="brick-viewer.js"></script>
<link href="https://fonts.googleapis.com/css?family=Material+Icons&display=block" rel="stylesheet">
<style>
body {
font-family: 'Open Sans', sans-serif;
font-size: 1.5em;
padding-left: 0.5em;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<brick-viewer src="path/to/model.ldraw"></brick-viewer>
</body>
</html>
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
{
"extends": "/samples/base.json",
"files": {
"brick-viewer.ts": {},
"index.html": {}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { LitElement, html } from 'lit';
import { customElement } from 'lit/decorators.js';

@customElement('brick-viewer')
class BrickViewer extends LitElement {
render() {
return html`<div>Brick viewer</div>`;
}
}
Loading