mirror of
https://github.com/cocos/cocos4.git
synced 2026-12-01 15:52:40 +08:00
@@ -2,7 +2,7 @@ import { Asset } from '../../assets/asset';
|
||||
import { ccclass, property } from '../../core/data/class-decorator';
|
||||
import { GFXPrimitiveMode } from '../../gfx/define';
|
||||
import { GFXBlendState, GFXDepthStencilState, GFXRasterizerState } from '../../gfx/pipeline-state';
|
||||
import { RenderPassStage } from '../../pipeline/render-pipeline';
|
||||
import { RenderPassStage } from '../../pipeline/define';
|
||||
|
||||
export interface IPropertyInfo {
|
||||
type: number; // auto-extracted if not specified
|
||||
|
||||
@@ -24,6 +24,7 @@
|
||||
****************************************************************************/
|
||||
import { Asset } from '../../assets/asset';
|
||||
import { ccclass, property } from '../../core/data/class-decorator';
|
||||
import { murmurhash2_32_gc } from '../../core/utils/murmurhash2_gc';
|
||||
import { GFXBindingType } from '../../gfx/define';
|
||||
import { Effect } from '../../renderer/core/effect';
|
||||
import { IPassOverrides, Pass } from '../../renderer/core/pass';
|
||||
@@ -54,6 +55,7 @@ export class Material extends Asset {
|
||||
|
||||
protected _passes: Pass[] = [];
|
||||
protected _owner: any = null;
|
||||
protected _hash = 0;
|
||||
|
||||
@property
|
||||
set effectAsset (val: EffectAsset | null) {
|
||||
@@ -87,6 +89,10 @@ export class Material extends Asset {
|
||||
return this._passes;
|
||||
}
|
||||
|
||||
get hash () {
|
||||
return this._hash;
|
||||
}
|
||||
|
||||
public setDefines (defines: Record<string, number | boolean>) {
|
||||
this._defines = defines;
|
||||
this.update();
|
||||
@@ -99,6 +105,7 @@ export class Material extends Asset {
|
||||
*/
|
||||
public setProperty (name: string, val: any, passIdx?: number) {
|
||||
if (!val) { console.warn(`illegal property value: ${val}.`); return; }
|
||||
let success = false;
|
||||
if (passIdx === undefined) { // set property for all applicable passes
|
||||
const passes = this._passes;
|
||||
const len = passes.length;
|
||||
@@ -106,6 +113,7 @@ export class Material extends Asset {
|
||||
const pass = passes[i];
|
||||
if (this._uploadProperty(pass, name, val)) {
|
||||
this._props[i][name] = val;
|
||||
success = true;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
@@ -113,14 +121,15 @@ export class Material extends Asset {
|
||||
const pass = this._passes[passIdx];
|
||||
if (this._uploadProperty(pass, name, val)) {
|
||||
this._props[passIdx][name] = val;
|
||||
} else {
|
||||
console.warn(`illegal property name: ${name}.`); return;
|
||||
success = true;
|
||||
}
|
||||
}
|
||||
if (!success) { console.warn(`illegal property name: ${name}.`); return; }
|
||||
}
|
||||
|
||||
public copy (mat: Material) {
|
||||
this._props.length = mat._props.length;
|
||||
this._props.fill({});
|
||||
for (let i = 0; i < mat._props.length; i++) {
|
||||
Object.assign(this._props[i], mat._props[i]);
|
||||
}
|
||||
@@ -143,6 +152,7 @@ export class Material extends Asset {
|
||||
} else {
|
||||
this._passes[idx].rebuildWithOverrides(passInfos[idx], overrides);
|
||||
}
|
||||
this.prepareHash();
|
||||
}
|
||||
|
||||
public update (asset: EffectAsset | string | null = this._effectAsset, keepProps: boolean = true) {
|
||||
@@ -177,6 +187,7 @@ export class Material extends Asset {
|
||||
} else {
|
||||
this._props.fill({});
|
||||
}
|
||||
this.prepareHash();
|
||||
}
|
||||
|
||||
protected _uploadProperty (pass: Pass, name: string, val: any) {
|
||||
@@ -192,6 +203,14 @@ export class Material extends Asset {
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
protected prepareHash () {
|
||||
let str = '';
|
||||
for (const pass of this._passes) {
|
||||
str += pass.serializePipelineStates();
|
||||
}
|
||||
this._hash = murmurhash2_32_gc(str, 666);
|
||||
}
|
||||
}
|
||||
|
||||
cc.Material = Material;
|
||||
|
||||
@@ -248,8 +248,10 @@ export interface IPrimitive {
|
||||
indexUnit: IndexUnit;
|
||||
};
|
||||
|
||||
// for raycast purpose
|
||||
geomInfo?: {
|
||||
/**
|
||||
* Geometric info for raycast purposes.
|
||||
*/
|
||||
geometricInfo?: {
|
||||
doubleSided?: boolean;
|
||||
range: IBufferRange;
|
||||
};
|
||||
@@ -501,7 +503,7 @@ export class Mesh extends Asset {
|
||||
inputAssemblerInfo.indexBuffer = indexBuffer;
|
||||
}
|
||||
|
||||
const geomInfo: any = primitive.geomInfo;
|
||||
const geomInfo: any = primitive.geometricInfo;
|
||||
if (geomInfo) {
|
||||
geomInfo.indices = ib;
|
||||
geomInfo.positions = new Float32Array(buffer, geomInfo.range.offset, geomInfo.range.length / 4);
|
||||
|
||||
@@ -101,7 +101,7 @@ export function createMesh (geometry: IGeometry) {
|
||||
|
||||
// Create primitive.
|
||||
const primitive: IPrimitive = {
|
||||
primitiveMode: geometry.primitiveMode,
|
||||
primitiveMode: geometry.primitiveMode || GFXPrimitiveMode.TRIANGLE_LIST,
|
||||
vertexBundelIndices: [0],
|
||||
};
|
||||
if (indexBuffer) {
|
||||
@@ -116,9 +116,9 @@ export function createMesh (geometry: IGeometry) {
|
||||
}
|
||||
|
||||
// geometric info for raycasting
|
||||
if (geometry.primitiveMode >= GFXPrimitiveMode.TRIANGLE_LIST) {
|
||||
if (primitive.primitiveMode >= GFXPrimitiveMode.TRIANGLE_LIST) {
|
||||
const geomInfo = Float32Array.from(geometry.positions);
|
||||
primitive.geomInfo = {
|
||||
primitive.geometricInfo = {
|
||||
doubleSided: geometry.doubleSided,
|
||||
range: { offset: bufferBlob.getLength(), length: geomInfo.byteLength },
|
||||
};
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { Vec3 } from '../../core/value-types';
|
||||
import { vec3 } from '../../core/vmath';
|
||||
import { GFXPrimitiveMode } from '../../gfx/define';
|
||||
import { IGeometry, IGeometryOptions } from './define';
|
||||
|
||||
interface IBoxOptions extends IGeometryOptions {
|
||||
@@ -132,7 +131,6 @@ export default function box (options?: IBoxOptions): IGeometry {
|
||||
_buildPlane(2, ws, ls); // TOP
|
||||
|
||||
return {
|
||||
primitiveMode: GFXPrimitiveMode.TRIANGLE_LIST,
|
||||
positions,
|
||||
normals,
|
||||
uvs,
|
||||
|
||||
@@ -8,11 +8,6 @@ export interface IGeometryOptions {
|
||||
}
|
||||
|
||||
export interface IGeometry {
|
||||
/**
|
||||
* Topology of the geometry vertices.
|
||||
*/
|
||||
primitiveMode: GFXPrimitiveMode;
|
||||
|
||||
/**
|
||||
* Vertex positions.
|
||||
*/
|
||||
@@ -61,6 +56,11 @@ export interface IGeometry {
|
||||
*/
|
||||
colors?: number[];
|
||||
|
||||
/**
|
||||
* Topology of the geometry vertices. Default is TRIANGLE_LIST.
|
||||
*/
|
||||
primitiveMode?: GFXPrimitiveMode;
|
||||
|
||||
/**
|
||||
* whether rays casting from the back face of this geometry could collide with it
|
||||
*/
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
'use strict';
|
||||
|
||||
import { vec3 } from '../../core/vmath';
|
||||
import { GFXPrimitiveMode } from '../../gfx/define';
|
||||
|
||||
/**
|
||||
* @param {Number} radius
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
/**
|
||||
* JS Implementation of MurmurHash2
|
||||
*
|
||||
* @author <a href="mailto:gary.court@gmail.com">Gary Court</a>
|
||||
* @see http://github.com/garycourt/murmurhash-js
|
||||
* @author <a href="mailto:aappleby@gmail.com">Austin Appleby</a>
|
||||
* @see http://sites.google.com/site/murmurhash/
|
||||
*
|
||||
* @param {string} str ASCII only
|
||||
* @param {number} seed Positive integer only
|
||||
* @return {number} 32-bit positive integer hash
|
||||
*/
|
||||
|
||||
export function murmurhash2_32_gc(str, seed) {
|
||||
var
|
||||
l = str.length,
|
||||
h = seed ^ l,
|
||||
i = 0,
|
||||
k;
|
||||
|
||||
while (l >= 4) {
|
||||
k =
|
||||
((str.charCodeAt(i) & 0xff)) |
|
||||
((str.charCodeAt(++i) & 0xff) << 8) |
|
||||
((str.charCodeAt(++i) & 0xff) << 16) |
|
||||
((str.charCodeAt(++i) & 0xff) << 24);
|
||||
|
||||
k = (((k & 0xffff) * 0x5bd1e995) + ((((k >>> 16) * 0x5bd1e995) & 0xffff) << 16));
|
||||
k ^= k >>> 24;
|
||||
k = (((k & 0xffff) * 0x5bd1e995) + ((((k >>> 16) * 0x5bd1e995) & 0xffff) << 16));
|
||||
|
||||
h = (((h & 0xffff) * 0x5bd1e995) + ((((h >>> 16) * 0x5bd1e995) & 0xffff) << 16)) ^ k;
|
||||
|
||||
l -= 4;
|
||||
++i;
|
||||
}
|
||||
|
||||
switch (l) {
|
||||
case 3: h ^= (str.charCodeAt(i + 2) & 0xff) << 16;
|
||||
case 2: h ^= (str.charCodeAt(i + 1) & 0xff) << 8;
|
||||
case 1: h ^= (str.charCodeAt(i) & 0xff);
|
||||
h = (((h & 0xffff) * 0x5bd1e995) + ((((h >>> 16) * 0x5bd1e995) & 0xffff) << 16));
|
||||
}
|
||||
|
||||
h ^= h >>> 13;
|
||||
h = (((h & 0xffff) * 0x5bd1e995) + ((((h >>> 16) * 0x5bd1e995) & 0xffff) << 16));
|
||||
h ^= h >>> 15;
|
||||
|
||||
return h >>> 0;
|
||||
}
|
||||
@@ -63,4 +63,5 @@ export abstract class GFXShader extends GFXObject {
|
||||
|
||||
public abstract initialize (info: IGFXShaderInfo): boolean;
|
||||
public abstract destroy ();
|
||||
public get name () { return this._name; }
|
||||
}
|
||||
|
||||
@@ -3,7 +3,6 @@ import { GFXBuffer, GFXBufferSource, IGFXBufferInfo } from '../buffer';
|
||||
import { GFXCommandAllocator, IGFXCommandAllocatorInfo } from '../command-allocator';
|
||||
import { GFXCommandBuffer, IGFXCommandBufferInfo } from '../command-buffer';
|
||||
import {
|
||||
GFXAddress,
|
||||
GFXBindingType,
|
||||
GFXBufferTextureCopy,
|
||||
GFXBufferUsageBit,
|
||||
@@ -11,7 +10,6 @@ import {
|
||||
GFXFormat,
|
||||
GFXFormatInfos,
|
||||
GFXFormatSize,
|
||||
GFXPrimitiveMode,
|
||||
GFXQueueType,
|
||||
GFXTextureFlagBit,
|
||||
GFXTextureType,
|
||||
@@ -75,29 +73,29 @@ import { WebGLGFXTexture } from './webgl-texture';
|
||||
import { WebGLGFXTextureView } from './webgl-texture-view';
|
||||
import { WebGLGFXWindow } from './webgl-window';
|
||||
|
||||
const WebGLPrimitives = new Map([
|
||||
[ GFXPrimitiveMode.POINT_LIST, WebGLRenderingContext.POINTS ],
|
||||
[ GFXPrimitiveMode.LINE_LIST, WebGLRenderingContext.LINES ],
|
||||
[ GFXPrimitiveMode.LINE_LOOP, WebGLRenderingContext.LINE_LOOP ],
|
||||
[ GFXPrimitiveMode.LINE_STRIP, WebGLRenderingContext.LINE_STRIP ],
|
||||
[ GFXPrimitiveMode.TRIANGLE_LIST, WebGLRenderingContext.TRIANGLES ],
|
||||
[ GFXPrimitiveMode.TRIANGLE_STRIP, WebGLRenderingContext.TRIANGLE_STRIP ],
|
||||
[ GFXPrimitiveMode.TRIANGLE_FAN, WebGLRenderingContext.TRIANGLE_FAN ],
|
||||
[ GFXPrimitiveMode.LINE_LIST_ADJACENCY, WebGLRenderingContext.NONE ],
|
||||
[ GFXPrimitiveMode.LINE_STRIP_ADJACENCY, WebGLRenderingContext.NONE ],
|
||||
[ GFXPrimitiveMode.ISO_LINE_LIST, WebGLRenderingContext.NONE ],
|
||||
[ GFXPrimitiveMode.TRIANGLE_LIST_ADJACENCY, WebGLRenderingContext.NONE ],
|
||||
[ GFXPrimitiveMode.TRIANGLE_STRIP_ADJACENCY, WebGLRenderingContext.NONE ],
|
||||
[ GFXPrimitiveMode.TRIANGLE_PATCH_ADJACENCY, WebGLRenderingContext.NONE ],
|
||||
[ GFXPrimitiveMode.QUAD_PATCH_LIST, WebGLRenderingContext.NONE ],
|
||||
]);
|
||||
const WebGLPrimitives: GLenum[] = [
|
||||
WebGLRenderingContext.POINTS,
|
||||
WebGLRenderingContext.LINES,
|
||||
WebGLRenderingContext.LINE_STRIP,
|
||||
WebGLRenderingContext.LINE_LOOP,
|
||||
WebGLRenderingContext.NONE,
|
||||
WebGLRenderingContext.NONE,
|
||||
WebGLRenderingContext.NONE,
|
||||
WebGLRenderingContext.TRIANGLES,
|
||||
WebGLRenderingContext.TRIANGLE_STRIP,
|
||||
WebGLRenderingContext.TRIANGLE_FAN,
|
||||
WebGLRenderingContext.NONE,
|
||||
WebGLRenderingContext.NONE,
|
||||
WebGLRenderingContext.NONE,
|
||||
WebGLRenderingContext.NONE,
|
||||
];
|
||||
|
||||
const WebGLWraps = new Map([
|
||||
[ GFXAddress.WRAP, WebGLRenderingContext.REPEAT ],
|
||||
[ GFXAddress.MIRROR, WebGLRenderingContext.MIRRORED_REPEAT ],
|
||||
[ GFXAddress.CLAMP, WebGLRenderingContext.CLAMP_TO_EDGE ],
|
||||
[ GFXAddress.BORDER, WebGLRenderingContext.CLAMP_TO_EDGE ],
|
||||
]);
|
||||
const WebGLWraps: GLenum[] = [
|
||||
WebGLRenderingContext.REPEAT,
|
||||
WebGLRenderingContext.MIRRORED_REPEAT,
|
||||
WebGLRenderingContext.CLAMP_TO_EDGE,
|
||||
WebGLRenderingContext.CLAMP_TO_EDGE,
|
||||
];
|
||||
|
||||
export class WebGLGFXDevice extends GFXDevice {
|
||||
|
||||
@@ -793,9 +791,9 @@ export class WebGLGFXDevice extends GFXDevice {
|
||||
glMagFilter = WebGLRenderingContext.NEAREST;
|
||||
}
|
||||
|
||||
const glWrapS = (info.addressU !== undefined ? WebGLWraps.get(info.addressU)! : WebGLRenderingContext.REPEAT);
|
||||
const glWrapT = (info.addressU !== undefined ? WebGLWraps.get(info.addressU)! : WebGLRenderingContext.REPEAT);
|
||||
const glWrapR = (info.addressU !== undefined ? WebGLWraps.get(info.addressU)! : WebGLRenderingContext.REPEAT);
|
||||
const glWrapS = (info.addressU !== undefined ? WebGLWraps[info.addressU] : WebGLRenderingContext.REPEAT);
|
||||
const glWrapT = (info.addressU !== undefined ? WebGLWraps[info.addressU] : WebGLRenderingContext.REPEAT);
|
||||
const glWrapR = (info.addressU !== undefined ? WebGLWraps[info.addressU] : WebGLRenderingContext.REPEAT);
|
||||
|
||||
const gpuSampler: WebGLGPUSampler = {
|
||||
objType: WebGLGPUObjectType.SAMPLER,
|
||||
@@ -872,7 +870,7 @@ export class WebGLGFXDevice extends GFXDevice {
|
||||
|
||||
const gpuPipelineState: WebGLGPUPipelineState = {
|
||||
objType: WebGLGPUObjectType.PIPELINE_STATE,
|
||||
glPrimitive: WebGLPrimitives.get(info.primitive)!,
|
||||
glPrimitive: WebGLPrimitives[info.primitive],
|
||||
gpuShader,
|
||||
rs: info.rs,
|
||||
dss: info.dss,
|
||||
|
||||
@@ -211,7 +211,7 @@ export class Pass {
|
||||
if (this._pipelineState) { this._pipelineState.destroy(); }
|
||||
const ors = Object.assign({}, overrides);
|
||||
this._createPipelineState(info, (states) => {
|
||||
if (overrides.primitive !== undefined) { states.primitive = overrides.primitive; }
|
||||
if (overrides.primitive !== undefined) { this._primitive = states.primitive = overrides.primitive; }
|
||||
Object.assign(states.rs, ors.rs);
|
||||
Object.assign(states.dss, ors.dss);
|
||||
if (ors.bs) {
|
||||
@@ -246,6 +246,15 @@ export class Pass {
|
||||
(this._bindingLayout as GFXBindingLayout).update();
|
||||
}
|
||||
|
||||
public serializePipelineStates () {
|
||||
const ps = this._pipelineState as GFXPipelineState;
|
||||
let res = `${ps.shader.name},${this._stage},${ps.primitive}`;
|
||||
res += serializeBlendState(ps.blendState);
|
||||
res += serializeDepthStencilState(ps.depthStencilState);
|
||||
res += serializeRasterizerState(ps.rasterizerState);
|
||||
return res;
|
||||
}
|
||||
|
||||
protected _createPipelineState (info: Partial<IPassInfo>, override?: (states: IGFXPipelineStateInfo) => any) {
|
||||
if (info.primitive) { this._primitive = info.primitive; }
|
||||
if (info.stage) { this._stage = info.stage; }
|
||||
@@ -287,3 +296,27 @@ export class Pass {
|
||||
get bindingLayout () { return this._bindingLayout as GFXBindingLayout; }
|
||||
get primitive (): GFXPrimitiveMode { return this._primitive; }
|
||||
}
|
||||
|
||||
function serializeBlendState (bs: GFXBlendState) {
|
||||
let res = `,bs,${bs.isA2C},${bs.blendColor}`;
|
||||
for (const t of bs.targets) {
|
||||
res += `,bt,${t.blend},${t.blendEq},${t.blendAlphaEq},${t.blendColorMask}`;
|
||||
res += `,${t.blendSrc},${t.blendDst},${t.blendSrcAlpha},${t.blendDstAlpha}`;
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
function serializeRasterizerState (rs: GFXRasterizerState) {
|
||||
const res = `,rs,${rs.cullMode},${rs.depthBias},${rs.depthBiasFactor},${rs.isFrontFaceCCW}`;
|
||||
return res;
|
||||
}
|
||||
|
||||
// tslint:disable: max-line-length
|
||||
function serializeDepthStencilState (dss: GFXDepthStencilState) {
|
||||
let res = `,dss,${dss.depthTest},${dss.depthWrite},${dss.depthFunc}`;
|
||||
res += `,${dss.stencilTestFront},${dss.stencilFuncFront},${dss.stencilRefFront},${dss.stencilReadMaskFront}`;
|
||||
res += `,${dss.stencilFailOpFront},${dss.stencilZFailOpFront},${dss.stencilPassOpFront},${dss.stencilWriteMaskFront}`;
|
||||
res += `,${dss.stencilTestBack},${dss.stencilFuncBack},${dss.stencilRefBack},${dss.stencilReadMaskBack}`;
|
||||
res += `,${dss.stencilFailOpBack},${dss.stencilZFailOpBack},${dss.stencilPassOpBack},${dss.stencilWriteMaskBack}`;
|
||||
return res;
|
||||
}
|
||||
|
||||
@@ -126,9 +126,9 @@ export class ProgramLib {
|
||||
const vert = customDef + tmpl.vert;
|
||||
const frag = customDef + tmpl.frag;
|
||||
|
||||
tmpl.blocks = tmpl.blocks.concat(convertToBlockInfo(UBOGlobal.BLOCK), convertToBlockInfo(UBOLocal.BLOCK));
|
||||
tmpl.blocks = tmpl.blocks.concat(globals, locals);
|
||||
|
||||
const instanceName = Object.keys(defines).reduce((acc, cur) => `${acc}|${cur}`, name);
|
||||
const instanceName = Object.keys(defines).reduce((acc, cur) => defines[cur] ? `${acc}|${cur}` : acc, name);
|
||||
program = this._device.createShader({
|
||||
name: instanceName,
|
||||
blocks: tmpl.blocks,
|
||||
@@ -143,6 +143,9 @@ export class ProgramLib {
|
||||
}
|
||||
}
|
||||
|
||||
const globals = convertToBlockInfo(UBOGlobal.BLOCK);
|
||||
const locals = convertToBlockInfo(UBOLocal.BLOCK);
|
||||
|
||||
function convertToUniformInfo (uniform: GFXUniform): IBlockMember {
|
||||
return {
|
||||
name: uniform.name,
|
||||
|
||||
@@ -0,0 +1,233 @@
|
||||
// camera
|
||||
|
||||
"use strict";
|
||||
|
||||
var _dec, _class;
|
||||
|
||||
function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
|
||||
|
||||
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
|
||||
|
||||
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
|
||||
|
||||
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
|
||||
|
||||
function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
|
||||
|
||||
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
|
||||
|
||||
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
|
||||
|
||||
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
|
||||
|
||||
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
|
||||
|
||||
var FirstPersonCamera = (_dec = cc._decorator.ccclass(), _dec(_class =
|
||||
/*#__PURE__*/
|
||||
function (_cc$Component) {
|
||||
_inherits(FirstPersonCamera, _cc$Component);
|
||||
|
||||
function FirstPersonCamera() {
|
||||
var _this;
|
||||
|
||||
_classCallCheck(this, FirstPersonCamera);
|
||||
|
||||
_this = _possibleConstructorReturn(this, _getPrototypeOf(FirstPersonCamera).call(this));
|
||||
_this._lbtnDown = false;
|
||||
_this._rbtnDown = false;
|
||||
_this._keyStates = new Array(128);
|
||||
|
||||
_this._keyStates.fill(false);
|
||||
|
||||
return _this;
|
||||
}
|
||||
|
||||
_createClass(FirstPersonCamera, [{
|
||||
key: "start",
|
||||
value: function start() {
|
||||
var _this2 = this;
|
||||
|
||||
var cameraComponent = this.node.getComponent("cc.CameraComponent");
|
||||
|
||||
if (!cameraComponent) {
|
||||
console.error("Cannot find cc.CameraComponent on node ".concat(this.node.name));
|
||||
}
|
||||
|
||||
cc.eventManager.setEnabled(true);
|
||||
var mouseListener = cc.EventListener.create({
|
||||
event: cc.EventListener.MOUSE,
|
||||
onMouseDown: function onMouseDown() {
|
||||
return _this2._mouseDownHandler.apply(_this2, arguments);
|
||||
},
|
||||
onMouseMove: function onMouseMove() {
|
||||
return _this2._mouseMoveHandler.apply(_this2, arguments);
|
||||
},
|
||||
onMouseUp: function onMouseUp() {
|
||||
return _this2._mouseUpHandler.apply(_this2, arguments);
|
||||
},
|
||||
onMouseScroll: function onMouseScroll() {
|
||||
return _this2._mouseWheelHandler.apply(_this2, arguments);
|
||||
}
|
||||
});
|
||||
cc.eventManager.addListener(mouseListener, 1);
|
||||
var keyListener = cc.EventListener.create({
|
||||
event: cc.EventListener.KEYBOARD,
|
||||
onKeyPressed: function onKeyPressed() {
|
||||
return _this2._keyDownHandler.apply(_this2, arguments);
|
||||
},
|
||||
onKeyReleased: function onKeyReleased() {
|
||||
return _this2._keyUpHandler.apply(_this2, arguments);
|
||||
}
|
||||
});
|
||||
cc.eventManager.addListener(keyListener, 1);
|
||||
}
|
||||
}, {
|
||||
key: "update",
|
||||
value: function update(dt) {
|
||||
var _this3 = this;
|
||||
|
||||
var translationDelta = dt * 10;
|
||||
|
||||
var isKeyPressing = function isKeyPressing(keystr) {
|
||||
return _this3._keyStates[keystr.charCodeAt(0)];
|
||||
};
|
||||
|
||||
if (isKeyPressing("W")) {
|
||||
this._translate(this._getForward(), translationDelta);
|
||||
}
|
||||
|
||||
if (isKeyPressing("S")) {
|
||||
this._translate(this._getForward(), -translationDelta);
|
||||
}
|
||||
|
||||
if (isKeyPressing("A")) {
|
||||
this._translate(this._getRight(), -translationDelta);
|
||||
}
|
||||
|
||||
if (isKeyPressing("D")) {
|
||||
this._translate(this._getRight(), translationDelta);
|
||||
}
|
||||
|
||||
if (isKeyPressing("Q")) {
|
||||
this._translate(cc.v3(0, 1, 0), -translationDelta);
|
||||
}
|
||||
|
||||
if (isKeyPressing("E")) {
|
||||
this._translate(cc.v3(0, 1, 0), translationDelta);
|
||||
}
|
||||
}
|
||||
}, {
|
||||
key: "_mouseWheelHandler",
|
||||
value: function _mouseWheelHandler(event) {
|
||||
var delta = event._scrollY / 120; // forward to screen is positive
|
||||
|
||||
this._translate(this._getForward(), delta);
|
||||
}
|
||||
}, {
|
||||
key: "_mouseDownHandler",
|
||||
value: function _mouseDownHandler(event) {
|
||||
if (event._button === 0) {
|
||||
this._lbtnDown = true;
|
||||
} else if (event._button === 1) {
|
||||
this._mbtnDown = true;
|
||||
} else if (event._button === 2) {
|
||||
cc.game.canvas.requestPointerLock();
|
||||
this._rbtnDown = true;
|
||||
}
|
||||
}
|
||||
}, {
|
||||
key: "_mouseUpHandler",
|
||||
value: function _mouseUpHandler(event) {
|
||||
if (event._button === 0) {
|
||||
this._lbtnDown = false;
|
||||
} else if (event._button === 1) {
|
||||
this._mbtnDown = false;
|
||||
} else if (event._button === 2) {
|
||||
document.exitPointerLock();
|
||||
this._rbtnDown = false;
|
||||
}
|
||||
}
|
||||
}, {
|
||||
key: "_mouseMoveHandler",
|
||||
value: function _mouseMoveHandler(event) {
|
||||
var dx = event.movementX;
|
||||
var dy = -event.movementY;
|
||||
|
||||
if (dx !== 0) {
|
||||
if (this._rbtnDown) {
|
||||
this._rotateSelfHorizon(dx / 5);
|
||||
}
|
||||
}
|
||||
|
||||
if (dy !== 0) {
|
||||
if (this._rbtnDown) {
|
||||
this._rotateSelfVertical(dy / 5);
|
||||
}
|
||||
}
|
||||
}
|
||||
}, {
|
||||
key: "_keyDownHandler",
|
||||
value: function _keyDownHandler(keycode) {
|
||||
if (keycode < this._keyStates.length) {
|
||||
this._keyStates[keycode] = true;
|
||||
}
|
||||
}
|
||||
}, {
|
||||
key: "_keyUpHandler",
|
||||
value: function _keyUpHandler(keycode) {
|
||||
if (keycode < this._keyStates.length) {
|
||||
this._keyStates[keycode] = false;
|
||||
}
|
||||
}
|
||||
}, {
|
||||
key: "_translate",
|
||||
value: function _translate(direction, delta) {
|
||||
var position = this.node.getPosition();
|
||||
cc.vmath.vec3.scaleAndAdd(position, position, direction, delta);
|
||||
this.node.setPosition(position);
|
||||
}
|
||||
}, {
|
||||
key: "_rotateSelfHorizon",
|
||||
value: function _rotateSelfHorizon(delta) {
|
||||
var rotation = this.node.getRotation();
|
||||
var up = cc.v3(0, 1, 0); //const up = this._getUp();
|
||||
|
||||
cc.vmath.quat.rotateAround(rotation, rotation, up, -delta / 360.0 * 3.14159265);
|
||||
this.node.setRotation(rotation);
|
||||
}
|
||||
}, {
|
||||
key: "_rotateSelfVertical",
|
||||
value: function _rotateSelfVertical(delta) {
|
||||
var rotation = this.node.getRotation(); //const right = cc.v3(1, 0, 0);
|
||||
|
||||
var right = this._getRight();
|
||||
|
||||
cc.vmath.quat.rotateAround(rotation, rotation, right, delta / 360.0 * 3.14159265);
|
||||
this.node.setRotation(rotation);
|
||||
}
|
||||
}, {
|
||||
key: "_getForward",
|
||||
value: function _getForward() {
|
||||
return this._getDirection(0, 0, -1);
|
||||
}
|
||||
}, {
|
||||
key: "_getRight",
|
||||
value: function _getRight() {
|
||||
return this._getDirection(1, 0, 0);
|
||||
}
|
||||
}, {
|
||||
key: "_getUp",
|
||||
value: function _getUp() {
|
||||
return this._getDirection(0, 1, 0);
|
||||
}
|
||||
}, {
|
||||
key: "_getDirection",
|
||||
value: function _getDirection(x, y, z) {
|
||||
var result = cc.v3(x, y, z);
|
||||
cc.vmath.vec3.transformQuat(result, result, this.node.getRotation());
|
||||
return result;
|
||||
}
|
||||
}]);
|
||||
|
||||
return FirstPersonCamera;
|
||||
}(cc.Component)) || _class);
|
||||
+16
-11
@@ -28,6 +28,7 @@
|
||||
</canvas>
|
||||
|
||||
<script src="../bin/cocos-3d.dev.js"></script>
|
||||
<script src="./camera.js"></script>
|
||||
<script>
|
||||
const $body = document.body;
|
||||
const bcr = $body.getBoundingClientRect();
|
||||
@@ -44,15 +45,16 @@
|
||||
textureAsset.image = new cc.ImageAsset(imgElms[0]);
|
||||
return textureAsset;
|
||||
}
|
||||
function getRandom() { return Math.random() * 128 + 127; }
|
||||
const geomList = ['box', 'sphere', 'cylinder', 'cone', 'torus', 'capsule'];
|
||||
function onStart() {
|
||||
const root = cc.director.root;
|
||||
const scene = new cc.Scene();
|
||||
|
||||
const cameraNode = new cc.Node();
|
||||
const cameraNode = new cc.Node('Camera');
|
||||
cameraNode.parent = scene;
|
||||
cameraNode.setPosition(4, 4, -2);
|
||||
cameraNode.lookAt(cc.v3(0, 0, 20));
|
||||
cameraNode.setPosition(20, 0, 115);
|
||||
cameraNode.setRotationFromEuler(0, 30, 0);
|
||||
cameraNode.addComponent(FirstPersonCamera);
|
||||
const camComp = cameraNode.addComponent(cc.CameraComponent);
|
||||
|
||||
const texture = createTexture(cc.game.canvas.getElementsByTagName('img'));
|
||||
@@ -62,7 +64,7 @@
|
||||
const color = cc.color()
|
||||
for (let i = 0; i < len; i++) {
|
||||
const material = new cc.Material();
|
||||
material.setDefines({ USE_COLOR: true, USE_TEXTURE: true });
|
||||
material.setDefines({ USE_COLOR: true });
|
||||
// parsed effect file is embedded in cocos/3d/builtin/effects.js
|
||||
material.effectName = 'builtin-effect-unlit';
|
||||
material.setProperty('mainTexture', texture);
|
||||
@@ -72,14 +74,15 @@
|
||||
modelNode.parent = scene;
|
||||
const modelCom = modelNode.addComponent('cc.ModelComponent');
|
||||
modelCom.material = material;
|
||||
modelCom.mesh = cc.utils.createMesh(cc.primitives.box());
|
||||
modelCom.mesh = cc.utils.createMesh(cc.primitives[geomList[i % geomList.length]]());
|
||||
modelNode.setPosition(0, 0, i * 2);
|
||||
models.push(modelNode);
|
||||
}
|
||||
const handle = passes[0].getHandle('color');
|
||||
|
||||
let buttonDown = false, pos = cc.v2();
|
||||
canv.addEventListener('mousedown', () => buttonDown = true);
|
||||
canv.addEventListener('mouseup', () => buttonDown = false);
|
||||
canv.addEventListener('mousedown', (e) => buttonDown = (!e.button) ? true : buttonDown);
|
||||
canv.addEventListener('mouseup', (e) => buttonDown = (!e.button) ? false : buttonDown);
|
||||
canv.addEventListener('mousemove', (e) => (pos.x = e.x, pos.y = e.y));
|
||||
|
||||
cc.director.on(cc.Director.EVENT_AFTER_UPDATE, () => {
|
||||
@@ -89,10 +92,12 @@
|
||||
if (res.length) res.forEach((r) => console.log(r.node.name, r.distance));
|
||||
}
|
||||
models.forEach((m, i) => {
|
||||
const t = cc.director._totalFrames / 60;
|
||||
const rad = i * 0.4;
|
||||
const dt = cc.director._deltaTime;
|
||||
const t = cc.director._totalFrames / (60);
|
||||
const rad = i * Math.PI * 8 / len;
|
||||
const x = Math.cos(rad + t), y = Math.sin(rad + t);
|
||||
m.setPosition(x * 2, y * 2, i * 2);
|
||||
let z = m._lpos.z + dt; if (z > len * 2) z = 0;
|
||||
m.setPosition(x * 2, y * 2, z);
|
||||
color.fromHSV((x + 1) * 0.5, 0.5, 1);
|
||||
passes[i].setUniform(handle, color);
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user