Boucle du Hainaut : application de réalité augmentée (v46)

PWA three.js + LocAR : pylônes et câbles de la ligne 380 kV sur le tracé
projeté, à l'échelle réelle, cachés par le relief (SPW 10 m), les obstacles
LiDAR (1/2/4 m) et les bâtiments OpenStreetMap. Photo avant/après, calage
de la vue, mini-carte, hors-ligne complet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
mathieuandClaude Opus 5.5 committed 2026-11-15 22:19:19 +01:00
commit 3662fd4993
3571 files changed
+83668

No files matched your search

+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2024 AR.js organisation, unless stated otherwise in individual source files
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+21
View File
@@ -0,0 +1,21 @@
The MIT License
Copyright © 2010-2025 three.js authors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
+697
View File
@@ -0,0 +1,697 @@
import {
ShaderLib,
ShaderMaterial,
UniformsLib,
UniformsUtils,
Vector2,
} from 'three';
UniformsLib.line = {
worldUnits: { value: 1 },
linewidth: { value: 1 },
resolution: { value: new Vector2( 1, 1 ) },
dashOffset: { value: 0 },
dashScale: { value: 1 },
dashSize: { value: 1 },
gapSize: { value: 1 } // todo FIX - maybe change to totalSize
};
ShaderLib[ 'line' ] = {
uniforms: UniformsUtils.merge( [
UniformsLib.common,
UniformsLib.fog,
UniformsLib.line
] ),
vertexShader:
/* glsl */`
#include <common>
#include <color_pars_vertex>
#include <fog_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
uniform float linewidth;
uniform vec2 resolution;
attribute vec3 instanceStart;
attribute vec3 instanceEnd;
attribute vec3 instanceColorStart;
attribute vec3 instanceColorEnd;
#ifdef WORLD_UNITS
varying vec4 worldPos;
varying vec3 worldStart;
varying vec3 worldEnd;
#ifdef USE_DASH
varying vec2 vUv;
#endif
#else
varying vec2 vUv;
#endif
#ifdef USE_DASH
uniform float dashScale;
attribute float instanceDistanceStart;
attribute float instanceDistanceEnd;
varying float vLineDistance;
#endif
void trimSegment( const in vec4 start, inout vec4 end ) {
// trim end segment so it terminates between the camera plane and the near plane
// conservative estimate of the near plane
float a = projectionMatrix[ 2 ][ 2 ]; // 3nd entry in 3th column
float b = projectionMatrix[ 3 ][ 2 ]; // 3nd entry in 4th column
float nearEstimate = - 0.5 * b / a;
float alpha = ( nearEstimate - start.z ) / ( end.z - start.z );
end.xyz = mix( start.xyz, end.xyz, alpha );
}
void main() {
#ifdef USE_COLOR
vColor.xyz = ( position.y < 0.5 ) ? instanceColorStart : instanceColorEnd;
#endif
#ifdef USE_DASH
vLineDistance = ( position.y < 0.5 ) ? dashScale * instanceDistanceStart : dashScale * instanceDistanceEnd;
vUv = uv;
#endif
float aspect = resolution.x / resolution.y;
// camera space
vec4 start = modelViewMatrix * vec4( instanceStart, 1.0 );
vec4 end = modelViewMatrix * vec4( instanceEnd, 1.0 );
#ifdef WORLD_UNITS
worldStart = start.xyz;
worldEnd = end.xyz;
#else
vUv = uv;
#endif
// special case for perspective projection, and segments that terminate either in, or behind, the camera plane
// clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
// but we need to perform ndc-space calculations in the shader, so we must address this issue directly
// perhaps there is a more elegant solution -- WestLangley
bool perspective = ( projectionMatrix[ 2 ][ 3 ] == - 1.0 ); // 4th entry in the 3rd column
if ( perspective ) {
if ( start.z < 0.0 && end.z >= 0.0 ) {
trimSegment( start, end );
} else if ( end.z < 0.0 && start.z >= 0.0 ) {
trimSegment( end, start );
}
}
// clip space
vec4 clipStart = projectionMatrix * start;
vec4 clipEnd = projectionMatrix * end;
// ndc space
vec3 ndcStart = clipStart.xyz / clipStart.w;
vec3 ndcEnd = clipEnd.xyz / clipEnd.w;
// direction
vec2 dir = ndcEnd.xy - ndcStart.xy;
// account for clip-space aspect ratio
dir.x *= aspect;
dir = normalize( dir );
#ifdef WORLD_UNITS
vec3 worldDir = normalize( end.xyz - start.xyz );
vec3 tmpFwd = normalize( mix( start.xyz, end.xyz, 0.5 ) );
vec3 worldUp = normalize( cross( worldDir, tmpFwd ) );
vec3 worldFwd = cross( worldDir, worldUp );
worldPos = position.y < 0.5 ? start: end;
// height offset
float hw = linewidth * 0.5;
worldPos.xyz += position.x < 0.0 ? hw * worldUp : - hw * worldUp;
// don't extend the line if we're rendering dashes because we
// won't be rendering the endcaps
#ifndef USE_DASH
// cap extension
worldPos.xyz += position.y < 0.5 ? - hw * worldDir : hw * worldDir;
// add width to the box
worldPos.xyz += worldFwd * hw;
// endcaps
if ( position.y > 1.0 || position.y < 0.0 ) {
worldPos.xyz -= worldFwd * 2.0 * hw;
}
#endif
// project the worldpos
vec4 clip = projectionMatrix * worldPos;
// shift the depth of the projected points so the line
// segments overlap neatly
vec3 clipPose = ( position.y < 0.5 ) ? ndcStart : ndcEnd;
clip.z = clipPose.z * clip.w;
#else
vec2 offset = vec2( dir.y, - dir.x );
// undo aspect ratio adjustment
dir.x /= aspect;
offset.x /= aspect;
// sign flip
if ( position.x < 0.0 ) offset *= - 1.0;
// endcaps
if ( position.y < 0.0 ) {
offset += - dir;
} else if ( position.y > 1.0 ) {
offset += dir;
}
// adjust for linewidth
offset *= linewidth;
// adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
offset /= resolution.y;
// select end
vec4 clip = ( position.y < 0.5 ) ? clipStart : clipEnd;
// back to clip space
offset *= clip.w;
clip.xy += offset;
#endif
gl_Position = clip;
vec4 mvPosition = ( position.y < 0.5 ) ? start : end; // this is an approximation
#include <logdepthbuf_vertex>
#include <clipping_planes_vertex>
#include <fog_vertex>
}
`,
fragmentShader:
/* glsl */`
uniform vec3 diffuse;
uniform float opacity;
uniform float linewidth;
#ifdef USE_DASH
uniform float dashOffset;
uniform float dashSize;
uniform float gapSize;
#endif
varying float vLineDistance;
#ifdef WORLD_UNITS
varying vec4 worldPos;
varying vec3 worldStart;
varying vec3 worldEnd;
#ifdef USE_DASH
varying vec2 vUv;
#endif
#else
varying vec2 vUv;
#endif
#include <common>
#include <color_pars_fragment>
#include <fog_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
vec2 closestLineToLine(vec3 p1, vec3 p2, vec3 p3, vec3 p4) {
float mua;
float mub;
vec3 p13 = p1 - p3;
vec3 p43 = p4 - p3;
vec3 p21 = p2 - p1;
float d1343 = dot( p13, p43 );
float d4321 = dot( p43, p21 );
float d1321 = dot( p13, p21 );
float d4343 = dot( p43, p43 );
float d2121 = dot( p21, p21 );
float denom = d2121 * d4343 - d4321 * d4321;
float numer = d1343 * d4321 - d1321 * d4343;
mua = numer / denom;
mua = clamp( mua, 0.0, 1.0 );
mub = ( d1343 + d4321 * ( mua ) ) / d4343;
mub = clamp( mub, 0.0, 1.0 );
return vec2( mua, mub );
}
void main() {
float alpha = opacity;
vec4 diffuseColor = vec4( diffuse, alpha );
#include <clipping_planes_fragment>
#ifdef USE_DASH
if ( vUv.y < - 1.0 || vUv.y > 1.0 ) discard; // discard endcaps
if ( mod( vLineDistance + dashOffset, dashSize + gapSize ) > dashSize ) discard; // todo - FIX
#endif
#ifdef WORLD_UNITS
// Find the closest points on the view ray and the line segment
vec3 rayEnd = normalize( worldPos.xyz ) * 1e5;
vec3 lineDir = worldEnd - worldStart;
vec2 params = closestLineToLine( worldStart, worldEnd, vec3( 0.0, 0.0, 0.0 ), rayEnd );
vec3 p1 = worldStart + lineDir * params.x;
vec3 p2 = rayEnd * params.y;
vec3 delta = p1 - p2;
float len = length( delta );
float norm = len / linewidth;
#ifndef USE_DASH
#ifdef USE_ALPHA_TO_COVERAGE
float dnorm = fwidth( norm );
alpha = 1.0 - smoothstep( 0.5 - dnorm, 0.5 + dnorm, norm );
#else
if ( norm > 0.5 ) {
discard;
}
#endif
#endif
#else
#ifdef USE_ALPHA_TO_COVERAGE
// artifacts appear on some hardware if a derivative is taken within a conditional
float a = vUv.x;
float b = ( vUv.y > 0.0 ) ? vUv.y - 1.0 : vUv.y + 1.0;
float len2 = a * a + b * b;
float dlen = fwidth( len2 );
if ( abs( vUv.y ) > 1.0 ) {
alpha = 1.0 - smoothstep( 1.0 - dlen, 1.0 + dlen, len2 );
}
#else
if ( abs( vUv.y ) > 1.0 ) {
float a = vUv.x;
float b = ( vUv.y > 0.0 ) ? vUv.y - 1.0 : vUv.y + 1.0;
float len2 = a * a + b * b;
if ( len2 > 1.0 ) discard;
}
#endif
#endif
#include <logdepthbuf_fragment>
#include <color_fragment>
gl_FragColor = vec4( diffuseColor.rgb, alpha );
#include <tonemapping_fragment>
#include <colorspace_fragment>
#include <fog_fragment>
#include <premultiplied_alpha_fragment>
}
`
};
/**
* A material for drawing wireframe-style geometries.
*
* Unlike {@link LineBasicMaterial}, it supports arbitrary line widths and allows using world units
* instead of screen space units. This material is used with {@link LineSegments2} and {@link Line2}.
*
* This module can only be used with {@link WebGLRenderer}. When using {@link WebGPURenderer},
* use {@link Line2NodeMaterial}.
*
* @augments ShaderMaterial
* @three_import import { LineMaterial } from 'three/addons/lines/LineMaterial.js';
*/
class LineMaterial extends ShaderMaterial {
/**
* Constructs a new line segments geometry.
*
* @param {Object} [parameters] - An object with one or more properties
* defining the material's appearance. Any property of the material
* (including any property from inherited materials) can be passed
* in here. Color values can be passed any type of value accepted
* by {@link Color#set}.
*/
constructor( parameters ) {
super( {
type: 'LineMaterial',
uniforms: UniformsUtils.clone( ShaderLib[ 'line' ].uniforms ),
vertexShader: ShaderLib[ 'line' ].vertexShader,
fragmentShader: ShaderLib[ 'line' ].fragmentShader,
clipping: true // required for clipping support
} );
/**
* This flag can be used for type testing.
*
* @type {boolean}
* @readonly
* @default true
*/
this.isLineMaterial = true;
this.setValues( parameters );
}
/**
* The material's color.
*
* @type {Color}
* @default (1,1,1)
*/
get color() {
return this.uniforms.diffuse.value;
}
set color( value ) {
this.uniforms.diffuse.value = value;
}
/**
* Whether the material's sizes (width, dash gaps) are in world units.
*
* @type {boolean}
* @default false
*/
get worldUnits() {
return 'WORLD_UNITS' in this.defines;
}
set worldUnits( value ) {
if ( value === true ) {
this.defines.WORLD_UNITS = '';
} else {
delete this.defines.WORLD_UNITS;
}
}
/**
* Controls line thickness in CSS pixel units when `worldUnits` is `false` (default),
* or in world units when `worldUnits` is `true`.
*
* @type {number}
* @default 1
*/
get linewidth() {
return this.uniforms.linewidth.value;
}
set linewidth( value ) {
if ( ! this.uniforms.linewidth ) return;
this.uniforms.linewidth.value = value;
}
/**
* Whether the line is dashed, or solid.
*
* @type {boolean}
* @default false
*/
get dashed() {
return 'USE_DASH' in this.defines;
}
set dashed( value ) {
if ( ( value === true ) !== this.dashed ) {
this.needsUpdate = true;
}
if ( value === true ) {
this.defines.USE_DASH = '';
} else {
delete this.defines.USE_DASH;
}
}
/**
* The scale of the dashes and gaps.
*
* @type {number}
* @default 1
*/
get dashScale() {
return this.uniforms.dashScale.value;
}
set dashScale( value ) {
this.uniforms.dashScale.value = value;
}
/**
* The size of the dash.
*
* @type {number}
* @default 1
*/
get dashSize() {
return this.uniforms.dashSize.value;
}
set dashSize( value ) {
this.uniforms.dashSize.value = value;
}
/**
* Where in the dash cycle the dash starts.
*
* @type {number}
* @default 0
*/
get dashOffset() {
return this.uniforms.dashOffset.value;
}
set dashOffset( value ) {
this.uniforms.dashOffset.value = value;
}
/**
* The size of the gap.
*
* @type {number}
* @default 0
*/
get gapSize() {
return this.uniforms.gapSize.value;
}
set gapSize( value ) {
this.uniforms.gapSize.value = value;
}
/**
* The opacity.
*
* @type {number}
* @default 1
*/
get opacity() {
return this.uniforms.opacity.value;
}
set opacity( value ) {
if ( ! this.uniforms ) return;
this.uniforms.opacity.value = value;
}
/**
* The size of the viewport, in screen pixels. This must be kept updated to make
* screen-space rendering accurate.The `LineSegments2.onBeforeRender` callback
* performs the update for visible objects.
*
* @type {Vector2}
*/
get resolution() {
return this.uniforms.resolution.value;
}
set resolution( value ) {
this.uniforms.resolution.value.copy( value );
}
/**
* Whether to use alphaToCoverage or not. When enabled, this can improve the
* anti-aliasing of line edges when using MSAA.
*
* @type {boolean}
*/
get alphaToCoverage() {
return 'USE_ALPHA_TO_COVERAGE' in this.defines;
}
set alphaToCoverage( value ) {
if ( ! this.defines ) return;
if ( ( value === true ) !== this.alphaToCoverage ) {
this.needsUpdate = true;
}
if ( value === true ) {
this.defines.USE_ALPHA_TO_COVERAGE = '';
} else {
delete this.defines.USE_ALPHA_TO_COVERAGE;
}
}
}
export { LineMaterial };
+426
View File
@@ -0,0 +1,426 @@
import {
Box3,
InstancedInterleavedBuffer,
InterleavedBufferAttribute,
Line3,
MathUtils,
Matrix4,
Mesh,
Sphere,
Vector3,
Vector4
} from 'three';
import { LineSegmentsGeometry } from './LineSegmentsGeometry.js';
import { LineMaterial } from './LineMaterial.js';
const _viewport = new Vector4();
const _start = new Vector3();
const _end = new Vector3();
const _start4 = new Vector4();
const _end4 = new Vector4();
const _ssOrigin = new Vector4();
const _ssOrigin3 = new Vector3();
const _mvMatrix = new Matrix4();
const _line = new Line3();
const _closestPoint = new Vector3();
const _box = new Box3();
const _sphere = new Sphere();
const _clipToWorldVector = new Vector4();
let _ray, _lineWidth;
// Returns the margin required to expand by in world space given the distance from the camera,
// line width, resolution, and camera projection
function getWorldSpaceHalfWidth( camera, distance, resolution ) {
// transform into clip space, adjust the x and y values by the pixel width offset, then
// transform back into world space to get world offset. Note clip space is [-1, 1] so full
// width does not need to be halved.
_clipToWorldVector.set( 0, 0, - distance, 1.0 ).applyMatrix4( camera.projectionMatrix );
_clipToWorldVector.multiplyScalar( 1.0 / _clipToWorldVector.w );
_clipToWorldVector.x = _lineWidth / resolution.width;
_clipToWorldVector.y = _lineWidth / resolution.height;
_clipToWorldVector.applyMatrix4( camera.projectionMatrixInverse );
_clipToWorldVector.multiplyScalar( 1.0 / _clipToWorldVector.w );
return Math.abs( Math.max( _clipToWorldVector.x, _clipToWorldVector.y ) );
}
function raycastWorldUnits( lineSegments, intersects ) {
const matrixWorld = lineSegments.matrixWorld;
const geometry = lineSegments.geometry;
const instanceStart = geometry.attributes.instanceStart;
const instanceEnd = geometry.attributes.instanceEnd;
const segmentCount = Math.min( geometry.instanceCount, instanceStart.count );
for ( let i = 0, l = segmentCount; i < l; i ++ ) {
_line.start.fromBufferAttribute( instanceStart, i );
_line.end.fromBufferAttribute( instanceEnd, i );
_line.applyMatrix4( matrixWorld );
const pointOnLine = new Vector3();
const point = new Vector3();
_ray.distanceSqToSegment( _line.start, _line.end, point, pointOnLine );
const isInside = point.distanceTo( pointOnLine ) < _lineWidth * 0.5;
if ( isInside ) {
intersects.push( {
point,
pointOnLine,
distance: _ray.origin.distanceTo( point ),
object: lineSegments,
face: null,
faceIndex: i,
uv: null,
uv1: null,
} );
}
}
}
function raycastScreenSpace( lineSegments, camera, intersects ) {
const projectionMatrix = camera.projectionMatrix;
const material = lineSegments.material;
const resolution = material.resolution;
const matrixWorld = lineSegments.matrixWorld;
const geometry = lineSegments.geometry;
const instanceStart = geometry.attributes.instanceStart;
const instanceEnd = geometry.attributes.instanceEnd;
const segmentCount = Math.min( geometry.instanceCount, instanceStart.count );
const near = - camera.near;
//
// pick a point 1 unit out along the ray to avoid the ray origin
// sitting at the camera origin which will cause "w" to be 0 when
// applying the projection matrix.
_ray.at( 1, _ssOrigin );
// ndc space [ - 1.0, 1.0 ]
_ssOrigin.w = 1;
_ssOrigin.applyMatrix4( camera.matrixWorldInverse );
_ssOrigin.applyMatrix4( projectionMatrix );
_ssOrigin.multiplyScalar( 1 / _ssOrigin.w );
// screen space
_ssOrigin.x *= resolution.x / 2;
_ssOrigin.y *= resolution.y / 2;
_ssOrigin.z = 0;
_ssOrigin3.copy( _ssOrigin );
_mvMatrix.multiplyMatrices( camera.matrixWorldInverse, matrixWorld );
for ( let i = 0, l = segmentCount; i < l; i ++ ) {
_start4.fromBufferAttribute( instanceStart, i );
_end4.fromBufferAttribute( instanceEnd, i );
_start4.w = 1;
_end4.w = 1;
// camera space
_start4.applyMatrix4( _mvMatrix );
_end4.applyMatrix4( _mvMatrix );
// skip the segment if it's entirely behind the camera
const isBehindCameraNear = _start4.z > near && _end4.z > near;
if ( isBehindCameraNear ) {
continue;
}
// trim the segment if it extends behind camera near
if ( _start4.z > near ) {
const deltaDist = _start4.z - _end4.z;
const t = ( _start4.z - near ) / deltaDist;
_start4.lerp( _end4, t );
} else if ( _end4.z > near ) {
const deltaDist = _end4.z - _start4.z;
const t = ( _end4.z - near ) / deltaDist;
_end4.lerp( _start4, t );
}
// clip space
_start4.applyMatrix4( projectionMatrix );
_end4.applyMatrix4( projectionMatrix );
// ndc space [ - 1.0, 1.0 ]
_start4.multiplyScalar( 1 / _start4.w );
_end4.multiplyScalar( 1 / _end4.w );
// screen space
_start4.x *= resolution.x / 2;
_start4.y *= resolution.y / 2;
_end4.x *= resolution.x / 2;
_end4.y *= resolution.y / 2;
// create 2d segment
_line.start.copy( _start4 );
_line.start.z = 0;
_line.end.copy( _end4 );
_line.end.z = 0;
// get closest point on ray to segment
const param = _line.closestPointToPointParameter( _ssOrigin3, true );
_line.at( param, _closestPoint );
// check if the intersection point is within clip space
const zPos = MathUtils.lerp( _start4.z, _end4.z, param );
const isInClipSpace = zPos >= - 1 && zPos <= 1;
const isInside = _ssOrigin3.distanceTo( _closestPoint ) < _lineWidth * 0.5;
if ( isInClipSpace && isInside ) {
_line.start.fromBufferAttribute( instanceStart, i );
_line.end.fromBufferAttribute( instanceEnd, i );
_line.start.applyMatrix4( matrixWorld );
_line.end.applyMatrix4( matrixWorld );
const pointOnLine = new Vector3();
const point = new Vector3();
_ray.distanceSqToSegment( _line.start, _line.end, point, pointOnLine );
intersects.push( {
point: point,
pointOnLine: pointOnLine,
distance: _ray.origin.distanceTo( point ),
object: lineSegments,
face: null,
faceIndex: i,
uv: null,
uv1: null,
} );
}
}
}
/**
* A series of lines drawn between pairs of vertices.
*
* This adds functionality beyond {@link LineSegments}, like arbitrary line width and changing width
* to be in world units. {@link Line2} extends this object, forming a polyline instead of individual
* segments.
*
* This module can only be used with {@link WebGLRenderer}. When using {@link WebGPURenderer},
* import the class from `lines/webgpu/LineSegments2.js`.
*
* ```js
* const geometry = new LineSegmentsGeometry();
* geometry.setPositions( positions );
* geometry.setColors( colors );
*
* const material = new LineMaterial( { linewidth: 5, vertexColors: true } };
*
* const lineSegments = new LineSegments2( geometry, material );
* scene.add( lineSegments );
* ```
*
* @augments Mesh
* @three_import import { LineSegments2 } from 'three/addons/lines/LineSegments2.js';
*/
class LineSegments2 extends Mesh {
/**
* Constructs a new wide line.
*
* @param {LineSegmentsGeometry} [geometry] - The line geometry.
* @param {LineMaterial} [material] - The line material.
*/
constructor( geometry = new LineSegmentsGeometry(), material = new LineMaterial( { color: Math.random() * 0xffffff } ) ) {
super( geometry, material );
/**
* This flag can be used for type testing.
*
* @type {boolean}
* @readonly
* @default true
*/
this.isLineSegments2 = true;
this.type = 'LineSegments2';
}
/**
* Computes an array of distance values which are necessary for rendering dashed lines.
* For each vertex in the geometry, the method calculates the cumulative length from the
* current point to the very beginning of the line.
*
* @return {LineSegments2} A reference to this instance.
*/
computeLineDistances() {
// for backwards-compatibility, but could be a method of LineSegmentsGeometry...
const geometry = this.geometry;
const instanceStart = geometry.attributes.instanceStart;
const instanceEnd = geometry.attributes.instanceEnd;
const lineDistances = new Float32Array( 2 * instanceStart.count );
for ( let i = 0, j = 0, l = instanceStart.count; i < l; i ++, j += 2 ) {
_start.fromBufferAttribute( instanceStart, i );
_end.fromBufferAttribute( instanceEnd, i );
lineDistances[ j ] = ( j === 0 ) ? 0 : lineDistances[ j - 1 ];
lineDistances[ j + 1 ] = lineDistances[ j ] + _start.distanceTo( _end );
}
const instanceDistanceBuffer = new InstancedInterleavedBuffer( lineDistances, 2, 1 ); // d0, d1
geometry.setAttribute( 'instanceDistanceStart', new InterleavedBufferAttribute( instanceDistanceBuffer, 1, 0 ) ); // d0
geometry.setAttribute( 'instanceDistanceEnd', new InterleavedBufferAttribute( instanceDistanceBuffer, 1, 1 ) ); // d1
return this;
}
/**
* Computes intersection points between a casted ray and this instance.
*
* @param {Raycaster} raycaster - The raycaster.
* @param {Array<Object>} intersects - The target array that holds the intersection points.
*/
raycast( raycaster, intersects ) {
const worldUnits = this.material.worldUnits;
const camera = raycaster.camera;
if ( camera === null && ! worldUnits ) {
console.error( 'LineSegments2: "Raycaster.camera" needs to be set in order to raycast against LineSegments2 while worldUnits is set to false.' );
}
const threshold = ( raycaster.params.Line2 !== undefined ) ? raycaster.params.Line2.threshold || 0 : 0;
_ray = raycaster.ray;
const matrixWorld = this.matrixWorld;
const geometry = this.geometry;
const material = this.material;
_lineWidth = material.linewidth + threshold;
// check if we intersect the sphere bounds
if ( geometry.boundingSphere === null ) {
geometry.computeBoundingSphere();
}
_sphere.copy( geometry.boundingSphere ).applyMatrix4( matrixWorld );
// increase the sphere bounds by the worst case line screen space width
let sphereMargin;
if ( worldUnits ) {
sphereMargin = _lineWidth * 0.5;
} else {
const distanceToSphere = Math.max( camera.near, _sphere.distanceToPoint( _ray.origin ) );
sphereMargin = getWorldSpaceHalfWidth( camera, distanceToSphere, material.resolution );
}
_sphere.radius += sphereMargin;
if ( _ray.intersectsSphere( _sphere ) === false ) {
return;
}
// check if we intersect the box bounds
if ( geometry.boundingBox === null ) {
geometry.computeBoundingBox();
}
_box.copy( geometry.boundingBox ).applyMatrix4( matrixWorld );
// increase the box bounds by the worst case line width
let boxMargin;
if ( worldUnits ) {
boxMargin = _lineWidth * 0.5;
} else {
const distanceToBox = Math.max( camera.near, _box.distanceToPoint( _ray.origin ) );
boxMargin = getWorldSpaceHalfWidth( camera, distanceToBox, material.resolution );
}
_box.expandByScalar( boxMargin );
if ( _ray.intersectsBox( _box ) === false ) {
return;
}
if ( worldUnits ) {
raycastWorldUnits( this, intersects );
} else {
raycastScreenSpace( this, camera, intersects );
}
}
onBeforeRender( renderer ) {
const uniforms = this.material.uniforms;
if ( uniforms && uniforms.resolution ) {
renderer.getViewport( _viewport );
this.material.uniforms.resolution.value.set( _viewport.z, _viewport.w );
}
}
}
export { LineSegments2 };
+298
View File
@@ -0,0 +1,298 @@
import {
Box3,
Float32BufferAttribute,
InstancedBufferGeometry,
InstancedInterleavedBuffer,
InterleavedBufferAttribute,
Sphere,
Vector3,
WireframeGeometry
} from 'three';
const _box = new Box3();
const _vector = new Vector3();
/**
* A series of vertex pairs, forming line segments.
*
* This is used in {@link LineSegments2} to describe the shape.
*
* @augments InstancedBufferGeometry
* @three_import import { LineSegmentsGeometry } from 'three/addons/lines/LineSegmentsGeometry.js';
*/
class LineSegmentsGeometry extends InstancedBufferGeometry {
/**
* Constructs a new line segments geometry.
*/
constructor() {
super();
/**
* This flag can be used for type testing.
*
* @type {boolean}
* @readonly
* @default true
*/
this.isLineSegmentsGeometry = true;
this.type = 'LineSegmentsGeometry';
const positions = [ - 1, 2, 0, 1, 2, 0, - 1, 1, 0, 1, 1, 0, - 1, 0, 0, 1, 0, 0, - 1, - 1, 0, 1, - 1, 0 ];
const uvs = [ - 1, 2, 1, 2, - 1, 1, 1, 1, - 1, - 1, 1, - 1, - 1, - 2, 1, - 2 ];
const index = [ 0, 2, 1, 2, 3, 1, 2, 4, 3, 4, 5, 3, 4, 6, 5, 6, 7, 5 ];
this.setIndex( index );
this.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
}
/**
* Applies the given 4x4 transformation matrix to the geometry.
*
* @param {Matrix4} matrix - The matrix to apply.
* @return {LineSegmentsGeometry} A reference to this instance.
*/
applyMatrix4( matrix ) {
const start = this.attributes.instanceStart;
const end = this.attributes.instanceEnd;
if ( start !== undefined ) {
start.applyMatrix4( matrix );
end.applyMatrix4( matrix );
start.needsUpdate = true;
}
if ( this.boundingBox !== null ) {
this.computeBoundingBox();
}
if ( this.boundingSphere !== null ) {
this.computeBoundingSphere();
}
return this;
}
/**
* Sets the given line positions for this geometry. The length must be a multiple of six since
* each line segment is defined by a start end vertex in the pattern `(xyz xyz)`.
*
* @param {Float32Array|Array<number>} array - The position data to set.
* @return {LineSegmentsGeometry} A reference to this geometry.
*/
setPositions( array ) {
let lineSegments;
if ( array instanceof Float32Array ) {
lineSegments = array;
} else if ( Array.isArray( array ) ) {
lineSegments = new Float32Array( array );
}
const instanceBuffer = new InstancedInterleavedBuffer( lineSegments, 6, 1 ); // xyz, xyz
this.setAttribute( 'instanceStart', new InterleavedBufferAttribute( instanceBuffer, 3, 0 ) ); // xyz
this.setAttribute( 'instanceEnd', new InterleavedBufferAttribute( instanceBuffer, 3, 3 ) ); // xyz
this.instanceCount = this.attributes.instanceStart.count;
//
this.computeBoundingBox();
this.computeBoundingSphere();
return this;
}
/**
* Sets the given line colors for this geometry. The length must be a multiple of six since
* each line segment is defined by a start end color in the pattern `(rgb rgb)`.
*
* @param {Float32Array|Array<number>} array - The position data to set.
* @return {LineSegmentsGeometry} A reference to this geometry.
*/
setColors( array ) {
let colors;
if ( array instanceof Float32Array ) {
colors = array;
} else if ( Array.isArray( array ) ) {
colors = new Float32Array( array );
}
const instanceColorBuffer = new InstancedInterleavedBuffer( colors, 6, 1 ); // rgb, rgb
this.setAttribute( 'instanceColorStart', new InterleavedBufferAttribute( instanceColorBuffer, 3, 0 ) ); // rgb
this.setAttribute( 'instanceColorEnd', new InterleavedBufferAttribute( instanceColorBuffer, 3, 3 ) ); // rgb
return this;
}
/**
* Setups this line segments geometry from the given wireframe geometry.
*
* @param {WireframeGeometry} geometry - The geometry that should be used as a data source for this geometry.
* @return {LineSegmentsGeometry} A reference to this geometry.
*/
fromWireframeGeometry( geometry ) {
this.setPositions( geometry.attributes.position.array );
return this;
}
/**
* Setups this line segments geometry from the given edges geometry.
*
* @param {EdgesGeometry} geometry - The geometry that should be used as a data source for this geometry.
* @return {LineSegmentsGeometry} A reference to this geometry.
*/
fromEdgesGeometry( geometry ) {
this.setPositions( geometry.attributes.position.array );
return this;
}
/**
* Setups this line segments geometry from the given mesh.
*
* @param {Mesh} mesh - The mesh geometry that should be used as a data source for this geometry.
* @return {LineSegmentsGeometry} A reference to this geometry.
*/
fromMesh( mesh ) {
this.fromWireframeGeometry( new WireframeGeometry( mesh.geometry ) );
// set colors, maybe
return this;
}
/**
* Setups this line segments geometry from the given line segments.
*
* @param {LineSegments} lineSegments - The line segments that should be used as a data source for this geometry.
* Assumes the source geometry is not using indices.
* @return {LineSegmentsGeometry} A reference to this geometry.
*/
fromLineSegments( lineSegments ) {
const geometry = lineSegments.geometry;
this.setPositions( geometry.attributes.position.array ); // assumes non-indexed
// set colors, maybe
return this;
}
computeBoundingBox() {
if ( this.boundingBox === null ) {
this.boundingBox = new Box3();
}
const start = this.attributes.instanceStart;
const end = this.attributes.instanceEnd;
if ( start !== undefined && end !== undefined ) {
this.boundingBox.setFromBufferAttribute( start );
_box.setFromBufferAttribute( end );
this.boundingBox.union( _box );
}
}
computeBoundingSphere() {
if ( this.boundingSphere === null ) {
this.boundingSphere = new Sphere();
}
if ( this.boundingBox === null ) {
this.computeBoundingBox();
}
const start = this.attributes.instanceStart;
const end = this.attributes.instanceEnd;
if ( start !== undefined && end !== undefined ) {
const center = this.boundingSphere.center;
this.boundingBox.getCenter( center );
let maxRadiusSq = 0;
for ( let i = 0, il = start.count; i < il; i ++ ) {
_vector.fromBufferAttribute( start, i );
maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector ) );
_vector.fromBufferAttribute( end, i );
maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector ) );
}
this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
if ( isNaN( this.boundingSphere.radius ) ) {
console.error( 'THREE.LineSegmentsGeometry.computeBoundingSphere(): Computed radius is NaN. The instanced position data is likely to have NaN values.', this );
}
}
}
toJSON() {
// todo
}
}
export { LineSegmentsGeometry };
+415
View File
@@ -0,0 +1,415 @@
import * as e from "three";
import { Euler as t, EventDispatcher as n, MathUtils as r, Quaternion as i, Vector3 as a } from "three";
//#region lib/three/event-emitter.ts
var o = class {
constructor() {
this.emit = (e, ...t) => {
this.eventHandlers[e]?.forEach((e) => {
e(...t);
});
}, this.off = (e, t) => {
if (this.eventHandlers[e]) {
let n = this.eventHandlers[e].indexOf(t);
n > -1 && this.eventHandlers[e].splice(n, 1);
}
}, this.eventHandlers = {};
}
on(e, t) {
this.eventHandlers[e] === void 0 && (this.eventHandlers[e] = []), this.eventHandlers[e].push(t);
}
}, s = class extends o {
#e;
constructor({ cameraOptions: t, canvas: n, gpsOptions: r, videoConstraints: i, deviceOrientationOptions: a, serverLogger: o, projection: s, threeObjects: c, dimensionsProvider: u }) {
if (c && t) throw Error("LocAR.App: ERROR: can only specify one of cameraOptions and threeObjects");
super(), this.dimensionsProvider = u;
let { width: d, height: f } = this.#t(), p = d / f;
this.origHfov = c?.camera ? l.vtoh(c.camera.fov, p) : t?.hFov || 80, this.cameraFeedDimensions = null, this.camera = c?.camera || new e.PerspectiveCamera(l.htov(this.origHfov, p), p, t?.near || .001, t?.far || 1e3), this.scene = c?.scene || new e.Scene(), c ? this.renderer = c.renderer : (n ? (this.renderer = new e.WebGLRenderer({
canvas: n,
alpha: !0
}), this.renderer.setClearColor(65280, 0)) : (this.renderer = new e.WebGLRenderer({ alpha: !0 }), this.renderer.setClearColor(65280, 0), this.renderer.domElement.style.position = "relative", this.renderer.domElement.style.zIndex = "999", document.body.appendChild(this.renderer.domElement)), this.renderer.setSize(d, f), this.renderer.setAnimationLoop(() => {
this.deviceOrientationControls?.update(), this.renderer.render(this.scene, this.camera);
let e = this.#e?.raycast(this.camera, this.scene) ?? [];
e.length > 0 && this.emit("objectsIntersected", { intersections: e });
}), window.addEventListener("resize", () => {
let { width: e, height: t } = this.#t();
this.renderer.setSize(e, t), this.camera.aspect = e / t, this.syncFovWithWebcam(this.camera.aspect);
}));
let m = a || { enabled: !0 };
this.locar = new l(this.scene, this.camera, r, o, s), this.webcam = new w(i), this.deviceOrientationControls = m.enabled === !0 ? new S(this.camera, m) : null, this.#e = null;
}
start() {
return new Promise((e, t) => {
this.webcam.on("webcamstarted", (e) => {
let t = e.videoWidth > e.videoHeight;
this.cameraFeedDimensions = {
landWidth: t ? e.videoWidth : e.videoHeight,
landHeight: t ? e.videoHeight : e.videoWidth
};
let { width: n, height: r } = this.#t();
this.matchFovToWebcam(e.videoWidth, e.videoHeight, n / r), this.camera.updateProjectionMatrix(), this.emit("webcamstarted", {
...e,
landVideoWidth: this.cameraFeedDimensions.landWidth,
landVideoHeight: this.cameraFeedDimensions.landHeight
});
}), this.webcam.on("webcamerror", (e) => {
t({
code: e.code,
message: e.message
});
}), this.deviceOrientationControls === null ? e(this.locar) : (this.deviceOrientationControls?.on("deviceorientationgranted", (t) => {
t.target.connect(), e(this.locar);
}), this.deviceOrientationControls.on("deviceorientationerror", (e) => {
t({
code: e.code,
message: e.message
});
}), this.deviceOrientationControls.init());
});
}
syncFovWithWebcam(e) {
if (e === void 0) {
let { width: t, height: n } = this.#t();
e = t / n;
}
if (this.cameraFeedDimensions !== null) {
let t = e > 1 ? this.cameraFeedDimensions.landWidth : this.cameraFeedDimensions.landHeight, n = e > 1 ? this.cameraFeedDimensions.landHeight : this.cameraFeedDimensions.landWidth;
this.matchFovToWebcam(t, n, e);
}
this.camera.updateProjectionMatrix();
}
matchFovToWebcam(e, t, n) {
if (n < e / t) {
let { width: r, height: i } = this.#t(), a = i / t * e, o = l.fovScale(this.origHfov, r / a);
this.camera.fov = l.htov(o, n);
} else this.camera.fov = l.htov(this.origHfov, n);
}
on(e, t) {
e == "objectsIntersected" && this.#e === null && (this.#e = new C(this.renderer)), super.on(e, t);
}
#t() {
return this.dimensionsProvider?.() ?? {
width: window.innerWidth,
height: window.innerHeight
};
}
}, c = class {
constructor() {
this.project = (e, t) => [this.#e(e), this.#t(t)], this.unproject = (e) => [this.#n(e[0]), this.#r(e[1])], this.#e = (e) => e / 180 * this.HALF_EARTH, this.#t = (e) => Math.log(Math.tan((90 + e) * Math.PI / 360)) / (Math.PI / 180) * this.HALF_EARTH / 180, this.#n = (e) => e / this.HALF_EARTH * 180, this.#r = (e) => {
var t = e / this.HALF_EARTH * 180;
return t = 180 / Math.PI * (2 * Math.atan(Math.exp(t * Math.PI / 180)) - Math.PI / 2), t;
}, this.getID = () => "epsg:3857", this.EARTH = 40075016.68, this.HALF_EARTH = 20037508.34;
}
#e;
#t;
#n;
#r;
}, l = class t extends o {
#e;
#t;
#n;
#r;
#i;
#a;
#o;
#s;
#c;
constructor(e, t, n = {}, r = null, i = new c()) {
super(), this.scene = e, this.camera = t, this.#e = i, this.#t = null, this.#n = 0, this.#r = 100, this.#i = null, this.setGpsOptions(n), this.#a = null, this.#o = 0, this.#s = 0, this.#c = r;
}
setProjection(e) {
this.#e = e;
}
setGpsOptions(e = {}) {
e.gpsMinDistance !== void 0 && (this.#n = e.gpsMinDistance), e.gpsMinAccuracy !== void 0 && (this.#r = e.gpsMinAccuracy);
}
async startGps() {
if (this.#c) {
let e = await (await this.#c.sendData("/gps/start", {
gpsMinDistance: this.#n,
gpsMinAccuracy: this.#r
})).json();
this.#s = e.session;
}
return this.#i === null ? (this.#i = navigator.geolocation.watchPosition((e) => {
this.#f(e);
}, (e) => {
this.emit("gpserror", e);
}, { enableHighAccuracy: !0 }), !0) : !1;
}
stopGps() {
return this.#i === null ? !1 : (navigator.geolocation.clearWatch(this.#i), this.#i = null, !0);
}
fakeGps(e, t, n = null, r = 0) {
n !== null && this.setElevation(n), this.#f({ coords: {
longitude: e,
latitude: t,
accuracy: r
} });
}
lonLatToWorldCoords(e, t) {
let n = this.#e.project(e, t);
return this.eastNorthToWorldCoords(n);
}
eastNorthToWorldCoords(e) {
if (this.#a) e[0] -= this.#a[0], e[1] -= this.#a[1];
else throw "No initial position determined";
return [e[0], -e[1]];
}
add(e, t, n, r, i = {}) {
e.properties = i, this.#u(e, t, n, r || 0), this.scene.add(e), this.#c?.sendData("/object/new", {
position: e.position,
x: e.position.x,
z: e.position.z,
session: this.#s,
properties: i
});
}
addGeoLine(t, n, r = 1) {
let i = this.createGeoLine(t, r);
n.setValues({ side: e.DoubleSide });
let a = new e.Mesh(i, n);
return this.scene.add(a), a;
}
createGeoLine(t, n = 1) {
let r = t.map(((t) => {
let [n, r] = this.lonLatToWorldCoords(t[0], t[1]);
return new e.Vector3(n, t[2] || 0, r);
}));
return this.#l(r, n);
}
#l(t, n) {
let r, i, a, o, s = 0, c = 0, l = [], u, d = t.length - 1, f = [];
for (let e = 0; e < d; e++) r = t[e + 1].x - t[e].x, i = t[e + 1].z - t[e].z, a = t[e + 1].y - t[e].y, o = Math.sqrt(r * r + a * a + i * i), s = -(n / 2 * i) / o, c = n / 2 * r / o, u = [
t[e].x - s,
t[e].y,
t[e].z - c,
t[e].x + s,
t[e].y,
t[e].z + c
], e > 0 && u.forEach((e, t) => {
e = (e + l[t]) / 2;
}), f.push(...u), l = [
t[e + 1].x - s,
t[e + 1].y,
t[e + 1].z - c,
t[e + 1].x + s,
t[e + 1].y,
t[e + 1].z + c
];
f.push(t[d].x - s), f.push(t[d].y), f.push(t[d].z - c), f.push(t[d].x + s), f.push(t[d].y), f.push(t[d].z + c);
let p = [];
for (let e = 0; e < d; e++) p.push(e * 2, e * 2 + 1, e * 2 + 2), p.push(e * 2 + 1, e * 2 + 3, e * 2 + 2);
let m = new e.BufferGeometry(), h = new Float32Array(f);
return m.setIndex(p), m.setAttribute("position", new e.BufferAttribute(h, 3)), m.computeBoundingBox(), m;
}
#u(e, t, n, r) {
let i = this.lonLatToWorldCoords(t, n);
r !== void 0 && (e.position.y = r), [e.position.x, e.position.z] = i;
}
setElevation(e) {
this.camera.position.y = e;
}
#d(e, t) {
this.#a = this.#e.project(e, t);
}
#f(e) {
let n = Number.MAX_VALUE;
this.#o++, this.#c?.sendData("/gps/new", {
gpsCount: this.#o,
lat: e.coords.latitude,
lon: e.coords.longitude,
acc: e.coords.accuracy,
session: this.#s
}), e.coords.accuracy <= this.#r && (this.#t === null ? this.#t = {
latitude: e.coords.latitude,
longitude: e.coords.longitude
} : n = t.haversineDist(this.#t, e.coords), n >= this.#n && (this.#t.longitude = e.coords.longitude, this.#t.latitude = e.coords.latitude, this.#a || (this.#d(e.coords.longitude, e.coords.latitude), this.#c?.sendData("/worldorigin/new", {
gpsCount: this.#o,
lat: e.coords.latitude,
lon: e.coords.longitude,
session: this.#s,
initialPosition: this.#a
})), this.#u(this.camera, e.coords.longitude, e.coords.latitude), this.#c?.sendData("/gps/accepted", {
gpsCount: this.#o,
cameraX: this.camera.position.x,
cameraZ: this.camera.position.z,
session: this.#s,
distMoved: n
}), this.emit("gpsupdate", {
position: e,
distMoved: n
})));
}
static haversineDist(t, n) {
let r = e.MathUtils.degToRad(n.longitude - t.longitude), i = e.MathUtils.degToRad(n.latitude - t.latitude), a = Math.sin(i / 2) * Math.sin(i / 2) + Math.cos(e.MathUtils.degToRad(t.latitude)) * Math.cos(e.MathUtils.degToRad(n.latitude)) * (Math.sin(r / 2) * Math.sin(r / 2));
return 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)) * 6371e3;
}
getLastKnownLocation() {
return this.#t;
}
static htov(e, t) {
return this.fovScale(e, 1 / t);
}
static vtoh(e, t) {
return this.fovScale(e, t);
}
static fovScale(e, t) {
return 2 * Math.atan(t * Math.tan(Math.PI / 180 * (e / 2))) * (180 / Math.PI);
}
}, u = "locar-device-orientation-permission-modal", d = "locar-device-orientation-permission-button", f = "locar-device-orientation-permission-message", p = "locar-device-orientation-permission-inner", m = "locar-device-orientation-permission-button-inner", h = "This immersive website requires access to your device motion sensors.", g = navigator.userAgent.match(/iPhone|iPad|iPod/i) || /Macintosh/i.test(navigator.userAgent) && navigator.maxTouchPoints != null && navigator.maxTouchPoints > 1, _ = new a(0, 0, 1), v = new t(), y = new i(), b = new i(-Math.sqrt(.5), 0, 0, Math.sqrt(.5));
2 * Math.PI;
var x = .5 * Math.PI, S = class extends n {
constructor(e, n = {}) {
super(), this.init = () => {
window.DeviceOrientationEvent === void 0 ? this.eventEmitter.emit("deviceorientationerror", {
code: "LOCAR_DEVICE_ORIENTATION_NOT_SUPPORTED",
message: "Device orientation API not supported"
}) : window.isSecureContext === !1 ? this.eventEmitter.emit("deviceorientationerror", {
code: "LOCAR_DEVICE_ORIENTATION_NO_HTTPS",
message: "DeviceOrientationEvent is only available in secure contexts (https)"
}) : typeof window.DeviceOrientationEvent.requestPermission == "function" && this.enablePermissionDialog ? this.obtainPermissionGesture() : this.eventEmitter.emit("deviceorientationgranted", { target: this });
}, this.eventEmitter = new o();
let a = this;
this.object = e, this.object.rotation.reorder("YXZ"), this.enabled = !0, this.deviceOrientation = null, this.screenOrientation = 0, this.alphaOffset = 0, this.orientationOffset = 0, this.initialOffset = null, this.lastQuaternion = null, this.orientationChangeEventName = "ondeviceorientationabsolute" in window ? "deviceorientationabsolute" : "deviceorientation", this.smoothingFactor = n.smoothingFactor || .2, this.enablePermissionDialog = n.enablePermissionDialog ?? !0, this.enableInlineStyling = n.enableStyling ?? !0, this.preferConfirmDialog = n.preferConfirmDialog ?? !1, this.orientationChangeThreshold = n.orientationChangeThreshold ?? 0;
let s = (t) => {
let { alpha: n, beta: i, gamma: o, webkitCompassHeading: s } = t;
if (n ??= 0, i ??= 0, o ??= 0, s ??= 0, g) {
let e = 360 - s;
a.alphaOffset = r.degToRad(e - n), a.deviceOrientation = {
alpha: n,
beta: i,
gamma: o,
webkitCompassHeading: s
};
} else n < 0 && (n += 360), a.deviceOrientation = {
alpha: n,
beta: i,
gamma: o
};
window.dispatchEvent(new CustomEvent("camera-rotation-change", { detail: { cameraRotation: e.rotation } }));
}, c = () => {
a.screenOrientation = window.screen.orientation?.angle ?? 0, g && (a.screenOrientation === 90 ? a.orientationOffset = -x : a.screenOrientation === -90 ? a.orientationOffset = x : a.orientationOffset = 0);
}, l = (e, t, n, r, i) => {
v.set(n, t, -r, "YXZ"), e.setFromEuler(v), e.multiply(b), e.multiply(y.setFromAxisAngle(_, -i));
};
this.connect = () => {
c(), window.addEventListener("orientationchange", c), window.addEventListener(a.orientationChangeEventName, s), a.enabled = !0;
}, this.disconnect = () => {
window.removeEventListener("orientationchange", c), window.removeEventListener(a.orientationChangeEventName, s), a.enabled = !1, a.initialOffset = !1, a.deviceOrientation = null, a.lastQuaternion = null;
}, this.requestOrientationPermissions = () => {
window.DeviceOrientationEvent !== void 0 && typeof window.DeviceOrientationEvent.requestPermission == "function" ? window.DeviceOrientationEvent.requestPermission().then((e) => {
e === "granted" ? this.eventEmitter.emit("deviceorientationgranted", { target: this }) : this.eventEmitter.emit("deviceorientationerror", {
code: "LOCAR_DEVICE_ORIENTATION_PERMISSION_DENIED",
message: "Permission for device orientation denied - AR will not work correctly"
});
}).catch((e) => {
this.eventEmitter.emit("deviceorientationerror", {
code: "LOCAR_DEVICE_ORIENTATION_PERMISSION_FAILED",
message: "Permission request for device orientation failed - AR will not work correctly",
error: JSON.stringify(e, null, 2)
});
}) : this.eventEmitter.emit("deviceorientationerror", {
code: "LOCAR_DEVICE_ORIENTATION_INTERNAL_ERROR",
message: "Internal error: no requestPermission() found although requestOrientationPermissions() was called - please raise an issue on GitHub"
});
}, this.update = () => {
if (a.enabled === !1) return;
let e = a.deviceOrientation;
if (e) {
let n = e.alpha ? r.degToRad(e.alpha) + a.alphaOffset : 0, o = e.beta ? r.degToRad(e.beta) : 0, s = e.gamma ? r.degToRad(e.gamma) : 0, c = a.screenOrientation ? r.degToRad(a.screenOrientation) : 0, u = new i();
if (g) {
l(u, n, o, s, c);
let i = new t().setFromQuaternion(u, "YXZ");
i.y = r.degToRad(360 - (e.webkitCompassHeading ?? 0)) + (a.orientationOffset || 0), u.setFromEuler(i);
} else l(u, n, o, s, c);
if (a.lastQuaternion && a.orientationChangeThreshold > 0 && u.angleTo(a.lastQuaternion) < a.orientationChangeThreshold) return;
if (a.smoothingFactor < 1 && a.lastQuaternion) {
let e = 1 - a.smoothingFactor;
a.object.quaternion.slerp(u, e);
} else a.object.quaternion.copy(u);
a.lastQuaternion = a.object.quaternion.clone(), window.dispatchEvent(new CustomEvent("camera-rotation-change", { detail: { cameraRotation: a.object.rotation } }));
}
}, this.getCorrectedHeading = () => {
let { deviceOrientation: e } = a;
if (!e) return 0;
let t = 0;
return g ? (t = 360 - (e.webkitCompassHeading ?? 0), a.orientationOffset && (t += a.orientationOffset * (180 / Math.PI), t = (t + 360) % 360)) : (e.absolute === !0 || a.orientationChangeEventName, t = e.alpha ? e.alpha : 0, t = (360 - t) % 360, t < 0 && (t += 360)), t;
}, this.updateAlphaOffset = () => {
a.initialOffset = !1;
}, this.dispose = () => {
a.disconnect();
}, this.getAlpha = () => {
let { deviceOrientation: e } = a;
return e && e.alpha ? r.degToRad(e.alpha) + a.alphaOffset : 0;
}, this.getBeta = () => {
let { deviceOrientation: e } = a;
return e && e.beta ? r.degToRad(e.beta) : 0;
}, this.getGamma = () => {
let { deviceOrientation: e } = a;
return e && e.gamma ? r.degToRad(e.gamma) : 0;
}, this.createObtainPermissionGestureDialog = () => {
let e = document.createElement("div");
e.classList.add(u);
let t = document.createElement("div");
t.classList.add(p);
let n = document.createElement("div");
n.classList.add(f);
let r = document.createElement("div");
r.classList.add(m);
let i = document.createElement("button");
i.classList.add(d), document.body.appendChild(e), this.enableInlineStyling === !0 && (e.style.fontFamily = "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol'", e.style.display = "flex", e.style.position = "fixed", e.style.zIndex = "100000", e.style.justifyContent = "center", e.style.alignItems = "center", e.style.backgroundColor = "rgba(0,0,0,0.2)", e.style.inset = "0", e.style.padding = "20px", t.style.backgroundColor = "rgba(220, 220, 220, 0.85)", t.style.padding = "6px 0", t.style.borderRadius = "10px", t.style.width = "100%", t.style.maxWidth = "400px", n.style.padding = "10px 12px", n.style.textAlign = "center", n.style.fontWeight = "400", n.style.fontSize = "13px", n.style.display = "flex", n.style.justifyContent = "center", n.style.alignItems = "center", r.style.display = "block", r.style.textAlign = "center", r.style.textDecoration = "none", r.style.borderTop = "rgb(180,180,180) solid 1px", i.style.display = "block", i.style.width = "100%", i.style.textAlign = "center", i.style.appearance = "none", i.style.background = "none", i.style.border = "none", i.style.outline = "none", i.style.padding = "10px", i.style.fontWeight = "400", i.style.fontSize = "16px", i.style.color = "#2e7cf1", i.style.cursor = "pointer"), e.appendChild(t), t.appendChild(n), t.appendChild(r), n.appendChild(document.createTextNode(h)), i.addEventListener("click", () => {
this.requestOrientationPermissions(), e.style.display = "none";
}), i.appendChild(document.createTextNode("OK")), r.appendChild(i), document.body.appendChild(e);
}, this.obtainPermissionGesture = () => {
this.preferConfirmDialog === !0 ? window.confirm(h) && this.requestOrientationPermissions() : this.createObtainPermissionGestureDialog();
};
}
on(e, t) {
this.eventEmitter.on(e, t);
}
}, C = class {
constructor(t) {
this.raycaster = new e.Raycaster(), this.normalisedMousePosition = null, t.domElement.addEventListener("click", (n) => {
let r = t.domElement.getBoundingClientRect();
this.normalisedMousePosition = new e.Vector2((n.clientX - r.left) / t.domElement.clientWidth * 2 - 1, -((n.clientY - r.top) / t.domElement.clientHeight * 2) + 1);
});
}
raycast(e, t) {
if (this.normalisedMousePosition !== null) {
this.raycaster.setFromCamera(this.normalisedMousePosition, e);
let n = this.raycaster.intersectObjects(t.children, !0);
return this.normalisedMousePosition = null, n;
}
return [];
}
}, w = class extends o {
#e;
constructor(e = { video: { facingMode: "environment" } }, t) {
super(), t ? this.video = document.querySelector(t) : (this.video = document.createElement("video"), this.video.setAttribute("autoplay", "true"), this.video.setAttribute("playsinline", "true"), this.video.style.cssText += "\n width: 100%;\n height: 100%;\n object-fit: cover;\n background: black;\n position: absolute;\n top: 0px;\n left: 0px;\n z-index: -100; \n ", document.body.appendChild(this.video)), this.#e = null, navigator.mediaDevices && navigator.mediaDevices.getUserMedia ? navigator.mediaDevices.getUserMedia(e).then((e) => {
this.#e = e, this.video?.addEventListener("loadedmetadata", () => {
this.video.play(), this.emit("webcamstarted", {
videoWidth: this.video.videoWidth,
videoHeight: this.video.videoHeight
});
}), this.video && (this.video.srcObject = e);
}).catch((e) => {
this.emit("webcamerror", {
code: e.name,
message: e.message
});
}) : this.emit("webcamerror", {
code: "LOCAR_NO_MEDIA_DEVICES_API",
message: "Media devices API not supported"
});
}
getVideoDimensions() {
return `w ${this.video.videoWidth}, h ${this.video.videoHeight}`;
}
dispose() {
(this.#e?.getTracks() ?? []).forEach((e) => {
e.stop();
}), this.#e = null, this.video?.remove(), this.video = null;
}
};
//#endregion
export { s as App, C as ClickHandler, S as DeviceOrientationControls, o as EventEmitter, l as LocAR, c as SphMercProjection, w as Webcam };
+58952
View File
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff