Skip to content
from flask import Flask, request
app = Flask(__name__)
# Bad response code
error_400 = "Bad parameters or missing parameters", 400
error_500 = "Internal server error", 500
# Mandatory for good response
response_header = {"content-type": "application/json"}
response_body = {
"ErrorNumber": 0,
"ErrorMessage": "",
"Value": "Dummy",
}
# Optional for params and good response
optional = {
"ClientID": 0,
"ClientTransactionID": 0,
"ServerTransactionID": 0,
}
path = "/api/v1/switch/<int:device_number>/"
def check(var):
if tipo == int:
try:
return int(var)
except (KeyError, ValueError) as e:
return None
elif tipo == float:
try:
return float(var)
except (KeyError, ValueError) as e:
return None
elif tipo == bool:
try:
if var.lower() == "true":
return True
elif var.lower() == "false":
return False
else:
return None
except (KeyError, ValueError) as e:
return None
else:
try:
return str(var)
except (KeyError, ValueError) as e:
return None
def check_param(param, tipo):
return check(request.args[param], tipo)
def check_data(data, tipo):
return check(api.payload[data], tipo)
def dummy(device_number):
return "Not Implemented"
def canwrite(device_number):
params = [check_param('Id', int)]
if any(p is None for p in params):
return error_400
value = True # Perform get operation here
response_body["Value"] = value
return response_body, 200, response_header
def maxswitch(device_number):
params = [check_param('Id', int)]
if any(p is None for p in params):
return error_400
value = 1 # Perform get operation here
response_body["Value"] = value
return response_body, 200, response_header
def getswitch(device_number):
params = [check_param('Id', int)]
if any(p is None for p in params):
return error_400
value = True # Perform get operation here
response_body["Value"] = value
return response_body, 200, response_header
def getswitchname(device_number):
params = [check_param('Id', int)]
if any(p is None for p in params):
return error_400
value = "switch name" # Perform get operation here
response_body["Value"] = value
return response_body, 200, response_header
def getminswitchvalue(device_number):
params = [check_param('Id', int)]
if any(p is None for p in params):
return error_400
value = "switch name" # Perform get operation here
response_body["Value"] = value
return response_body, 200, response_header
def getswitchdescription(device_number):
params = [check_param('Id', int)]
if any(p is None for p in params):
return error_400
value = "switch description" # Perform get operation here
response_body["Value"] = value
return response_body, 200, response_header
def minswitchvalue(device_number):
params = [check_param('Id', int)]
if any(p is None for p in params):
return error_400
value = 0.001 # Perform get operation here
response_body["Value"] = value
return response_body, 200, response_header
def maxswitchvalue(device_number):
params = [check_param('Id', int)]
if any(p is None for p in params):
return error_400
value = 0.999 # Perform get operation here
response_body["Value"] = value
return response_body, 200, response_header
def getswitchvalue(device_number):
params = [check_param('Id', int)]
if any(p is None for p in params):
return error_400
value = 0.123 # Perform get operation here
response_body["Value"] = value
return response_body, 200, response_header
def switchstep(device_number):
params = [check_param('Id', int)]
if any(p is None for p in params):
return error_400
value = 0.001 # Perform get operation here
response_body["Value"] = value
return response_body, 200, response_header
def setswitch(device_number):
data = [check_data('Id', int),
check_data('State', int)]
if any(d is None for d in data):
return error_400
value = data[1] # Perform set operation here
response_body["Value"] = value
return response_body, 200, response_header
def setswitchname(device_number):
data = [check_data('Id', int),
check_data('Name', int)]
if any(d is None for d in data):
return error_400
value = data[1] # Perform set operation here
response_body["Value"] = value
return response_body, 200, response_header
def setswitchvalue(device_number):
data = [check_data('Id', int),
check_data('Value', int)]
if any(d is None for d in data):
return error_400
value = data[1] # Perform set operation here
response_body["Value"] = value
return response_body, 200, response_header
# Common GET
app.add_url_rule(path+"connected", view_func=dummy)
app.add_url_rule(path+"description", view_func=dummy)
app.add_url_rule(path+"driverinfo", view_func=dummy)
app.add_url_rule(path+"driverversion", view_func=dummy)
app.add_url_rule(path+"interfaceversion", view_func=dummy)
app.add_url_rule(path+"name", view_func=dummy)
app.add_url_rule(path+"supportedactions", view_func=dummy)
# Common PUT
app.add_url_rule(path+"action", view_func=dummy, methods=["PUT"])
app.add_url_rule(path+"commandblind", view_func=dummy, methods=["PUT"])
app.add_url_rule(path+"commandbool", view_func=dummy, methods=["PUT"])
app.add_url_rule(path+"commandstring", view_func=dummy, methods=["PUT"])
app.add_url_rule(path+"connected", view_func=dummy, methods=["PUT"])
# Switch GET
app.add_url_rule(path+"maxswitch", view_func=maxswitch)
app.add_url_rule(path+"canwrite", view_func=canwrite)
app.add_url_rule(path+"getswitch", view_func=getswitch)
app.add_url_rule(path+"getswitchdescription", view_func=getswitchdescription)
app.add_url_rule(path+"getswitchname", view_func=getswitchname)
app.add_url_rule(path+"getswitchvalue", view_func=getswitchvalue)
app.add_url_rule(path+"minswitchvalue", view_func=minswitchvalue)
app.add_url_rule(path+"maxswitchvalue", view_func=maxswitchvalue)
app.add_url_rule(path+"switchstep", view_func=switchstep)
# Switch PUT
app.add_url_rule(path+"setswitch", view_func=setswitch, methods=["PUT"])
app.add_url_rule(path+"setswitchname", view_func=setswitchname, methods=["PUT"])
app.add_url_rule(path+"setswitchvalue", view_func=setswitchvalue, methods=["PUT"])
if __name__ == "__main__":
app.run(debug=True)
from aotools.turbulence.phasescreen import ft_phase_screen
from astropy.modeling import models
import gnuplotlib as gp
import numpy as np
aperture = 400 # mm RADIUS
focal_distance = 6400 # mm
wavelength = 0.0005 # mm
defocus_distance = 1 # mm
# Pupil
padding = 4
y, x = np.mgrid[-aperture*padding:aperture*padding, -aperture*padding:aperture*padding]
ring = models.Ring2D(amplitude=1, x_0=0, y_0=0, r_in=0.2*aperture, r_out=aperture)
pupil = ring(x,y)
# Atmosphere
r_0 = 0.2 # m
L_0 = 100 # m
l_0 = wavelength*0.001 # m
mm_in_m = 0.001 # unit of our "pixels" in m
phase_screen = ft_phase_screen(r_0, 2*aperture*padding, mm_in_m, L_0, l_0)
wavefront = pupil #* np.exp( 1j * phase_screen + 0j)
# Defocus
ptv = defocus_distance * 8*(focal_distance/(2*aperture))**2
r = np.sqrt(x**2 + y**2)
phase_angle = 12*(r**2 - 1) * ptv
kernel_def = np.exp(1j * phase_angle / wavelength *2*np.pi)
defocused_pupil = wavefront * kernel_def
defocused_psf = np.fft.fftshift(np.fft.fft2(defocused_pupil))
defocused_psf = np.abs(defocused_psf)**2
# gp.plotimage(pupil, set=["term x11 1", "size square"])
# gp.plotimage(defocused_psf, set=["term x11 2", "size square"])
import aotools
from aotools.turbulence import phasescreen
from astropy.convolution import convolve, convolve_fft, Gaussian2DKernel
def simulate_defocused_seeing_limited_psf(shape, pixel_scale, seeing, aperture, defocus):
# create an Airy disk model with the given diameter
airy = models.AiryDisk2D(radius=aperture, x_0=shape[0] // 2, y_0=shape[1] // 2)
y, x = np.mgrid[-aperture:aperture, -aperture:aperture]
airy_disk = airy(x,y)
# convolve with a Gaussian kernel to simulate seeing
seeing_kernel = Gaussian2DKernel(seeing / pixel_scale)
seeing_limited = convolve_fft(airy_disk, seeing_kernel)
# simulate atmosphere with a phase screen
np.random.seed(0)
screen = phasescreen.ft_phase_screen(
r0=0.2,
N=shape[0]*2,
delta=1,
L0=10,
l0=0.01,
)
phase_screen = np.exp(1j * screen)
seeing_limited *= np.abs(phase_screen)
# simulate defocus
defocus_kernel = Ring2D(r_in=0.2*aperture, r_out=aperture, amplitude=1)
defocus_psf = defocus_kernel(x,y)
defocus_psf /= np.sum(defocus_psf)
defocus_psf = convolve(seeing_limited, np.pad(defocus_psf, ((0,1),(0,1)), 0), boundary='extend')
return defocus_psf
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# System modules
import json # for users
# Third-party modules
from flask import Blueprint
from flask_restx import Api, reqparse
from flask_httpauth import HTTPBasicAuth
# Custom modules
from .server import web as server_web
# from .blocks import web as blocks_web
# from .control import web as control_web
# from .display import web as display_web
# from .environment import web as environment_web
# #from .home import web as home_web
# from .init import web as init_web
# from .other import web as other_web
# from .templates import web as templates_web
# from .testfulvio import web as testfulvio_web
# from .webcam import web as webcam_web
auth = HTTPBasicAuth()
users_file = 'users.json'
try:
with open(users_file) as json_file:
users = json.load(json_file)
except FileNotFoundError as e:
print(f"{users_file} containing user:pass not found")
exit(0)
@auth.verify_password
def verify(username, password):
if not (username and password):
return False
return users.get(username) == password
############################
# WEB VIEW
############################
web_blueprint = Blueprint('web', __name__)
web = Api(web_blueprint,
title='OARPAF Web view for observatory control',
version='1.0',
description='A description',
decorators=[auth.login_required], # on every page.
)
web.add_namespace(server_web)
# web.add_namespace(blocks_web)
# web.add_namespace(control_web)
# web.add_namespace(display_web)
# web.add_namespace(environment_web)
# #web.add_namespace(home_web)
# web.add_namespace(init_web)
# web.add_namespace(other_web)
# web.add_namespace(templates_web)
# web.add_namespace(testfulvio_web)
# web.add_namespace(webcam_web)
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''Web pages for observation blocks'''
# Third-party modules
from flask import make_response, render_template, request
from flask_restx import Namespace, Resource
from utils.data_access_object import ObservationBlockObject as DAO
dao = DAO("ob")
tpl = DAO("defaults")
web = Namespace('blocks', description='OB generator')
############################
# WEB VIEW
############################
web = Namespace('blocks', description='OB generator')
@web.route("/")
class BlockListWeb(Resource):
"""Show and create OBs"""
def get(self):
"""Show all observation OB files"""
data = dao.todos
return make_response(render_template("blocks.html", data=data, tpl=tpl.todos))
@web.route("/<string:name>")
@web.param("name", "The uniqe name of the OB")
class BlockWeb(Resource):
"""Show a selected OB, update it, or add a new
template in it.
"""
def get(self, name):
"""Show a specific OB"""
included = request.args.get("included") or False
data = dao.show(name)
#data = block.get(name)
return make_response(render_template("block.html",
data=data, tpl=tpl.todos,
included=included))
@web.route("/<string:name>/<int:instance>")
@web.param("name", "The uniqe name of the OB")
@web.param("instance", "The template instance in the selected OB")
class BlockInstanceWeb(Resource):
def get(self, name, instance):
"""Show a specific template instance of the selected OB"""
data = dao.show(name)
data["content"] = [data["content"][instance]]
return make_response(render_template("block.html", data=data))
# return [data]
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''REST API for fits files'''
# System modules
import time
# Third-party modules
from astropy.time import Time
from flask import Response, make_response, render_template, request
from flask_restx import Namespace, Resource, fields
# Custom modules
# import devices
############################
# WEB VIEW
############################
web = Namespace('display', description='Display fits file interface')
@web.route("/")
class Init(Resource):
def get(self):
data = {}
return make_response(render_template("display.html", data=data))
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Third-party modules
from flask import Response, make_response, render_template, request
from flask_restx import Model, Namespace, Resource, fields
# Custom modules
import devices
############################
# WEB VIEW
############################
web = Namespace('environment', description='Meteo Weather page')
@web.route("/")
class EnvironmentWeb(Resource):
""" Weatherpage """
def get(self):
""" Display the meteo """
data = Status().get()
exclude = ["Barometric_trend", "Battery_status", "Battery_volts",
"ET_day", "ET_month", "ET_year",
"Storm_start_date", "Forecast_rule_number", "Forecast_icon"
]
for e in exclude:
data["external"].pop(e, None)
return make_response(render_template("meteo.html", data=data))
......@@ -3,13 +3,10 @@
# System modules
import json
import socket
from time import sleep
# Third-party modules
import subprocess
from time import sleep
import ping3
import requests
from astropy.time import Time
from flask import Response, make_response, render_template, request
......@@ -26,132 +23,17 @@ from .telescope import Status as Tel_Status
from .webcam import Snapshot as Web_Snapshot
from .templates import BobRun as Seq_Status
############################
# REST API
############################
api = Namespace('home', description='Home page API')
@api.route("/ping")
class Ping(Resource):
"""Ping the servers"""
def get(self):
"""Servers status"""
def ping(address, timeout=0.1):
try:
res = ping3.ping(address, timeout=timeout)
return True if res else False
except Exception as e:
res = None
res = {
"response": {
"Ascom server": ping("10.185.119.105"), # ping("ascom"),
"Scientific camera": ping("10.185.119.104"), # ping("ccd-sbig"),
"Meteo station": ping("10.185.119.107"), # ping("meteo"),
"TCS server": ping("10.185.119.102"), # ping("grigioni"),
"All sky camera": ping("130.251.11.11"), # ping("130.251.11.11"),
"Domotics server": ping("130.251.19.26"), # ping("grafana10.com.diten.unige.it"),
"Cabinet switch": ping("10.185.119.108"), # ping("fork"),
"Webcam": ping("10.185.119.106"), # ping("ipcam"),
},
"error": []
}
return res
@api.route("/ports")
class Ports(Resource):
"""Check the ports"""
def req(address, timeout=timeout):
def get(self):
"""Port status"""
timeout = 0.1
def nmap(address, port):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
connection = socket.create_connection(
(address, port), timeout=timeout)
res = True
except TimeoutError as e:
res = None
except ConnectionRefusedError as e:
res = False
except socket.gaierror:
res = False
except OSError as e:
res = False
sock.close()
return res
res = {
"response": {
"Ascom server": nmap("10.185.119.105", 533), # nmap('ascom', 533),
"Scientific camera": nmap("10.185.119.104", 80), # nmap('ccd-sbig', 80),
"Meteo station": nmap("10.185.119.107", 5001), # nmap('meteo', 5001),
"TCS server": nmap("10.185.119.102", 65432), # nmap('grigioni', 65432),
"All sky camera": nmap("130.251.11.11", 80), # nmap('130.251.11.11', 80),
"Domotics server": nmap("130.251.19.26", 7070), # nmap('grafana10.com.diten.unige.it', 7070),
"Cabinet switch": nmap("10.185.119.108", 9000), # nmap('fork', 9000),
"Webcam": nmap("10.185.119.106", 554), # nmap('ipcam', 554),
},
"error": []
}
return res
@api.route("/tests")
class Tests(Resource):
"""Test the servers"""
def get(self):
"""Response from servers"""
timeout = 0.1
def req(address, timeout=timeout):
try:
res = requests.get(address, timeout=timeout)
return True if res.status_code == 200 else False
except requests.exceptions.ConnectTimeout as e:
return None
except requests.exceptions.ConnectionError as e:
return None
except requests.exceptions.ReadTimeout as e:
return None
res = {
"response": {
"Ascom server": req("http://10.185.119.105:533/api/v1/switch/0/getswitch?id=1"),
"Scientific camera": req("http://10.185.119.104/api/VersionNumbers.cgi"),
"Meteo station": req("http://10.185.119.107:5533/api/environment/meteo/clock", timeout=0.1),
"TCS server": req("http://10.185.119.102:5533/api/telescope/coordinates"),
"All sky camera": "Boooh",
"Domotics server": req("http://130.251.19.26:5533/api/camera/power"),
"Cabinet switch": req("http://10.185.119.108:5533/api/telescope/power"),
"Webcam": req("http://10.185.119.106:BigBang2021@ipcam/image/jpeg.cgi"),
# "Ascom server": req("http://ascom:533/api/v1/switch/0/getswitch?id=1"),
# "Scientific camera": req("http://ccd-sbig/api/VersionNumbers.cgi"),
# "Meteo station": req("http://fork:5533/api/environment/meteo/clock", timeout=0.1),
# "TCS server": req("http://fork:5533/api/telescope/coordinates"),
# "All sky camera": "Boooh",
# "Domotics server": req("http://fork:5533/api/camera/power"),
# "Cabinet switch": req("http://fork:5533/api/telescope/power"),
# "Webcam": req("http://admin:BigBang2021@ipcam/image/jpeg.cgi"),
},
"error": []
}
return res
try:
res = requests.get(address, timeout=timeout)
return True if res.status_code == 200 else False
except requests.exceptions.ConnectTimeout as e:
return None
except requests.exceptions.ConnectionError as e:
return None
except requests.exceptions.ReadTimeout as e:
return None
############################
# WEB VIEW
......@@ -162,25 +44,10 @@ web = Namespace('home', description='Home page')
@web.route("/")
class HomeWeb(Resource):
"""Show the home page"""
def get(self):
"""Load the home page"""
ping = Ping()
res = ping.get()
ping = res["response"]
ports = Ports()
res = ports.get()
ports = res["response"]
tests = Tests()
res = tests.get()
tests = res["response"]
print(ports)
data = [ping, ports, tests]
data = [{}, {}, {}]
return make_response(render_template("index.html", data=data))
############################
......
......@@ -5,76 +5,12 @@
from flask import make_response, render_template
from flask_restx import Namespace, Resource, fields
class TodoDAO(object):
def __init__(self):
self.counter = 0
self.todos = []
def read(self, id):
for todo in self.todos:
if todo["id"] == id:
return todo
def create(self, data):
todo = data
todo["id"] = self.counter = self.counter + 1
self.todos.append(todo)
return todo
def update(self, id, data):
todo = self.read(id)
todo.update(data)
return todo
def delete(self, id):
todo = self.read(id)
self.todos.remove(todo)
DAO = TodoDAO()
DAO.create({"task": "first"})
DAO.create({"task": "second"})
#############################################
# JSON
#############################################
api = Namespace('other', description='Other tests')
@api.route("/")
class TodoListApi(Resource):
def get(self):
return DAO.todos
def post(self):
return DAO.create(api.payload), 201
@api.route("/<int:id>")
class TodoApi(Resource):
def get(self, id):
return DAO.read(id)
def delete(self, id):
DAO.delete(id)
return "", 204
def put(self, id):
return DAO.update(id, api.payload)
#############################################
# WEB
#############################################
web = Namespace('other', description='Web snippets')
@web.route("/display")
class Display(Resource):
......
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''Web pages'''
# Third-party modules
from astropy.time import Time
from flask import make_response, render_template, request
from flask_restx import Namespace, Resource
from utils.data_access_object import ObservationBlockObject as DAO
dao = DAO("ob")
tpl = DAO("defaults")
############################
# WEB VIEW
############################
web = Namespace('/', description='All pages')
@web.route("/blocks/")
class BlockListWeb(Resource):
"""Show and create OBs"""
def get(self):
"""Show all observation OB files"""
data = dao.todos
return make_response(render_template("blocks.html", data=data, tpl=tpl.todos))
@web.route("/blocks/<string:name>/")
@web.param("name", "The uniqe name of the OB")
class BlockWeb(Resource):
"""Show a selected OB, update it, or add a new
template in it.
"""
def get(self, name):
"""Show a specific OB"""
included = request.args.get("included") or False
data = dao.show(name)
#data = block.get(name)
return make_response(render_template("block.html",
data=data, tpl=tpl.todos,
included=included))
@web.route("/blocks/<string:name>/<int:instance>/")
@web.param("name", "The uniqe name of the OB")
@web.param("instance", "The template instance in the selected OB")
class BlockInstanceWeb(Resource):
def get(self, name, instance):
"""Show a specific template instance of the selected OB"""
data = dao.show(name)
data["content"] = [data["content"][instance]]
return make_response(render_template("block.html", data=data))
# return [data]
@web.route("/control/")
class ControlWeb(Resource):
def get(self):
data = {}
return make_response(render_template("control.html", data=data))
@web.route("/display/")
class DisplayWeb(Resource):
def get(self):
data = {}
return make_response(render_template("display.html", data=data))
@web.route("/environment/")
class EnvironmentWeb(Resource):
""" Weatherpage """
def get(self):
""" Display the meteo """
data = Status().get()
exclude = ["Barometric_trend", "Battery_status", "Battery_volts",
"ET_day", "ET_month", "ET_year",
"Storm_start_date", "Forecast_rule_number", "Forecast_icon"
]
for e in exclude:
data["external"].pop(e, None)
return make_response(render_template("meteo.html", data=data))
@web.route("/init/")
class InitWeb(Resource):
def get(self):
data = {}
return make_response(render_template("init.html", data=data))
@web.route("/other/button/")
class ButtonWeb(Resource):
def get(self):
data = {}
return make_response(render_template("other/button.html", data=data))
@web.route("/other/fits/")
class FitsWeb(Resource):
def get(self):
# System modules
import io
# Third-party modules
from astropy.io import fits
from flask import send_file
with open("./data/fits/test.fits", mode='rb') as hdul:
data = hdul.read()
fitsdata = send_file(
io.BytesIO(data),
mimetype='image/fits',
as_attachment=True,
download_name='ciccio.fits')
return make_response(fitsdata)
@web.route("/sequencer/")
class BobWeb(Resource):
def get(self):
data = dao.todos
return make_response(render_template("sequencer.html", data=data))
@web.route("/testfulvio/test/")
class TestWeb(Resource):
"""First get/post test web page of Fulvio."""
def get(self):
"""GET fulvio test web page."""
data = {}
return make_response(render_template("other/fulvio.html", data=data))
@web.route("/webcam/")
class WebcamWeb(Resource):
def get(self):
data = {}
return make_response(render_template("webcam.html", data=data))
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# System modules
# Third-party modules
from flask import Response, make_response, render_template, request
from flask_restx import Namespace, Resource, fields
import json
# Custom modules
from sequencer import Sequencer
from utils.data_access_object import ObservationBlockObject as DAO
dao = DAO("ob")
############################
# WEB VIEW
############################
web = Namespace('sequencer', description='Web Sequencer interface')
@web.route("/")
class BobWeb(Resource):
def get(self):
data = dao.todos
return make_response(render_template("sequencer.html", data=data))
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''REST API test for Fulvio'''
# Third-party modules
from flask import Response, make_response, render_template, request
from flask_restx import Namespace, Resource, fields
# Custom modules
# import devices
############################
# WEB VIEW
############################
web = Namespace('fulvio', description='Web fulvio test pages')
@web.route("/test")
class TestWeb(Resource):
"""First get/post test web page of Fulvio."""
def get(self):
"""GET fulvio test web page."""
data = {}
return make_response(render_template("other/fulvio.html", data=data))
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''Web pages for IP camera related operations'''
# System modules
# Third-party modules
from flask import Response, make_response, render_template, request
from flask_restx import Namespace, Resource, fields
# Custom modules
#import devices
############################
# WEB VIEW
############################
web = Namespace('webcam', description='Web webcam interface')
@web.route("/")
class Init(Resource):
def get(self):
data = {}
return make_response(render_template("webcam.html", data=data))
# These are the variables a, b, c in the file.
A 1 0.1
B 2 0.2
C 3 0.3
A 1 0.1
B 2 0.2
C 3 0.3
A 1 0.1
B 2 0.2
C 3 0.3
from astropy.io import fits
from astropy.time import Time
import glob
from utils.analysis import fit_star
filenames = glob.glob("../arp/arp.CLEAN*fits")
filenames.sort()
start = Time.now()
params1 = []
params2 = []
mjd = []
for f in filenames:
data = fits.getdata(f)
mjd.append(fits.getheader(f)["MJD-OBS"])
data1 = data[data.shape[1]//2-20:data.shape[1]//2+20, data.shape[0]//2-20:data.shape[0]//2+20]
p1 = fit_star(data1, display=False)
params1.append(p1)
data2 = data[2106-20:2106+20, 3293-20:3292+20]
p2 = fit_star(data2, display=False)
params2.append(p2)
print((Time.now()-start).to("second"))
import gnuplotlib as gp
import numpy as np
peak1 = [p.peak for p in params1]
peak2 = [p.peak for p in params2]
gp.plot(np.array(mjd), np.array(peak2)/np.array(peak1), terminal="x11 1")
import {
EventDispatcher,
MOUSE,
Quaternion,
Spherical,
TOUCH,
Vector2,
Vector3
} from './three.module.js';
// OrbitControls performs orbiting, dollying (zooming), and panning.
// Unlike TrackballControls, it maintains the "up" direction object.up (+Y by default).
//
// Orbit - left mouse / touch: one-finger move
// Zoom - middle mouse, or mousewheel / touch: two-finger spread or squish
// Pan - right mouse, or left mouse + ctrl/meta/shiftKey, or arrow keys / touch: two-finger move
const _changeEvent = { type: 'change' };
const _startEvent = { type: 'start' };
const _endEvent = { type: 'end' };
class OrbitControls extends EventDispatcher {
constructor( object, domElement ) {
super();
this.object = object;
this.domElement = domElement;
this.domElement.style.touchAction = 'none'; // disable touch scroll
// Set to false to disable this control
this.enabled = true;
// "target" sets the location of focus, where the object orbits around
this.target = new Vector3();
// How far you can dolly in and out ( PerspectiveCamera only )
this.minDistance = 0;
this.maxDistance = Infinity;
// How far you can zoom in and out ( OrthographicCamera only )
this.minZoom = 0;
this.maxZoom = Infinity;
// How far you can orbit vertically, upper and lower limits.
// Range is 0 to Math.PI radians.
this.minPolarAngle = 0; // radians
this.maxPolarAngle = Math.PI; // radians
// How far you can orbit horizontally, upper and lower limits.
// If set, the interval [ min, max ] must be a sub-interval of [ - 2 PI, 2 PI ], with ( max - min < 2 PI )
this.minAzimuthAngle = - Infinity; // radians
this.maxAzimuthAngle = Infinity; // radians
// Set to true to enable damping (inertia)
// If damping is enabled, you must call controls.update() in your animation loop
this.enableDamping = false;
this.dampingFactor = 0.05;
// This option actually enables dollying in and out; left as "zoom" for backwards compatibility.
// Set to false to disable zooming
this.enableZoom = true;
this.zoomSpeed = 1.0;
// Set to false to disable rotating
this.enableRotate = true;
this.rotateSpeed = 1.0;
// Set to false to disable panning
this.enablePan = true;
this.panSpeed = 1.0;
this.screenSpacePanning = true; // if false, pan orthogonal to world-space direction camera.up
this.keyPanSpeed = 7.0; // pixels moved per arrow key push
// Set to true to automatically rotate around the target
// If auto-rotate is enabled, you must call controls.update() in your animation loop
this.autoRotate = false;
this.autoRotateSpeed = 2.0; // 30 seconds per orbit when fps is 60
// The four arrow keys
this.keys = { LEFT: 'ArrowLeft', UP: 'ArrowUp', RIGHT: 'ArrowRight', BOTTOM: 'ArrowDown' };
// Mouse buttons
this.mouseButtons = { LEFT: MOUSE.ROTATE, MIDDLE: MOUSE.DOLLY, RIGHT: MOUSE.PAN };
// Touch fingers
this.touches = { ONE: TOUCH.ROTATE, TWO: TOUCH.DOLLY_PAN };
// for reset
this.target0 = this.target.clone();
this.position0 = this.object.position.clone();
this.zoom0 = this.object.zoom;
// the target DOM element for key events
this._domElementKeyEvents = null;
//
// public methods
//
this.getPolarAngle = function () {
return spherical.phi;
};
this.getAzimuthalAngle = function () {
return spherical.theta;
};
this.getDistance = function () {
return this.object.position.distanceTo( this.target );
};
this.listenToKeyEvents = function ( domElement ) {
domElement.addEventListener( 'keydown', onKeyDown );
this._domElementKeyEvents = domElement;
};
this.stopListenToKeyEvents = function () {
this._domElementKeyEvents.removeEventListener( 'keydown', onKeyDown );
this._domElementKeyEvents = null;
};
this.saveState = function () {
scope.target0.copy( scope.target );
scope.position0.copy( scope.object.position );
scope.zoom0 = scope.object.zoom;
};
this.reset = function () {
scope.target.copy( scope.target0 );
scope.object.position.copy( scope.position0 );
scope.object.zoom = scope.zoom0;
scope.object.updateProjectionMatrix();
scope.dispatchEvent( _changeEvent );
scope.update();
state = STATE.NONE;
};
// this method is exposed, but perhaps it would be better if we can make it private...
this.update = function () {
const offset = new Vector3();
// so camera.up is the orbit axis
const quat = new Quaternion().setFromUnitVectors( object.up, new Vector3( 0, 1, 0 ) );
const quatInverse = quat.clone().invert();
const lastPosition = new Vector3();
const lastQuaternion = new Quaternion();
const twoPI = 2 * Math.PI;
return function update() {
const position = scope.object.position;
offset.copy( position ).sub( scope.target );
// rotate offset to "y-axis-is-up" space
offset.applyQuaternion( quat );
// angle from z-axis around y-axis
spherical.setFromVector3( offset );
if ( scope.autoRotate && state === STATE.NONE ) {
rotateLeft( getAutoRotationAngle() );
}
if ( scope.enableDamping ) {
spherical.theta += sphericalDelta.theta * scope.dampingFactor;
spherical.phi += sphericalDelta.phi * scope.dampingFactor;
} else {
spherical.theta += sphericalDelta.theta;
spherical.phi += sphericalDelta.phi;
}
// restrict theta to be between desired limits
let min = scope.minAzimuthAngle;
let max = scope.maxAzimuthAngle;
if ( isFinite( min ) && isFinite( max ) ) {
if ( min < - Math.PI ) min += twoPI; else if ( min > Math.PI ) min -= twoPI;
if ( max < - Math.PI ) max += twoPI; else if ( max > Math.PI ) max -= twoPI;
if ( min <= max ) {
spherical.theta = Math.max( min, Math.min( max, spherical.theta ) );
} else {
spherical.theta = ( spherical.theta > ( min + max ) / 2 ) ?
Math.max( min, spherical.theta ) :
Math.min( max, spherical.theta );
}
}
// restrict phi to be between desired limits
spherical.phi = Math.max( scope.minPolarAngle, Math.min( scope.maxPolarAngle, spherical.phi ) );
spherical.makeSafe();
spherical.radius *= scale;
// restrict radius to be between desired limits
spherical.radius = Math.max( scope.minDistance, Math.min( scope.maxDistance, spherical.radius ) );
// move target to panned location
if ( scope.enableDamping === true ) {
scope.target.addScaledVector( panOffset, scope.dampingFactor );
} else {
scope.target.add( panOffset );
}
offset.setFromSpherical( spherical );
// rotate offset back to "camera-up-vector-is-up" space
offset.applyQuaternion( quatInverse );
position.copy( scope.target ).add( offset );
scope.object.lookAt( scope.target );
if ( scope.enableDamping === true ) {
sphericalDelta.theta *= ( 1 - scope.dampingFactor );
sphericalDelta.phi *= ( 1 - scope.dampingFactor );
panOffset.multiplyScalar( 1 - scope.dampingFactor );
} else {
sphericalDelta.set( 0, 0, 0 );
panOffset.set( 0, 0, 0 );
}
scale = 1;
// update condition is:
// min(camera displacement, camera rotation in radians)^2 > EPS
// using small-angle approximation cos(x/2) = 1 - x^2 / 8
if ( zoomChanged ||
lastPosition.distanceToSquared( scope.object.position ) > EPS ||
8 * ( 1 - lastQuaternion.dot( scope.object.quaternion ) ) > EPS ) {
scope.dispatchEvent( _changeEvent );
lastPosition.copy( scope.object.position );
lastQuaternion.copy( scope.object.quaternion );
zoomChanged = false;
return true;
}
return false;
};
}();
this.dispose = function () {
scope.domElement.removeEventListener( 'contextmenu', onContextMenu );
scope.domElement.removeEventListener( 'pointerdown', onPointerDown );
scope.domElement.removeEventListener( 'pointercancel', onPointerUp );
scope.domElement.removeEventListener( 'wheel', onMouseWheel );
scope.domElement.removeEventListener( 'pointermove', onPointerMove );
scope.domElement.removeEventListener( 'pointerup', onPointerUp );
if ( scope._domElementKeyEvents !== null ) {
scope._domElementKeyEvents.removeEventListener( 'keydown', onKeyDown );
scope._domElementKeyEvents = null;
}
//scope.dispatchEvent( { type: 'dispose' } ); // should this be added here?
};
//
// internals
//
const scope = this;
const STATE = {
NONE: - 1,
ROTATE: 0,
DOLLY: 1,
PAN: 2,
TOUCH_ROTATE: 3,
TOUCH_PAN: 4,
TOUCH_DOLLY_PAN: 5,
TOUCH_DOLLY_ROTATE: 6
};
let state = STATE.NONE;
const EPS = 0.000001;
// current position in spherical coordinates
const spherical = new Spherical();
const sphericalDelta = new Spherical();
let scale = 1;
const panOffset = new Vector3();
let zoomChanged = false;
const rotateStart = new Vector2();
const rotateEnd = new Vector2();
const rotateDelta = new Vector2();
const panStart = new Vector2();
const panEnd = new Vector2();
const panDelta = new Vector2();
const dollyStart = new Vector2();
const dollyEnd = new Vector2();
const dollyDelta = new Vector2();
const pointers = [];
const pointerPositions = {};
function getAutoRotationAngle() {
return 2 * Math.PI / 60 / 60 * scope.autoRotateSpeed;
}
function getZoomScale() {
return Math.pow( 0.95, scope.zoomSpeed );
}
function rotateLeft( angle ) {
sphericalDelta.theta -= angle;
}
function rotateUp( angle ) {
sphericalDelta.phi -= angle;
}
const panLeft = function () {
const v = new Vector3();
return function panLeft( distance, objectMatrix ) {
v.setFromMatrixColumn( objectMatrix, 0 ); // get X column of objectMatrix
v.multiplyScalar( - distance );
panOffset.add( v );
};
}();
const panUp = function () {
const v = new Vector3();
return function panUp( distance, objectMatrix ) {
if ( scope.screenSpacePanning === true ) {
v.setFromMatrixColumn( objectMatrix, 1 );
} else {
v.setFromMatrixColumn( objectMatrix, 0 );
v.crossVectors( scope.object.up, v );
}
v.multiplyScalar( distance );
panOffset.add( v );
};
}();
// deltaX and deltaY are in pixels; right and down are positive
const pan = function () {
const offset = new Vector3();
return function pan( deltaX, deltaY ) {
const element = scope.domElement;
if ( scope.object.isPerspectiveCamera ) {
// perspective
const position = scope.object.position;
offset.copy( position ).sub( scope.target );
let targetDistance = offset.length();
// half of the fov is center to top of screen
targetDistance *= Math.tan( ( scope.object.fov / 2 ) * Math.PI / 180.0 );
// we use only clientHeight here so aspect ratio does not distort speed
panLeft( 2 * deltaX * targetDistance / element.clientHeight, scope.object.matrix );
panUp( 2 * deltaY * targetDistance / element.clientHeight, scope.object.matrix );
} else if ( scope.object.isOrthographicCamera ) {
// orthographic
panLeft( deltaX * ( scope.object.right - scope.object.left ) / scope.object.zoom / element.clientWidth, scope.object.matrix );
panUp( deltaY * ( scope.object.top - scope.object.bottom ) / scope.object.zoom / element.clientHeight, scope.object.matrix );
} else {
// camera neither orthographic nor perspective
console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - pan disabled.' );
scope.enablePan = false;
}
};
}();
function dollyOut( dollyScale ) {
if ( scope.object.isPerspectiveCamera ) {
scale /= dollyScale;
} else if ( scope.object.isOrthographicCamera ) {
scope.object.zoom = Math.max( scope.minZoom, Math.min( scope.maxZoom, scope.object.zoom * dollyScale ) );
scope.object.updateProjectionMatrix();
zoomChanged = true;
} else {
console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.' );
scope.enableZoom = false;
}
}
function dollyIn( dollyScale ) {
if ( scope.object.isPerspectiveCamera ) {
scale *= dollyScale;
} else if ( scope.object.isOrthographicCamera ) {
scope.object.zoom = Math.max( scope.minZoom, Math.min( scope.maxZoom, scope.object.zoom / dollyScale ) );
scope.object.updateProjectionMatrix();
zoomChanged = true;
} else {
console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.' );
scope.enableZoom = false;
}
}
//
// event callbacks - update the object state
//
function handleMouseDownRotate( event ) {
rotateStart.set( event.clientX, event.clientY );
}
function handleMouseDownDolly( event ) {
dollyStart.set( event.clientX, event.clientY );
}
function handleMouseDownPan( event ) {
panStart.set( event.clientX, event.clientY );
}
function handleMouseMoveRotate( event ) {
rotateEnd.set( event.clientX, event.clientY );
rotateDelta.subVectors( rotateEnd, rotateStart ).multiplyScalar( scope.rotateSpeed );
const element = scope.domElement;
rotateLeft( 2 * Math.PI * rotateDelta.x / element.clientHeight ); // yes, height
rotateUp( 2 * Math.PI * rotateDelta.y / element.clientHeight );
rotateStart.copy( rotateEnd );
scope.update();
}
function handleMouseMoveDolly( event ) {
dollyEnd.set( event.clientX, event.clientY );
dollyDelta.subVectors( dollyEnd, dollyStart );
if ( dollyDelta.y > 0 ) {
dollyOut( getZoomScale() );
} else if ( dollyDelta.y < 0 ) {
dollyIn( getZoomScale() );
}
dollyStart.copy( dollyEnd );
scope.update();
}
function handleMouseMovePan( event ) {
panEnd.set( event.clientX, event.clientY );
panDelta.subVectors( panEnd, panStart ).multiplyScalar( scope.panSpeed );
pan( panDelta.x, panDelta.y );
panStart.copy( panEnd );
scope.update();
}
function handleMouseWheel( event ) {
if ( event.deltaY < 0 ) {
dollyIn( getZoomScale() );
} else if ( event.deltaY > 0 ) {
dollyOut( getZoomScale() );
}
scope.update();
}
function handleKeyDown( event ) {
let needsUpdate = false;
switch ( event.code ) {
case scope.keys.UP:
if ( event.ctrlKey || event.metaKey || event.shiftKey ) {
rotateUp( 2 * Math.PI * scope.rotateSpeed / scope.domElement.clientHeight );
} else {
pan( 0, scope.keyPanSpeed );
}
needsUpdate = true;
break;
case scope.keys.BOTTOM:
if ( event.ctrlKey || event.metaKey || event.shiftKey ) {
rotateUp( - 2 * Math.PI * scope.rotateSpeed / scope.domElement.clientHeight );
} else {
pan( 0, - scope.keyPanSpeed );
}
needsUpdate = true;
break;
case scope.keys.LEFT:
if ( event.ctrlKey || event.metaKey || event.shiftKey ) {
rotateLeft( 2 * Math.PI * scope.rotateSpeed / scope.domElement.clientHeight );
} else {
pan( scope.keyPanSpeed, 0 );
}
needsUpdate = true;
break;
case scope.keys.RIGHT:
if ( event.ctrlKey || event.metaKey || event.shiftKey ) {
rotateLeft( - 2 * Math.PI * scope.rotateSpeed / scope.domElement.clientHeight );
} else {
pan( - scope.keyPanSpeed, 0 );
}
needsUpdate = true;
break;
}
if ( needsUpdate ) {
// prevent the browser from scrolling on cursor keys
event.preventDefault();
scope.update();
}
}
function handleTouchStartRotate() {
if ( pointers.length === 1 ) {
rotateStart.set( pointers[ 0 ].pageX, pointers[ 0 ].pageY );
} else {
const x = 0.5 * ( pointers[ 0 ].pageX + pointers[ 1 ].pageX );
const y = 0.5 * ( pointers[ 0 ].pageY + pointers[ 1 ].pageY );
rotateStart.set( x, y );
}
}
function handleTouchStartPan() {
if ( pointers.length === 1 ) {
panStart.set( pointers[ 0 ].pageX, pointers[ 0 ].pageY );
} else {
const x = 0.5 * ( pointers[ 0 ].pageX + pointers[ 1 ].pageX );
const y = 0.5 * ( pointers[ 0 ].pageY + pointers[ 1 ].pageY );
panStart.set( x, y );
}
}
function handleTouchStartDolly() {
const dx = pointers[ 0 ].pageX - pointers[ 1 ].pageX;
const dy = pointers[ 0 ].pageY - pointers[ 1 ].pageY;
const distance = Math.sqrt( dx * dx + dy * dy );
dollyStart.set( 0, distance );
}
function handleTouchStartDollyPan() {
if ( scope.enableZoom ) handleTouchStartDolly();
if ( scope.enablePan ) handleTouchStartPan();
}
function handleTouchStartDollyRotate() {
if ( scope.enableZoom ) handleTouchStartDolly();
if ( scope.enableRotate ) handleTouchStartRotate();
}
function handleTouchMoveRotate( event ) {
if ( pointers.length == 1 ) {
rotateEnd.set( event.pageX, event.pageY );
} else {
const position = getSecondPointerPosition( event );
const x = 0.5 * ( event.pageX + position.x );
const y = 0.5 * ( event.pageY + position.y );
rotateEnd.set( x, y );
}
rotateDelta.subVectors( rotateEnd, rotateStart ).multiplyScalar( scope.rotateSpeed );
const element = scope.domElement;
rotateLeft( 2 * Math.PI * rotateDelta.x / element.clientHeight ); // yes, height
rotateUp( 2 * Math.PI * rotateDelta.y / element.clientHeight );
rotateStart.copy( rotateEnd );
}
function handleTouchMovePan( event ) {
if ( pointers.length === 1 ) {
panEnd.set( event.pageX, event.pageY );
} else {
const position = getSecondPointerPosition( event );
const x = 0.5 * ( event.pageX + position.x );
const y = 0.5 * ( event.pageY + position.y );
panEnd.set( x, y );
}
panDelta.subVectors( panEnd, panStart ).multiplyScalar( scope.panSpeed );
pan( panDelta.x, panDelta.y );
panStart.copy( panEnd );
}
function handleTouchMoveDolly( event ) {
const position = getSecondPointerPosition( event );
const dx = event.pageX - position.x;
const dy = event.pageY - position.y;
const distance = Math.sqrt( dx * dx + dy * dy );
dollyEnd.set( 0, distance );
dollyDelta.set( 0, Math.pow( dollyEnd.y / dollyStart.y, scope.zoomSpeed ) );
dollyOut( dollyDelta.y );
dollyStart.copy( dollyEnd );
}
function handleTouchMoveDollyPan( event ) {
if ( scope.enableZoom ) handleTouchMoveDolly( event );
if ( scope.enablePan ) handleTouchMovePan( event );
}
function handleTouchMoveDollyRotate( event ) {
if ( scope.enableZoom ) handleTouchMoveDolly( event );
if ( scope.enableRotate ) handleTouchMoveRotate( event );
}
//
// event handlers - FSM: listen for events and reset state
//
function onPointerDown( event ) {
if ( scope.enabled === false ) return;
if ( pointers.length === 0 ) {
scope.domElement.setPointerCapture( event.pointerId );
scope.domElement.addEventListener( 'pointermove', onPointerMove );
scope.domElement.addEventListener( 'pointerup', onPointerUp );
}
//
addPointer( event );
if ( event.pointerType === 'touch' ) {
onTouchStart( event );
} else {
onMouseDown( event );
}
}
function onPointerMove( event ) {
if ( scope.enabled === false ) return;
if ( event.pointerType === 'touch' ) {
onTouchMove( event );
} else {
onMouseMove( event );
}
}
function onPointerUp( event ) {
removePointer( event );
if ( pointers.length === 0 ) {
scope.domElement.releasePointerCapture( event.pointerId );
scope.domElement.removeEventListener( 'pointermove', onPointerMove );
scope.domElement.removeEventListener( 'pointerup', onPointerUp );
}
scope.dispatchEvent( _endEvent );
state = STATE.NONE;
}
function onMouseDown( event ) {
let mouseAction;
switch ( event.button ) {
case 0:
mouseAction = scope.mouseButtons.LEFT;
break;
case 1:
mouseAction = scope.mouseButtons.MIDDLE;
break;
case 2:
mouseAction = scope.mouseButtons.RIGHT;
break;
default:
mouseAction = - 1;
}
switch ( mouseAction ) {
case MOUSE.DOLLY:
if ( scope.enableZoom === false ) return;
handleMouseDownDolly( event );
state = STATE.DOLLY;
break;
case MOUSE.ROTATE:
if ( event.ctrlKey || event.metaKey || event.shiftKey ) {
if ( scope.enablePan === false ) return;
handleMouseDownPan( event );
state = STATE.PAN;
} else {
if ( scope.enableRotate === false ) return;
handleMouseDownRotate( event );
state = STATE.ROTATE;
}
break;
case MOUSE.PAN:
if ( event.ctrlKey || event.metaKey || event.shiftKey ) {
if ( scope.enableRotate === false ) return;
handleMouseDownRotate( event );
state = STATE.ROTATE;
} else {
if ( scope.enablePan === false ) return;
handleMouseDownPan( event );
state = STATE.PAN;
}
break;
default:
state = STATE.NONE;
}
if ( state !== STATE.NONE ) {
scope.dispatchEvent( _startEvent );
}
}
function onMouseMove( event ) {
switch ( state ) {
case STATE.ROTATE:
if ( scope.enableRotate === false ) return;
handleMouseMoveRotate( event );
break;
case STATE.DOLLY:
if ( scope.enableZoom === false ) return;
handleMouseMoveDolly( event );
break;
case STATE.PAN:
if ( scope.enablePan === false ) return;
handleMouseMovePan( event );
break;
}
}
function onMouseWheel( event ) {
if ( scope.enabled === false || scope.enableZoom === false || state !== STATE.NONE ) return;
event.preventDefault();
scope.dispatchEvent( _startEvent );
handleMouseWheel( event );
scope.dispatchEvent( _endEvent );
}
function onKeyDown( event ) {
if ( scope.enabled === false || scope.enablePan === false ) return;
handleKeyDown( event );
}
function onTouchStart( event ) {
trackPointer( event );
switch ( pointers.length ) {
case 1:
switch ( scope.touches.ONE ) {
case TOUCH.ROTATE:
if ( scope.enableRotate === false ) return;
handleTouchStartRotate();
state = STATE.TOUCH_ROTATE;
break;
case TOUCH.PAN:
if ( scope.enablePan === false ) return;
handleTouchStartPan();
state = STATE.TOUCH_PAN;
break;
default:
state = STATE.NONE;
}
break;
case 2:
switch ( scope.touches.TWO ) {
case TOUCH.DOLLY_PAN:
if ( scope.enableZoom === false && scope.enablePan === false ) return;
handleTouchStartDollyPan();
state = STATE.TOUCH_DOLLY_PAN;
break;
case TOUCH.DOLLY_ROTATE:
if ( scope.enableZoom === false && scope.enableRotate === false ) return;
handleTouchStartDollyRotate();
state = STATE.TOUCH_DOLLY_ROTATE;
break;
default:
state = STATE.NONE;
}
break;
default:
state = STATE.NONE;
}
if ( state !== STATE.NONE ) {
scope.dispatchEvent( _startEvent );
}
}
function onTouchMove( event ) {
trackPointer( event );
switch ( state ) {
case STATE.TOUCH_ROTATE:
if ( scope.enableRotate === false ) return;
handleTouchMoveRotate( event );
scope.update();
break;
case STATE.TOUCH_PAN:
if ( scope.enablePan === false ) return;
handleTouchMovePan( event );
scope.update();
break;
case STATE.TOUCH_DOLLY_PAN:
if ( scope.enableZoom === false && scope.enablePan === false ) return;
handleTouchMoveDollyPan( event );
scope.update();
break;
case STATE.TOUCH_DOLLY_ROTATE:
if ( scope.enableZoom === false && scope.enableRotate === false ) return;
handleTouchMoveDollyRotate( event );
scope.update();
break;
default:
state = STATE.NONE;
}
}
function onContextMenu( event ) {
if ( scope.enabled === false ) return;
event.preventDefault();
}
function addPointer( event ) {
pointers.push( event );
}
function removePointer( event ) {
delete pointerPositions[ event.pointerId ];
for ( let i = 0; i < pointers.length; i ++ ) {
if ( pointers[ i ].pointerId == event.pointerId ) {
pointers.splice( i, 1 );
return;
}
}
}
function trackPointer( event ) {
let position = pointerPositions[ event.pointerId ];
if ( position === undefined ) {
position = new Vector2();
pointerPositions[ event.pointerId ] = position;
}
position.set( event.pageX, event.pageY );
}
function getSecondPointerPosition( event ) {
const pointer = ( event.pointerId === pointers[ 0 ].pointerId ) ? pointers[ 1 ] : pointers[ 0 ];
return pointerPositions[ pointer.pointerId ];
}
//
scope.domElement.addEventListener( 'contextmenu', onContextMenu );
scope.domElement.addEventListener( 'pointerdown', onPointerDown );
scope.domElement.addEventListener( 'pointercancel', onPointerUp );
scope.domElement.addEventListener( 'wheel', onMouseWheel, { passive: false } );
// force an update at start
this.update();
}
}
export { OrbitControls };